1 | # dns/trunk/DNSDB.pm
|
---|
2 | # Abstraction functions for DNS administration
|
---|
3 | ##
|
---|
4 | # $Id: DNSDB.pm 548 2013-12-11 21:01:18Z 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 Net::SMTP;
|
---|
30 | use NetAddr::IP 4.027 qw(:lower);
|
---|
31 | use POSIX;
|
---|
32 | use Fcntl qw(:flock);
|
---|
33 | use Time::TAI64 qw(:tai64);
|
---|
34 |
|
---|
35 | use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
|
---|
36 |
|
---|
37 | $VERSION = 1.1; ##VERSION##
|
---|
38 | @ISA = qw(Exporter);
|
---|
39 | @EXPORT_OK = qw(
|
---|
40 | &initGlobals &login &initActionLog
|
---|
41 | &getPermissions &changePermissions &comparePermissions
|
---|
42 | &changeGroup
|
---|
43 | &connectDB &finish
|
---|
44 | &addDomain &delZone &domainName &revName &domainID &revID &addRDNS
|
---|
45 | &getZoneCount &getZoneList &getZoneLocation
|
---|
46 | &addGroup &delGroup &getChildren &groupName
|
---|
47 | &getGroupCount &getGroupList
|
---|
48 | &addUser &updateUser &delUser &userFullName &userStatus &getUserData
|
---|
49 | &getUserCount &getUserList &getUserDropdown
|
---|
50 | &addLoc &updateLoc &delLoc &getLoc
|
---|
51 | &getLocCount &getLocList &getLocDropdown
|
---|
52 | &getSOA &updateSOA &getRecLine &getRecList &getRecCount
|
---|
53 | &addRec &updateRec &delRec
|
---|
54 | &getLogCount &getLogEntries
|
---|
55 | &getRevPattern
|
---|
56 | &getTypelist
|
---|
57 | &parentID
|
---|
58 | &isParent
|
---|
59 | &zoneStatus &getZonesByCIDR &importAXFR
|
---|
60 | &export
|
---|
61 | &mailNotify
|
---|
62 | %typemap %reverse_typemap
|
---|
63 | @permtypes $permlist %permchains
|
---|
64 | );
|
---|
65 |
|
---|
66 | @EXPORT = qw(%typemap %reverse_typemap @permtypes $permlist %permchains);
|
---|
67 | %EXPORT_TAGS = ( ALL => [qw(
|
---|
68 | &initGlobals &login &initActionLog
|
---|
69 | &getPermissions &changePermissions &comparePermissions
|
---|
70 | &changeGroup
|
---|
71 | &connectDB &finish
|
---|
72 | &addDomain &delZone &domainName &revName &domainID &revID &addRDNS
|
---|
73 | &getZoneCount &getZoneList &getZoneLocation
|
---|
74 | &addGroup &delGroup &getChildren &groupName
|
---|
75 | &getGroupCount &getGroupList
|
---|
76 | &addUser &updateUser &delUser &userFullName &userStatus &getUserData
|
---|
77 | &getUserCount &getUserList &getUserDropdown
|
---|
78 | &addLoc &updateLoc &delLoc &getLoc
|
---|
79 | &getLocCount &getLocList &getLocDropdown
|
---|
80 | &getSOA &updateSOA &getRecLine &getRecList &getRecCount
|
---|
81 | &addRec &updateRec &delRec
|
---|
82 | &getLogCount &getLogEntries
|
---|
83 | &getRevPattern
|
---|
84 | &getTypelist
|
---|
85 | &parentID
|
---|
86 | &isParent
|
---|
87 | &zoneStatus &getZonesByCIDR &importAXFR
|
---|
88 | &export
|
---|
89 | &mailNotify
|
---|
90 | %typemap %reverse_typemap
|
---|
91 | @permtypes $permlist %permchains
|
---|
92 | )]
|
---|
93 | );
|
---|
94 |
|
---|
95 | our $errstr = '';
|
---|
96 | our $resultstr = '';
|
---|
97 |
|
---|
98 | # Arguably defined wholly in the db, but little reason to change without supporting code changes
|
---|
99 | # group_view, user_view permissions? separate rDNS permission(s)?
|
---|
100 | our @permtypes = qw (
|
---|
101 | group_edit group_create group_delete
|
---|
102 | user_edit user_create user_delete
|
---|
103 | domain_edit domain_create domain_delete
|
---|
104 | record_edit record_create record_delete record_locchg
|
---|
105 | location_edit location_create location_delete location_view
|
---|
106 | self_edit admin
|
---|
107 | );
|
---|
108 | our $permlist = join(',',@permtypes);
|
---|
109 |
|
---|
110 | # Some permissions more or less require certain others.
|
---|
111 | our %permchains = (
|
---|
112 | user_edit => 'self_edit',
|
---|
113 | location_edit => 'location_view',
|
---|
114 | location_create => 'location_view',
|
---|
115 | location_delete => 'location_view',
|
---|
116 | record_locchg => 'location_view',
|
---|
117 | );
|
---|
118 |
|
---|
119 | # DNS record type map and reverse map.
|
---|
120 | # loaded from the database, from http://www.iana.org/assignments/dns-parameters
|
---|
121 | our %typemap;
|
---|
122 | our %reverse_typemap;
|
---|
123 |
|
---|
124 | ## (Semi)private variables
|
---|
125 |
|
---|
126 | # Hash of functions for validating record types. Filled in initGlobals() since
|
---|
127 | # it relies on visibility flags from the rectypes table in the DB
|
---|
128 | my %validators;
|
---|
129 |
|
---|
130 | # Entity-relationship reference hashes.
|
---|
131 | my %par_tbl = (
|
---|
132 | group => 'groups',
|
---|
133 | user => 'users',
|
---|
134 | defrec => 'default_records',
|
---|
135 | defrevrec => 'default_rev_records',
|
---|
136 | domain => 'domains',
|
---|
137 | revzone => 'revzones',
|
---|
138 | record => 'records'
|
---|
139 | );
|
---|
140 | my %id_col = (
|
---|
141 | group => 'group_id',
|
---|
142 | user => 'user_id',
|
---|
143 | defrec => 'record_id',
|
---|
144 | defrevrec => 'record_id',
|
---|
145 | domain => 'domain_id',
|
---|
146 | revzone => 'rdns_id',
|
---|
147 | record => 'record_id'
|
---|
148 | );
|
---|
149 | my %par_col = (
|
---|
150 | group => 'parent_group_id',
|
---|
151 | user => 'group_id',
|
---|
152 | defrec => 'group_id',
|
---|
153 | defrevrec => 'group_id',
|
---|
154 | domain => 'group_id',
|
---|
155 | revzone => 'group_id',
|
---|
156 | record => 'domain_id'
|
---|
157 | );
|
---|
158 | my %par_type = (
|
---|
159 | group => 'group',
|
---|
160 | user => 'group',
|
---|
161 | defrec => 'group',
|
---|
162 | defrevrec => 'group',
|
---|
163 | domain => 'group',
|
---|
164 | revzone => 'group',
|
---|
165 | record => 'domain'
|
---|
166 | );
|
---|
167 |
|
---|
168 | ##
|
---|
169 | ## Constructor and destructor
|
---|
170 | ##
|
---|
171 |
|
---|
172 | sub new {
|
---|
173 | my $this = shift;
|
---|
174 | my $class = ref($this) || $this;
|
---|
175 | my %args = @_;
|
---|
176 |
|
---|
177 | # Prepopulate a basic config. Note some of these *will* cause errors if left unset.
|
---|
178 | # note: add appropriate stanzas in __cfgload() to parse these
|
---|
179 | my %defconfig = (
|
---|
180 | # The only configuration options not loadable from a config file.
|
---|
181 | configfile => "/etc/dnsdb/dnsdb.conf", ##CFG_LEAF##
|
---|
182 |
|
---|
183 | # Database connection info
|
---|
184 | dbname => 'dnsdb',
|
---|
185 | dbuser => 'dnsdb',
|
---|
186 | dbpass => 'secret',
|
---|
187 | dbhost => '',
|
---|
188 |
|
---|
189 | # Email notice settings
|
---|
190 | mailhost => 'smtp.example.com',
|
---|
191 | mailnotify => 'dnsdb@example.com', # to
|
---|
192 | mailsender => 'dnsdb@example.com', # from
|
---|
193 | mailname => 'DNS Administration',
|
---|
194 | orgname => 'Example Corp',
|
---|
195 | domain => 'example.com',
|
---|
196 |
|
---|
197 | # Template directory
|
---|
198 | templatedir => 'templates/',
|
---|
199 | # fmeh. this is a real web path, not a logical internal one. hm..
|
---|
200 | # cssdir => 'templates/',
|
---|
201 | sessiondir => 'session/',
|
---|
202 | exportcache => 'cache/',
|
---|
203 |
|
---|
204 | # Session params
|
---|
205 | timeout => '1h', # passed as-is to CGI::Session
|
---|
206 |
|
---|
207 | # Other miscellanea
|
---|
208 | log_failures => 1, # log all evarthing by default
|
---|
209 | perpage => 15,
|
---|
210 | max_fcgi_requests => 100, # reasonable default?
|
---|
211 | force_refresh => 1,
|
---|
212 | lowercase => 0, # mangle as little as possible by default
|
---|
213 | );
|
---|
214 |
|
---|
215 | # Config file parse calls.
|
---|
216 | # If we are passed a blank argument for $args{configfile},
|
---|
217 | # we should NOT parse the default config file - we will
|
---|
218 | # rely on hardcoded defaults OR caller-specified values.
|
---|
219 | # If we are passed a non-blank argument, parse that file.
|
---|
220 | # If no config file is specified, parse the default one.
|
---|
221 | my %siteconfig;
|
---|
222 | if (defined($args{configfile})) {
|
---|
223 | if ($args{configfile}) {
|
---|
224 | return if !__cfgload($args{configfile}, \%siteconfig);
|
---|
225 | }
|
---|
226 | } else {
|
---|
227 | return if !__cfgload($defconfig{configfile}, \%siteconfig);
|
---|
228 | }
|
---|
229 |
|
---|
230 | # Assemble the object. Apply configuration hashes in order of precedence.
|
---|
231 | my $self = {
|
---|
232 | # Hardcoded defaults
|
---|
233 | %defconfig,
|
---|
234 | # Default config file OR caller-specified one, loaded above
|
---|
235 | %siteconfig,
|
---|
236 | # Caller-specified arguments
|
---|
237 | %args
|
---|
238 | };
|
---|
239 | bless $self, $class;
|
---|
240 |
|
---|
241 | # Several settings are booleans. Handle multiple possible ways of setting them.
|
---|
242 | for my $boolopt ('log_failures', 'force_refresh', 'lowercase') {
|
---|
243 | if ($self->{$boolopt} ne '1' && $self->{$boolopt} ne '0') {
|
---|
244 | # true/false, on/off, yes/no all valid.
|
---|
245 | if ($self->{$boolopt} =~ /^(?:true|false|t|f|on|off|yes|no)$/) {
|
---|
246 | if ($self->{$boolopt} =~ /(?:true|t|on|yes)/) {
|
---|
247 | $self->{$boolopt} = 1;
|
---|
248 | } else {
|
---|
249 | $self->{$boolopt} = 0;
|
---|
250 | }
|
---|
251 | } else {
|
---|
252 | warn "Bad $boolopt setting $self->{$boolopt}\n";
|
---|
253 | $self->{$boolopt} = 1;
|
---|
254 | }
|
---|
255 | }
|
---|
256 | }
|
---|
257 |
|
---|
258 | # Try to connect to the DB, and initialize a number of handy globals.
|
---|
259 | $self->{dbh} = connectDB($self->{dbname}, $self->{dbuser}, $self->{dbpass}, $self->{dbhost}) or return;
|
---|
260 | $self->initGlobals();
|
---|
261 |
|
---|
262 | return $self;
|
---|
263 | }
|
---|
264 |
|
---|
265 | sub DESTROY {
|
---|
266 | my $self = shift;
|
---|
267 | $self->{dbh}->disconnect if $self->{dbh};
|
---|
268 | }
|
---|
269 |
|
---|
270 | sub errstr { $DNSDB::errstr; }
|
---|
271 |
|
---|
272 | ##
|
---|
273 | ## utility functions
|
---|
274 | ##
|
---|
275 |
|
---|
276 | ## DNSDB::_rectable()
|
---|
277 | # Takes default+rdns flags, returns appropriate table name
|
---|
278 | sub _rectable {
|
---|
279 | my $def = shift;
|
---|
280 | my $rev = shift;
|
---|
281 |
|
---|
282 | return 'records' if $def ne 'y';
|
---|
283 | return 'default_records' if $rev ne 'y';
|
---|
284 | return 'default_rev_records';
|
---|
285 | } # end _rectable()
|
---|
286 |
|
---|
287 | ## DNSDB::_recparent()
|
---|
288 | # Takes default+rdns flags, returns appropriate parent-id column name
|
---|
289 | sub _recparent {
|
---|
290 | my $def = shift;
|
---|
291 | my $rev = shift;
|
---|
292 |
|
---|
293 | return 'group_id' if $def eq 'y';
|
---|
294 | return 'rdns_id' if $rev eq 'y';
|
---|
295 | return 'domain_id';
|
---|
296 | } # end _recparent()
|
---|
297 |
|
---|
298 | ## DNSDB::_ipparent()
|
---|
299 | # Check an IP to be added in a reverse zone to see if it's really in the requested parent.
|
---|
300 | # Takes default and reverse flags, IP (fragment) to check, parent zone ID,
|
---|
301 | # and a reference to a NetAddr::IP object (also used to pass back a fully-reconstructed IP for
|
---|
302 | # database insertion)
|
---|
303 | sub _ipparent {
|
---|
304 | my $self = shift;
|
---|
305 | my $dbh = $self->{dbh};
|
---|
306 | my $defrec = shift;
|
---|
307 | my $revrec = shift;
|
---|
308 | my $val = shift;
|
---|
309 | my $id = shift;
|
---|
310 | my $addr = shift;
|
---|
311 |
|
---|
312 | return if $revrec ne 'y'; # this sub not useful in forward zones
|
---|
313 |
|
---|
314 | $$addr = NetAddr::IP->new($$val); #necessary?
|
---|
315 |
|
---|
316 | # subsub to split, reverse, and overlay an IP fragment on a netblock
|
---|
317 | sub __rev_overlay {
|
---|
318 | my $splitme = shift; # ':' or '.', m'lud?
|
---|
319 | my $parnet = shift;
|
---|
320 | my $val = shift;
|
---|
321 | my $addr = shift;
|
---|
322 |
|
---|
323 | my $joinme = $splitme;
|
---|
324 | $splitme = '\.' if $splitme eq '.';
|
---|
325 | my @working = reverse(split($splitme, $parnet->addr));
|
---|
326 | my @parts = reverse(split($splitme, $$val));
|
---|
327 | for (my $i = 0; $i <= $#parts; $i++) {
|
---|
328 | $working[$i] = $parts[$i];
|
---|
329 | }
|
---|
330 | my $checkme = NetAddr::IP->new(join($joinme, reverse(@working))) or return 0;
|
---|
331 | return 0 unless $checkme->within($parnet);
|
---|
332 | $$addr = $checkme; # force "correct" IP to be recorded.
|
---|
333 | return 1;
|
---|
334 | }
|
---|
335 |
|
---|
336 | my ($parstr) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id = ?", undef, ($id));
|
---|
337 | my $parnet = NetAddr::IP->new($parstr);
|
---|
338 |
|
---|
339 | # Fail early on v6-in-v4 or v4-in-v6. We're not accepting these ATM.
|
---|
340 | return 0 if $parnet->addr =~ /\./ && $$val =~ /:/;
|
---|
341 | return 0 if $parnet->addr =~ /:/ && $$val =~ /\./;
|
---|
342 |
|
---|
343 | if ($$addr && ($$val =~ /^[\da-fA-F][\da-fA-F:]+[\da-fA-F]$/ || $$val =~ m|/\d+$|)) {
|
---|
344 | # the only case where NetAddr::IP's acceptance of legitimate IPs is "correct" is for a proper IPv6 address,
|
---|
345 | # or a netblock (only expected on templates)
|
---|
346 | # the rest we have to restructure before fiddling. *sigh*
|
---|
347 | return 1 if $$addr->within($parnet);
|
---|
348 | } else {
|
---|
349 | # We don't have a complete IP in $$val (yet)... unless we have a netblock
|
---|
350 | if ($parnet->addr =~ /:/) {
|
---|
351 | $$val =~ s/^:+//; # gotta strip'em all...
|
---|
352 | return __rev_overlay(':', $parnet, $val, $addr);
|
---|
353 | }
|
---|
354 | if ($parnet->addr =~ /\./) {
|
---|
355 | $$val =~ s/^\.+//;
|
---|
356 | return __rev_overlay('.', $parnet, $val, $addr);
|
---|
357 | }
|
---|
358 | # should be impossible to get here...
|
---|
359 | }
|
---|
360 | # ... and here.
|
---|
361 | # can't do nuttin' in forward zones
|
---|
362 | } # end _ipparent()
|
---|
363 |
|
---|
364 | ## DNSDB::_hostparent()
|
---|
365 | # A little different than _ipparent above; this tries to *find* the parent zone of a hostname
|
---|
366 | # Takes a hostname.
|
---|
367 | # Returns the domain ID of the parent domain if one was found.
|
---|
368 | sub _hostparent {
|
---|
369 | my $self = shift;
|
---|
370 | my $dbh = $self->{dbh};
|
---|
371 | my $hname = shift;
|
---|
372 |
|
---|
373 | $hname =~ s/^\*\.//; # this should be impossible to find in the domains table.
|
---|
374 | my @hostbits = split /\./, $hname;
|
---|
375 | my $sth = $dbh->prepare("SELECT count(*),domain_id FROM domains WHERE lower(domain) = lower(?) GROUP BY domain_id");
|
---|
376 | foreach (@hostbits) {
|
---|
377 | $sth->execute($hname);
|
---|
378 | my ($found, $parid) = $sth->fetchrow_array;
|
---|
379 | if ($found) {
|
---|
380 | return $parid;
|
---|
381 | }
|
---|
382 | $hname =~ s/^$_\.//;
|
---|
383 | }
|
---|
384 | } # end _hostparent()
|
---|
385 |
|
---|
386 | ## DNSDB::_log()
|
---|
387 | # Log an action
|
---|
388 | # Takes a log entry hash containing at least:
|
---|
389 | # group_id, log entry
|
---|
390 | # and optionally one or more of:
|
---|
391 | # domain_id, rdns_id
|
---|
392 | # The %userdata hash provides the user ID, username, and fullname
|
---|
393 | sub _log {
|
---|
394 | my $self = shift;
|
---|
395 | my $dbh = $self->{dbh};
|
---|
396 |
|
---|
397 | my %args = @_;
|
---|
398 |
|
---|
399 | $args{rdns_id} = 0 if !$args{rdns_id};
|
---|
400 | $args{domain_id} = 0 if !$args{domain_id};
|
---|
401 |
|
---|
402 | ##fixme: farm out the actual logging to different subs for file, syslog, internal, etc based on config
|
---|
403 | # if ($self->{log_channel} eq 'sql') {
|
---|
404 | $dbh->do("INSERT INTO log (domain_id,rdns_id,group_id,entry,user_id,email,name) VALUES (?,?,?,?,?,?,?)",
|
---|
405 | undef,
|
---|
406 | ($args{domain_id}, $args{rdns_id}, $args{group_id}, $args{entry},
|
---|
407 | $self->{loguserid}, $self->{logusername}, $self->{logfullname}) );
|
---|
408 | # } elsif ($self->{log_channel} eq 'file') {
|
---|
409 | # } elsif ($self->{log_channel} eq 'syslog') {
|
---|
410 | # }
|
---|
411 | } # end _log
|
---|
412 |
|
---|
413 |
|
---|
414 | ##
|
---|
415 | ## Record validation subs.
|
---|
416 | ##
|
---|
417 |
|
---|
418 | ## All of these subs take substantially the same arguments:
|
---|
419 | # a hash containing at least the following keys:
|
---|
420 | # - defrec (default/live flag)
|
---|
421 | # - revrec (forward/reverse flag)
|
---|
422 | # - id (parent entity ID)
|
---|
423 | # - host (hostname)
|
---|
424 | # - rectype
|
---|
425 | # - val (IP, hostname [CNAME/MX/SRV] or text)
|
---|
426 | # - addr (NetAddr::IP object from val. May be undef.)
|
---|
427 | # MX and SRV record validation also expect distance, and SRV records expect weight and port as well.
|
---|
428 | # host, rectype, and addr should be references as these may be modified in validation
|
---|
429 |
|
---|
430 | # A record
|
---|
431 | sub _validate_1 {
|
---|
432 | my $self = shift;
|
---|
433 | my $dbh = $self->{dbh};
|
---|
434 |
|
---|
435 | my %args = @_;
|
---|
436 |
|
---|
437 | return ('FAIL', 'Reverse zones cannot contain A records') if $args{revrec} eq 'y';
|
---|
438 |
|
---|
439 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
440 | # or the intended parent domain for live records.
|
---|
441 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
442 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/);
|
---|
443 |
|
---|
444 | # Check IP is well-formed, and that it's a v4 address
|
---|
445 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
|
---|
446 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
447 | unless ${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/;
|
---|
448 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
449 | unless $args{addr} && !$args{addr}->{isv6};
|
---|
450 | # coerce IP/value to normalized form for storage
|
---|
451 | ${$args{val}} = $args{addr}->addr;
|
---|
452 |
|
---|
453 | return ('OK','OK');
|
---|
454 | } # done A record
|
---|
455 |
|
---|
456 | # NS record
|
---|
457 | sub _validate_2 {
|
---|
458 | my $self = shift;
|
---|
459 | my $dbh = $self->{dbh};
|
---|
460 |
|
---|
461 | my %args = @_;
|
---|
462 |
|
---|
463 | # Check that the target of the record is within the parent.
|
---|
464 | # Yes, host<->val are mixed up here; can't see a way to avoid it. :(
|
---|
465 | if ($args{defrec} eq 'n') {
|
---|
466 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
467 | if ($args{revrec} eq 'y') {
|
---|
468 | my $tmpip = NetAddr::IP->new(${$args{val}});
|
---|
469 | my $pname = $self->revName($args{id});
|
---|
470 | return ('FAIL',"${$args{val}} not within $pname")
|
---|
471 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$tmpip);
|
---|
472 | # Sub the returned thing for ZONE? This could get stupid if you have typos...
|
---|
473 | ${$args{val}} =~ s/ZONE/$tmpip->address/;
|
---|
474 | } else {
|
---|
475 | my $pname = $self->domainName($args{id});
|
---|
476 | ${$args{host}} = $pname if ${$args{host}} !~ /\.$pname$/;
|
---|
477 | }
|
---|
478 | } else {
|
---|
479 | # Default reverse NS records should always refer to the implied parent
|
---|
480 | ${$args{host}} = 'DOMAIN' if $args{revrec} eq 'n';
|
---|
481 | ${$args{val}} = 'ZONE' if $args{revrec} eq 'y';
|
---|
482 | }
|
---|
483 |
|
---|
484 | # Let this lie for now. Needs more magic.
|
---|
485 | # # Check IP is well-formed, and that it's a v4 address
|
---|
486 | # return ('FAIL',"A record must be a valid IPv4 address")
|
---|
487 | # unless $addr && !$addr->{isv6};
|
---|
488 | # # coerce IP/value to normalized form for storage
|
---|
489 | # $$val = $addr->addr;
|
---|
490 |
|
---|
491 | return ('OK','OK');
|
---|
492 | } # done NS record
|
---|
493 |
|
---|
494 | # CNAME record
|
---|
495 | sub _validate_5 {
|
---|
496 | my $self = shift;
|
---|
497 | my $dbh = $self->{dbh};
|
---|
498 |
|
---|
499 | my %args = @_;
|
---|
500 |
|
---|
501 | # Not really true, but these are only useful for delegating smaller-than-/24 IP blocks.
|
---|
502 | # This is fundamentally a messy operation and should really just be taken care of by the
|
---|
503 | # export process, not manual maintenance of the necessary records.
|
---|
504 | return ('FAIL', 'Reverse zones cannot contain CNAME records') if $args{revrec} eq 'y';
|
---|
505 |
|
---|
506 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
507 | # or the intended parent domain for live records.
|
---|
508 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
509 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
510 |
|
---|
511 | return ('OK','OK');
|
---|
512 | } # done CNAME record
|
---|
513 |
|
---|
514 | # SOA record
|
---|
515 | sub _validate_6 {
|
---|
516 | # Smart monkeys won't stick their fingers in here; we have
|
---|
517 | # separate dedicated routines to deal with SOA records.
|
---|
518 | return ('OK','OK');
|
---|
519 | } # done SOA record
|
---|
520 |
|
---|
521 | # PTR record
|
---|
522 | sub _validate_12 {
|
---|
523 | my $self = shift;
|
---|
524 | my $dbh = $self->{dbh};
|
---|
525 |
|
---|
526 | my %args = @_;
|
---|
527 |
|
---|
528 | if ($args{revrec} eq 'y') {
|
---|
529 | if ($args{defrec} eq 'n') {
|
---|
530 | return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
531 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
532 | ${$args{val}} = $args{addr}->addr;
|
---|
533 | } else {
|
---|
534 | if (${$args{val}} =~ /\./) {
|
---|
535 | # looks like a v4 or fragment
|
---|
536 | if (${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/) {
|
---|
537 | # woo! a complete IP! validate it and normalize, or fail.
|
---|
538 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
539 | or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
|
---|
540 | ${$args{val}} = $args{addr}->addr;
|
---|
541 | } else {
|
---|
542 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
543 | }
|
---|
544 | } elsif (${$args{val}} =~ /[a-f:]/) {
|
---|
545 | # looks like a v6 or fragment
|
---|
546 | ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
|
---|
547 | if ($args{addr}) {
|
---|
548 | if ($args{addr}->addr =~ /^0/) {
|
---|
549 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
550 | } else {
|
---|
551 | ${$args{val}} = $args{addr}->addr;
|
---|
552 | }
|
---|
553 | }
|
---|
554 | } else {
|
---|
555 | # bare number (probably). These could be v4 or v6, so we'll
|
---|
556 | # expand on these on creation of a reverse zone.
|
---|
557 | ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
|
---|
558 | }
|
---|
559 | ${$args{host}} =~ s/\.*$/\.$self->{domain}/ if ${$args{host}} !~ /(?:$self->{domain}|ADMINDOMAIN)$/;
|
---|
560 | }
|
---|
561 |
|
---|
562 | # Multiple PTR records do NOT generally do what most people believe they do,
|
---|
563 | # and tend to fail in the most awkward way possible. Check and warn.
|
---|
564 | # We use $val instead of $addr->addr since we may be in a defrec, and may have eg "ZONE::42" or "ZONE.12"
|
---|
565 |
|
---|
566 | my @checkvals = (${$args{val}});
|
---|
567 | if (${$args{val}} =~ /,/) {
|
---|
568 | # push . and :: variants into checkvals if val has ,
|
---|
569 | my $tmp;
|
---|
570 | ($tmp = ${$args{val}}) =~ s/,/./;
|
---|
571 | push @checkvals, $tmp;
|
---|
572 | ($tmp = ${$args{val}}) =~ s/,/::/;
|
---|
573 | push @checkvals, $tmp;
|
---|
574 | }
|
---|
575 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ?");
|
---|
576 | foreach my $checkme (@checkvals) {
|
---|
577 | if ($args{update}) {
|
---|
578 | # Record update. There should usually be an existing PTR (the record being updated)
|
---|
579 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
580 | " WHERE val = ?", undef, ($checkme)) };
|
---|
581 | return ('WARN', "PTR record for $checkme already exists; adding another will probably not do what you want")
|
---|
582 | if @ptrs && (!grep /^$args{update}$/, @ptrs);
|
---|
583 | } else {
|
---|
584 | # New record. Always warn if a PTR exists
|
---|
585 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
586 | " WHERE val = ?", undef, ($checkme));
|
---|
587 | return ('WARN', "PTR record for $checkme already exists; adding another will probably not do what you want")
|
---|
588 | if $ptrcount;
|
---|
589 | }
|
---|
590 | }
|
---|
591 |
|
---|
592 | } else {
|
---|
593 | # Not absolutely true but only useful if you hack things up for sub-/24 v4 reverse delegations
|
---|
594 | # Simpler to just create the reverse zone and grant access for the customer to edit it, and create direct
|
---|
595 | # PTR records on export
|
---|
596 | return ('FAIL',"Forward zones cannot contain PTR records");
|
---|
597 | }
|
---|
598 |
|
---|
599 | return ('OK','OK');
|
---|
600 | } # done PTR record
|
---|
601 |
|
---|
602 | # MX record
|
---|
603 | sub _validate_15 {
|
---|
604 | my $self = shift;
|
---|
605 | my $dbh = $self->{dbh};
|
---|
606 |
|
---|
607 | my %args = @_;
|
---|
608 |
|
---|
609 | # Not absolutely true but WTF use is an MX record for a reverse zone?
|
---|
610 | return ('FAIL', 'Reverse zones cannot contain MX records') if $args{revrec} eq 'y';
|
---|
611 |
|
---|
612 | return ('FAIL', "Distance is required for MX records") unless defined(${$args{dist}});
|
---|
613 | ${$args{dist}} =~ s/\s*//g;
|
---|
614 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
|
---|
615 |
|
---|
616 | ${$args{fields}} = "distance,";
|
---|
617 | push @{$args{vallist}}, ${$args{dist}};
|
---|
618 |
|
---|
619 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
620 | # or the intended parent domain for live records.
|
---|
621 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
622 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
623 |
|
---|
624 | # hmm.. this might work. except possibly for something pointing to "deadbeef.ca". <g>
|
---|
625 | # if ($type == $reverse_typemap{NS} || $type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
|
---|
626 | # if ($val =~ /^\s*[\da-f:.]+\s*$/) {
|
---|
627 | # return ('FAIL',"$val is not a valid IP address") if !$addr;
|
---|
628 | # }
|
---|
629 | # }
|
---|
630 |
|
---|
631 | return ('OK','OK');
|
---|
632 | } # done MX record
|
---|
633 |
|
---|
634 | # TXT record
|
---|
635 | sub _validate_16 {
|
---|
636 | # Could arguably put a WARN return here on very long (>512) records
|
---|
637 | return ('OK','OK');
|
---|
638 | } # done TXT record
|
---|
639 |
|
---|
640 | # RP record
|
---|
641 | sub _validate_17 {
|
---|
642 | # Probably have to validate these some day
|
---|
643 | return ('OK','OK');
|
---|
644 | } # done RP record
|
---|
645 |
|
---|
646 | # AAAA record
|
---|
647 | sub _validate_28 {
|
---|
648 | my $self = shift;
|
---|
649 | my $dbh = $self->{dbh};
|
---|
650 |
|
---|
651 | my %args = @_;
|
---|
652 |
|
---|
653 | return ('FAIL', 'Reverse zones cannot contain AAAA records') if $args{revrec} eq 'y';
|
---|
654 |
|
---|
655 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
656 | # or the intended parent domain for live records.
|
---|
657 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
658 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
659 |
|
---|
660 | # Check IP is well-formed, and that it's a v6 address
|
---|
661 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
|
---|
662 | unless $args{addr} && $args{addr}->{isv6};
|
---|
663 | # coerce IP/value to normalized form for storage
|
---|
664 | ${$args{val}} = $args{addr}->addr;
|
---|
665 |
|
---|
666 | return ('OK','OK');
|
---|
667 | } # done AAAA record
|
---|
668 |
|
---|
669 | # SRV record
|
---|
670 | sub _validate_33 {
|
---|
671 | my $self = shift;
|
---|
672 | my $dbh = $self->{dbh};
|
---|
673 |
|
---|
674 | my %args = @_;
|
---|
675 |
|
---|
676 | # Not absolutely true but WTF use is an SRV record for a reverse zone?
|
---|
677 | return ('FAIL', 'Reverse zones cannot contain SRV records') if $args{revrec} eq 'y';
|
---|
678 |
|
---|
679 | return ('FAIL', "Distance is required for SRV records") unless defined(${$args{dist}});
|
---|
680 | ${$args{dist}} =~ s/\s*//g;
|
---|
681 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
|
---|
682 |
|
---|
683 | return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]")
|
---|
684 | unless ${$args{host}} =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/;
|
---|
685 | return ('FAIL',"Port and weight are required for SRV records")
|
---|
686 | unless defined(${$args{weight}}) && defined(${$args{port}});
|
---|
687 | ${$args{weight}} =~ s/\s*//g;
|
---|
688 | ${$args{port}} =~ s/\s*//g;
|
---|
689 |
|
---|
690 | return ('FAIL',"Port and weight are required, and must be numeric")
|
---|
691 | unless ${$args{weight}} =~ /^\d+$/ && ${$args{port}} =~ /^\d+$/;
|
---|
692 |
|
---|
693 | ${$args{fields}} = "distance,weight,port,";
|
---|
694 | push @{$args{vallist}}, (${$args{dist}}, ${$args{weight}}, ${$args{port}});
|
---|
695 |
|
---|
696 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
697 | # or the intended parent domain for live records.
|
---|
698 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
699 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
700 |
|
---|
701 | return ('OK','OK');
|
---|
702 | } # done SRV record
|
---|
703 |
|
---|
704 | # Now the custom types
|
---|
705 |
|
---|
706 | # A+PTR record. With a very little bit of magic we can also use this sub to validate AAAA+PTR. Whee!
|
---|
707 | sub _validate_65280 {
|
---|
708 | my $self = shift;
|
---|
709 | my $dbh = $self->{dbh};
|
---|
710 |
|
---|
711 | my %args = @_;
|
---|
712 |
|
---|
713 | my $code = 'OK';
|
---|
714 | my $msg = 'OK';
|
---|
715 |
|
---|
716 | if ($args{defrec} eq 'n') {
|
---|
717 | # live record; revrec determines whether we validate the PTR or A component first.
|
---|
718 |
|
---|
719 | if ($args{revrec} eq 'y') {
|
---|
720 | ($code,$msg) = $self->_validate_12(%args);
|
---|
721 | return ($code,$msg) if $code eq 'FAIL';
|
---|
722 |
|
---|
723 | # check A+PTR is really v4
|
---|
724 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
725 | if ${$args{rectype}} == 65280 && $args{addr}->{isv6};
|
---|
726 | # check AAAA+PTR is really v6
|
---|
727 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
|
---|
728 | if ${$args{rectype}} == 65281 && !$args{addr}->{isv6};
|
---|
729 |
|
---|
730 | # Check if the reqested domain exists. If not, coerce the type down to PTR and warn.
|
---|
731 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) {
|
---|
732 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
733 | " as PTR instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
734 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
735 | $msg = $addmsg if $code eq 'OK';
|
---|
736 | ${$args{rectype}} = $reverse_typemap{PTR};
|
---|
737 | return ('WARN', $msg);
|
---|
738 | }
|
---|
739 |
|
---|
740 | # Add domain ID to field list and values
|
---|
741 | ${$args{fields}} .= "domain_id,";
|
---|
742 | push @{$args{vallist}}, ${$args{domid}};
|
---|
743 |
|
---|
744 | } else {
|
---|
745 | ($code,$msg) = $self->_validate_1(%args) if ${$args{rectype}} == 65280;
|
---|
746 | ($code,$msg) = $self->_validate_28(%args) if ${$args{rectype}} == 65281;
|
---|
747 | return ($code,$msg) if $code eq 'FAIL';
|
---|
748 |
|
---|
749 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
750 | # work here since we don't *know* which parent to put it in.
|
---|
751 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
752 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
753 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
754 | if (!$revid) {
|
---|
755 | $msg = "Record ".($args{update} ? 'updated' : 'added')." as ".(${$args{rectype}} == 65280 ? 'A' : 'AAAA').
|
---|
756 | " instead of $typemap{${$args{rectype}}}; reverse zone not found for ${$args{val}}";
|
---|
757 | ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
758 | return ('WARN', $msg);
|
---|
759 | }
|
---|
760 |
|
---|
761 | # Check for duplicate PTRs. Note we don't have to play games with $code and $msg, because
|
---|
762 | # by definition there can't be duplicate PTRs if the reverse zone isn't managed here.
|
---|
763 | if ($args{update}) {
|
---|
764 | # Record update. There should usually be an existing PTR (the record being updated)
|
---|
765 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
766 | " WHERE val = ?", undef, (${$args{val}})) };
|
---|
767 | if (@ptrs && (!grep /^$args{update}$/, @ptrs)) {
|
---|
768 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
|
---|
769 | $code = 'WARN';
|
---|
770 | }
|
---|
771 | } else {
|
---|
772 | # New record. Always warn if a PTR exists
|
---|
773 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
774 | " WHERE val = ?", undef, (${$args{val}}));
|
---|
775 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want"
|
---|
776 | if $ptrcount;
|
---|
777 | $code = 'WARN' if $ptrcount;
|
---|
778 | }
|
---|
779 |
|
---|
780 | # my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
781 | # " WHERE val = ?", undef, ${$args{val}});
|
---|
782 | # if ($ptrcount) {
|
---|
783 | # my $curid = $dbh->selectrow_array("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
784 | # " WHERE val = ?
|
---|
785 | # $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
|
---|
786 | # $code = 'WARN';
|
---|
787 | # }
|
---|
788 |
|
---|
789 | ${$args{fields}} .= "rdns_id,";
|
---|
790 | push @{$args{vallist}}, $revid;
|
---|
791 | }
|
---|
792 |
|
---|
793 | } else { # defrec eq 'y'
|
---|
794 | if ($args{revrec} eq 'y') {
|
---|
795 | ($code,$msg) = $self->_validate_12(%args);
|
---|
796 | return ($code,$msg) if $code eq 'FAIL';
|
---|
797 | if (${$args{rectype}} == 65280) {
|
---|
798 | return ('FAIL',"A+PTR record must be a valid IPv4 address or fragment")
|
---|
799 | if ${$args{val}} =~ /:/;
|
---|
800 | ${$args{val}} =~ s/^ZONE,/ZONE./; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
801 | } elsif (${$args{rectype}} == 65281) {
|
---|
802 | return ('FAIL',"AAAA+PTR record must be a valid IPv6 address or fragment")
|
---|
803 | if ${$args{val}} =~ /\./;
|
---|
804 | ${$args{val}} =~ s/^ZONE,/ZONE::/; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
805 | }
|
---|
806 | } else {
|
---|
807 | # This is easy. I also can't see a real use-case for A/AAAA+PTR in *all* forward
|
---|
808 | # domains, since you wouldn't be able to substitute both domain and reverse zone
|
---|
809 | # sanely, and you'd end up with guaranteed over-replicated PTR records that would
|
---|
810 | # confuse the hell out of pretty much anything that uses them.
|
---|
811 | ##fixme: make this a config flag?
|
---|
812 | return ('FAIL', "$typemap{${$args{rectype}}} records not allowed in default domains");
|
---|
813 | }
|
---|
814 | }
|
---|
815 |
|
---|
816 | return ($code, $msg);
|
---|
817 | } # done A+PTR record
|
---|
818 |
|
---|
819 | # AAAA+PTR record
|
---|
820 | # A+PTR above has been magicked to handle AAAA+PTR as well.
|
---|
821 | sub _validate_65281 {
|
---|
822 | return _validate_65280(@_);
|
---|
823 | } # done AAAA+PTR record
|
---|
824 |
|
---|
825 | # PTR template record
|
---|
826 | sub _validate_65282 {
|
---|
827 | my $self = shift;
|
---|
828 | my $dbh = $self->{dbh};
|
---|
829 |
|
---|
830 | my %args = @_;
|
---|
831 |
|
---|
832 | # we're *this* >.< close to being able to just call _validate_12... unfortunately we can't, quite.
|
---|
833 | if ($args{revrec} eq 'y') {
|
---|
834 | if ($args{defrec} eq 'n') {
|
---|
835 | return ('FAIL', "Template block ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
836 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
837 | ##fixme: warn if $args{val} is not /31 or larger block?
|
---|
838 | ${$args{val}} = "$args{addr}";
|
---|
839 | } else {
|
---|
840 | if (${$args{val}} =~ /\./) {
|
---|
841 | # looks like a v4 or fragment
|
---|
842 | if (${$args{val}} =~ m|^\d+\.\d+\.\d+\.\d+(?:/\d+)?$|) {
|
---|
843 | # woo! a complete IP! validate it and normalize, or fail.
|
---|
844 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
845 | or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
|
---|
846 | ${$args{val}} = "$args{addr}";
|
---|
847 | } else {
|
---|
848 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
849 | }
|
---|
850 | } elsif (${$args{val}} =~ /[a-f:]/) {
|
---|
851 | # looks like a v6 or fragment
|
---|
852 | ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
|
---|
853 | if ($args{addr}) {
|
---|
854 | if ($args{addr}->addr =~ /^0/) {
|
---|
855 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
856 | } else {
|
---|
857 | ${$args{val}} = "$args{addr}";
|
---|
858 | }
|
---|
859 | }
|
---|
860 | } else {
|
---|
861 | # bare number (probably). These could be v4 or v6, so we'll
|
---|
862 | # expand on these on creation of a reverse zone.
|
---|
863 | ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
|
---|
864 | }
|
---|
865 | }
|
---|
866 | ##fixme: validate %-patterns?
|
---|
867 |
|
---|
868 | # Unlike single PTR records, there is absolutely no way to sanely support multiple
|
---|
869 | # PTR templates for the same block, since they expect to expand to all the individual
|
---|
870 | # IPs on export. Nested templates should be supported though.
|
---|
871 |
|
---|
872 | my @checkvals = (${$args{val}});
|
---|
873 | if (${$args{val}} =~ /,/) {
|
---|
874 | # push . and :: variants into checkvals if val has ,
|
---|
875 | my $tmp;
|
---|
876 | ($tmp = ${$args{val}}) =~ s/,/./;
|
---|
877 | push @checkvals, $tmp;
|
---|
878 | ($tmp = ${$args{val}}) =~ s/,/::/;
|
---|
879 | push @checkvals, $tmp;
|
---|
880 | }
|
---|
881 | ##fixme: this feels wrong still - need to restrict template pseudorecords to One Of Each
|
---|
882 | # Per Netblock such that they don't conflict on export
|
---|
883 | my $typeck;
|
---|
884 | # type 65282 -> ptr template -> look for any of 65282, 65283, 65284
|
---|
885 | $typeck = 'type=65283 OR type=65284' if ${$args{rectype}} == 65282;
|
---|
886 | # type 65283 -> a+ptr template -> v4 -> look for 65282 or 65283
|
---|
887 | $typeck = 'type=65283' if ${$args{rectype}} == 65282;
|
---|
888 | # type 65284 -> aaaa+ptr template -> v6 -> look for 65282 or 65284
|
---|
889 | $typeck = 'type=65284' if ${$args{rectype}} == 65282;
|
---|
890 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ? ".
|
---|
891 | "AND (type=65282 OR $typeck)");
|
---|
892 | foreach my $checkme (@checkvals) {
|
---|
893 | $pcsth->execute($checkme);
|
---|
894 | my ($rc) = $pcsth->fetchrow_array;
|
---|
895 | return ('FAIL', "Only one template pseudorecord may exist for a given IP block") if $rc > 1;
|
---|
896 | }
|
---|
897 |
|
---|
898 | } else {
|
---|
899 | return ('FAIL', "Forward zones cannot contain PTR records");
|
---|
900 | }
|
---|
901 |
|
---|
902 | return ('OK','OK');
|
---|
903 | } # done PTR template record
|
---|
904 |
|
---|
905 | # A+PTR template record
|
---|
906 | sub _validate_65283 {
|
---|
907 | my $self = shift;
|
---|
908 | my $dbh = $self->{dbh};
|
---|
909 |
|
---|
910 | my %args = @_;
|
---|
911 |
|
---|
912 | my ($code,$msg) = ('OK','OK');
|
---|
913 |
|
---|
914 | ##fixme: need to fiddle things since A+PTR templates are acceptable in live
|
---|
915 | # forward zones but not default records
|
---|
916 | if ($args{defrec} eq 'n') {
|
---|
917 | if ($args{revrec} eq 'n') {
|
---|
918 | ($code,$msg) = $self->_validate_1(%args) if ${$args{rectype}} == 65280;
|
---|
919 | ($code,$msg) = $self->_validate_28(%args) if ${$args{rectype}} == 65281;
|
---|
920 | return ($code,$msg) if $code eq 'FAIL';
|
---|
921 |
|
---|
922 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
923 | # work here since we don't *know* which parent to put it in.
|
---|
924 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
925 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
926 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
927 | # Fail if no match; we can't coerce a PTR-template type down to not include the PTR bit currently.
|
---|
928 | if (!$revid) {
|
---|
929 | $msg = "Can't ".($args{update} ? 'update' : 'add')." ${$args{host}}/${$args{val}} as ".
|
---|
930 | "$typemap{${$args{rectype}}}: reverse zone not found for ${$args{val}}";
|
---|
931 | ##fixme: add A template, AAAA template types?
|
---|
932 | # ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
933 | return ('FAIL', $msg);
|
---|
934 | }
|
---|
935 |
|
---|
936 | # Add reverse zone ID to field list and values
|
---|
937 | ${$args{fields}} .= "rdns_id,";
|
---|
938 | push @{$args{vallist}}, $revid;
|
---|
939 |
|
---|
940 | } else {
|
---|
941 | return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
942 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
943 | ${$args{val}} = "$args{addr}";
|
---|
944 |
|
---|
945 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) {
|
---|
946 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
947 | " as PTR template instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
948 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
949 | $msg = $addmsg if $code eq 'OK';
|
---|
950 | ${$args{rectype}} = 65282;
|
---|
951 | return ('WARN', $msg);
|
---|
952 | }
|
---|
953 |
|
---|
954 | # Add domain ID to field list and values
|
---|
955 | ${$args{fields}} .= "domain_id,";
|
---|
956 | push @{$args{vallist}}, ${$args{domid}};
|
---|
957 | }
|
---|
958 |
|
---|
959 | } else {
|
---|
960 | my ($code,$msg) = $self->_validate_65282(%args);
|
---|
961 | return ($code, $msg) if $code eq 'FAIL';
|
---|
962 | # get domain, check against ${$args{name}}
|
---|
963 | }
|
---|
964 |
|
---|
965 | return ('OK','OK');
|
---|
966 | } # done AAAA+PTR template record
|
---|
967 |
|
---|
968 | # AAAA+PTR template record
|
---|
969 | sub _validate_65284 {
|
---|
970 | return ('OK','OK');
|
---|
971 | } # done AAAA+PTR template record
|
---|
972 |
|
---|
973 | # Delegation record
|
---|
974 | # This is essentially a specialized clone of the NS record, primarily useful
|
---|
975 | # for delegating IPv4 sub-/24 reverse blocks
|
---|
976 | sub _validate_65285 {
|
---|
977 | my $self = shift;
|
---|
978 | my $dbh = $self->{dbh};
|
---|
979 |
|
---|
980 | my %args = @_;
|
---|
981 |
|
---|
982 | # Almost, but not quite, identical to NS record validation.
|
---|
983 |
|
---|
984 | # Check that the target of the record is within the parent.
|
---|
985 | # Yes, host<->val are mixed up here; can't see a way to avoid it. :(
|
---|
986 | if ($args{defrec} eq 'n') {
|
---|
987 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
988 | if ($args{revrec} eq 'y') {
|
---|
989 | my $tmpip = NetAddr::IP->new(${$args{val}});
|
---|
990 | my $pname = $self->revName($args{id});
|
---|
991 | return ('FAIL',"${$args{val}} not within $pname")
|
---|
992 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$tmpip);
|
---|
993 | # Normalize
|
---|
994 | ${$args{val}} = "$tmpip";
|
---|
995 | } else {
|
---|
996 | my $pname = $self->domainName($args{id});
|
---|
997 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
998 | }
|
---|
999 | } else {
|
---|
1000 | return ('FAIL',"Delegation records are not permitted in default record sets");
|
---|
1001 | }
|
---|
1002 | return ('OK','OK');
|
---|
1003 | }
|
---|
1004 |
|
---|
1005 |
|
---|
1006 | ##
|
---|
1007 | ## Record data substitution subs
|
---|
1008 | ##
|
---|
1009 |
|
---|
1010 | # Replace ZONE in hostname, or create (most of) the actual proper zone name
|
---|
1011 | sub _ZONE {
|
---|
1012 | my $zone = shift;
|
---|
1013 | my $string = shift;
|
---|
1014 | my $fr = shift || 'f'; # flag for forward/reverse order? nb: ignored for IP
|
---|
1015 | my $sep = shift || '-'; # Separator character - unlikely we'll ever need more than . or -
|
---|
1016 |
|
---|
1017 | my $prefix;
|
---|
1018 |
|
---|
1019 | $string =~ s/,/./ if !$zone->{isv6};
|
---|
1020 | $string =~ s/,/::/ if $zone->{isv6};
|
---|
1021 |
|
---|
1022 | # Subbing ZONE in the host. We need to properly ID the netblock range
|
---|
1023 | # The subbed text should have "network IP with trailing zeros stripped" for
|
---|
1024 | # blocks lined up on octet (for v4) or hex-quad (for v6) boundaries
|
---|
1025 | # For blocks that do NOT line up on these boundaries, we take the most
|
---|
1026 | # significant octet or 16-bit chunk of the "broadcast" IP and append it
|
---|
1027 | # after a double-dash
|
---|
1028 | # ie:
|
---|
1029 | # 8.0.0.0/6 -> 8.0.0.0 -> 11.255.255.255; sub should be 8--11
|
---|
1030 | # 10.0.0.0/12 -> 10.0.0.0 -> 10.0.0.0 -> 10.15.255.255; sub should be 10-0--15
|
---|
1031 | # 192.168.4.0/22 -> 192.168.4.0 -> 192.168.7.255; sub should be 192-168-4--7
|
---|
1032 | # 192.168.0.8/29 -> 192.168.0.8 -> 192.168.0.15; sub should be 192-168-0-8--15
|
---|
1033 | # Similar for v6
|
---|
1034 |
|
---|
1035 | if (!$zone->{isv6}) { # IPv4
|
---|
1036 |
|
---|
1037 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
1038 | # a funky subnet that had host bits set.
|
---|
1039 | my $bc = $zone->broadcast->addr;
|
---|
1040 |
|
---|
1041 | if ($zone->masklen > 24) {
|
---|
1042 | $bc =~ s/^\d+\.\d+\.\d+\.//;
|
---|
1043 | } elsif ($zone->masklen > 16) {
|
---|
1044 | $prefix =~ s/\.0$//;
|
---|
1045 | $bc =~ s/^\d+\.\d+\.//;
|
---|
1046 | } elsif ($zone->masklen > 8) {
|
---|
1047 | $bc =~ s/^\d+\.//;
|
---|
1048 | $prefix =~ s/\.0\.0$//;
|
---|
1049 | } else {
|
---|
1050 | $prefix =~ s/\.0\.0\.0$//;
|
---|
1051 | }
|
---|
1052 | if ($zone->masklen % 8) {
|
---|
1053 | $bc =~ s/(\.255)+$//;
|
---|
1054 | $prefix .= "--$bc"; #"--".zone->masklen; # use range or mask length?
|
---|
1055 | }
|
---|
1056 | if ($fr eq 'f') {
|
---|
1057 | $prefix =~ s/\.+/$sep/g;
|
---|
1058 | } else {
|
---|
1059 | $prefix = join($sep, reverse(split(/\./, $prefix)));
|
---|
1060 | }
|
---|
1061 |
|
---|
1062 | } else { # IPv6
|
---|
1063 |
|
---|
1064 | if ($fr eq 'f') {
|
---|
1065 |
|
---|
1066 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
1067 | # a funky subnet that had host bits set.
|
---|
1068 | my $bc = $zone->broadcast->addr;
|
---|
1069 | if (($zone->masklen % 16) != 0) {
|
---|
1070 | # Strip trailing :0 off $prefix, and :ffff off the broadcast IP
|
---|
1071 | for (my $i=0; $i<(7-int($zone->masklen / 16)); $i++) {
|
---|
1072 | $prefix =~ s/:0$//;
|
---|
1073 | $bc =~ s/:ffff$//;
|
---|
1074 | }
|
---|
1075 | # Strip the leading 16-bit chunks off the front of the broadcast IP
|
---|
1076 | $bc =~ s/^([a-f0-9]+:)+//;
|
---|
1077 | # Append the remaining 16-bit chunk to the prefix after "--"
|
---|
1078 | $prefix .= "--$bc";
|
---|
1079 | } else {
|
---|
1080 | # Strip off :0 from the end until we reach the netblock length.
|
---|
1081 | for (my $i=0; $i<(8-$zone->masklen / 16); $i++) {
|
---|
1082 | $prefix =~ s/:0$//;
|
---|
1083 | }
|
---|
1084 | }
|
---|
1085 | # Actually deal with the separator
|
---|
1086 | $prefix =~ s/:/$sep/g;
|
---|
1087 |
|
---|
1088 | } else { # $fr eq 'f'
|
---|
1089 |
|
---|
1090 | $prefix = $zone->network->full; # Just In Case someone managed to slip in
|
---|
1091 | # a funky subnet that had host bits set.
|
---|
1092 | my $bc = $zone->broadcast->full;
|
---|
1093 | $prefix =~ s/://g; # clean these out since they're not spaced right for this case
|
---|
1094 | $bc =~ s/://g;
|
---|
1095 | # Strip trailing 0 off $prefix, and f off the broadcast IP, to match the mask length
|
---|
1096 | for (my $i=0; $i<(31-int($zone->masklen / 4)); $i++) {
|
---|
1097 | $prefix =~ s/0$//;
|
---|
1098 | $bc =~ s/f$//;
|
---|
1099 | }
|
---|
1100 | # Split and reverse the order of the nibbles in the network/broadcast IPs
|
---|
1101 | # trim another 0 for nibble-aligned blocks first, but only if we really have a block, not an IP
|
---|
1102 | $prefix =~ s/0$// if $zone->masklen % 4 == 0 && $zone->masklen != 128;
|
---|
1103 | my @nbits = reverse split //, $prefix;
|
---|
1104 | my @bbits = reverse split //, $bc;
|
---|
1105 | # Handle the sub-nibble case. Eww. I feel dirty supporting this...
|
---|
1106 | $nbits[0] = "$nbits[0]-$bbits[0]" if ($zone->masklen % 4) != 0;
|
---|
1107 | # Glue it back together
|
---|
1108 | $prefix = join($sep, @nbits);
|
---|
1109 |
|
---|
1110 | } # $fr ne 'f'
|
---|
1111 |
|
---|
1112 | } # $zone->{isv6}
|
---|
1113 |
|
---|
1114 | # Do the substitution, finally
|
---|
1115 | $string =~ s/ZONE/$prefix/;
|
---|
1116 | $string =~ s/--/-/ if $sep ne '-'; # - as separator needs extra help for sub-octet v4 netblocks
|
---|
1117 | return $string;
|
---|
1118 | } # done _ZONE()
|
---|
1119 |
|
---|
1120 | # Not quite a substitution sub, but placed here as it's basically the inverse of above;
|
---|
1121 | # given the .arpa zone name, return the CIDR netblock the zone is for.
|
---|
1122 | # Supports v4 non-octet/non-classful netblocks as per the method outlined in the Grasshopper Book (2nd Ed p217-218)
|
---|
1123 | # Does NOT support non-quad v6 netblocks via the same scheme; it shouldn't ever be necessary.
|
---|
1124 | # Takes a nominal .arpa zone name, returns a success code and NetAddr::IP, or a fail code and message
|
---|
1125 | sub _zone2cidr {
|
---|
1126 | my $zone = shift;
|
---|
1127 |
|
---|
1128 | my $cidr;
|
---|
1129 | my $tmpcidr;
|
---|
1130 | my $warnmsg = '';
|
---|
1131 |
|
---|
1132 | if ($zone =~ /\.in-addr\.arpa\.?$/) {
|
---|
1133 | # v4 revzone, formal zone name type
|
---|
1134 | my $tmpzone = $zone;
|
---|
1135 | $tmpzone =~ s/\.in-addr\.arpa\.?//;
|
---|
1136 | return ('FAIL', "Non-numerics in apparent IPv4 reverse zone name") if $tmpzone !~ /^(?:\d+-)?[\d\.]+$/;
|
---|
1137 |
|
---|
1138 | # Snag the octet pieces
|
---|
1139 | my @octs = split /\./, $tmpzone;
|
---|
1140 |
|
---|
1141 | # Map result of a range manipulation to a mask length change. Cheaper than finding the 2-root of $octets[0]+1.
|
---|
1142 | # Note we will not support /31 blocks, mostly due to issues telling "24-31" -> .24/29 apart from
|
---|
1143 | # "24-31" -> .24/31", with a litte bit of "/31 is icky".
|
---|
1144 | my %maskmap = ( 3 => 2, 7 => 3, 15 => 4, 31 => 5, 63 => 6, 127 => 7,
|
---|
1145 | 30 => 2, 29 => 3, 28 => 4, 27 => 5, 26 => 6, 25 => 7
|
---|
1146 | );
|
---|
1147 |
|
---|
1148 | # Handle "range" blocks, eg, 80-83.168.192.in-addr.arpa (192.168.80.0/22)
|
---|
1149 | # Need to take the size of the range to offset the basic octet-based mask length,
|
---|
1150 | # and make sure the first number in the range gets used as the network address for the block
|
---|
1151 | # Alternate form: The second number is actually the real netmask, not the end of the range.
|
---|
1152 | my $masklen = 0;
|
---|
1153 | if ($octs[0] =~ /^((\d+)-(\d+))$/) { # take the range...
|
---|
1154 | if (24 < $3 && $3 < 31) {
|
---|
1155 | # we have a real netmask
|
---|
1156 | $masklen = -$maskmap{$3};
|
---|
1157 | } else {
|
---|
1158 | # we have a range. NB: only real CIDR ranges are supported
|
---|
1159 | $masklen -= $maskmap{-(eval $1)}; # find the mask base...
|
---|
1160 | }
|
---|
1161 | $octs[0] = $2; # set the base octet of the range...
|
---|
1162 | }
|
---|
1163 | @octs = reverse @octs; # We can reverse the octet pieces now that we've extracted and munged any ranges
|
---|
1164 |
|
---|
1165 | # arguably we should only allow sub-octet range/mask in-addr.arpa
|
---|
1166 | # specifications in the least significant octet, but the code is
|
---|
1167 | # simpler if we deal with sub-octet delegations at any level.
|
---|
1168 |
|
---|
1169 | # Now we find the "true" mask with the aid of the "base" calculated above
|
---|
1170 | if ($#octs == 0) {
|
---|
1171 | $masklen += 8;
|
---|
1172 | $tmpcidr = "$octs[0].0.0.0/$masklen"; # really hope we don't see one of these very often.
|
---|
1173 | } elsif ($#octs == 1) {
|
---|
1174 | $masklen += 16;
|
---|
1175 | $tmpcidr = "$octs[0].$octs[1].0.0/$masklen";
|
---|
1176 | } elsif ($#octs == 2) {
|
---|
1177 | $masklen += 24;
|
---|
1178 | $tmpcidr = "$octs[0].$octs[1].$octs[2].0/$masklen";
|
---|
1179 | } else {
|
---|
1180 | $masklen += 32;
|
---|
1181 | $tmpcidr = "$octs[0].$octs[1].$octs[2].$octs[3]/$masklen";
|
---|
1182 | }
|
---|
1183 |
|
---|
1184 | } elsif ($zone =~ /\.ip6\.arpa$/) {
|
---|
1185 | # v6 revzone, formal zone name type
|
---|
1186 | my $tmpzone = $zone;
|
---|
1187 | $tmpzone =~ s/\.ip6\.arpa\.?//;
|
---|
1188 | ##fixme: if-n-when we decide we can support sub-nibble v6 zone names, we'll need to change this segment
|
---|
1189 | return ('FAIL', "Non-hexadecimals in apparent IPv6 reverse zone name") if $tmpzone !~ /^[a-fA-F\d\.]+$/;
|
---|
1190 | my @quads = reverse(split(/\./, $tmpzone));
|
---|
1191 | $warnmsg .= "Apparent sub-/64 IPv6 reverse zone\n" if $#quads > 15;
|
---|
1192 | my $nc;
|
---|
1193 | foreach (@quads) {
|
---|
1194 | $tmpcidr .= $_;
|
---|
1195 | $tmpcidr .= ":" if ++$nc % 4 == 0;
|
---|
1196 | }
|
---|
1197 | my $nq = 1 if $nc % 4 != 0;
|
---|
1198 | my $mask = $nc * 4; # need to do this here because we probably increment it below
|
---|
1199 | while ($nc++ % 4 != 0) {
|
---|
1200 | $tmpcidr .= "0";
|
---|
1201 | }
|
---|
1202 | $tmpcidr .= ($nq ? '::' : ':')."/$mask";
|
---|
1203 | }
|
---|
1204 |
|
---|
1205 | # Just to be sure, use NetAddr::IP to validate. Saves a lot of nasty regex watching for valid octet values.
|
---|
1206 | return ('FAIL', "Invalid zone $zone (apparent netblock $tmpcidr)")
|
---|
1207 | unless $cidr = NetAddr::IP->new($tmpcidr);
|
---|
1208 |
|
---|
1209 | if ($warnmsg) {
|
---|
1210 | $errstr = $warnmsg;
|
---|
1211 | return ('WARN', $cidr);
|
---|
1212 | }
|
---|
1213 | return ('OK', $cidr);
|
---|
1214 | } # done _zone2cidr()
|
---|
1215 |
|
---|
1216 | # Record template %-parameter expansion, IPv4. Note that IPv6 doesn't
|
---|
1217 | # really have a sane way to handle this type of expansion at the moment
|
---|
1218 | # due to the size of the address space.
|
---|
1219 | # Takes a reference to a template string to be expanded, and an IP to use in the replacement.
|
---|
1220 | sub _template4_expand {
|
---|
1221 | my $tmpl = shift;
|
---|
1222 | my $ip = shift;
|
---|
1223 |
|
---|
1224 | my @ipparts = split /\./, $ip;
|
---|
1225 | my @iphex;
|
---|
1226 | my @ippad;
|
---|
1227 | for (@ipparts) {
|
---|
1228 | push @iphex, sprintf("%x", $_);
|
---|
1229 | push @ippad, sprintf("%0.3u", $_);
|
---|
1230 | }
|
---|
1231 |
|
---|
1232 | # IP substitutions in template records:
|
---|
1233 | #major patterns:
|
---|
1234 | #dashed IP, forward and reverse
|
---|
1235 | #underscoreed IP, forward and reverse
|
---|
1236 | #dotted IP, forward and reverse (even if forward is... dumb)
|
---|
1237 | # -> %r for reverse, %i for forward, leading -, _, or . to indicate separator, defaults to -
|
---|
1238 | # %r or %-r => %4d-%3d-%2d-%1d
|
---|
1239 | # %_r => %4d_%3d_%2d_%1d
|
---|
1240 | # %.r => %4d.%3d.%2d.%1d
|
---|
1241 | # %i or %-i => %1d-%2d-%3d-%4d
|
---|
1242 | # %_i => %1d_%2d_%3d_%4d
|
---|
1243 | # %.i => %1d.%2d.%3d.%4d
|
---|
1244 | $$tmpl =~ s/\%r/\%4d-\%3d-\%2d-\%1d/g;
|
---|
1245 | $$tmpl =~ s/\%([-._])r/\%4d$1\%3d$1\%2d$1\%1d/g;
|
---|
1246 | $$tmpl =~ s/\%i/\%1d-\%2d-\%3d-\%4d/g;
|
---|
1247 | $$tmpl =~ s/\%([-._])i/\%1d$1\%2d$1\%3d$1\%4d/g;
|
---|
1248 |
|
---|
1249 | #hex-coded IP
|
---|
1250 | # %h
|
---|
1251 | $$tmpl =~ s/\%h/$iphex[0]$iphex[1]$iphex[2]$iphex[3]/g;
|
---|
1252 |
|
---|
1253 | #IP as decimal-coded 32-bit value
|
---|
1254 | # %d
|
---|
1255 | my $iptmp = $ipparts[0]*256*256*256 + $ipparts[1]*256*256 + $ipparts[2]*256 + $ipparts[3];
|
---|
1256 | $$tmpl =~ s/\%d/$iptmp/g;
|
---|
1257 |
|
---|
1258 | #minor patterns (per-octet)
|
---|
1259 | # %[1234][dh0]
|
---|
1260 | #octet
|
---|
1261 | #hex-coded octet
|
---|
1262 | #0-padded octet
|
---|
1263 | $$tmpl =~ s/\%([1234])d/$ipparts[$1-1]/g;
|
---|
1264 | $$tmpl =~ s/\%([1234])h/$iphex[$1-1]/g;
|
---|
1265 | $$tmpl =~ s/\%([1234])0/$ippad[$1-1]/g;
|
---|
1266 | } # _template4_expand()
|
---|
1267 |
|
---|
1268 | # Broad syntactic check on the hostname. Checks for valid characters, correctly-expandable template patterns.
|
---|
1269 | # Takes the hostname, type, and live/default and forward/reverse flags
|
---|
1270 | # Returns true/false, sets errstr on failures
|
---|
1271 | sub _check_hostname_form {
|
---|
1272 | my ($hname,$rectype,$defrec,$revrec) = @_;
|
---|
1273 |
|
---|
1274 | if ($hname =~ /\%/ && ($rectype == 65282 || $rectype == 65283) ) {
|
---|
1275 | my $tmphost = $hname;
|
---|
1276 | # we don't actually need to test with the real IP passed; that saves a bit of fiddling.
|
---|
1277 | _template4_expand(\$tmphost, '10.10.10.10');
|
---|
1278 | if ($tmphost =~ /\%/) {
|
---|
1279 | $errstr = "Invalid template $hname";
|
---|
1280 | return;
|
---|
1281 | }
|
---|
1282 | } elsif ($revrec eq 'y') {
|
---|
1283 | # Reverse zones don't support @ in hostnames
|
---|
1284 | # Also skip failure on revzone TXT records; the hostname contains the TXT content in that case.
|
---|
1285 | if ($rectype != $reverse_typemap{TXT} && lc($hname) !~ /^[0-9a-z_.-]+$/) {
|
---|
1286 | $errstr = "Hostnames may not contain anything other than (0-9 a-z . _)";
|
---|
1287 | return;
|
---|
1288 | }
|
---|
1289 | } else {
|
---|
1290 | if (lc($hname) !~ /^(?:[0-9a-z_.-]+|@)$/) {
|
---|
1291 | # Don't mention @, because it would be far too wordy to explain the nuance of @
|
---|
1292 | $errstr = "Hostnames may not contain anything other than (0-9 a-z . _)";
|
---|
1293 | return;
|
---|
1294 | }
|
---|
1295 | }
|
---|
1296 | return 1;
|
---|
1297 | } # _check_hostname_form()
|
---|
1298 |
|
---|
1299 |
|
---|
1300 | ##
|
---|
1301 | ## Initialization and cleanup subs
|
---|
1302 | ##
|
---|
1303 |
|
---|
1304 | ## DNSDB::__cfgload()
|
---|
1305 | # Private sub to parse a config file and load it into %config
|
---|
1306 | # Takes a filename and a hashref to put the parsed entries in
|
---|
1307 | sub __cfgload {
|
---|
1308 | $errstr = '';
|
---|
1309 | my $cfgfile = shift;
|
---|
1310 | my $cfg = shift;
|
---|
1311 |
|
---|
1312 | if (open CFG, "<$cfgfile") {
|
---|
1313 | while (<CFG>) {
|
---|
1314 | chomp;
|
---|
1315 | s/^\s*//;
|
---|
1316 | next if /^#/;
|
---|
1317 | next if /^$/;
|
---|
1318 | # hmm. more complex bits in this file might require [heading] headers, maybe?
|
---|
1319 | # $mode = $1 if /^\[(a-z)+]/;
|
---|
1320 | # DB connect info
|
---|
1321 | $cfg->{dbname} = $1 if /^dbname\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1322 | $cfg->{dbuser} = $1 if /^dbuser\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1323 | $cfg->{dbpass} = $1 if /^dbpass\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1324 | $cfg->{dbhost} = $1 if /^dbhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1325 | # Mail settings
|
---|
1326 | $cfg->{mailhost} = $1 if /^mailhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1327 | $cfg->{mailnotify} = $1 if /^mailnotify\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
1328 | $cfg->{mailsender} = $1 if /^mailsender\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
1329 | $cfg->{mailname} = $1 if /^mailname\s*=\s*([a-z0-9\s_.-]+)/i;
|
---|
1330 | $cfg->{orgname} = $1 if /^orgname\s*=\s*([a-z0-9\s_.,'-]+)/i;
|
---|
1331 | $cfg->{domain} = $1 if /^domain\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1332 | # session - note this is fed directly to CGI::Session
|
---|
1333 | $cfg->{timeout} = $1 if /^[tT][iI][mM][eE][oO][uU][tT]\s*=\s*(\d+[smhdwMy]?)/;
|
---|
1334 | $cfg->{sessiondir} = $1 if m{^sessiondir\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
1335 | # misc
|
---|
1336 | $cfg->{log_failures} = $1 if /^log_failures\s*=\s*([a-z01]+)/i;
|
---|
1337 | $cfg->{perpage} = $1 if /^perpage\s*=\s*(\d+)/i;
|
---|
1338 | $cfg->{exportcache} = $1 if m{^exportcache\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
1339 | $cfg->{lowercase} = $1 if /^lowercase\s*=\s*([a-z01]+)/i;
|
---|
1340 | # not supported in dns.cgi yet
|
---|
1341 | # $cfg->{templatedir} = $1 if m{^templatedir\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
1342 | # $cfg->{templateoverride} = $1 if m{^templateoverride\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
1343 | # RPC options
|
---|
1344 | $cfg->{rpcmode} = $1 if /^rpc_mode\s*=\s*(socket|HTTP|XMLRPC)\s*$/i;
|
---|
1345 | $cfg->{maxfcgi} = $1 if /^max_fcgi_requests\s*=\s*(\d+)\s*$/i;
|
---|
1346 | $cfg->{force_refresh} = $1 if /^force_refresh\s*=\s*([a-z01]+)/i;
|
---|
1347 | if (my ($tmp) = /^rpc_iplist\s*=\s*(.+)/i) {
|
---|
1348 | my @ips = split /[,\s]+/, $tmp;
|
---|
1349 | my $rpcsys = shift @ips;
|
---|
1350 | push @{$cfg->{rpcacl}{$rpcsys}}, @ips;
|
---|
1351 | }
|
---|
1352 | }
|
---|
1353 | close CFG;
|
---|
1354 | } else {
|
---|
1355 | $errstr = "Couldn't load configuration file $cfgfile: $!";
|
---|
1356 | return;
|
---|
1357 | }
|
---|
1358 | return 1;
|
---|
1359 | } # end __cfgload()
|
---|
1360 |
|
---|
1361 |
|
---|
1362 | ## DNSDB::connectDB()
|
---|
1363 | # Creates connection to DNS database.
|
---|
1364 | # Requires the database name, username, and password.
|
---|
1365 | # Returns a handle to the db or undef on failure.
|
---|
1366 | # Set up for a PostgreSQL db; could be any transactional DBMS with the
|
---|
1367 | # right changes.
|
---|
1368 | # Called by new(); not intended to be called publicly.
|
---|
1369 | sub connectDB {
|
---|
1370 | $errstr = '';
|
---|
1371 | my $dbname = shift;
|
---|
1372 | my $user = shift;
|
---|
1373 | my $pass = shift;
|
---|
1374 | my $dbh;
|
---|
1375 | my $DSN = "DBI:Pg:dbname=$dbname";
|
---|
1376 |
|
---|
1377 | my $host = shift;
|
---|
1378 | $DSN .= ";host=$host" if $host;
|
---|
1379 |
|
---|
1380 | # Note that we want to autocommit by default, and we will turn it off locally as necessary.
|
---|
1381 | # We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
|
---|
1382 | $dbh = DBI->connect($DSN, $user, $pass, {
|
---|
1383 | AutoCommit => 1,
|
---|
1384 | PrintError => 0
|
---|
1385 | });
|
---|
1386 | if (!$dbh) {
|
---|
1387 | $errstr = $DBI::errstr;
|
---|
1388 | return;
|
---|
1389 | }
|
---|
1390 | #) if(!$dbh);
|
---|
1391 |
|
---|
1392 | local $dbh->{RaiseError} = 1;
|
---|
1393 |
|
---|
1394 | eval {
|
---|
1395 | ##fixme: initialize the DB if we can't find the table (since, by definition, there's
|
---|
1396 | # nothing there if we can't select from it...)
|
---|
1397 | my $tblsth = $dbh->prepare("SELECT count(*) FROM pg_catalog.pg_class WHERE relkind='r' AND relname=?");
|
---|
1398 | my ($tblcount) = $dbh->selectrow_array($tblsth, undef, ('misc'));
|
---|
1399 | # return (undef,$DBI::errstr) if $dbh->err;
|
---|
1400 |
|
---|
1401 | #if ($tblcount == 0) {
|
---|
1402 | # # create tables one at a time, checking for each.
|
---|
1403 | # return (undef, "check table misc missing");
|
---|
1404 | #}
|
---|
1405 |
|
---|
1406 | # Return here if we can't select.
|
---|
1407 | # This should retrieve the dbversion key.
|
---|
1408 | my $sth = $dbh->prepare("SELECT key,value FROM misc WHERE misc_id=1");
|
---|
1409 | $sth->execute();
|
---|
1410 | # return (undef,$DBI::errstr) if ($sth->err);
|
---|
1411 |
|
---|
1412 | ##fixme: do stuff to the DB on version mismatch
|
---|
1413 | # x.y series should upgrade on $DNSDB::VERSION > misc(key=>version)
|
---|
1414 | # DB should be downward-compatible; column defaults should give sane (if possibly
|
---|
1415 | # useless-and-needs-help) values in columns an older software stack doesn't know about.
|
---|
1416 |
|
---|
1417 | # See if the select returned anything (or null data). This should
|
---|
1418 | # succeed if the select executed, but...
|
---|
1419 | $sth->fetchrow();
|
---|
1420 | # return (undef,$DBI::errstr) if ($sth->err);
|
---|
1421 |
|
---|
1422 | $sth->finish;
|
---|
1423 |
|
---|
1424 | }; # wrapped DB checks
|
---|
1425 | if ($@) {
|
---|
1426 | $errstr = $@;
|
---|
1427 | return;
|
---|
1428 | }
|
---|
1429 |
|
---|
1430 | # If we get here, we should be OK.
|
---|
1431 | return $dbh;
|
---|
1432 | } # end connectDB
|
---|
1433 |
|
---|
1434 |
|
---|
1435 | ## DNSDB::finish()
|
---|
1436 | # Cleans up after database handles and so on.
|
---|
1437 | # Requires a database handle
|
---|
1438 | sub finish {
|
---|
1439 | my $self = shift;
|
---|
1440 | $self->{dbh}->disconnect;
|
---|
1441 | } # end finish
|
---|
1442 |
|
---|
1443 |
|
---|
1444 | ## DNSDB::initGlobals()
|
---|
1445 | # Initialize global variables
|
---|
1446 | # NB: this does NOT include web-specific session variables!
|
---|
1447 | sub initGlobals {
|
---|
1448 | my $self = shift;
|
---|
1449 | my $dbh = $self->{dbh};
|
---|
1450 |
|
---|
1451 | # load record types from database
|
---|
1452 | my $sth = $dbh->prepare("SELECT val,name,stdflag FROM rectypes");
|
---|
1453 | $sth->execute;
|
---|
1454 | while (my ($recval,$recname,$stdflag) = $sth->fetchrow_array()) {
|
---|
1455 | $typemap{$recval} = $recname;
|
---|
1456 | $reverse_typemap{$recname} = $recval;
|
---|
1457 | # now we fill the record validation function hash
|
---|
1458 | if ($stdflag < 5) {
|
---|
1459 | my $fn = "_validate_$recval";
|
---|
1460 | $validators{$recval} = \&$fn;
|
---|
1461 | } else {
|
---|
1462 | my $fn = "sub { return ('FAIL','Type $recval ($recname) not supported'); }";
|
---|
1463 | $validators{$recval} = eval $fn;
|
---|
1464 | }
|
---|
1465 | }
|
---|
1466 | } # end initGlobals
|
---|
1467 |
|
---|
1468 |
|
---|
1469 | ## DNSDB::initRPC()
|
---|
1470 | # Takes a remote username and remote fullname.
|
---|
1471 | # Sets up the RPC logging-pseudouser if needed.
|
---|
1472 | # Sets the %userdata hash for logging.
|
---|
1473 | # Returns undef on failure
|
---|
1474 | sub initRPC {
|
---|
1475 | my $self = shift;
|
---|
1476 | my $dbh = $self->{dbh};
|
---|
1477 | my %args = @_;
|
---|
1478 |
|
---|
1479 | return if !$args{username};
|
---|
1480 | return if !$args{fullname};
|
---|
1481 |
|
---|
1482 | $args{username} = "$args{username}/$args{rpcsys}";
|
---|
1483 |
|
---|
1484 | my $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
|
---|
1485 | " FROM users WHERE username=?", undef, ($args{username}) );
|
---|
1486 | if (!$tmpuser) {
|
---|
1487 | $dbh->do("INSERT INTO users (username,password,firstname,type) VALUES (?,'RPC',?,'R')", undef,
|
---|
1488 | ($args{username}, $args{fullname}) );
|
---|
1489 | $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
|
---|
1490 | " FROM users WHERE username=?", undef, ($args{username}) );
|
---|
1491 | }
|
---|
1492 | $tmpuser->{lastname} = '' if !$tmpuser->{lastname};
|
---|
1493 | $self->{loguserid} = $tmpuser->{userid};
|
---|
1494 | $self->{logusername} = $tmpuser->{username};
|
---|
1495 | $self->{logfullname} = "$tmpuser->{firstname} $tmpuser->{lastname} ($args{rpcsys})";
|
---|
1496 | return 1 if $tmpuser;
|
---|
1497 | } # end initRPC()
|
---|
1498 |
|
---|
1499 |
|
---|
1500 | ## DNSDB::login()
|
---|
1501 | # Takes a database handle, username and password
|
---|
1502 | # Returns a userdata hash (UID, GID, username, fullname parts) if username exists,
|
---|
1503 | # password matches the one on file, and account is not disabled
|
---|
1504 | # Returns undef otherwise
|
---|
1505 | sub login {
|
---|
1506 | my $self = shift;
|
---|
1507 | my $dbh = $self->{dbh};
|
---|
1508 | my $user = shift;
|
---|
1509 | my $pass = shift;
|
---|
1510 |
|
---|
1511 | my $userinfo = $dbh->selectrow_hashref("SELECT user_id,group_id,password,firstname,lastname,status".
|
---|
1512 | " FROM users WHERE username=?",
|
---|
1513 | undef, ($user) );
|
---|
1514 | return if !$userinfo;
|
---|
1515 | return if !$userinfo->{status};
|
---|
1516 |
|
---|
1517 | if ($userinfo->{password} =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
|
---|
1518 | # native passwords (crypt-md5)
|
---|
1519 | return if $userinfo->{password} ne unix_md5_crypt($pass,$1);
|
---|
1520 | } elsif ($userinfo->{password} =~ /^[0-9a-f]{32}$/) {
|
---|
1521 | # VegaDNS import (hex-coded MD5)
|
---|
1522 | return if $userinfo->{password} ne md5_hex($pass);
|
---|
1523 | } else {
|
---|
1524 | # plaintext (convenient now and then)
|
---|
1525 | return if $userinfo->{password} ne $pass;
|
---|
1526 | }
|
---|
1527 |
|
---|
1528 | return $userinfo;
|
---|
1529 | } # end login()
|
---|
1530 |
|
---|
1531 |
|
---|
1532 | ## DNSDB::initActionLog()
|
---|
1533 | # Set up action logging. Takes a database handle and user ID
|
---|
1534 | # Sets some internal globals and Does The Right Thing to set up a logging channel.
|
---|
1535 | # This sets up _log() to spew out log entries to the defined channel without worrying
|
---|
1536 | # about having to open a file or a syslog channel
|
---|
1537 | ##fixme Need to call _initActionLog_blah() for various logging channels, configured
|
---|
1538 | # via dnsdb.conf, in $self->{log_channel} or something
|
---|
1539 | # See https://secure.deepnet.cx/trac/dnsadmin/ticket/21
|
---|
1540 | sub initActionLog {
|
---|
1541 | my $self = shift;
|
---|
1542 | my $dbh = $self->{dbh};
|
---|
1543 | my $uid = shift;
|
---|
1544 |
|
---|
1545 | return if !$uid;
|
---|
1546 |
|
---|
1547 | # snag user info for logging. there's got to be a way to not have to pass this back
|
---|
1548 | # and forth from a caller, but web usage means no persistence we can rely on from
|
---|
1549 | # the server side.
|
---|
1550 | my ($username,$fullname) = $dbh->selectrow_array("SELECT username, firstname || ' ' || lastname".
|
---|
1551 | " FROM users WHERE user_id=?", undef, ($uid));
|
---|
1552 | ##fixme: errors are unpossible!
|
---|
1553 |
|
---|
1554 | $self->{logusername} = $username;
|
---|
1555 | $self->{loguserid} = $uid;
|
---|
1556 | $self->{logfullname} = $fullname;
|
---|
1557 |
|
---|
1558 | # convert to real check once we have other logging channels
|
---|
1559 | # if ($self->{log_channel} eq 'sql') {
|
---|
1560 | # Open Log, Sez Me!
|
---|
1561 | # }
|
---|
1562 |
|
---|
1563 | } # end initActionLog
|
---|
1564 |
|
---|
1565 |
|
---|
1566 | ## DNSDB::getPermissions()
|
---|
1567 | # Get permissions from DB
|
---|
1568 | # Requires DB handle, group or user flag, ID, and hashref.
|
---|
1569 | sub getPermissions {
|
---|
1570 | my $self = shift;
|
---|
1571 | my $dbh = $self->{dbh};
|
---|
1572 |
|
---|
1573 | my $type = shift;
|
---|
1574 | my $id = shift;
|
---|
1575 | my $hash = shift;
|
---|
1576 |
|
---|
1577 | my $sql = qq(
|
---|
1578 | SELECT
|
---|
1579 | p.admin,p.self_edit,
|
---|
1580 | p.group_create,p.group_edit,p.group_delete,
|
---|
1581 | p.user_create,p.user_edit,p.user_delete,
|
---|
1582 | p.domain_create,p.domain_edit,p.domain_delete,
|
---|
1583 | p.record_create,p.record_edit,p.record_delete,p.record_locchg,
|
---|
1584 | p.location_create,p.location_edit,p.location_delete,p.location_view
|
---|
1585 | FROM permissions p
|
---|
1586 | );
|
---|
1587 | if ($type eq 'group') {
|
---|
1588 | $sql .= qq(
|
---|
1589 | JOIN groups g ON g.permission_id=p.permission_id
|
---|
1590 | WHERE g.group_id=?
|
---|
1591 | );
|
---|
1592 | } else {
|
---|
1593 | $sql .= qq(
|
---|
1594 | JOIN users u ON u.permission_id=p.permission_id
|
---|
1595 | WHERE u.user_id=?
|
---|
1596 | );
|
---|
1597 | }
|
---|
1598 |
|
---|
1599 | my $sth = $dbh->prepare($sql);
|
---|
1600 |
|
---|
1601 | ##fixme? we don't trap other plain SELECT errors
|
---|
1602 | $sth->execute($id);
|
---|
1603 |
|
---|
1604 | # my $permref = $sth->fetchrow_hashref;
|
---|
1605 | # return $permref;
|
---|
1606 | # $hash = $permref;
|
---|
1607 | # Eww. Need to learn how to forcibly drop a hashref onto an existing hash.
|
---|
1608 | ($hash->{admin},$hash->{self_edit},
|
---|
1609 | $hash->{group_create},$hash->{group_edit},$hash->{group_delete},
|
---|
1610 | $hash->{user_create},$hash->{user_edit},$hash->{user_delete},
|
---|
1611 | $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete},
|
---|
1612 | $hash->{record_create},$hash->{record_edit},$hash->{record_delete},$hash->{record_locchg},
|
---|
1613 | $hash->{location_create},$hash->{location_edit},$hash->{location_delete},$hash->{location_view}
|
---|
1614 | ) = $sth->fetchrow_array;
|
---|
1615 |
|
---|
1616 | } # end getPermissions()
|
---|
1617 |
|
---|
1618 |
|
---|
1619 | ## DNSDB::changePermissions()
|
---|
1620 | # Update an ACL entry
|
---|
1621 | # Takes a db handle, type, owner-id, and hashref for the changed permissions.
|
---|
1622 | sub changePermissions {
|
---|
1623 | my $self = shift;
|
---|
1624 | my $dbh = $self->{dbh};
|
---|
1625 | my $type = shift;
|
---|
1626 | my $id = shift;
|
---|
1627 | my $newperms = shift;
|
---|
1628 | my $inherit = shift || 0;
|
---|
1629 |
|
---|
1630 | my $resultmsg = '';
|
---|
1631 |
|
---|
1632 | # see if we're switching from inherited to custom. for bonus points,
|
---|
1633 | # snag the permid and parent permid anyway, since we'll need the permid
|
---|
1634 | # to set/alter custom perms, and both if we're switching from custom to
|
---|
1635 | # inherited.
|
---|
1636 | my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id,".
|
---|
1637 | ($type eq 'user' ? 'u.group_id,u.username' : 'u.parent_group_id,u.group_name').
|
---|
1638 | " FROM ".($type eq 'user' ? 'users' : 'groups')." u ".
|
---|
1639 | " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ".
|
---|
1640 | " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?");
|
---|
1641 | $sth->execute($id);
|
---|
1642 |
|
---|
1643 | my ($wasinherited,$permid,$parpermid,$parid,$name) = $sth->fetchrow_array;
|
---|
1644 |
|
---|
1645 | # hack phtoui
|
---|
1646 | # group id 1 is "special" in that it's it's own parent (err... possibly.)
|
---|
1647 | # may make its parent id 0 which doesn't exist, and as a bonus is Perl-false.
|
---|
1648 | $wasinherited = 0 if ($type eq 'group' && $id == 1);
|
---|
1649 |
|
---|
1650 | local $dbh->{AutoCommit} = 0;
|
---|
1651 | local $dbh->{RaiseError} = 1;
|
---|
1652 |
|
---|
1653 | # Wrap all the SQL in a transaction
|
---|
1654 | eval {
|
---|
1655 | if ($inherit) {
|
---|
1656 |
|
---|
1657 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ".
|
---|
1658 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) );
|
---|
1659 | $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) );
|
---|
1660 |
|
---|
1661 | } else {
|
---|
1662 |
|
---|
1663 | if ($wasinherited) { # munge new permission entry in if we're switching from inherited perms
|
---|
1664 | ##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users
|
---|
1665 | # ... if'n'when we have groups with fully inherited permissions.
|
---|
1666 | # SQL is coo
|
---|
1667 | $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ".
|
---|
1668 | "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) );
|
---|
1669 | ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ".
|
---|
1670 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) );
|
---|
1671 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ".
|
---|
1672 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) );
|
---|
1673 | }
|
---|
1674 |
|
---|
1675 | # and now set the permissions we were passed
|
---|
1676 | foreach (@permtypes) {
|
---|
1677 | if (defined ($newperms->{$_})) {
|
---|
1678 | $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) );
|
---|
1679 | }
|
---|
1680 | }
|
---|
1681 |
|
---|
1682 | } # (inherited->)? custom
|
---|
1683 |
|
---|
1684 | if ($type eq 'user') {
|
---|
1685 | $resultmsg = "Updated permissions for user $name";
|
---|
1686 | } else {
|
---|
1687 | $resultmsg = "Updated default permissions for group $name";
|
---|
1688 | }
|
---|
1689 | $self->_log(group_id => ($type eq 'user' ? $parid : $id), entry => $resultmsg);
|
---|
1690 | $dbh->commit;
|
---|
1691 | }; # end eval
|
---|
1692 | if ($@) {
|
---|
1693 | my $msg = $@;
|
---|
1694 | eval { $dbh->rollback; };
|
---|
1695 | return ('FAIL',"Error changing permissions: $msg");
|
---|
1696 | }
|
---|
1697 |
|
---|
1698 | return ('OK',$resultmsg);
|
---|
1699 | } # end changePermissions()
|
---|
1700 |
|
---|
1701 |
|
---|
1702 | ## DNSDB::comparePermissions()
|
---|
1703 | # Compare two permission hashes
|
---|
1704 | # Returns '>', '<', '=', '!'
|
---|
1705 | sub comparePermissions {
|
---|
1706 | my $p1 = shift;
|
---|
1707 | my $p2 = shift;
|
---|
1708 |
|
---|
1709 | my $retval = '='; # assume equality until proven otherwise
|
---|
1710 |
|
---|
1711 | no warnings "uninitialized";
|
---|
1712 |
|
---|
1713 | foreach (@permtypes) {
|
---|
1714 | next if $p1->{$_} == $p2->{$_}; # equal is good
|
---|
1715 | if ($p1->{$_} && !$p2->{$_}) {
|
---|
1716 | if ($retval eq '<') { # if we've already found an unequal pair where
|
---|
1717 | $retval = '!'; # $p2 has more access, and we now find a pair
|
---|
1718 | last; # where $p1 has more access, the overall access
|
---|
1719 | } # is neither greater or lesser, it's unequal.
|
---|
1720 | $retval = '>';
|
---|
1721 | }
|
---|
1722 | if (!$p1->{$_} && $p2->{$_}) {
|
---|
1723 | if ($retval eq '>') { # if we've already found an unequal pair where
|
---|
1724 | $retval = '!'; # $p1 has more access, and we now find a pair
|
---|
1725 | last; # where $p2 has more access, the overall access
|
---|
1726 | } # is neither greater or lesser, it's unequal.
|
---|
1727 | $retval = '<';
|
---|
1728 | }
|
---|
1729 | }
|
---|
1730 | return $retval;
|
---|
1731 | } # end comparePermissions()
|
---|
1732 |
|
---|
1733 |
|
---|
1734 | ## DNSDB::changeGroup()
|
---|
1735 | # Change group ID of an entity
|
---|
1736 | # Takes a database handle, entity type, entity ID, and new group ID
|
---|
1737 | sub changeGroup {
|
---|
1738 | my $self = shift;
|
---|
1739 | my $dbh = $self->{dbh};
|
---|
1740 | my $type = shift;
|
---|
1741 | my $id = shift;
|
---|
1742 | my $newgrp = shift;
|
---|
1743 |
|
---|
1744 | ##fixme: fail on not enough args
|
---|
1745 | #return ('FAIL', "Missing
|
---|
1746 |
|
---|
1747 | return ('FAIL', "Can't change the group of a $type")
|
---|
1748 | unless grep /^$type$/, ('domain','revzone','user','group'); # could be extended for defrecs?
|
---|
1749 |
|
---|
1750 | # Collect some names for logging and messages
|
---|
1751 | my $entname;
|
---|
1752 | if ($type eq 'domain') {
|
---|
1753 | $entname = $self->domainName($id);
|
---|
1754 | } elsif ($type eq 'revzone') {
|
---|
1755 | $entname = $self->revName($id);
|
---|
1756 | } elsif ($type eq 'user') {
|
---|
1757 | $entname = $self->userFullName($id, '%u');
|
---|
1758 | } elsif ($type eq 'group') {
|
---|
1759 | $entname = $self->groupName($id);
|
---|
1760 | }
|
---|
1761 |
|
---|
1762 | my ($oldgid) = $dbh->selectrow_array("SELECT group_id FROM $par_tbl{$type} WHERE $id_col{$type}=?",
|
---|
1763 | undef, ($id));
|
---|
1764 | my $oldgname = $self->groupName($oldgid);
|
---|
1765 | my $newgname = $self->groupName($newgrp);
|
---|
1766 |
|
---|
1767 | return ('FAIL', "Can't move things into a group that doesn't exist") if !$newgname;
|
---|
1768 |
|
---|
1769 | return ('WARN', "Nothing to do, new group is the same as the old group") if $oldgid == $newgrp;
|
---|
1770 |
|
---|
1771 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
1772 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
1773 | local $dbh->{AutoCommit} = 0;
|
---|
1774 | local $dbh->{RaiseError} = 1;
|
---|
1775 |
|
---|
1776 | eval {
|
---|
1777 | $dbh->do("UPDATE $par_tbl{$type} SET group_id=? WHERE $id_col{$type}=?", undef, ($newgrp, $id));
|
---|
1778 | # Log the change in both the old and new groups
|
---|
1779 | $self->_log(group_id => $oldgid, entry => "Moved $type $entname from $oldgname to $newgname");
|
---|
1780 | $self->_log(group_id => $newgrp, entry => "Moved $type $entname from $oldgname to $newgname");
|
---|
1781 | $dbh->commit;
|
---|
1782 | };
|
---|
1783 | if ($@) {
|
---|
1784 | my $msg = $@;
|
---|
1785 | eval { $dbh->rollback; };
|
---|
1786 | if ($self->{log_failures}) {
|
---|
1787 | $self->_log(group_id => $oldgid, entry => "Error moving $type $entname to $newgname: $msg");
|
---|
1788 | $dbh->commit; # since we enabled transactions earlier
|
---|
1789 | }
|
---|
1790 | return ('FAIL',"Error moving $type $entname to $newgname: $msg");
|
---|
1791 | }
|
---|
1792 |
|
---|
1793 | return ('OK',"Moved $type $entname from $oldgname to $newgname");
|
---|
1794 | } # end changeGroup()
|
---|
1795 |
|
---|
1796 |
|
---|
1797 | ##
|
---|
1798 | ## Processing subs
|
---|
1799 | ##
|
---|
1800 |
|
---|
1801 | ## DNSDB::addDomain()
|
---|
1802 | # Add a domain
|
---|
1803 | # Takes a database handle, domain name, numeric group, boolean(ish) state (active/inactive),
|
---|
1804 | # and user info hash (for logging).
|
---|
1805 | # Returns a status code and message
|
---|
1806 | sub addDomain {
|
---|
1807 | $errstr = '';
|
---|
1808 | my $self = shift;
|
---|
1809 | my $dbh = $self->{dbh};
|
---|
1810 | my $domain = shift;
|
---|
1811 | return ('FAIL',"Domain must not be blank\n") if !$domain;
|
---|
1812 | my $group = shift;
|
---|
1813 | return ('FAIL',"Group must be specified\n") if !defined($group);
|
---|
1814 | my $state = shift;
|
---|
1815 | return ('FAIL',"Domain status must be specified\n") if !defined($state);
|
---|
1816 | my $defloc = shift || '';
|
---|
1817 |
|
---|
1818 | $state = 1 if $state =~ /^active$/;
|
---|
1819 | $state = 1 if $state =~ /^on$/;
|
---|
1820 | $state = 0 if $state =~ /^inactive$/;
|
---|
1821 | $state = 0 if $state =~ /^off$/;
|
---|
1822 |
|
---|
1823 | return ('FAIL',"Invalid domain status") if $state !~ /^\d+$/;
|
---|
1824 |
|
---|
1825 | $domain = lc($domain) if $self->{lowercase};
|
---|
1826 |
|
---|
1827 | return ('FAIL', "Invalid characters in domain") if $domain !~ /^[a-zA-Z0-9_.-]+$/;
|
---|
1828 |
|
---|
1829 | my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)");
|
---|
1830 | my $dom_id;
|
---|
1831 |
|
---|
1832 | # quick check to start to see if we've already got one
|
---|
1833 | $sth->execute($domain);
|
---|
1834 | ($dom_id) = $sth->fetchrow_array;
|
---|
1835 |
|
---|
1836 | return ('FAIL', "Domain already exists") if $dom_id;
|
---|
1837 |
|
---|
1838 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
1839 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
1840 | local $dbh->{AutoCommit} = 0;
|
---|
1841 | local $dbh->{RaiseError} = 1;
|
---|
1842 |
|
---|
1843 | # Wrap all the SQL in a transaction
|
---|
1844 | eval {
|
---|
1845 | # insert the domain...
|
---|
1846 | $dbh->do("INSERT INTO domains (domain,group_id,status,default_location) VALUES (?,?,?,?)", undef,
|
---|
1847 | ($domain, $group, $state, $defloc));
|
---|
1848 |
|
---|
1849 | # get the ID...
|
---|
1850 | ($dom_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
1851 | undef, ($domain));
|
---|
1852 |
|
---|
1853 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
1854 | entry => "Added ".($state ? 'active' : 'inactive')." domain $domain");
|
---|
1855 |
|
---|
1856 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
1857 | my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
1858 | my $sth_in = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,distance,weight,port,ttl,location)".
|
---|
1859 | " VALUES ($dom_id,?,?,?,?,?,?,?,?)");
|
---|
1860 | $sth->execute($group);
|
---|
1861 | while (my ($host, $type, $val, $dist, $weight, $port, $ttl) = $sth->fetchrow_array()) {
|
---|
1862 | $host =~ s/DOMAIN/$domain/g;
|
---|
1863 | $val =~ s/DOMAIN/$domain/g;
|
---|
1864 | $sth_in->execute($host, $type, $val, $dist, $weight, $port, $ttl, $defloc);
|
---|
1865 | if ($typemap{$type} eq 'SOA') {
|
---|
1866 | my @tmp1 = split /:/, $host;
|
---|
1867 | my @tmp2 = split /:/, $val;
|
---|
1868 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
1869 | entry => "[new $domain] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
1870 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl");
|
---|
1871 | } else {
|
---|
1872 | my $logentry = "[new $domain] Added record '$host $typemap{$type}";
|
---|
1873 | $logentry .= " [distance $dist]" if $typemap{$type} eq 'MX';
|
---|
1874 | $logentry .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$type} eq 'SRV';
|
---|
1875 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
1876 | entry => $logentry." $val', TTL $ttl");
|
---|
1877 | }
|
---|
1878 | }
|
---|
1879 |
|
---|
1880 | # once we get here, we should have suceeded.
|
---|
1881 | $dbh->commit;
|
---|
1882 | }; # end eval
|
---|
1883 |
|
---|
1884 | if ($@) {
|
---|
1885 | my $msg = $@;
|
---|
1886 | eval { $dbh->rollback; };
|
---|
1887 | $self->_log(group_id => $group, entry => "Failed adding domain $domain ($msg)")
|
---|
1888 | if $self->{log_failures};
|
---|
1889 | $dbh->commit; # since we enabled transactions earlier
|
---|
1890 | return ('FAIL',$msg);
|
---|
1891 | } else {
|
---|
1892 | return ('OK',$dom_id);
|
---|
1893 | }
|
---|
1894 | } # end addDomain
|
---|
1895 |
|
---|
1896 |
|
---|
1897 | ## DNSDB::delZone()
|
---|
1898 | # Delete a forward or reverse zone.
|
---|
1899 | # Takes a database handle, zone ID, and forward/reverse flag.
|
---|
1900 | # for now, just delete the records, then the domain.
|
---|
1901 | # later we may want to archive it in some way instead (status code 2, for example?)
|
---|
1902 | sub delZone {
|
---|
1903 | my $self = shift;
|
---|
1904 | my $dbh = $self->{dbh};
|
---|
1905 | my $zoneid = shift;
|
---|
1906 | my $revrec = shift;
|
---|
1907 |
|
---|
1908 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
1909 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
1910 | local $dbh->{AutoCommit} = 0;
|
---|
1911 | local $dbh->{RaiseError} = 1;
|
---|
1912 |
|
---|
1913 | my $msg = '';
|
---|
1914 | my $failmsg = '';
|
---|
1915 | my $zone = ($revrec eq 'n' ? $self->domainName($zoneid) : $self->revName($zoneid));
|
---|
1916 |
|
---|
1917 | return ('FAIL', ($revrec eq 'n' ? 'Domain' : 'Reverse zone')." ID $zoneid doesn't exist") if !$zone;
|
---|
1918 |
|
---|
1919 | # Set this up here since we may use if if $self->{log_failures} is enabled
|
---|
1920 | my %loghash;
|
---|
1921 | $loghash{domain_id} = $zoneid if $revrec eq 'n';
|
---|
1922 | $loghash{rdns_id} = $zoneid if $revrec eq 'y';
|
---|
1923 | $loghash{group_id} = $self->parentID(
|
---|
1924 | id => $zoneid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec);
|
---|
1925 |
|
---|
1926 | # Wrap all the SQL in a transaction
|
---|
1927 | eval {
|
---|
1928 | # Disentangle custom record types before removing the
|
---|
1929 | # ones that are only in the zone to be deleted
|
---|
1930 | if ($revrec eq 'n') {
|
---|
1931 | my $sth = $dbh->prepare("UPDATE records SET type=?,domain_id=0 WHERE domain_id=? AND type=?");
|
---|
1932 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
1933 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65280);
|
---|
1934 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65281);
|
---|
1935 | $sth->execute(65282, $zoneid, 65283);
|
---|
1936 | $sth->execute(65282, $zoneid, 65284);
|
---|
1937 | $failmsg = "Failure removing domain records";
|
---|
1938 | $dbh->do("DELETE FROM records WHERE domain_id=?", undef, ($zoneid));
|
---|
1939 | $failmsg = "Failure removing domain";
|
---|
1940 | $dbh->do("DELETE FROM domains WHERE domain_id=?", undef, ($zoneid));
|
---|
1941 | } else {
|
---|
1942 | my $sth = $dbh->prepare("UPDATE records SET type=?,rdns_id=0 WHERE rdns_id=? AND type=?");
|
---|
1943 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
1944 | $sth->execute($reverse_typemap{A}, $zoneid, 65280);
|
---|
1945 | $sth->execute($reverse_typemap{AAAA}, $zoneid, 65281);
|
---|
1946 | # We don't have an "A template" or "AAAA template" type, although it might be useful for symmetry.
|
---|
1947 | # $sth->execute(65286?, $zoneid, 65283);
|
---|
1948 | # $sth->execute(65286?, $zoneid, 65284);
|
---|
1949 | $failmsg = "Failure removing reverse records";
|
---|
1950 | $dbh->do("DELETE FROM records WHERE rdns_id=?", undef, ($zoneid));
|
---|
1951 | $failmsg = "Failure removing reverse zone";
|
---|
1952 | $dbh->do("DELETE FROM revzones WHERE rdns_id=?", undef, ($zoneid));
|
---|
1953 | }
|
---|
1954 |
|
---|
1955 | $msg = "Deleted ".($revrec eq 'n' ? 'domain' : 'reverse zone')." $zone";
|
---|
1956 | $loghash{entry} = $msg;
|
---|
1957 | $self->_log(%loghash);
|
---|
1958 |
|
---|
1959 | # once we get here, we should have suceeded.
|
---|
1960 | $dbh->commit;
|
---|
1961 | }; # end eval
|
---|
1962 |
|
---|
1963 | if ($@) {
|
---|
1964 | $msg = $@;
|
---|
1965 | eval { $dbh->rollback; };
|
---|
1966 | $loghash{entry} = "Error deleting $zone: $msg ($failmsg)";
|
---|
1967 | if ($self->{log_failures}) {
|
---|
1968 | $self->_log(%loghash);
|
---|
1969 | $dbh->commit; # since we enabled transactions earlier
|
---|
1970 | }
|
---|
1971 | return ('FAIL', $loghash{entry});
|
---|
1972 | } else {
|
---|
1973 | return ('OK', $msg);
|
---|
1974 | }
|
---|
1975 |
|
---|
1976 | } # end delZone()
|
---|
1977 |
|
---|
1978 |
|
---|
1979 | ## DNSDB::domainName()
|
---|
1980 | # Return the domain name based on a domain ID
|
---|
1981 | # Takes a database handle and the domain ID
|
---|
1982 | # Returns the domain name or undef on failure
|
---|
1983 | sub domainName {
|
---|
1984 | $errstr = '';
|
---|
1985 | my $self = shift;
|
---|
1986 | my $dbh = $self->{dbh};
|
---|
1987 | my $domid = shift;
|
---|
1988 | my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
|
---|
1989 | $errstr = $DBI::errstr if !$domname;
|
---|
1990 | return $domname if $domname;
|
---|
1991 | } # end domainName()
|
---|
1992 |
|
---|
1993 |
|
---|
1994 | ## DNSDB::revName()
|
---|
1995 | # Return the reverse zone name based on an rDNS ID
|
---|
1996 | # Takes a database handle and the rDNS ID
|
---|
1997 | # Returns the reverse zone name or undef on failure
|
---|
1998 | sub revName {
|
---|
1999 | $errstr = '';
|
---|
2000 | my $self = shift;
|
---|
2001 | my $dbh = $self->{dbh};
|
---|
2002 | my $revid = shift;
|
---|
2003 | my ($revname) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id=?", undef, ($revid) );
|
---|
2004 | $errstr = $DBI::errstr if !$revname;
|
---|
2005 | return $revname if $revname;
|
---|
2006 | } # end revName()
|
---|
2007 |
|
---|
2008 |
|
---|
2009 | ## DNSDB::domainID()
|
---|
2010 | # Takes a database handle and domain name
|
---|
2011 | # Returns the domain ID number
|
---|
2012 | sub domainID {
|
---|
2013 | $errstr = '';
|
---|
2014 | my $self = shift;
|
---|
2015 | my $dbh = $self->{dbh};
|
---|
2016 | my $domain = shift;
|
---|
2017 | my ($domid) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
2018 | undef, ($domain) );
|
---|
2019 | if (!$domid) {
|
---|
2020 | if ($dbh->err) {
|
---|
2021 | $errstr = $DBI::errstr;
|
---|
2022 | } else {
|
---|
2023 | $errstr = "Domain $domain not present";
|
---|
2024 | }
|
---|
2025 | }
|
---|
2026 | return $domid if $domid;
|
---|
2027 | } # end domainID()
|
---|
2028 |
|
---|
2029 |
|
---|
2030 | ## DNSDB::revID()
|
---|
2031 | # Takes a database handle and reverse zone name
|
---|
2032 | # Returns the rDNS ID number
|
---|
2033 | sub revID {
|
---|
2034 | $errstr = '';
|
---|
2035 | my $self = shift;
|
---|
2036 | my $dbh = $self->{dbh};
|
---|
2037 | my $revzone = shift;
|
---|
2038 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ($revzone) );
|
---|
2039 | if (!$revid) {
|
---|
2040 | if ($dbh->err) {
|
---|
2041 | $errstr = $DBI::errstr;
|
---|
2042 | } else {
|
---|
2043 | $errstr = "Reverse zone $revzone not present";
|
---|
2044 | }
|
---|
2045 | }
|
---|
2046 | return $revid if $revid;
|
---|
2047 | } # end revID()
|
---|
2048 |
|
---|
2049 |
|
---|
2050 | ## DNSDB::addRDNS
|
---|
2051 | # Adds a reverse DNS zone
|
---|
2052 | # Takes a database handle, CIDR block, reverse DNS pattern, numeric group,
|
---|
2053 | # and boolean(ish) state (active/inactive)
|
---|
2054 | # Returns a status code and message
|
---|
2055 | sub addRDNS {
|
---|
2056 | my $self = shift;
|
---|
2057 | my $dbh = $self->{dbh};
|
---|
2058 | my $zone = NetAddr::IP->new(shift);
|
---|
2059 |
|
---|
2060 | return ('FAIL',"Zone name must be a valid CIDR netblock") unless ($zone && $zone->addr !~ /^0/);
|
---|
2061 | my $revpatt = shift; # construct a custom (A/AAAA+)? PTR template record
|
---|
2062 | my $group = shift;
|
---|
2063 | my $state = shift;
|
---|
2064 | my $defloc = shift || '';
|
---|
2065 |
|
---|
2066 | $state = 1 if $state =~ /^active$/;
|
---|
2067 | $state = 1 if $state =~ /^on$/;
|
---|
2068 | $state = 0 if $state =~ /^inactive$/;
|
---|
2069 | $state = 0 if $state =~ /^off$/;
|
---|
2070 |
|
---|
2071 | return ('FAIL',"Invalid zone status") if $state !~ /^\d+$/;
|
---|
2072 |
|
---|
2073 | # quick check to start to see if we've already got one
|
---|
2074 | my ($rdns_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ("$zone"));
|
---|
2075 |
|
---|
2076 | return ('FAIL', "Zone already exists") if $rdns_id;
|
---|
2077 |
|
---|
2078 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
2079 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
2080 | local $dbh->{AutoCommit} = 0;
|
---|
2081 | local $dbh->{RaiseError} = 1;
|
---|
2082 |
|
---|
2083 | my $warnstr = '';
|
---|
2084 | my $defttl = 3600; # 1 hour should be reasonable. And unless things have gone horribly
|
---|
2085 | # wrong, we should have a value to override this anyway.
|
---|
2086 |
|
---|
2087 | # Wrap all the SQL in a transaction
|
---|
2088 | eval {
|
---|
2089 | # insert the zone...
|
---|
2090 | $dbh->do("INSERT INTO revzones (revnet,group_id,status,default_location) VALUES (?,?,?,?)", undef,
|
---|
2091 | ($zone, $group, $state, $defloc) );
|
---|
2092 |
|
---|
2093 | # get the ID...
|
---|
2094 | ($rdns_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
2095 |
|
---|
2096 | $self->_log(rdns_id => $rdns_id, group_id => $group,
|
---|
2097 | entry => "Added ".($state ? 'active' : 'inactive')." reverse zone $zone");
|
---|
2098 |
|
---|
2099 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
2100 | my $sth = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
2101 | my $sth_in = $dbh->prepare("INSERT INTO records (rdns_id,domain_id,host,type,val,ttl,location)".
|
---|
2102 | " VALUES ($rdns_id,?,?,?,?,?,?)");
|
---|
2103 | $sth->execute($group);
|
---|
2104 | while (my ($host,$type,$val,$ttl) = $sth->fetchrow_array()) {
|
---|
2105 | # Silently skip v4/v6 mismatches. This is not an error, this is expected.
|
---|
2106 | if ($zone->{isv6}) {
|
---|
2107 | next if ($type == 65280 || $type == 65283);
|
---|
2108 | } else {
|
---|
2109 | next if ($type == 65281 || $type == 65284);
|
---|
2110 | }
|
---|
2111 |
|
---|
2112 | $host =~ s/ADMINDOMAIN/$self->{domain}/g;
|
---|
2113 |
|
---|
2114 | # Check to make sure the IP stubs will fit in the zone. Under most usage failures here should be rare.
|
---|
2115 | # On failure, tack a note on to a warning string and continue without adding this record.
|
---|
2116 | # While we're at it, we substitute $zone for ZONE in the value.
|
---|
2117 | if ($val eq 'ZONE') {
|
---|
2118 | # If we've got a pattern, we skip the default record version on (A+)PTR-template types
|
---|
2119 | next if $revpatt && ($type == 65282 || $type == 65283);
|
---|
2120 | ##fixme? do we care if we have multiple whole-zone templates?
|
---|
2121 | $val = $zone->network;
|
---|
2122 | } elsif ($val =~ /ZONE/) {
|
---|
2123 | my $tmpval = $val;
|
---|
2124 | $tmpval =~ s/ZONE//;
|
---|
2125 | # Bend the rules and allow single-trailing-number PTR or PTR template records to be inserted
|
---|
2126 | # as either v4 or v6. May make this an off-by-default config flag
|
---|
2127 | # Note that the origin records that may trigger this **SHOULD** already have ZONE,\d
|
---|
2128 | if ($type == 12 || $type == 65282) {
|
---|
2129 | $tmpval =~ s/[,.]/::/ if ($tmpval =~ /^[,.]\d+$/ && $zone->{isv6});
|
---|
2130 | $tmpval =~ s/[,:]+/./ if ($tmpval =~ /^(?:,|::)\d+$/ && !$zone->{isv6});
|
---|
2131 | }
|
---|
2132 | my $addr;
|
---|
2133 | if ($self->_ipparent('n', 'y', \$tmpval, $rdns_id, \$addr)) {
|
---|
2134 | $val = $addr->addr;
|
---|
2135 | } else {
|
---|
2136 | $warnstr .= "\nDefault record '$val $typemap{$type} $host' doesn't fit in $zone, skipping";
|
---|
2137 | next;
|
---|
2138 | }
|
---|
2139 | }
|
---|
2140 |
|
---|
2141 | # Substitute $zone for ZONE in the hostname, but only for non-NS records.
|
---|
2142 | # NS records get this substitution on the value instead.
|
---|
2143 | $host = _ZONE($zone, $host) if $type != 2;
|
---|
2144 |
|
---|
2145 | # Fill in the forward domain ID if we can find it, otherwise:
|
---|
2146 | # Coerce type down to PTR or PTR template if we can't
|
---|
2147 | my $domid = 0;
|
---|
2148 | if ($type >= 65280) {
|
---|
2149 | if (!($domid = $self->_hostparent($host))) {
|
---|
2150 | $warnstr .= "\nRecord added as PTR instead of $typemap{$type}; domain not found for $host";
|
---|
2151 | $type = $reverse_typemap{PTR};
|
---|
2152 | $domid = 0; # just to be explicit.
|
---|
2153 | }
|
---|
2154 | }
|
---|
2155 |
|
---|
2156 | $sth_in->execute($domid,$host,$type,$val,$ttl,$defloc);
|
---|
2157 |
|
---|
2158 | if ($typemap{$type} eq 'SOA') {
|
---|
2159 | my @tmp1 = split /:/, $host;
|
---|
2160 | my @tmp2 = split /:/, $val;
|
---|
2161 | $self->_log(rdns_id => $rdns_id, group_id => $group,
|
---|
2162 | entry => "[new $zone] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
2163 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl");
|
---|
2164 | $defttl = $tmp2[3];
|
---|
2165 | } else {
|
---|
2166 | my $logentry = "[new $zone] Added record '$host $typemap{$type} $val', TTL $ttl";
|
---|
2167 | $logentry .= ", default location ".$self->getLoc($defloc)->{description} if $defloc;
|
---|
2168 | $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group, entry => $logentry);
|
---|
2169 | }
|
---|
2170 | }
|
---|
2171 |
|
---|
2172 | # Generate record based on provided pattern.
|
---|
2173 | if ($revpatt) {
|
---|
2174 | my $host;
|
---|
2175 | my $type = ($zone->{isv6} ? 65284 : 65283);
|
---|
2176 | my $val = $zone->network;
|
---|
2177 |
|
---|
2178 | # Substitute $zone for ZONE in the hostname.
|
---|
2179 | $host = _ZONE($zone, $revpatt);
|
---|
2180 |
|
---|
2181 | my $domid = 0;
|
---|
2182 | if (!($domid = $self->_hostparent($host))) {
|
---|
2183 | $warnstr .= "\nDefault pattern added as PTR template instead of $typemap{$type}; domain not found for $host";
|
---|
2184 | $type = 65282;
|
---|
2185 | $domid = 0; # just to be explicit.
|
---|
2186 | }
|
---|
2187 |
|
---|
2188 | $sth_in->execute($domid,$host,$type,$val,$defttl,$defloc);
|
---|
2189 | my $logentry = "[new $zone] Added record '$host $typemap{$type}";
|
---|
2190 | $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group,
|
---|
2191 | entry => $logentry." $val', TTL $defttl from pattern");
|
---|
2192 | }
|
---|
2193 |
|
---|
2194 | # If there are warnings (presumably about default records skipped for cause) log them
|
---|
2195 | $self->_log(rdns_id => $rdns_id, group_id => $group, entry => "Warning(s) adding $zone:$warnstr")
|
---|
2196 | if $warnstr;
|
---|
2197 |
|
---|
2198 | # once we get here, we should have suceeded.
|
---|
2199 | $dbh->commit;
|
---|
2200 | }; # end eval
|
---|
2201 |
|
---|
2202 | if ($@) {
|
---|
2203 | my $msg = $@;
|
---|
2204 | eval { $dbh->rollback; };
|
---|
2205 | $self->_log(group_id => $group, entry => "Failed adding reverse zone $zone ($msg)")
|
---|
2206 | if $self->{log_failures};
|
---|
2207 | $dbh->commit; # since we enabled transactions earlier
|
---|
2208 | return ('FAIL',$msg);
|
---|
2209 | } else {
|
---|
2210 | my $retcode = 'OK';
|
---|
2211 | if ($warnstr) {
|
---|
2212 | $resultstr = $warnstr;
|
---|
2213 | $retcode = 'WARN';
|
---|
2214 | }
|
---|
2215 | return ($retcode, $rdns_id);
|
---|
2216 | }
|
---|
2217 |
|
---|
2218 | } # end addRDNS()
|
---|
2219 |
|
---|
2220 |
|
---|
2221 | ## DNSDB::getZoneCount
|
---|
2222 | # Get count of zones in group or groups
|
---|
2223 | # Takes a database handle and hash containing:
|
---|
2224 | # - the "current" group
|
---|
2225 | # - an array of "acceptable" groups
|
---|
2226 | # - a flag for forward/reverse zones
|
---|
2227 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
2228 | # Returns an integer count of the resulting zone list.
|
---|
2229 | sub getZoneCount {
|
---|
2230 | my $self = shift;
|
---|
2231 | my $dbh = $self->{dbh};
|
---|
2232 |
|
---|
2233 | my %args = @_;
|
---|
2234 |
|
---|
2235 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
2236 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
2237 | $errstr = "Bad or missing curgroup argument";
|
---|
2238 | return;
|
---|
2239 | }
|
---|
2240 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
2241 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
2242 | $errstr = "Bad childlist argument";
|
---|
2243 | return;
|
---|
2244 | }
|
---|
2245 |
|
---|
2246 | my @filterargs;
|
---|
2247 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
2248 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
2249 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
2250 | push @filterargs, $args{filter} if $args{filter};
|
---|
2251 |
|
---|
2252 | my $sql;
|
---|
2253 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
2254 | if ($args{revrec} eq 'n') {
|
---|
2255 | $sql = "SELECT count(*) FROM domains".
|
---|
2256 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
2257 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
2258 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
2259 | } else {
|
---|
2260 | $sql = "SELECT count(*) FROM revzones".
|
---|
2261 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
2262 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
|
---|
2263 | ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
2264 | }
|
---|
2265 | my ($count) = $dbh->selectrow_array($sql, undef, @filterargs);
|
---|
2266 | return $count;
|
---|
2267 | } # end getZoneCount()
|
---|
2268 |
|
---|
2269 |
|
---|
2270 | ## DNSDB::getZoneList()
|
---|
2271 | # Get a list of zones in the specified group(s)
|
---|
2272 | # Takes the same arguments as getZoneCount() above
|
---|
2273 | # Returns a reference to an array of hashrefs suitable for feeding to HTML::Template
|
---|
2274 | sub getZoneList {
|
---|
2275 | my $self = shift;
|
---|
2276 | my $dbh = $self->{dbh};
|
---|
2277 |
|
---|
2278 | my %args = @_;
|
---|
2279 |
|
---|
2280 | my @zonelist;
|
---|
2281 |
|
---|
2282 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
2283 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
2284 |
|
---|
2285 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
2286 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
2287 | $errstr = "Bad or missing curgroup argument";
|
---|
2288 | return;
|
---|
2289 | }
|
---|
2290 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
2291 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
2292 | $errstr = "Bad childlist argument";
|
---|
2293 | return;
|
---|
2294 | }
|
---|
2295 |
|
---|
2296 | my @filterargs;
|
---|
2297 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
2298 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
2299 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
2300 | push @filterargs, $args{filter} if $args{filter};
|
---|
2301 |
|
---|
2302 | my $sql;
|
---|
2303 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
2304 | if ($args{revrec} eq 'n') {
|
---|
2305 | $args{sortby} = 'domain' if !$args{sortby} || !grep /^$args{sortby}$/, ('domain','group','status');
|
---|
2306 | $sql = "SELECT domain_id,domain,status,groups.group_name AS group FROM domains".
|
---|
2307 | " INNER JOIN groups ON domains.group_id=groups.group_id".
|
---|
2308 | " WHERE domains.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
2309 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
2310 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
2311 | } else {
|
---|
2312 | ##fixme: arguably startwith here is irrelevant. depends on the UI though.
|
---|
2313 | $args{sortby} = 'revnet' if !$args{sortby} || !grep /^$args{sortby}$/, ('revnet','group','status');
|
---|
2314 | $sql = "SELECT rdns_id,revnet,status,groups.group_name AS group FROM revzones".
|
---|
2315 | " INNER JOIN groups ON revzones.group_id=groups.group_id".
|
---|
2316 | " WHERE revzones.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
2317 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
|
---|
2318 | ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
2319 | }
|
---|
2320 | # A common tail.
|
---|
2321 | $sql .= " ORDER BY ".($args{sortby} eq 'group' ? 'groups.group_name' : $args{sortby})." $args{sortorder} ".
|
---|
2322 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage}".
|
---|
2323 | " OFFSET ".$args{offset}*$self->{perpage});
|
---|
2324 | my $sth = $dbh->prepare($sql);
|
---|
2325 | $sth->execute(@filterargs);
|
---|
2326 | my $rownum = 0;
|
---|
2327 |
|
---|
2328 | while (my @data = $sth->fetchrow_array) {
|
---|
2329 | my %row;
|
---|
2330 | $row{domain_id} = $data[0];
|
---|
2331 | $row{domain} = $data[1];
|
---|
2332 | $row{status} = $data[2];
|
---|
2333 | $row{group} = $data[3];
|
---|
2334 | push @zonelist, \%row;
|
---|
2335 | }
|
---|
2336 |
|
---|
2337 | return \@zonelist;
|
---|
2338 | } # end getZoneList()
|
---|
2339 |
|
---|
2340 |
|
---|
2341 | ## DNSDB::getZoneLocation()
|
---|
2342 | # Retrieve the default location for a zone.
|
---|
2343 | # Takes a database handle, forward/reverse flag, and zone ID
|
---|
2344 | sub getZoneLocation {
|
---|
2345 | my $self = shift;
|
---|
2346 | my $dbh = $self->{dbh};
|
---|
2347 | my $revrec = shift;
|
---|
2348 | my $zoneid = shift;
|
---|
2349 |
|
---|
2350 | my ($loc) = $dbh->selectrow_array("SELECT default_location FROM ".
|
---|
2351 | ($revrec eq 'n' ? 'domains WHERE domain_id = ?' : 'revzones WHERE rdns_id = ?'),
|
---|
2352 | undef, ($zoneid));
|
---|
2353 | return $loc;
|
---|
2354 | } # end getZoneLocation()
|
---|
2355 |
|
---|
2356 |
|
---|
2357 | ## DNSDB::addGroup()
|
---|
2358 | # Add a group
|
---|
2359 | # Takes a database handle, group name, parent group, hashref for permissions,
|
---|
2360 | # and optional template-vs-cloneme flag for the default records
|
---|
2361 | # Returns a status code and message
|
---|
2362 | sub addGroup {
|
---|
2363 | $errstr = '';
|
---|
2364 | my $self = shift;
|
---|
2365 | my $dbh = $self->{dbh};
|
---|
2366 | my $groupname = shift;
|
---|
2367 | my $pargroup = shift;
|
---|
2368 | my $permissions = shift;
|
---|
2369 |
|
---|
2370 | # 0 indicates "custom", hardcoded.
|
---|
2371 | # Any other value clones that group's default records, if it exists.
|
---|
2372 | my $inherit = shift || 0;
|
---|
2373 | ##fixme: need a flag to indicate clone records or <?> ?
|
---|
2374 |
|
---|
2375 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
2376 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
2377 | local $dbh->{AutoCommit} = 0;
|
---|
2378 | local $dbh->{RaiseError} = 1;
|
---|
2379 |
|
---|
2380 | my ($group_id) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($groupname));
|
---|
2381 |
|
---|
2382 | return ('FAIL', "Group already exists") if $group_id;
|
---|
2383 |
|
---|
2384 | # Wrap all the SQL in a transaction
|
---|
2385 | eval {
|
---|
2386 | $dbh->do("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)", undef, ($pargroup, $groupname) );
|
---|
2387 |
|
---|
2388 | my ($groupid) = $dbh->selectrow_array("SELECT currval('groups_group_id_seq')");
|
---|
2389 |
|
---|
2390 | # We work through the whole set of permissions instead of specifying them so
|
---|
2391 | # that when we add a new permission, we don't have to change the code anywhere
|
---|
2392 | # that doesn't explicitly deal with that specific permission.
|
---|
2393 | my @permvals;
|
---|
2394 | foreach (@permtypes) {
|
---|
2395 | if (!defined ($permissions->{$_})) {
|
---|
2396 | push @permvals, 0;
|
---|
2397 | } else {
|
---|
2398 | push @permvals, $permissions->{$_};
|
---|
2399 | }
|
---|
2400 | }
|
---|
2401 | $dbh->do("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")",
|
---|
2402 | undef, ($groupid, @permvals) );
|
---|
2403 | my ($permid) = $dbh->selectrow_array("SELECT currval('permissions_permission_id_seq')");
|
---|
2404 | $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
|
---|
2405 |
|
---|
2406 | # Default records
|
---|
2407 | my $sthf = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
|
---|
2408 | "VALUES ($groupid,?,?,?,?,?,?,?)");
|
---|
2409 | my $sthr = $dbh->prepare("INSERT INTO default_rev_records (group_id,host,type,val,ttl) ".
|
---|
2410 | "VALUES ($groupid,?,?,?,?)");
|
---|
2411 | if ($inherit) {
|
---|
2412 | # Duplicate records from parent. Actually relying on inherited records feels
|
---|
2413 | # very fragile, and it would be problematic to roll over at a later time.
|
---|
2414 | my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
2415 | $sth2->execute($pargroup);
|
---|
2416 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
2417 | $sthf->execute(@clonedata);
|
---|
2418 | }
|
---|
2419 | # And now the reverse records
|
---|
2420 | $sth2 = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
2421 | $sth2->execute($pargroup);
|
---|
2422 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
2423 | $sthr->execute(@clonedata);
|
---|
2424 | }
|
---|
2425 | } else {
|
---|
2426 | ##fixme: Hardcoding is Bad, mmmmkaaaay?
|
---|
2427 | # reasonable basic defaults for SOA, MX, NS, and minimal hosting
|
---|
2428 | # could load from a config file, but somewhere along the line we need hardcoded bits.
|
---|
2429 | $sthf->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
|
---|
2430 | $sthf->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
|
---|
2431 | $sthf->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
|
---|
2432 | $sthf->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
|
---|
2433 | $sthf->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
|
---|
2434 | $sthf->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
|
---|
2435 | # reasonable basic defaults for generic reverse zone. Same as initial SQL tabledef.
|
---|
2436 | $sthr->execute('hostmaster.ADMINDOMAIN:ns1.ADMINDOMAIN', 6, '10800:3600:604800:10800', 86400);
|
---|
2437 | $sthr->execute('unused-%r.ADMINDOMAIN', 65283, 'ZONE', 3600);
|
---|
2438 | }
|
---|
2439 |
|
---|
2440 | $self->_log(group_id => $pargroup, entry => "Added group $groupname");
|
---|
2441 |
|
---|
2442 | # once we get here, we should have suceeded.
|
---|
2443 | $dbh->commit;
|
---|
2444 | }; # end eval
|
---|
2445 |
|
---|
2446 | if ($@) {
|
---|
2447 | my $msg = $@;
|
---|
2448 | eval { $dbh->rollback; };
|
---|
2449 | if ($self->{log_failures}) {
|
---|
2450 | $self->_log(group_id => $pargroup, entry => "Failed to add group $groupname: $msg");
|
---|
2451 | $dbh->commit;
|
---|
2452 | }
|
---|
2453 | return ('FAIL',$msg);
|
---|
2454 | }
|
---|
2455 |
|
---|
2456 | return ('OK','OK');
|
---|
2457 | } # end addGroup()
|
---|
2458 |
|
---|
2459 |
|
---|
2460 | ## DNSDB::delGroup()
|
---|
2461 | # Delete a group.
|
---|
2462 | # Takes a group ID
|
---|
2463 | # Returns a status code and message
|
---|
2464 | sub delGroup {
|
---|
2465 | my $self = shift;
|
---|
2466 | my $dbh = $self->{dbh};
|
---|
2467 | my $groupid = shift;
|
---|
2468 |
|
---|
2469 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
2470 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
2471 | local $dbh->{AutoCommit} = 0;
|
---|
2472 | local $dbh->{RaiseError} = 1;
|
---|
2473 |
|
---|
2474 | ##fixme: locate "knowable" error conditions and deal with them before the eval
|
---|
2475 | # ... or inside, whatever.
|
---|
2476 | # -> domains still exist in group
|
---|
2477 | # -> ...
|
---|
2478 | my $failmsg = '';
|
---|
2479 | my $resultmsg = '';
|
---|
2480 |
|
---|
2481 | # collect some pieces for logging and error messages
|
---|
2482 | my $groupname = $self->groupName($groupid);
|
---|
2483 | my $parid = $self->parentID(id => $groupid, type => 'group');
|
---|
2484 |
|
---|
2485 | # Wrap all the SQL in a transaction
|
---|
2486 | eval {
|
---|
2487 | # Check for Things in the group
|
---|
2488 | $failmsg = "Can't remove group $groupname";
|
---|
2489 | my ($grpcnt) = $dbh->selectrow_array("SELECT count(*) FROM groups WHERE parent_group_id=?", undef, ($groupid));
|
---|
2490 | die "$grpcnt groups still in group\n" if $grpcnt;
|
---|
2491 | my ($domcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($groupid));
|
---|
2492 | die "$domcnt domains still in group\n" if $domcnt;
|
---|
2493 | my ($revcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($groupid));
|
---|
2494 | die "$revcnt reverse zones still in group\n" if $revcnt;
|
---|
2495 | my ($usercnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($groupid));
|
---|
2496 | die "$usercnt users still in group\n" if $usercnt;
|
---|
2497 |
|
---|
2498 | $failmsg = "Failed to delete default records for $groupname";
|
---|
2499 | $dbh->do("DELETE from default_records WHERE group_id=?", undef, ($groupid));
|
---|
2500 | $failmsg = "Failed to delete default reverse records for $groupname";
|
---|
2501 | $dbh->do("DELETE from default_rev_records WHERE group_id=?", undef, ($groupid));
|
---|
2502 | $failmsg = "Failed to remove group $groupname";
|
---|
2503 | $dbh->do("DELETE from groups WHERE group_id=?", undef, ($groupid));
|
---|
2504 |
|
---|
2505 | $self->_log(group_id => $parid, entry => "Deleted group $groupname");
|
---|
2506 | $resultmsg = "Deleted group $groupname";
|
---|
2507 |
|
---|
2508 | # once we get here, we should have suceeded.
|
---|
2509 | $dbh->commit;
|
---|
2510 | }; # end eval
|
---|
2511 |
|
---|
2512 | if ($@) {
|
---|
2513 | my $msg = $@;
|
---|
2514 | eval { $dbh->rollback; };
|
---|
2515 | if ($self->{log_failures}) {
|
---|
2516 | $self->_log(group_id => $parid, entry => "$failmsg: $msg");
|
---|
2517 | $dbh->commit; # since we enabled transactions earlier
|
---|
2518 | }
|
---|
2519 | return ('FAIL',"$failmsg: $msg");
|
---|
2520 | }
|
---|
2521 |
|
---|
2522 | return ('OK',$resultmsg);
|
---|
2523 | } # end delGroup()
|
---|
2524 |
|
---|
2525 |
|
---|
2526 | ## DNSDB::getChildren()
|
---|
2527 | # Get a list of all groups whose parent^n is group <n>
|
---|
2528 | # Takes a database handle, group ID, reference to an array to put the group IDs in,
|
---|
2529 | # and an optional flag to return only immediate children or all children-of-children
|
---|
2530 | # default to returning all children
|
---|
2531 | # Calls itself
|
---|
2532 | sub getChildren {
|
---|
2533 | $errstr = '';
|
---|
2534 | my $self = shift;
|
---|
2535 | my $dbh = $self->{dbh};
|
---|
2536 | my $rootgroup = shift;
|
---|
2537 | my $groupdest = shift;
|
---|
2538 | my $immed = shift || 'all';
|
---|
2539 |
|
---|
2540 | # special break for default group; otherwise we get stuck.
|
---|
2541 | if ($rootgroup == 1) {
|
---|
2542 | # by definition, group 1 is the Root Of All Groups
|
---|
2543 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
|
---|
2544 | ($immed ne 'all' ? " AND parent_group_id=1" : '')." ORDER BY group_name");
|
---|
2545 | $sth->execute;
|
---|
2546 | while (my @this = $sth->fetchrow_array) {
|
---|
2547 | push @$groupdest, @this;
|
---|
2548 | }
|
---|
2549 | } else {
|
---|
2550 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=? ORDER BY group_name");
|
---|
2551 | $sth->execute($rootgroup);
|
---|
2552 | return if $sth->rows == 0;
|
---|
2553 | my @grouplist;
|
---|
2554 | while (my ($group) = $sth->fetchrow_array) {
|
---|
2555 | push @$groupdest, $group;
|
---|
2556 | $self->getChildren($group, $groupdest) if $immed eq 'all';
|
---|
2557 | }
|
---|
2558 | }
|
---|
2559 | } # end getChildren()
|
---|
2560 |
|
---|
2561 |
|
---|
2562 | ## DNSDB::groupName()
|
---|
2563 | # Return the group name based on a group ID
|
---|
2564 | # Takes a database handle and the group ID
|
---|
2565 | # Returns the group name or undef on failure
|
---|
2566 | sub groupName {
|
---|
2567 | $errstr = '';
|
---|
2568 | my $self = shift;
|
---|
2569 | my $dbh = $self->{dbh};
|
---|
2570 | my $groupid = shift;
|
---|
2571 | my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
|
---|
2572 | $sth->execute($groupid);
|
---|
2573 | my ($groupname) = $sth->fetchrow_array();
|
---|
2574 | $errstr = $DBI::errstr if !$groupname;
|
---|
2575 | return $groupname if $groupname;
|
---|
2576 | } # end groupName
|
---|
2577 |
|
---|
2578 |
|
---|
2579 | ## DNSDB::getGroupCount()
|
---|
2580 | # Get count of subgroups in group or groups
|
---|
2581 | # Takes a database handle and hash containing:
|
---|
2582 | # - the "current" group
|
---|
2583 | # - an array of "acceptable" groups
|
---|
2584 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
2585 | # Returns an integer count of the resulting group list.
|
---|
2586 | sub getGroupCount {
|
---|
2587 | my $self = shift;
|
---|
2588 | my $dbh = $self->{dbh};
|
---|
2589 |
|
---|
2590 | my %args = @_;
|
---|
2591 |
|
---|
2592 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
2593 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
2594 | $errstr = "Bad or missing curgroup argument";
|
---|
2595 | return;
|
---|
2596 | }
|
---|
2597 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
2598 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
2599 | $errstr = "Bad childlist argument";
|
---|
2600 | return;
|
---|
2601 | }
|
---|
2602 |
|
---|
2603 | my @filterargs;
|
---|
2604 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
2605 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
2606 | push @filterargs, $args{filter} if $args{filter};
|
---|
2607 |
|
---|
2608 | my $sql = "SELECT count(*) FROM groups ".
|
---|
2609 | "WHERE parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
2610 | ($args{startwith} ? " AND group_name ~* ?" : '').
|
---|
2611 | ($args{filter} ? " AND group_name ~* ?" : '');
|
---|
2612 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
2613 | $errstr = $dbh->errstr if !$count;
|
---|
2614 | return $count;
|
---|
2615 | } # end getGroupCount
|
---|
2616 |
|
---|
2617 |
|
---|
2618 | ## DNSDB::getGroupList()
|
---|
2619 | # Get a list of sub^n-groups in the specified group(s)
|
---|
2620 | # Takes the same arguments as getGroupCount() above
|
---|
2621 | # Returns an arrayref containing hashrefs suitable for feeding straight to HTML::Template
|
---|
2622 | sub getGroupList {
|
---|
2623 | my $self = shift;
|
---|
2624 | my $dbh = $self->{dbh};
|
---|
2625 |
|
---|
2626 | my %args = @_;
|
---|
2627 |
|
---|
2628 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
2629 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
2630 | $errstr = "Bad or missing curgroup argument";
|
---|
2631 | return;
|
---|
2632 | }
|
---|
2633 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
2634 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
2635 | $errstr = "Bad childlist argument";
|
---|
2636 | return;
|
---|
2637 | }
|
---|
2638 |
|
---|
2639 | my @filterargs;
|
---|
2640 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
2641 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
2642 | push @filterargs, $args{filter} if $args{filter};
|
---|
2643 |
|
---|
2644 | # protection against bad or missing arguments
|
---|
2645 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
2646 | $args{sortby} = 'group' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
2647 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
2648 |
|
---|
2649 | # munge sortby for columns in database
|
---|
2650 | $args{sortby} = 'g.group_name' if $args{sortby} eq 'group';
|
---|
2651 | $args{sortby} = 'g2.group_name' if $args{sortby} eq 'parent';
|
---|
2652 |
|
---|
2653 | my $sql = q(SELECT g.group_id AS groupid, g.group_name AS groupname, g2.group_name AS pgroup
|
---|
2654 | FROM groups g
|
---|
2655 | INNER JOIN groups g2 ON g2.group_id=g.parent_group_id
|
---|
2656 | ).
|
---|
2657 | " WHERE g.parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
2658 | ($args{startwith} ? " AND g.group_name ~* ?" : '').
|
---|
2659 | ($args{filter} ? " AND g.group_name ~* ?" : '').
|
---|
2660 | " GROUP BY g.group_id, g.group_name, g2.group_name ".
|
---|
2661 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
2662 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
2663 | my $glist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
2664 | $errstr = $dbh->errstr if !$glist;
|
---|
2665 |
|
---|
2666 | # LEFT JOINs make the result set balloon beyond sanity just to include counts;
|
---|
2667 | # this means there's lots of crunching needed to trim the result set back down.
|
---|
2668 | # So instead we track the order of the groups, and push the counts into the
|
---|
2669 | # arrayref result separately.
|
---|
2670 | ##fixme: put this whole sub in a transaction? might be
|
---|
2671 | # needed for accurate results on very busy systems.
|
---|
2672 | ##fixme: large group lists need prepared statements?
|
---|
2673 | #my $ucsth = $dbh->prepare("SELECT count(*) FROM users WHERE group_id=?");
|
---|
2674 | #my $dcsth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
|
---|
2675 | #my $rcsth = $dbh->prepare("SELECT count(*) FROM revzones WHERE group_id=?");
|
---|
2676 | foreach (@{$glist}) {
|
---|
2677 | my ($ucnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($$_{groupid}));
|
---|
2678 | $$_{nusers} = $ucnt;
|
---|
2679 | my ($dcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($$_{groupid}));
|
---|
2680 | $$_{ndomains} = $dcnt;
|
---|
2681 | my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($$_{groupid}));
|
---|
2682 | $$_{nrevzones} = $rcnt;
|
---|
2683 | }
|
---|
2684 |
|
---|
2685 | return $glist;
|
---|
2686 | } # end getGroupList
|
---|
2687 |
|
---|
2688 |
|
---|
2689 | ## DNSDB::groupID()
|
---|
2690 | # Return the group ID based on the group name
|
---|
2691 | # Takes a database handle and the group name
|
---|
2692 | # Returns the group ID or undef on failure
|
---|
2693 | sub groupID {
|
---|
2694 | $errstr = '';
|
---|
2695 | my $self = shift;
|
---|
2696 | my $dbh = $self->{dbh};
|
---|
2697 | my $group = shift;
|
---|
2698 | my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($group) );
|
---|
2699 | $errstr = $DBI::errstr if !$grpid;
|
---|
2700 | return $grpid if $grpid;
|
---|
2701 | } # end groupID()
|
---|
2702 |
|
---|
2703 |
|
---|
2704 | ## DNSDB::addUser()
|
---|
2705 | # Add a user.
|
---|
2706 | # Takes a DB handle, username, group ID, password, state (active/inactive).
|
---|
2707 | # Optionally accepts:
|
---|
2708 | # user type (user/admin) - defaults to user
|
---|
2709 | # permissions string - defaults to inherit from group
|
---|
2710 | # three valid forms:
|
---|
2711 | # i - Inherit permissions
|
---|
2712 | # c:<user_id> - Clone permissions from <user_id>
|
---|
2713 | # C:<permission list> - Set these specific permissions
|
---|
2714 | # first name - defaults to username
|
---|
2715 | # last name - defaults to blank
|
---|
2716 | # phone - defaults to blank (could put other data within column def)
|
---|
2717 | # Returns (OK,<uid>) on success, (FAIL,<message>) on failure
|
---|
2718 | sub addUser {
|
---|
2719 | $errstr = '';
|
---|
2720 | my $self = shift;
|
---|
2721 | my $dbh = $self->{dbh};
|
---|
2722 | my $username = shift;
|
---|
2723 | my $group = shift;
|
---|
2724 | my $pass = shift;
|
---|
2725 | my $state = shift;
|
---|
2726 |
|
---|
2727 | return ('FAIL', "Missing one or more required entries") if !defined($state);
|
---|
2728 | return ('FAIL', "Username must not be blank") if !$username;
|
---|
2729 |
|
---|
2730 | # Munge in some alternate state values
|
---|
2731 | $state = 1 if $state =~ /^active$/;
|
---|
2732 | $state = 1 if $state =~ /^on$/;
|
---|
2733 | $state = 0 if $state =~ /^inactive$/;
|
---|
2734 | $state = 0 if $state =~ /^off$/;
|
---|
2735 |
|
---|
2736 | my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
|
---|
2737 |
|
---|
2738 | my $permstring = shift || 'i'; # default is to inhert permissions from group
|
---|
2739 |
|
---|
2740 | my $fname = shift || $username;
|
---|
2741 | my $lname = shift || '';
|
---|
2742 | my $phone = shift || ''; # not going format-check
|
---|
2743 |
|
---|
2744 | my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
|
---|
2745 | my $user_id;
|
---|
2746 |
|
---|
2747 | # quick check to start to see if we've already got one
|
---|
2748 | $sth->execute($username);
|
---|
2749 | ($user_id) = $sth->fetchrow_array;
|
---|
2750 |
|
---|
2751 | return ('FAIL', "User already exists") if $user_id;
|
---|
2752 |
|
---|
2753 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
2754 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
2755 | local $dbh->{AutoCommit} = 0;
|
---|
2756 | local $dbh->{RaiseError} = 1;
|
---|
2757 |
|
---|
2758 | # Wrap all the SQL in a transaction
|
---|
2759 | eval {
|
---|
2760 | # insert the user... note we set inherited perms by default since
|
---|
2761 | # it's simple and cleans up some other bits of state
|
---|
2762 | my $sth = $dbh->prepare("INSERT INTO users ".
|
---|
2763 | "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
|
---|
2764 | "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
|
---|
2765 | $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);
|
---|
2766 |
|
---|
2767 | # get the ID...
|
---|
2768 | ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");
|
---|
2769 |
|
---|
2770 | # Permissions! Gotta set'em all!
|
---|
2771 | die "Invalid permission string $permstring\n"
|
---|
2772 | if $permstring !~ /^(?:
|
---|
2773 | i # inherit
|
---|
2774 | |c:\d+ # clone
|
---|
2775 | # custom. no, the leading , is not a typo
|
---|
2776 | |C:(?:,(?:group|user|domain|record|location|self)_(?:edit|create|delete|locchg|view))*
|
---|
2777 | )$/x;
|
---|
2778 | # bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
|
---|
2779 | if ($permstring ne 'i') {
|
---|
2780 | # for cloned or custom permissions, we have to create a new permissions entry.
|
---|
2781 | my $clonesrc = $group;
|
---|
2782 | if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
|
---|
2783 | $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
|
---|
2784 | "SELECT $permlist,? FROM permissions WHERE permission_id=".
|
---|
2785 | "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
|
---|
2786 | undef, ($user_id,$clonesrc) );
|
---|
2787 | $dbh->do("UPDATE users SET permission_id=".
|
---|
2788 | "(SELECT permission_id FROM permissions WHERE user_id=?) ".
|
---|
2789 | "WHERE user_id=?", undef, ($user_id, $user_id) );
|
---|
2790 | }
|
---|
2791 | if ($permstring =~ /^C:/) {
|
---|
2792 | # finally for custom permissions, we set the passed-in permissions (and unset
|
---|
2793 | # any that might have been brought in by the clone operation above)
|
---|
2794 | my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
|
---|
2795 | undef, ($user_id) );
|
---|
2796 | foreach (@permtypes) {
|
---|
2797 | if ($permstring =~ /,$_/) {
|
---|
2798 | $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
|
---|
2799 | } else {
|
---|
2800 | $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
|
---|
2801 | }
|
---|
2802 | }
|
---|
2803 | }
|
---|
2804 |
|
---|
2805 | $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
|
---|
2806 |
|
---|
2807 | ##fixme: add another table to hold name/email for log table?
|
---|
2808 |
|
---|
2809 | $self->_log(group_id => $group, entry => "Added user $username ($fname $lname)");
|
---|
2810 | # once we get here, we should have suceeded.
|
---|
2811 | $dbh->commit;
|
---|
2812 | }; # end eval
|
---|
2813 |
|
---|
2814 | if ($@) {
|
---|
2815 | my $msg = $@;
|
---|
2816 | eval { $dbh->rollback; };
|
---|
2817 | if ($self->{log_failures}) {
|
---|
2818 | $self->_log(group_id => $group, entry => "Error adding user $username: $msg");
|
---|
2819 | $dbh->commit; # since we enabled transactions earlier
|
---|
2820 | }
|
---|
2821 | return ('FAIL',"Error adding user $username: $msg");
|
---|
2822 | }
|
---|
2823 |
|
---|
2824 | return ('OK',"User $username ($fname $lname) added");
|
---|
2825 | } # end addUser
|
---|
2826 |
|
---|
2827 |
|
---|
2828 | ## DNSDB::getUserCount()
|
---|
2829 | # Get count of users in group
|
---|
2830 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
2831 | # - a reference list of secondary groups
|
---|
2832 | # - a filter string
|
---|
2833 | # - a "Starts with" string
|
---|
2834 | sub getUserCount {
|
---|
2835 | my $self = shift;
|
---|
2836 | my $dbh = $self->{dbh};
|
---|
2837 |
|
---|
2838 | my %args = @_;
|
---|
2839 |
|
---|
2840 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
2841 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
2842 | $errstr = "Bad or missing curgroup argument";
|
---|
2843 | return;
|
---|
2844 | }
|
---|
2845 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
2846 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
2847 | $errstr = "Bad childlist argument";
|
---|
2848 | return;
|
---|
2849 | }
|
---|
2850 |
|
---|
2851 | my @filterargs;
|
---|
2852 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
2853 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
2854 | push @filterargs, $args{filter} if $args{filter};
|
---|
2855 |
|
---|
2856 | my $sql = "SELECT count(*) FROM users ".
|
---|
2857 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
2858 | ($args{startwith} ? " AND username ~* ?" : '').
|
---|
2859 | ($args{filter} ? " AND username ~* ?" : '');
|
---|
2860 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
2861 | $errstr = $dbh->errstr if !$count;
|
---|
2862 | return $count;
|
---|
2863 | } # end getUserCount()
|
---|
2864 |
|
---|
2865 |
|
---|
2866 | ## DNSDB::getUserList()
|
---|
2867 | # Get list of users
|
---|
2868 | # Takes the same arguments as getUserCount() above, plus optional:
|
---|
2869 | # - sort field
|
---|
2870 | # - sort order
|
---|
2871 | # - offset/return-all-everything flag (defaults to $perpage records)
|
---|
2872 | sub getUserList {
|
---|
2873 | my $self = shift;
|
---|
2874 | my $dbh = $self->{dbh};
|
---|
2875 |
|
---|
2876 | my %args = @_;
|
---|
2877 |
|
---|
2878 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
2879 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
2880 | $errstr = "Bad or missing curgroup argument";
|
---|
2881 | return;
|
---|
2882 | }
|
---|
2883 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
2884 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
2885 | $errstr = "Bad childlist argument";
|
---|
2886 | return;
|
---|
2887 | }
|
---|
2888 |
|
---|
2889 | my @filterargs;
|
---|
2890 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
2891 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
2892 | push @filterargs, $args{filter} if $args{filter};
|
---|
2893 |
|
---|
2894 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
2895 | my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
2896 | fname => 'fname');
|
---|
2897 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
2898 |
|
---|
2899 | # protection against bad or missing arguments
|
---|
2900 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
2901 | $args{sortby} = 'u.username' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
2902 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
2903 |
|
---|
2904 | my $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ".
|
---|
2905 | "FROM users u ".
|
---|
2906 | "INNER JOIN groups g ON u.group_id=g.group_id ".
|
---|
2907 | "WHERE u.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
2908 | ($args{startwith} ? " AND u.username ~* ?" : '').
|
---|
2909 | ($args{filter} ? " AND u.username ~* ?" : '').
|
---|
2910 | " AND NOT u.type = 'R' ".
|
---|
2911 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
2912 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
2913 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
2914 | $errstr = $dbh->errstr if !$ulist;
|
---|
2915 | return $ulist;
|
---|
2916 | } # end getUserList()
|
---|
2917 |
|
---|
2918 |
|
---|
2919 | ## DNSDB::getUserDropdown()
|
---|
2920 | # Get a list of usernames for use in a dropdown menu.
|
---|
2921 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
2922 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
2923 | sub getUserDropdown {
|
---|
2924 | my $self = shift;
|
---|
2925 | my $dbh = $self->{dbh};
|
---|
2926 | my $grp = shift;
|
---|
2927 | my $sel = shift || 0;
|
---|
2928 |
|
---|
2929 | my $sth = $dbh->prepare("SELECT username,user_id FROM users WHERE group_id=?");
|
---|
2930 | $sth->execute($grp);
|
---|
2931 |
|
---|
2932 | my @userlist;
|
---|
2933 | while (my ($username,$uid) = $sth->fetchrow_array) {
|
---|
2934 | my %row = (
|
---|
2935 | username => $username,
|
---|
2936 | uid => $uid,
|
---|
2937 | selected => ($sel == $uid ? 1 : 0)
|
---|
2938 | );
|
---|
2939 | push @userlist, \%row;
|
---|
2940 | }
|
---|
2941 | return \@userlist;
|
---|
2942 | } # end getUserDropdown()
|
---|
2943 |
|
---|
2944 |
|
---|
2945 | ## DNSDB:: updateUser()
|
---|
2946 | # Update general data about user
|
---|
2947 | sub updateUser {
|
---|
2948 | my $self = shift;
|
---|
2949 | my $dbh = $self->{dbh};
|
---|
2950 |
|
---|
2951 | ##fixme: tweak calling convention so that we can update any given bit of data
|
---|
2952 | my $uid = shift;
|
---|
2953 | my $username = shift;
|
---|
2954 | my $group = shift;
|
---|
2955 | my $pass = shift;
|
---|
2956 | my $state = shift;
|
---|
2957 | my $type = shift || 'u';
|
---|
2958 | my $fname = shift || $username;
|
---|
2959 | my $lname = shift || '';
|
---|
2960 | my $phone = shift || ''; # not going format-check
|
---|
2961 |
|
---|
2962 | my $resultmsg = '';
|
---|
2963 |
|
---|
2964 | # Munge in some alternate state values
|
---|
2965 | $state = 1 if $state =~ /^active$/;
|
---|
2966 | $state = 1 if $state =~ /^on$/;
|
---|
2967 | $state = 0 if $state =~ /^inactive$/;
|
---|
2968 | $state = 0 if $state =~ /^off$/;
|
---|
2969 |
|
---|
2970 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
2971 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
2972 | local $dbh->{AutoCommit} = 0;
|
---|
2973 | local $dbh->{RaiseError} = 1;
|
---|
2974 |
|
---|
2975 | my $sth;
|
---|
2976 |
|
---|
2977 | # Password can be left blank; if so we assume there's one on file.
|
---|
2978 | # Actual blank passwords are bad, mm'kay?
|
---|
2979 | if (!$pass) {
|
---|
2980 | ($pass) = $dbh->selectrow_array("SELECT password FROM users WHERE user_id=?", undef, ($uid));
|
---|
2981 | } else {
|
---|
2982 | $pass = unix_md5_crypt($pass);
|
---|
2983 | }
|
---|
2984 |
|
---|
2985 | eval {
|
---|
2986 | $dbh->do("UPDATE users SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?".
|
---|
2987 | " WHERE user_id=?", undef, ($username, $pass, $fname, $lname, $phone, $type, $state, $uid));
|
---|
2988 | $resultmsg = "Updated user info for $username ($fname $lname)";
|
---|
2989 | $self->_log(group_id => $group, entry => $resultmsg);
|
---|
2990 | $dbh->commit;
|
---|
2991 | };
|
---|
2992 | if ($@) {
|
---|
2993 | my $msg = $@;
|
---|
2994 | eval { $dbh->rollback; };
|
---|
2995 | if ($self->{log_failures}) {
|
---|
2996 | $self->_log(group_id => $group, entry => "Error updating user $username: $msg");
|
---|
2997 | $dbh->commit; # since we enabled transactions earlier
|
---|
2998 | }
|
---|
2999 | return ('FAIL',"Error updating user $username: $msg");
|
---|
3000 | }
|
---|
3001 |
|
---|
3002 | return ('OK',$resultmsg);
|
---|
3003 | } # end updateUser()
|
---|
3004 |
|
---|
3005 |
|
---|
3006 | ## DNSDB::delUser()
|
---|
3007 | # Delete a user.
|
---|
3008 | # Takes a database handle and user ID
|
---|
3009 | # Returns a success/failure code and matching message
|
---|
3010 | sub delUser {
|
---|
3011 | my $self = shift;
|
---|
3012 | my $dbh = $self->{dbh};
|
---|
3013 | my $userid = shift;
|
---|
3014 |
|
---|
3015 | return ('FAIL',"Bad userid") if !defined($userid);
|
---|
3016 |
|
---|
3017 | my $userdata = $self->getUserData($userid);
|
---|
3018 |
|
---|
3019 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
3020 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
3021 | local $dbh->{AutoCommit} = 0;
|
---|
3022 | local $dbh->{RaiseError} = 1;
|
---|
3023 |
|
---|
3024 | eval {
|
---|
3025 | $dbh->do("DELETE FROM users WHERE user_id=?", undef, ($userid));
|
---|
3026 | $self->_log(group_id => $userdata->{group_id},
|
---|
3027 | entry => "Deleted user ID $userid/".$userdata->{username}.
|
---|
3028 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")");
|
---|
3029 | $dbh->commit;
|
---|
3030 | };
|
---|
3031 | if ($@) {
|
---|
3032 | my $msg = $@;
|
---|
3033 | eval { $dbh->rollback; };
|
---|
3034 | if ($self->{log_failures}) {
|
---|
3035 | $self->_log(group_id => $userdata->{group_id}, entry => "Error deleting user ID ".
|
---|
3036 | "$userid/".$userdata->{username}.": $msg");
|
---|
3037 | $dbh->commit;
|
---|
3038 | }
|
---|
3039 | return ('FAIL',"Error deleting user $userid/".$userdata->{username}.": $msg");
|
---|
3040 | }
|
---|
3041 |
|
---|
3042 | return ('OK',"Deleted user ".$userdata->{username}." (".$userdata->{firstname}." ".$userdata->{lastname}.")");
|
---|
3043 | } # end delUser
|
---|
3044 |
|
---|
3045 |
|
---|
3046 | ## DNSDB::userFullName()
|
---|
3047 | # Return a pretty string!
|
---|
3048 | # Takes a user_id and optional printf-ish string to indicate which pieces where:
|
---|
3049 | # %u for the username
|
---|
3050 | # %f for the first name
|
---|
3051 | # %l for the last name
|
---|
3052 | # All other text in the passed string will be left as-is.
|
---|
3053 | ##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
|
---|
3054 | sub userFullName {
|
---|
3055 | $errstr = '';
|
---|
3056 | my $self = shift;
|
---|
3057 | my $dbh = $self->{dbh};
|
---|
3058 | my $userid = shift;
|
---|
3059 | my $fullformat = shift || '%f %l (%u)';
|
---|
3060 | my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
|
---|
3061 | $sth->execute($userid);
|
---|
3062 | my ($uname,$fname,$lname) = $sth->fetchrow_array();
|
---|
3063 | $errstr = $DBI::errstr if !$uname;
|
---|
3064 |
|
---|
3065 | $fullformat =~ s/\%u/$uname/g;
|
---|
3066 | $fullformat =~ s/\%f/$fname/g;
|
---|
3067 | $fullformat =~ s/\%l/$lname/g;
|
---|
3068 |
|
---|
3069 | return $fullformat;
|
---|
3070 | } # end userFullName
|
---|
3071 |
|
---|
3072 |
|
---|
3073 | ## DNSDB::userStatus()
|
---|
3074 | # Sets and/or returns a user's status
|
---|
3075 | # Takes a database handle, user ID and optionally a status argument
|
---|
3076 | # Returns undef on errors.
|
---|
3077 | sub userStatus {
|
---|
3078 | my $self = shift;
|
---|
3079 | my $dbh = $self->{dbh};
|
---|
3080 | my $id = shift;
|
---|
3081 | my $newstatus = shift || 'mu';
|
---|
3082 |
|
---|
3083 | return undef if $id !~ /^\d+$/;
|
---|
3084 |
|
---|
3085 | my $userdata = $self->getUserData($id);
|
---|
3086 |
|
---|
3087 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
3088 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
3089 | local $dbh->{AutoCommit} = 0;
|
---|
3090 | local $dbh->{RaiseError} = 1;
|
---|
3091 |
|
---|
3092 | if ($newstatus ne 'mu') {
|
---|
3093 | # ooo, fun! let's see what we were passed for status
|
---|
3094 | eval {
|
---|
3095 | $newstatus = 0 if $newstatus eq 'useroff';
|
---|
3096 | $newstatus = 1 if $newstatus eq 'useron';
|
---|
3097 | $dbh->do("UPDATE users SET status=? WHERE user_id=?", undef, ($newstatus, $id));
|
---|
3098 |
|
---|
3099 | $resultstr = ($newstatus ? 'Enabled' : 'Disabled')." user ".$userdata->{username}.
|
---|
3100 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")";
|
---|
3101 |
|
---|
3102 | my %loghash;
|
---|
3103 | $loghash{group_id} = $self->parentID(id => $id, type => 'user');
|
---|
3104 | $loghash{entry} = $resultstr;
|
---|
3105 | $self->_log(%loghash);
|
---|
3106 |
|
---|
3107 | $dbh->commit;
|
---|
3108 | };
|
---|
3109 | if ($@) {
|
---|
3110 | my $msg = $@;
|
---|
3111 | eval { $dbh->rollback; };
|
---|
3112 | $resultstr = '';
|
---|
3113 | $errstr = $msg;
|
---|
3114 | ##fixme: failure logging?
|
---|
3115 | return;
|
---|
3116 | }
|
---|
3117 | }
|
---|
3118 |
|
---|
3119 | my ($status) = $dbh->selectrow_array("SELECT status FROM users WHERE user_id=?", undef, ($id));
|
---|
3120 | return $status;
|
---|
3121 | } # end userStatus()
|
---|
3122 |
|
---|
3123 |
|
---|
3124 | ## DNSDB::getUserData()
|
---|
3125 | # Get misc user data for display
|
---|
3126 | sub getUserData {
|
---|
3127 | my $self = shift;
|
---|
3128 | my $dbh = $self->{dbh};
|
---|
3129 | my $uid = shift;
|
---|
3130 |
|
---|
3131 | my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
|
---|
3132 | "FROM users WHERE user_id=?");
|
---|
3133 | $sth->execute($uid);
|
---|
3134 | return $sth->fetchrow_hashref();
|
---|
3135 | } # end getUserData()
|
---|
3136 |
|
---|
3137 |
|
---|
3138 | ## DNSDB::addLoc()
|
---|
3139 | # Add a new location.
|
---|
3140 | # Takes a database handle, group ID, short and long description, and a comma-separated
|
---|
3141 | # list of IP addresses.
|
---|
3142 | # Returns ('OK',<location>) on success, ('FAIL',<failmsg>) on failure
|
---|
3143 | sub addLoc {
|
---|
3144 | my $self = shift;
|
---|
3145 | my $dbh = $self->{dbh};
|
---|
3146 | my $grp = shift;
|
---|
3147 | my $shdesc = shift;
|
---|
3148 | my $comments = shift;
|
---|
3149 | my $iplist = shift;
|
---|
3150 |
|
---|
3151 | # $shdesc gets set to the generated location ID if possible, but these can be de-undefined here.
|
---|
3152 | $comments = '' if !$comments;
|
---|
3153 | $iplist = '' if !$iplist;
|
---|
3154 |
|
---|
3155 | my $loc;
|
---|
3156 |
|
---|
3157 | # Generate a location ID. This is, by spec, a two-character widget. We'll use [a-z][a-z]
|
---|
3158 | # for now; 676 locations should satisfy all but the largest of the huge networks.
|
---|
3159 | # Not sure whether these are case-sensitive, or what other rules might apply - in any case
|
---|
3160 | # the absolute maximum is 16K (256*256) since it's parsed by tinydns as a two-character field.
|
---|
3161 |
|
---|
3162 | # add just after "my $origloc = $loc;":
|
---|
3163 | # # These expand the possible space from 26^2 to 52^2 [* note in testing only 2052 were achieved],
|
---|
3164 | # # and wrap it around.
|
---|
3165 | # # Yes, they skip a couple of possibles. No, I don't care.
|
---|
3166 | # $loc = 'aA' if $loc eq 'zz';
|
---|
3167 | # $loc = 'Aa' if $loc eq 'zZ';
|
---|
3168 | # $loc = 'ZA' if $loc eq 'Zz';
|
---|
3169 | # $loc = 'aa' if $loc eq 'ZZ';
|
---|
3170 |
|
---|
3171 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
3172 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
3173 | local $dbh->{AutoCommit} = 0;
|
---|
3174 | local $dbh->{RaiseError} = 1;
|
---|
3175 |
|
---|
3176 | ##fixme: There is probably a far better way to do this. Sequential increments
|
---|
3177 | # are marginally less stupid that pure random generation though, and the existence
|
---|
3178 | # check makes sure we don't stomp on an imported one.
|
---|
3179 |
|
---|
3180 | eval {
|
---|
3181 | # Get the "last" location. Note this is the only use for loc_id, because selecting on location Does Funky Things
|
---|
3182 | ($loc) = $dbh->selectrow_array("SELECT location FROM locations ORDER BY loc_id DESC LIMIT 1");
|
---|
3183 | ($loc) = ($loc =~ /^(..)/) if $loc;
|
---|
3184 | my $origloc = $loc;
|
---|
3185 | $loc = 'aa' if !$loc;
|
---|
3186 | # Make a change...
|
---|
3187 | $loc++;
|
---|
3188 | # ... and keep changing if it exists
|
---|
3189 | while ($dbh->selectrow_array("SELECT count(*) FROM locations WHERE location LIKE ?", undef, ($loc.'%'))) {
|
---|
3190 | $loc++;
|
---|
3191 | ($loc) = ($loc =~ /^(..)/);
|
---|
3192 | die "too many locations in use, can't add another one\n" if $loc eq $origloc;
|
---|
3193 | ##fixme: really need to handle this case faster somehow
|
---|
3194 | #if $loc eq $origloc die "<thwap> bad admin: all locations used, your network is too fragmented";
|
---|
3195 | }
|
---|
3196 | # And now we should have a unique location. tinydns fundamentally limits the
|
---|
3197 | # number of these but there's no doc on what characters are valid.
|
---|
3198 | $shdesc = $loc if !$shdesc;
|
---|
3199 | $dbh->do("INSERT INTO locations (location, group_id, iplist, description, comments) VALUES (?,?,?,?,?)",
|
---|
3200 | undef, ($loc, $grp, $iplist, $shdesc, $comments) );
|
---|
3201 | $self->_log(entry => "Added location ($shdesc, '$iplist')");
|
---|
3202 | $dbh->commit;
|
---|
3203 | };
|
---|
3204 | if ($@) {
|
---|
3205 | my $msg = $@;
|
---|
3206 | eval { $dbh->rollback; };
|
---|
3207 | if ($self->{log_failures}) {
|
---|
3208 | $shdesc = $loc if !$shdesc;
|
---|
3209 | $self->_log(entry => "Failed adding location ($shdesc, '$iplist'): $msg");
|
---|
3210 | $dbh->commit;
|
---|
3211 | }
|
---|
3212 | return ('FAIL',$msg);
|
---|
3213 | }
|
---|
3214 |
|
---|
3215 | return ('OK',$loc);
|
---|
3216 | } # end addLoc()
|
---|
3217 |
|
---|
3218 |
|
---|
3219 | ## DNSDB::updateLoc()
|
---|
3220 | # Update details of a location.
|
---|
3221 | # Takes a database handle, location ID, group ID, short description,
|
---|
3222 | # long comments/notes, and comma/space-separated IP list
|
---|
3223 | # Returns a result code and message
|
---|
3224 | sub updateLoc {
|
---|
3225 | my $self = shift;
|
---|
3226 | my $dbh = $self->{dbh};
|
---|
3227 | my $loc = shift;
|
---|
3228 | my $grp = shift;
|
---|
3229 | my $shdesc = shift;
|
---|
3230 | my $comments = shift;
|
---|
3231 | my $iplist = shift;
|
---|
3232 |
|
---|
3233 | $shdesc = '' if !$shdesc;
|
---|
3234 | $comments = '' if !$comments;
|
---|
3235 | $iplist = '' if !$iplist;
|
---|
3236 |
|
---|
3237 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
3238 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
3239 | local $dbh->{AutoCommit} = 0;
|
---|
3240 | local $dbh->{RaiseError} = 1;
|
---|
3241 |
|
---|
3242 | my $oldloc = $self->getLoc($loc);
|
---|
3243 | my $okmsg = "Updated location (".$oldloc->{description}.", '".$oldloc->{iplist}."') to ($shdesc, '$iplist')";
|
---|
3244 |
|
---|
3245 | eval {
|
---|
3246 | $dbh->do("UPDATE locations SET group_id=?,iplist=?,description=?,comments=? WHERE location=?",
|
---|
3247 | undef, ($grp, $iplist, $shdesc, $comments, $loc) );
|
---|
3248 | $self->_log(entry => $okmsg);
|
---|
3249 | $dbh->commit;
|
---|
3250 | };
|
---|
3251 | if ($@) {
|
---|
3252 | my $msg = $@;
|
---|
3253 | eval { $dbh->rollback; };
|
---|
3254 | if ($self->{log_failures}) {
|
---|
3255 | $shdesc = $loc if !$shdesc;
|
---|
3256 | $self->_log(entry => "Failed updating location ($shdesc, '$iplist'): $msg");
|
---|
3257 | $dbh->commit;
|
---|
3258 | }
|
---|
3259 | return ('FAIL',$msg);
|
---|
3260 | }
|
---|
3261 |
|
---|
3262 | return ('OK',$okmsg);
|
---|
3263 | } # end updateLoc()
|
---|
3264 |
|
---|
3265 |
|
---|
3266 | ## DNSDB::delLoc()
|
---|
3267 | sub delLoc {
|
---|
3268 | my $self = shift;
|
---|
3269 | my $dbh = $self->{dbh};
|
---|
3270 | my $loc = shift;
|
---|
3271 |
|
---|
3272 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
3273 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
3274 | local $dbh->{AutoCommit} = 0;
|
---|
3275 | local $dbh->{RaiseError} = 1;
|
---|
3276 |
|
---|
3277 | my $oldloc = $self->getLoc($loc);
|
---|
3278 | my $olddesc = ($oldloc->{description} ? $oldloc->{description} : $loc);
|
---|
3279 | my $okmsg = "Deleted location ($olddesc, '".$oldloc->{iplist}."')";
|
---|
3280 |
|
---|
3281 | eval {
|
---|
3282 | # Check for records with this location first. Deleting a location without deleting records
|
---|
3283 | # tagged for that location will render them unpublished without other warning.
|
---|
3284 | my ($r) = $dbh->selectrow_array("SELECT record_id FROM records WHERE location=? LIMIT 1", undef, ($loc) );
|
---|
3285 | die "Records still exist in location $olddesc\n" if $r;
|
---|
3286 | $dbh->do("DELETE FROM locations WHERE location=?", undef, ($loc) );
|
---|
3287 | $self->_log(entry => $okmsg);
|
---|
3288 | $dbh->commit;
|
---|
3289 | };
|
---|
3290 | if ($@) {
|
---|
3291 | my $msg = $@;
|
---|
3292 | eval { $dbh->rollback; };
|
---|
3293 | if ($self->{log_failures}) {
|
---|
3294 | $self->_log(entry => "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
|
---|
3295 | $dbh->commit;
|
---|
3296 | }
|
---|
3297 | return ('FAIL', "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
|
---|
3298 | }
|
---|
3299 |
|
---|
3300 | return ('OK',$okmsg);
|
---|
3301 | } # end delLoc()
|
---|
3302 |
|
---|
3303 |
|
---|
3304 | ## DNSDB::getLoc()
|
---|
3305 | # Get details about a location/view
|
---|
3306 | # Takes a database handle and location ID.
|
---|
3307 | # Returns a reference to a hash containing the group ID, IP list, description, and comments/notes
|
---|
3308 | sub getLoc {
|
---|
3309 | my $self = shift;
|
---|
3310 | my $dbh = $self->{dbh};
|
---|
3311 | my $loc = shift;
|
---|
3312 |
|
---|
3313 | my $sth = $dbh->prepare("SELECT group_id,iplist,description,comments FROM locations WHERE location=?");
|
---|
3314 | $sth->execute($loc);
|
---|
3315 | return $sth->fetchrow_hashref();
|
---|
3316 | } # end getLoc()
|
---|
3317 |
|
---|
3318 |
|
---|
3319 | ## DNSDB::getLocCount()
|
---|
3320 | # Get count of locations/views
|
---|
3321 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
3322 | # - a reference list of secondary groups
|
---|
3323 | # - a filter string
|
---|
3324 | # - a "Starts with" string
|
---|
3325 | sub getLocCount {
|
---|
3326 | my $self = shift;
|
---|
3327 | my $dbh = $self->{dbh};
|
---|
3328 |
|
---|
3329 | my %args = @_;
|
---|
3330 |
|
---|
3331 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
3332 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
3333 | $errstr = "Bad or missing curgroup argument";
|
---|
3334 | return;
|
---|
3335 | }
|
---|
3336 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
3337 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
3338 | $errstr = "Bad childlist argument";
|
---|
3339 | return;
|
---|
3340 | }
|
---|
3341 |
|
---|
3342 | my @filterargs;
|
---|
3343 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
3344 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
3345 | push @filterargs, $args{filter} if $args{filter};
|
---|
3346 |
|
---|
3347 | my $sql = "SELECT count(*) FROM locations ".
|
---|
3348 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
3349 | ($args{startwith} ? " AND description ~* ?" : '').
|
---|
3350 | ($args{filter} ? " AND description ~* ?" : '');
|
---|
3351 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
3352 | $errstr = $dbh->errstr if !$count;
|
---|
3353 | return $count;
|
---|
3354 | } # end getLocCount()
|
---|
3355 |
|
---|
3356 |
|
---|
3357 | ## DNSDB::getLocList()
|
---|
3358 | sub getLocList {
|
---|
3359 | my $self = shift;
|
---|
3360 | my $dbh = $self->{dbh};
|
---|
3361 |
|
---|
3362 | my %args = @_;
|
---|
3363 |
|
---|
3364 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
3365 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
3366 | $errstr = "Bad or missing curgroup argument";
|
---|
3367 | return;
|
---|
3368 | }
|
---|
3369 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
3370 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
3371 | $errstr = "Bad childlist argument";
|
---|
3372 | return;
|
---|
3373 | }
|
---|
3374 |
|
---|
3375 | my @filterargs;
|
---|
3376 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
3377 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
3378 | push @filterargs, $args{filter} if $args{filter};
|
---|
3379 |
|
---|
3380 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
3381 | # my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
3382 | # fname => 'fname');
|
---|
3383 | # $args{sortby} = $sortmap{$args{sortby}};
|
---|
3384 |
|
---|
3385 | # protection against bad or missing arguments
|
---|
3386 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
3387 | $args{sortby} = 'l.description' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
3388 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
3389 |
|
---|
3390 | my $sql = "SELECT l.location, l.description, l.iplist, g.group_name ".
|
---|
3391 | "FROM locations l ".
|
---|
3392 | "INNER JOIN groups g ON l.group_id=g.group_id ".
|
---|
3393 | "WHERE l.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
3394 | ($args{startwith} ? " AND l.description ~* ?" : '').
|
---|
3395 | ($args{filter} ? " AND l.description ~* ?" : '').
|
---|
3396 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
3397 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
3398 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
3399 | $errstr = $dbh->errstr if !$ulist;
|
---|
3400 | return $ulist;
|
---|
3401 | } # end getLocList()
|
---|
3402 |
|
---|
3403 |
|
---|
3404 | ## DNSDB::getLocDropdown()
|
---|
3405 | # Get a list of location names for use in a dropdown menu.
|
---|
3406 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
3407 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
3408 | sub getLocDropdown {
|
---|
3409 | my $self = shift;
|
---|
3410 | my $dbh = $self->{dbh};
|
---|
3411 | my $grp = shift;
|
---|
3412 | my $sel = shift || '';
|
---|
3413 |
|
---|
3414 | my $sth = $dbh->prepare(qq(
|
---|
3415 | SELECT description,location FROM locations
|
---|
3416 | WHERE group_id=?
|
---|
3417 | ORDER BY description
|
---|
3418 | ) );
|
---|
3419 | $sth->execute($grp);
|
---|
3420 |
|
---|
3421 | my @loclist;
|
---|
3422 | push @loclist, { locname => "(Default/All)", loc => '', selected => ($sel ? 0 : ($sel eq '' ? 1 : 0)) };
|
---|
3423 | while (my ($locname, $loc) = $sth->fetchrow_array) {
|
---|
3424 | my %row = (
|
---|
3425 | locname => $locname,
|
---|
3426 | loc => $loc,
|
---|
3427 | selected => ($sel eq $loc ? 1 : 0)
|
---|
3428 | );
|
---|
3429 | push @loclist, \%row;
|
---|
3430 | }
|
---|
3431 | return \@loclist;
|
---|
3432 | } # end getLocDropdown()
|
---|
3433 |
|
---|
3434 |
|
---|
3435 | ## DNSDB::getSOA()
|
---|
3436 | # Return all suitable fields from an SOA record in separate elements of a hash
|
---|
3437 | # Takes a database handle, default/live flag, domain/reverse flag, and parent ID
|
---|
3438 | sub getSOA {
|
---|
3439 | $errstr = '';
|
---|
3440 | my $self = shift;
|
---|
3441 | my $dbh = $self->{dbh};
|
---|
3442 | my $def = shift;
|
---|
3443 | my $rev = shift;
|
---|
3444 | my $id = shift;
|
---|
3445 |
|
---|
3446 | # (ab)use distance and weight columns to store SOA data? can't for default_rev_records...
|
---|
3447 | # - should really attach serial to the zone parent somewhere
|
---|
3448 |
|
---|
3449 | my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev).
|
---|
3450 | " WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}";
|
---|
3451 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
3452 | return if !$ret;
|
---|
3453 | ##fixme: stick a flag somewhere if the record doesn't exist. by the API, this is an impossible case, but...
|
---|
3454 |
|
---|
3455 | ($ret->{contact},$ret->{prins}) = split /:/, $ret->{host};
|
---|
3456 | delete $ret->{host};
|
---|
3457 | ($ret->{refresh},$ret->{retry},$ret->{expire},$ret->{minttl}) = split /:/, $ret->{val};
|
---|
3458 | delete $ret->{val};
|
---|
3459 |
|
---|
3460 | return $ret;
|
---|
3461 | } # end getSOA()
|
---|
3462 |
|
---|
3463 |
|
---|
3464 | ## DNSDB::updateSOA()
|
---|
3465 | # Update the specified SOA record
|
---|
3466 | # Takes a database handle, default/live flag, forward/reverse flag, and SOA data hash
|
---|
3467 | # Returns a two-element list with a result code and message
|
---|
3468 | sub updateSOA {
|
---|
3469 | my $self = shift;
|
---|
3470 | my $dbh = $self->{dbh};
|
---|
3471 | my $defrec = shift;
|
---|
3472 | my $revrec = shift;
|
---|
3473 |
|
---|
3474 | my %soa = @_;
|
---|
3475 |
|
---|
3476 | my $oldsoa = $self->getSOA($defrec, $revrec, $soa{id});
|
---|
3477 |
|
---|
3478 | my $msg;
|
---|
3479 | my %logdata;
|
---|
3480 | if ($defrec eq 'n') {
|
---|
3481 | $logdata{domain_id} = $soa{id} if $revrec eq 'n';
|
---|
3482 | $logdata{rdns_id} = $soa{id} if $revrec eq 'y';
|
---|
3483 | $logdata{group_id} = $self->parentID(id => $soa{id}, revrec => $revrec,
|
---|
3484 | type => ($revrec eq 'n' ? 'domain' : 'revzone') );
|
---|
3485 | } else {
|
---|
3486 | $logdata{group_id} = $soa{id};
|
---|
3487 | }
|
---|
3488 | my $parname = ($defrec eq 'y' ? $self->groupName($soa{id}) :
|
---|
3489 | ($revrec eq 'n' ? $self->domainName($soa{id}) : $self->revName($soa{id})) );
|
---|
3490 |
|
---|
3491 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
3492 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
3493 | local $dbh->{AutoCommit} = 0;
|
---|
3494 | local $dbh->{RaiseError} = 1;
|
---|
3495 |
|
---|
3496 | eval {
|
---|
3497 | my $sql = "UPDATE "._rectable($defrec, $revrec)." SET host=?, val=?, ttl=? WHERE record_id=? AND type=6";
|
---|
3498 | $dbh->do($sql, undef, ("$soa{contact}:$soa{prins}", "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}",
|
---|
3499 | $soa{ttl}, $oldsoa->{record_id}) );
|
---|
3500 | $msg = "Updated ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse ' : 'default ') : '').
|
---|
3501 | "SOA for $parname: ".
|
---|
3502 | "(ns $oldsoa->{prins}, contact $oldsoa->{contact}, refresh $oldsoa->{refresh},".
|
---|
3503 | " retry $oldsoa->{retry}, expire $oldsoa->{expire}, minTTL $oldsoa->{minttl}, TTL $oldsoa->{ttl}) to ".
|
---|
3504 | "(ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
|
---|
3505 | " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})";
|
---|
3506 |
|
---|
3507 | $logdata{entry} = $msg;
|
---|
3508 | $self->_log(%logdata);
|
---|
3509 |
|
---|
3510 | $dbh->commit;
|
---|
3511 | };
|
---|
3512 | if ($@) {
|
---|
3513 | $msg = $@;
|
---|
3514 | eval { $dbh->rollback; };
|
---|
3515 | $logdata{entry} = "Error updating ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse zone ' : 'default ') : '').
|
---|
3516 | "SOA record for $parname: $msg";
|
---|
3517 | if ($self->{log_failures}) {
|
---|
3518 | $self->_log(%logdata);
|
---|
3519 | $dbh->commit;
|
---|
3520 | }
|
---|
3521 | return ('FAIL', $logdata{entry});
|
---|
3522 | } else {
|
---|
3523 | return ('OK', $msg);
|
---|
3524 | }
|
---|
3525 | } # end updateSOA()
|
---|
3526 |
|
---|
3527 |
|
---|
3528 | ## DNSDB::getRecLine()
|
---|
3529 | # Return all data fields for a zone record in separate elements of a hash
|
---|
3530 | # Takes a database handle, default/live flag, forward/reverse flag, and record ID
|
---|
3531 | sub getRecLine {
|
---|
3532 | $errstr = '';
|
---|
3533 | my $self = shift;
|
---|
3534 | my $dbh = $self->{dbh};
|
---|
3535 | my $defrec = shift;
|
---|
3536 | my $revrec = shift;
|
---|
3537 | my $id = shift;
|
---|
3538 |
|
---|
3539 | ##fixme: do we need a knob to twist to switch between unix epoch and postgres time string?
|
---|
3540 | my $sql = "SELECT record_id,host,type,val,ttl".
|
---|
3541 | ($defrec eq 'n' ? ',location' : '').
|
---|
3542 | ($revrec eq 'n' ? ',distance,weight,port' : '').
|
---|
3543 | (($defrec eq 'y') ? ',group_id FROM ' : ',domain_id,rdns_id,stamp,stamp < now() AS ispast,expires,stampactive FROM ').
|
---|
3544 | _rectable($defrec,$revrec)." WHERE record_id=?";
|
---|
3545 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
3546 |
|
---|
3547 | if ($dbh->err) {
|
---|
3548 | $errstr = $DBI::errstr;
|
---|
3549 | return undef;
|
---|
3550 | }
|
---|
3551 |
|
---|
3552 | if (!$ret) {
|
---|
3553 | $errstr = "No such record";
|
---|
3554 | return undef;
|
---|
3555 | }
|
---|
3556 |
|
---|
3557 | # explicitly set a parent id
|
---|
3558 | if ($defrec eq 'y') {
|
---|
3559 | $ret->{parid} = $ret->{group_id};
|
---|
3560 | } else {
|
---|
3561 | $ret->{parid} = (($revrec eq 'n') ? $ret->{domain_id} : $ret->{rdns_id});
|
---|
3562 | # and a secondary if we have a custom type that lives in both a forward and reverse zone
|
---|
3563 | $ret->{secid} = (($revrec eq 'y') ? $ret->{domain_id} : $ret->{rdns_id}) if $ret->{type} > 65279;
|
---|
3564 | }
|
---|
3565 | $ret->{address} = $ret->{val}; # because.
|
---|
3566 |
|
---|
3567 | return $ret;
|
---|
3568 | }
|
---|
3569 |
|
---|
3570 |
|
---|
3571 | ##fixme: should use above (getRecLine()) to get lines for below?
|
---|
3572 | ## DNSDB::getRecList()
|
---|
3573 | # Return records for a group or zone
|
---|
3574 | # Takes a default/live flag, group or zone ID, start,
|
---|
3575 | # number of records, sort field, and sort order
|
---|
3576 | # Returns a reference to an array of hashes
|
---|
3577 | sub getRecList {
|
---|
3578 | $errstr = '';
|
---|
3579 | my $self = shift;
|
---|
3580 | my $dbh = $self->{dbh};
|
---|
3581 |
|
---|
3582 | my %args = @_;
|
---|
3583 |
|
---|
3584 | my @filterargs;
|
---|
3585 |
|
---|
3586 | push @filterargs, $args{filter} if $args{filter};
|
---|
3587 |
|
---|
3588 | # protection against bad or missing arguments
|
---|
3589 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
3590 | my $defsort;
|
---|
3591 | $defsort = 'host' if $args{revrec} eq 'n'; # default sort by host on domain record list
|
---|
3592 | $defsort = 'val' if $args{revrec} eq 'y'; # default sort by IP on revzone record list
|
---|
3593 | $args{sortby} = '' if !$args{sortby};
|
---|
3594 | $args{sortby} = $defsort if !$args{revrec};
|
---|
3595 | $args{sortby} = $defsort if $args{sortby} !~ /^[\w_,.]+$/;
|
---|
3596 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
3597 | my $perpage = ($args{nrecs} ? $args{nrecs} : $self->{perpage});
|
---|
3598 |
|
---|
3599 | # sort reverse zones on IP, correctly
|
---|
3600 | # do other fiddling with $args{sortby} while we're at it.
|
---|
3601 | $args{sortby} = "r.$args{sortby}";
|
---|
3602 | $args{sortby} = 'CAST (r.val AS inet)'
|
---|
3603 | if $args{revrec} eq 'y' && $args{defrec} eq 'n' && $args{sortby} eq 'r.val';
|
---|
3604 | $args{sortby} = 't.alphaorder' if $args{sortby} eq 'r.type';
|
---|
3605 |
|
---|
3606 | my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.ttl";
|
---|
3607 | $sql .= ",l.description AS locname" if $args{defrec} eq 'n';
|
---|
3608 | $sql .= ",r.distance,r.weight,r.port" if $args{revrec} eq 'n';
|
---|
3609 | $sql .= " FROM "._rectable($args{defrec},$args{revrec})." r ";
|
---|
3610 |
|
---|
3611 | # whee! multisort means just passing comma-separated fields in sortby!
|
---|
3612 | my $newsort = '';
|
---|
3613 | foreach my $sf (split /,/, $order) {
|
---|
3614 | $sf = "r.$sf";
|
---|
3615 | $sf =~ s/r\.type/t.alphaorder/;
|
---|
3616 | $newsort .= ",$sf";
|
---|
3617 | }
|
---|
3618 | $newsort =~ s/^,//;
|
---|
3619 |
|
---|
3620 | ##fixme: do we need a knob to twist to switch from unix epoch to postgres time string?
|
---|
3621 | my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.ttl";
|
---|
3622 | $sql .= ",l.description AS locname,stamp,r.stamp < now() AS ispast,r.expires,r.stampactive"
|
---|
3623 | if $args{defrec} eq 'n';
|
---|
3624 | $sql .= ",r.distance,r.weight,r.port" if $args{revrec} eq 'n';
|
---|
3625 | $sql .= " FROM "._rectable($args{defrec},$args{revrec})." r ";
|
---|
3626 | $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
|
---|
3627 | $sql .= "LEFT JOIN locations l ON r.location=l.location " if $args{defrec} eq 'n';
|
---|
3628 | $sql .= "WHERE "._recparent($args{defrec},$args{revrec})." = ?";
|
---|
3629 | $sql .= " AND NOT r.type=$reverse_typemap{SOA}";
|
---|
3630 | $sql .= " AND (r.host ~* ? OR r.val ~* ?)" if $args{filter};
|
---|
3631 | $sql .= " ORDER BY $args{sortby} $args{sortorder}";
|
---|
3632 | # ensure consistent ordering by sorting on record_id too
|
---|
3633 | $sql .= ", record_id $args{sortorder}";
|
---|
3634 | $sql .= ($args{offset} eq 'all' ? '' : " LIMIT $perpage OFFSET ".$args{offset}*$perpage);
|
---|
3635 |
|
---|
3636 | my @bindvars = ($args{id});
|
---|
3637 | push @bindvars, ($args{filter},$args{filter}) if $args{filter};
|
---|
3638 |
|
---|
3639 | my $ret = $dbh->selectall_arrayref($sql, { Slice => {} }, (@bindvars) );
|
---|
3640 | $errstr = "Error retrieving records: ".$dbh->errstr if !$ret;
|
---|
3641 |
|
---|
3642 | return $ret;
|
---|
3643 | } # end getRecList()
|
---|
3644 |
|
---|
3645 |
|
---|
3646 | ## DNSDB::getRecCount()
|
---|
3647 | # Return count of non-SOA records in zone (or default records in a group)
|
---|
3648 | # Takes a database handle, default/live flag, reverse/forward flag, group/domain ID,
|
---|
3649 | # and optional filtering modifier
|
---|
3650 | # Returns the count
|
---|
3651 | sub getRecCount {
|
---|
3652 | my $self = shift;
|
---|
3653 | my $dbh = $self->{dbh};
|
---|
3654 | my $defrec = shift;
|
---|
3655 | my $revrec = shift;
|
---|
3656 | my $id = shift;
|
---|
3657 | my $filter = shift || '';
|
---|
3658 |
|
---|
3659 | # keep the nasties down, since we can't ?-sub this bit. :/
|
---|
3660 | # note this is chars allowed in DNS hostnames
|
---|
3661 | $filter =~ s/[^a-zA-Z0-9_.:-]//g;
|
---|
3662 |
|
---|
3663 | my @bindvars = ($id);
|
---|
3664 | push @bindvars, $filter if $filter;
|
---|
3665 | my $sql = "SELECT count(*) FROM ".
|
---|
3666 | _rectable($defrec,$revrec).
|
---|
3667 | " WHERE "._recparent($defrec,$revrec)."=? ".
|
---|
3668 | "AND NOT type=$reverse_typemap{SOA}".
|
---|
3669 | ($filter ? " AND host ~* ?" : '');
|
---|
3670 | my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) );
|
---|
3671 |
|
---|
3672 | return $count;
|
---|
3673 |
|
---|
3674 | } # end getRecCount()
|
---|
3675 |
|
---|
3676 |
|
---|
3677 | ## DNSDB::addRec()
|
---|
3678 | # Add a new record to a domain or a group's default records
|
---|
3679 | # Takes a database handle, default/live flag, group/domain ID,
|
---|
3680 | # host, type, value, and TTL
|
---|
3681 | # Some types require additional detail: "distance" for MX and SRV,
|
---|
3682 | # and weight/port for SRV
|
---|
3683 | # Returns a status code and detail message in case of error
|
---|
3684 | ##fixme: pass a hash with the record data, not a series of separate values
|
---|
3685 | sub addRec {
|
---|
3686 | $errstr = '';
|
---|
3687 | my $self = shift;
|
---|
3688 | my $dbh = $self->{dbh};
|
---|
3689 | my $defrec = shift;
|
---|
3690 | my $revrec = shift;
|
---|
3691 | my $id = shift; # parent (group_id for defrecs, rdns_id for reverse records,
|
---|
3692 | # domain_id for domain records)
|
---|
3693 |
|
---|
3694 | my $host = shift;
|
---|
3695 | my $rectype = shift; # reference so we can coerce it if "+"-types can't find both zones
|
---|
3696 | my $val = shift;
|
---|
3697 | my $ttl = shift;
|
---|
3698 | my $location = shift;
|
---|
3699 | $location = '' if !$location;
|
---|
3700 |
|
---|
3701 | my $expires = shift;
|
---|
3702 | $expires = 1 if $expires eq 'until'; # Turn some special values into the appropriate booleans.
|
---|
3703 | $expires = 0 if $expires eq 'after';
|
---|
3704 | my $stamp = shift;
|
---|
3705 | $stamp = '' if !$stamp; # Timestamp should be a string at this point.
|
---|
3706 |
|
---|
3707 | # Spaces are evil.
|
---|
3708 | $host =~ s/^\s+//;
|
---|
3709 | $host =~ s/\s+$//;
|
---|
3710 | if ($typemap{$rectype} ne 'TXT') {
|
---|
3711 | # Leading or trailng spaces could be legit in TXT records.
|
---|
3712 | $val =~ s/^\s+//;
|
---|
3713 | $val =~ s/\s+$//;
|
---|
3714 | }
|
---|
3715 |
|
---|
3716 | if ($self->{lowercase}) {
|
---|
3717 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
3718 | $$host = lc($$host);
|
---|
3719 | $$val = lc($$val);
|
---|
3720 | } else {
|
---|
3721 | # TXT records should preserve user entry in the string.
|
---|
3722 | if ($revrec eq 'n') {
|
---|
3723 | $$host = lc($$host);
|
---|
3724 | } else {
|
---|
3725 | $$val = lc($$val);
|
---|
3726 | }
|
---|
3727 | }
|
---|
3728 | }
|
---|
3729 |
|
---|
3730 | # prep for validation
|
---|
3731 | my $addr = NetAddr::IP->new($$val);
|
---|
3732 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
3733 |
|
---|
3734 | my $domid = 0;
|
---|
3735 | my $revid = 0;
|
---|
3736 |
|
---|
3737 | my $retcode = 'OK'; # assume everything will go OK
|
---|
3738 | my $retmsg = '';
|
---|
3739 |
|
---|
3740 | # do simple validation first
|
---|
3741 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
|
---|
3742 |
|
---|
3743 | # Quick check on hostname parts. There are enough variations to justify a sub now.
|
---|
3744 | return ('FAIL', $errstr) if ! _check_hostname_form($$host, $$rectype, $defrec, $revrec);
|
---|
3745 |
|
---|
3746 | # Collect these even if we're only doing a simple A record so we can call *any* validation sub
|
---|
3747 | my $dist = shift;
|
---|
3748 | my $weight = shift;
|
---|
3749 | my $port = shift;
|
---|
3750 |
|
---|
3751 | my $fields;
|
---|
3752 | my @vallist;
|
---|
3753 |
|
---|
3754 | # Call the validation sub for the type requested.
|
---|
3755 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec, id => $id,
|
---|
3756 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
3757 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
3758 | fields => \$fields, vallist => \@vallist);
|
---|
3759 |
|
---|
3760 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
3761 |
|
---|
3762 | # Set up database fields and bind parameters
|
---|
3763 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
3764 | push @vallist, ($$host,$$rectype,$$val,$ttl,$id);
|
---|
3765 |
|
---|
3766 | if ($defrec eq 'n') {
|
---|
3767 | # locations are not for default records, silly coder!
|
---|
3768 | $fields .= ",location";
|
---|
3769 | push @vallist, $location;
|
---|
3770 | # timestamps are rare.
|
---|
3771 | if ($stamp) {
|
---|
3772 | $fields .= ",stamp,expires,stampactive";
|
---|
3773 | push @vallist, $stamp, $expires, 'y';
|
---|
3774 | } else {
|
---|
3775 | $fields .= ",stampactive";
|
---|
3776 | push @vallist, 'n';
|
---|
3777 | }
|
---|
3778 | }
|
---|
3779 |
|
---|
3780 | # a little magic to get the right number of ? placeholders based on how many values we're providing
|
---|
3781 | my $vallen = '?'.(',?'x$#vallist);
|
---|
3782 |
|
---|
3783 | # Put together the success log entry. We have to use this horrible kludge
|
---|
3784 | # because domain_id and rdns_id may or may not be present, and if they are,
|
---|
3785 | # they're not at a guaranteed consistent index in the array. wheee!
|
---|
3786 | my %logdata;
|
---|
3787 | my @ftmp = split /,/, $fields;
|
---|
3788 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
3789 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
3790 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
3791 | }
|
---|
3792 | $logdata{group_id} = $id if $defrec eq 'y';
|
---|
3793 | $logdata{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec)
|
---|
3794 | if $defrec eq 'n';
|
---|
3795 | $logdata{entry} = "Added ".($defrec eq 'y' ? 'default record' : 'record');
|
---|
3796 | # NS records for revzones get special treatment
|
---|
3797 | if ($revrec eq 'y' && $$rectype == 2) {
|
---|
3798 | $logdata{entry} .= " '$$val $typemap{$$rectype} $$host";
|
---|
3799 | } else {
|
---|
3800 | $logdata{entry} .= " '$$host $typemap{$$rectype} $$val";
|
---|
3801 | }
|
---|
3802 |
|
---|
3803 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
3804 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]"
|
---|
3805 | if $typemap{$$rectype} eq 'SRV';
|
---|
3806 | $logdata{entry} .= "', TTL $ttl";
|
---|
3807 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location;
|
---|
3808 | $logdata{entry} .= ($expires eq 'after' ? ', valid after ' : ', expires at ').$stamp if $stamp;
|
---|
3809 |
|
---|
3810 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
3811 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
3812 | local $dbh->{AutoCommit} = 0;
|
---|
3813 | local $dbh->{RaiseError} = 1;
|
---|
3814 |
|
---|
3815 | eval {
|
---|
3816 | $dbh->do("INSERT INTO "._rectable($defrec, $revrec)." ($fields) VALUES ($vallen)",
|
---|
3817 | undef, @vallist);
|
---|
3818 | $self->_log(%logdata);
|
---|
3819 | $dbh->commit;
|
---|
3820 | };
|
---|
3821 | if ($@) {
|
---|
3822 | my $msg = $@;
|
---|
3823 | eval { $dbh->rollback; };
|
---|
3824 | if ($self->{log_failures}) {
|
---|
3825 | $logdata{entry} = "Failed adding ".($defrec eq 'y' ? 'default ' : '').
|
---|
3826 | "record '$$host $typemap{$$rectype} $$val', TTL $ttl ($msg)";
|
---|
3827 | $self->_log(%logdata);
|
---|
3828 | $dbh->commit;
|
---|
3829 | }
|
---|
3830 | return ('FAIL',$msg);
|
---|
3831 | }
|
---|
3832 |
|
---|
3833 | $resultstr = $logdata{entry};
|
---|
3834 | return ($retcode, $retmsg);
|
---|
3835 |
|
---|
3836 | } # end addRec()
|
---|
3837 |
|
---|
3838 |
|
---|
3839 | ## DNSDB::updateRec()
|
---|
3840 | # Update a record
|
---|
3841 | # Takes a database handle, default and reverse flags, record ID, immediate parent ID, and new record data.
|
---|
3842 | # Returns a status code and message
|
---|
3843 | sub updateRec {
|
---|
3844 | $errstr = '';
|
---|
3845 |
|
---|
3846 | my $self = shift;
|
---|
3847 | my $dbh = $self->{dbh};
|
---|
3848 | my $defrec = shift;
|
---|
3849 | my $revrec = shift;
|
---|
3850 | my $id = shift;
|
---|
3851 | my $parid = shift; # immediate parent entity that we're descending from to update the record
|
---|
3852 |
|
---|
3853 | # all records have these
|
---|
3854 | my $host = shift;
|
---|
3855 | my $hostbk = $$host; # Keep a backup copy of the original, so we can WARN if the update mangles the domain
|
---|
3856 | my $rectype = shift;
|
---|
3857 | my $val = shift;
|
---|
3858 | my $ttl = shift;
|
---|
3859 | my $location = shift; # may be empty/null/undef depending on caller
|
---|
3860 | $location = '' if !$location;
|
---|
3861 |
|
---|
3862 | my $expires = shift;
|
---|
3863 | $expires = 1 if $expires eq 'until'; # Turn some special values into the appropriate booleans.
|
---|
3864 | $expires = 0 if $expires eq 'after';
|
---|
3865 | my $stamp = shift;
|
---|
3866 | $stamp = '' if !$stamp; # Timestamp should be a string at this point.
|
---|
3867 |
|
---|
3868 | # just set it to an empty string; failures will be caught later.
|
---|
3869 | $$host = '' if !$$host;
|
---|
3870 |
|
---|
3871 | # Spaces are evil.
|
---|
3872 | $host =~ s/^\s+//;
|
---|
3873 | $host =~ s/\s+$//;
|
---|
3874 | if ($typemap{$type} ne 'TXT') {
|
---|
3875 | # Leading or trailng spaces could be legit in TXT records.
|
---|
3876 | $val =~ s/^\s+//;
|
---|
3877 | $val =~ s/\s+$//;
|
---|
3878 | }
|
---|
3879 |
|
---|
3880 | if ($self->{lowercase}) {
|
---|
3881 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
3882 | $$host = lc($$host);
|
---|
3883 | $$val = lc($$val);
|
---|
3884 | } else {
|
---|
3885 | # TXT records should preserve user entry in the string.
|
---|
3886 | if ($revrec eq 'n') {
|
---|
3887 | $$host = lc($$host);
|
---|
3888 | } else {
|
---|
3889 | $$val = lc($$val);
|
---|
3890 | }
|
---|
3891 | }
|
---|
3892 | }
|
---|
3893 |
|
---|
3894 | # prep for validation
|
---|
3895 | my $addr = NetAddr::IP->new($$val);
|
---|
3896 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
3897 |
|
---|
3898 | my $domid = 0;
|
---|
3899 | my $revid = 0;
|
---|
3900 |
|
---|
3901 | my $retcode = 'OK'; # assume everything will go OK
|
---|
3902 | my $retmsg = '';
|
---|
3903 |
|
---|
3904 | # do simple validation first
|
---|
3905 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
|
---|
3906 |
|
---|
3907 | # Quick check on hostname parts. There are enough variations to justify a sub now.
|
---|
3908 | return ('FAIL', $errstr) if ! _check_hostname_form($$host, $$rectype, $defrec, $revrec);
|
---|
3909 |
|
---|
3910 | # only MX and SRV will use these
|
---|
3911 | my $dist = shift || 0;
|
---|
3912 | my $weight = shift || 0;
|
---|
3913 | my $port = shift || 0;
|
---|
3914 |
|
---|
3915 | my $fields;
|
---|
3916 | my @vallist;
|
---|
3917 |
|
---|
3918 | # get old record data so we have the right parent ID
|
---|
3919 | # and for logging (eventually)
|
---|
3920 | my $oldrec = $self->getRecLine($defrec, $revrec, $id);
|
---|
3921 |
|
---|
3922 | # Call the validation sub for the type requested.
|
---|
3923 | # Note the ID to pass here is the *parent*, not the record
|
---|
3924 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec,
|
---|
3925 | id => ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})),
|
---|
3926 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
3927 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
3928 | fields => \$fields, vallist => \@vallist,
|
---|
3929 | update => $id);
|
---|
3930 |
|
---|
3931 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
3932 |
|
---|
3933 | # Set up database fields and bind parameters. Note only the optional fields
|
---|
3934 | # (distance, weight, port, secondary parent ID) are added in the validation call above
|
---|
3935 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
3936 | push @vallist, ($$host,$$rectype,$$val,$ttl,
|
---|
3937 | ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})) );
|
---|
3938 |
|
---|
3939 | if ($defrec eq 'n') {
|
---|
3940 | # locations are not for default records, silly coder!
|
---|
3941 | $fields .= ",location";
|
---|
3942 | push @vallist, $location;
|
---|
3943 | # timestamps are rare.
|
---|
3944 | if ($stamp) {
|
---|
3945 | $fields .= ",stamp,expires,stampactive";
|
---|
3946 | push @vallist, $stamp, $expires, 'y';
|
---|
3947 | } else {
|
---|
3948 | $fields .= ",stampactive";
|
---|
3949 | push @vallist, 'n';
|
---|
3950 | }
|
---|
3951 | }
|
---|
3952 |
|
---|
3953 | # hack hack PTHUI
|
---|
3954 | # need to forcibly make sure we disassociate a record with a parent it's no longer related to.
|
---|
3955 | # eg, PTR records may not have a domain parent, or A/AAAA records may not have a revzone parent.
|
---|
3956 | # mainly needed for crossover types that got coerced down to "standard" types
|
---|
3957 | if ($defrec eq 'n') {
|
---|
3958 | if ($$rectype == $reverse_typemap{PTR}) {
|
---|
3959 | $fields .= ",domain_id";
|
---|
3960 | push @vallist, 0;
|
---|
3961 | }
|
---|
3962 | if ($$rectype == $reverse_typemap{A} || $$rectype == $reverse_typemap{AAAA}) {
|
---|
3963 | $fields .= ",rdns_id";
|
---|
3964 | push @vallist, 0;
|
---|
3965 | }
|
---|
3966 | }
|
---|
3967 | # fix fat-finger-originated record type changes
|
---|
3968 | if ($$rectype == 65285) {
|
---|
3969 | $fields .= ",rdns_id" if $revrec eq 'n';
|
---|
3970 | $fields .= ",domain_id" if $revrec eq 'y';
|
---|
3971 | push @vallist, 0;
|
---|
3972 | }
|
---|
3973 | if ($defrec eq 'n') {
|
---|
3974 | $domid = $parid if $revrec eq 'n';
|
---|
3975 | $revid = $parid if $revrec eq 'y';
|
---|
3976 | }
|
---|
3977 |
|
---|
3978 | # Put together the success log entry. Horrible kludge from addRec() copied as-is since
|
---|
3979 | # we don't know whether the passed arguments or retrieved values for domain_id and rdns_id
|
---|
3980 | # will be maintained (due to "not-in-zone" validation changes)
|
---|
3981 | my %logdata;
|
---|
3982 | $logdata{domain_id} = $domid;
|
---|
3983 | $logdata{rdns_id} = $revid;
|
---|
3984 | my @ftmp = split /,/, $fields;
|
---|
3985 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
3986 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
3987 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
3988 | }
|
---|
3989 | $logdata{group_id} = $parid if $defrec eq 'y';
|
---|
3990 | $logdata{group_id} = $self->parentID(id => $parid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec)
|
---|
3991 | if $defrec eq 'n';
|
---|
3992 | $logdata{entry} = "Updated ".($defrec eq 'y' ? 'default record' : 'record')." from\n";
|
---|
3993 | # NS records for revzones get special treatment
|
---|
3994 | if ($revrec eq 'y' && $$rectype == 2) {
|
---|
3995 | $logdata{entry} .= " '$oldrec->{val} $typemap{$oldrec->{type}} $oldrec->{host}";
|
---|
3996 | } else {
|
---|
3997 | $logdata{entry} .= " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
3998 | }
|
---|
3999 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
4000 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
4001 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
4002 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
4003 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location};
|
---|
4004 | $logdata{entry} .= ($oldrec->{expires} ? ', expires at ' : ', valid after ').$oldrec->{stamp}
|
---|
4005 | if $oldrec->{stampactive};
|
---|
4006 | $logdata{entry} .= "\nto\n";
|
---|
4007 | # More NS special
|
---|
4008 | if ($revrec eq 'y' && $$rectype == 2) {
|
---|
4009 | $logdata{entry} .= "'$$val $typemap{$$rectype} $$host";
|
---|
4010 | } else {
|
---|
4011 | $logdata{entry} .= "'$$host $typemap{$$rectype} $$val";
|
---|
4012 | }
|
---|
4013 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
4014 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$$rectype} eq 'SRV';
|
---|
4015 | $logdata{entry} .= "', TTL $ttl";
|
---|
4016 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location;
|
---|
4017 | $logdata{entry} .= ($expires eq 'after' ? ', valid after ' : ', expires at ').$stamp if $stamp;
|
---|
4018 |
|
---|
4019 | local $dbh->{AutoCommit} = 0;
|
---|
4020 | local $dbh->{RaiseError} = 1;
|
---|
4021 |
|
---|
4022 | # Fiddle the field list into something suitable for updates
|
---|
4023 | $fields =~ s/,/=?,/g;
|
---|
4024 | $fields .= "=?";
|
---|
4025 |
|
---|
4026 | eval {
|
---|
4027 | $dbh->do("UPDATE "._rectable($defrec,$revrec)." SET $fields WHERE record_id=?", undef, (@vallist, $id) );
|
---|
4028 | $self->_log(%logdata);
|
---|
4029 | $dbh->commit;
|
---|
4030 | };
|
---|
4031 | if ($@) {
|
---|
4032 | my $msg = $@;
|
---|
4033 | eval { $dbh->rollback; };
|
---|
4034 | if ($self->{log_failures}) {
|
---|
4035 | $logdata{entry} = "Failed updating ".($defrec eq 'y' ? 'default ' : '').
|
---|
4036 | "record '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
4037 | $self->_log(%logdata);
|
---|
4038 | $dbh->commit;
|
---|
4039 | }
|
---|
4040 | return ('FAIL', $msg);
|
---|
4041 | }
|
---|
4042 |
|
---|
4043 | $resultstr = $logdata{entry};
|
---|
4044 | return ($retcode, $retmsg);
|
---|
4045 | } # end updateRec()
|
---|
4046 |
|
---|
4047 |
|
---|
4048 | ## DNSDB::downconvert()
|
---|
4049 | # A mostly internal (not exported) semiutilty sub to downconvert from pseudotype <x>
|
---|
4050 | # to a compatible component type. Only a handful of operations are valid, anything
|
---|
4051 | # else is a null-op.
|
---|
4052 | # Takes the record ID and the new type. Returns boolean.
|
---|
4053 | sub downconvert {
|
---|
4054 | my $self = shift;
|
---|
4055 | my $dbh = $self->{dbh};
|
---|
4056 | my $recid = shift;
|
---|
4057 | my $newtype = shift;
|
---|
4058 |
|
---|
4059 | # also, only work on live records; little to no value trying to do this on default records.
|
---|
4060 | my $rec = $self->getRecLine('n', 'y', $recid);
|
---|
4061 |
|
---|
4062 | # hm?
|
---|
4063 | #return 1 if !$rec;
|
---|
4064 |
|
---|
4065 | return 1 if $rec->{type} < 65000; # Only the reverse-record pseudotypes can be downconverted
|
---|
4066 | return 1 if $rec->{type} == 65282; # Nowhere to go
|
---|
4067 |
|
---|
4068 | my $delpar;
|
---|
4069 | my @sqlargs;
|
---|
4070 | if ($rec->{type} == 65280) {
|
---|
4071 | return 1 if $newtype != 1 && $newtype != 12;
|
---|
4072 | $delpar = ($newtype == 1 ? 'rdns_id' : 'domain_id');
|
---|
4073 | push @sqlargs, 0, $newtype, $recid;
|
---|
4074 | } elsif ($rec->{type} == 65281) {
|
---|
4075 | return 1 if $newtype != 28 && $newtype != 12;
|
---|
4076 | $delpar = ($newtype == 28 ? 'rdns_id' : 'domain_id');
|
---|
4077 | push @sqlargs, 0, $newtype, $recid;
|
---|
4078 | } elsif ($rec->{type} == 65283) {
|
---|
4079 | return 1 if $newtype != 65282;
|
---|
4080 | $delpar = 'rdns_id';
|
---|
4081 | } elsif ($rec->{type} == 65284) {
|
---|
4082 | return 1 if $newtype != 65282;
|
---|
4083 | $delpar = 'rdns_id';
|
---|
4084 | } else {
|
---|
4085 | # Your llama is on fire.
|
---|
4086 | }
|
---|
4087 |
|
---|
4088 | local $dbh->{AutoCommit} = 0;
|
---|
4089 | local $dbh->{RaiseError} = 1;
|
---|
4090 |
|
---|
4091 | eval {
|
---|
4092 | $dbh->do("UPDATE records SET $delpar = ?, type = ? WHERE record_id = ?", undef, @sqlargs);
|
---|
4093 | $dbh->commit;
|
---|
4094 | };
|
---|
4095 | if ($@) {
|
---|
4096 | $errstr = $@;
|
---|
4097 | eval { $dbh->rollback; };
|
---|
4098 | return 0;
|
---|
4099 | }
|
---|
4100 | return 1;
|
---|
4101 | } # end downconvert()
|
---|
4102 |
|
---|
4103 |
|
---|
4104 | ## DNSDB::delRec()
|
---|
4105 | # Delete a record.
|
---|
4106 | sub delRec {
|
---|
4107 | $errstr = '';
|
---|
4108 | my $self = shift;
|
---|
4109 | my $dbh = $self->{dbh};
|
---|
4110 | my $defrec = shift;
|
---|
4111 | my $revrec = shift;
|
---|
4112 | my $id = shift;
|
---|
4113 |
|
---|
4114 | my $oldrec = $self->getRecLine($defrec, $revrec, $id);
|
---|
4115 |
|
---|
4116 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
4117 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
4118 | local $dbh->{AutoCommit} = 0;
|
---|
4119 | local $dbh->{RaiseError} = 1;
|
---|
4120 |
|
---|
4121 | # Put together the log entry
|
---|
4122 | my %logdata;
|
---|
4123 | $logdata{domain_id} = $oldrec->{domain_id};
|
---|
4124 | $logdata{rdns_id} = $oldrec->{rdns_id};
|
---|
4125 | $logdata{group_id} = $oldrec->{group_id} if $defrec eq 'y';
|
---|
4126 | $logdata{group_id} = $self->parentID(id => $oldrec->{domain_id}, type => ($revrec eq 'n' ? 'domain' : 'revzone'),
|
---|
4127 | revrec => $revrec)
|
---|
4128 | if $defrec eq 'n';
|
---|
4129 | $logdata{entry} = "Deleted ".($defrec eq 'y' ? 'default record ' : 'record ').
|
---|
4130 | "'$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
4131 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
4132 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
4133 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
4134 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
4135 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location};
|
---|
4136 |
|
---|
4137 | eval {
|
---|
4138 | my $sth = $dbh->do("DELETE FROM "._rectable($defrec,$revrec)." WHERE record_id=?", undef, ($id));
|
---|
4139 | $self->_log(%logdata);
|
---|
4140 | $dbh->commit;
|
---|
4141 | };
|
---|
4142 | if ($@) {
|
---|
4143 | my $msg = $@;
|
---|
4144 | eval { $dbh->rollback; };
|
---|
4145 | if ($self->{log_failures}) {
|
---|
4146 | $logdata{entry} = "Error deleting ".($defrec eq 'y' ? 'default record' : 'record').
|
---|
4147 | " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
4148 | $self->_log(%logdata);
|
---|
4149 | $dbh->commit;
|
---|
4150 | }
|
---|
4151 | return ('FAIL', $msg);
|
---|
4152 | }
|
---|
4153 |
|
---|
4154 | return ('OK',$logdata{entry});
|
---|
4155 | } # end delRec()
|
---|
4156 |
|
---|
4157 |
|
---|
4158 | ## DNSDB::getLogCount()
|
---|
4159 | # Get a count of log entries
|
---|
4160 | # Takes a database handle and a hash containing at least:
|
---|
4161 | # - Entity ID and entity type as the primary log "slice"
|
---|
4162 | sub getLogCount {
|
---|
4163 | my $self = shift;
|
---|
4164 | my $dbh = $self->{dbh};
|
---|
4165 |
|
---|
4166 | my %args = @_;
|
---|
4167 |
|
---|
4168 | my @filterargs;
|
---|
4169 | ##fixme: which fields do we want to filter on?
|
---|
4170 | # push @filterargs,
|
---|
4171 |
|
---|
4172 | $errstr = 'Missing primary parent ID and/or type';
|
---|
4173 | # fail early if we don't have a "prime" ID to look for log entries for
|
---|
4174 | return if !$args{id};
|
---|
4175 |
|
---|
4176 | # or if the prime id type is missing or invalid
|
---|
4177 | return if !$args{logtype};
|
---|
4178 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
4179 | $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
|
---|
4180 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
|
---|
4181 |
|
---|
4182 | my $sql = "SELECT count(*) FROM log ".
|
---|
4183 | "WHERE $id_col{$args{logtype}}=?".
|
---|
4184 | ($args{filter} ? " AND entry ~* ?" : '');
|
---|
4185 | my ($count) = $dbh->selectrow_array($sql, undef, ($args{id}, @filterargs) );
|
---|
4186 | $errstr = $dbh->errstr if !$count;
|
---|
4187 | return $count;
|
---|
4188 | } # end getLogCount()
|
---|
4189 |
|
---|
4190 |
|
---|
4191 | ## DNSDB::getLogEntries()
|
---|
4192 | # Get a list of log entries
|
---|
4193 | # Takes arguments as with getLogCount() above, plus optional:
|
---|
4194 | # - sort field
|
---|
4195 | # - sort order
|
---|
4196 | # - offset for pagination
|
---|
4197 | sub getLogEntries {
|
---|
4198 | my $self = shift;
|
---|
4199 | my $dbh = $self->{dbh};
|
---|
4200 |
|
---|
4201 | my %args = @_;
|
---|
4202 |
|
---|
4203 | my @filterargs;
|
---|
4204 |
|
---|
4205 | # fail early if we don't have a "prime" ID to look for log entries for
|
---|
4206 | return if !$args{id};
|
---|
4207 |
|
---|
4208 | # or if the prime id type is missing or invalid
|
---|
4209 | return if !$args{logtype};
|
---|
4210 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
4211 | $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
|
---|
4212 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
|
---|
4213 |
|
---|
4214 | # Sorting defaults
|
---|
4215 | $args{sortorder} = 'DESC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
4216 | $args{sortby} = 'stamp' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
4217 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
4218 |
|
---|
4219 | my %sortmap = (fname => 'name', username => 'email', entry => 'entry', stamp => 'stamp');
|
---|
4220 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
4221 |
|
---|
4222 | my $sql = "SELECT user_id AS userid, email AS useremail, name AS userfname, entry AS logentry, ".
|
---|
4223 | "date_trunc('second',stamp) AS logtime ".
|
---|
4224 | "FROM log ".
|
---|
4225 | "WHERE $id_col{$args{logtype}}=?".
|
---|
4226 | ($args{filter} ? " AND entry ~* ?" : '').
|
---|
4227 | " ORDER BY $args{sortby} $args{sortorder}, log_id $args{sortorder}".
|
---|
4228 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
4229 | my $loglist = $dbh->selectall_arrayref($sql, { Slice => {} }, ($args{id}, @filterargs) );
|
---|
4230 | $errstr = $dbh->errstr if !$loglist;
|
---|
4231 | return $loglist;
|
---|
4232 | } # end getLogEntries()
|
---|
4233 |
|
---|
4234 |
|
---|
4235 | ## IPDB::getRevPattern()
|
---|
4236 | # Get the narrowest template pattern applicable to a passed CIDR address (may be a netblock or an IP)
|
---|
4237 | sub getRevPattern {
|
---|
4238 | my $self = shift;
|
---|
4239 | my $dbh = $self->{dbh};
|
---|
4240 | my $cidr = shift;
|
---|
4241 | my $group = shift || 1; # just in case
|
---|
4242 |
|
---|
4243 | # for speed! Casting and comparing even ~7K records takes ~2.5s, so narrow it down to one revzone first.
|
---|
4244 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >>= ? AND group_id = ?",
|
---|
4245 | undef, ($cidr, $group) );
|
---|
4246 |
|
---|
4247 | ##fixme? may need to narrow things down more by octet-chopping and doing text comparisons before casting.
|
---|
4248 | my ($revpatt) = $dbh->selectrow_array("SELECT host FROM records ".
|
---|
4249 | "WHERE (type in (12,65280,65281,65282,65283,65284)) AND rdns_id = ? AND CAST (val AS inet) >>= ? ".
|
---|
4250 | "ORDER BY CAST (val AS inet) DESC LIMIT 1", undef, ($revid, $cidr) );
|
---|
4251 | return $revpatt;
|
---|
4252 | } # end getRevPattern()
|
---|
4253 |
|
---|
4254 |
|
---|
4255 | ## DNSDB::getTypelist()
|
---|
4256 | # Get a list of record types for various UI dropdowns
|
---|
4257 | # Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A)
|
---|
4258 | # Returns an arrayref to list of hashrefs perfect for HTML::Template
|
---|
4259 | sub getTypelist {
|
---|
4260 | my $self = shift;
|
---|
4261 | my $dbh = $self->{dbh};
|
---|
4262 | my $recgroup = shift;
|
---|
4263 | my $type = shift || $reverse_typemap{A};
|
---|
4264 |
|
---|
4265 | # also accepting $webvar{revrec}!
|
---|
4266 | $recgroup = 'f' if $recgroup eq 'n';
|
---|
4267 | $recgroup = 'r' if $recgroup eq 'y';
|
---|
4268 |
|
---|
4269 | my $sql = "SELECT val,name FROM rectypes WHERE ";
|
---|
4270 | if ($recgroup eq 'r') {
|
---|
4271 | # reverse zone types
|
---|
4272 | $sql .= "stdflag=2 OR stdflag=3";
|
---|
4273 | } elsif ($recgroup eq 'l') {
|
---|
4274 | # DNS lookup types. Note we avoid our custom types >= 65280, since those are entirely internal.
|
---|
4275 | $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280";
|
---|
4276 | } else {
|
---|
4277 | # default; forward zone types. technically $type eq 'f' but not worth the error message.
|
---|
4278 | $sql .= "stdflag=1 OR stdflag=2";
|
---|
4279 | $sql .= " AND val < 65280" if $recgroup eq 'fo'; # An extra flag to trim off the pseudotypes as well.
|
---|
4280 | }
|
---|
4281 | $sql .= " ORDER BY listorder";
|
---|
4282 |
|
---|
4283 | my $sth = $dbh->prepare($sql);
|
---|
4284 | $sth->execute;
|
---|
4285 | my @typelist;
|
---|
4286 | while (my ($rval,$rname) = $sth->fetchrow_array()) {
|
---|
4287 | my %row = ( recval => $rval, recname => $rname );
|
---|
4288 | $row{tselect} = 1 if $rval == $type;
|
---|
4289 | push @typelist, \%row;
|
---|
4290 | }
|
---|
4291 |
|
---|
4292 | # Add SOA on lookups since it's not listed in other dropdowns.
|
---|
4293 | if ($recgroup eq 'l') {
|
---|
4294 | my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
|
---|
4295 | $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
|
---|
4296 | push @typelist, \%row;
|
---|
4297 | }
|
---|
4298 |
|
---|
4299 | return \@typelist;
|
---|
4300 | } # end getTypelist()
|
---|
4301 |
|
---|
4302 |
|
---|
4303 | ## DNSDB::parentID()
|
---|
4304 | # Get ID of entity that is nearest parent to requested id
|
---|
4305 | # Takes a database handle and a hash of entity ID, entity type, optional parent type flag
|
---|
4306 | # (domain/reverse zone or group), and optional default/live and forward/reverse flags
|
---|
4307 | # Returns the ID or undef on failure
|
---|
4308 | sub parentID {
|
---|
4309 | my $self = shift;
|
---|
4310 | my $dbh = $self->{dbh};
|
---|
4311 |
|
---|
4312 | my %args = @_;
|
---|
4313 |
|
---|
4314 | # clean up the parent-type. Set it to group if not set; coerce revzone to domain for simpler logic
|
---|
4315 | $args{partype} = 'group' if !$args{partype};
|
---|
4316 | $args{partype} = 'domain' if $args{partype} eq 'revzone';
|
---|
4317 |
|
---|
4318 | # clean up defrec and revrec. default to live record, forward zone
|
---|
4319 | $args{defrec} = 'n' if !$args{defrec};
|
---|
4320 | $args{revrec} = 'n' if !$args{revrec};
|
---|
4321 |
|
---|
4322 | if ($par_type{$args{partype}} eq 'domain') {
|
---|
4323 | # only live records can have a domain/zone parent
|
---|
4324 | return unless ($args{type} eq 'record' && $args{defrec} eq 'n');
|
---|
4325 | my $result = $dbh->selectrow_hashref("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
4326 | " FROM records WHERE record_id = ?",
|
---|
4327 | undef, ($args{id}) ) or return;
|
---|
4328 | return $result;
|
---|
4329 | } else {
|
---|
4330 | # snag some arguments that will either fall through or be overwritten to save some code duplication
|
---|
4331 | my $tmpid = $args{id};
|
---|
4332 | my $type = $args{type};
|
---|
4333 | if ($type eq 'record' && $args{defrec} eq 'n') {
|
---|
4334 | # Live records go through the records table first.
|
---|
4335 | ($tmpid) = $dbh->selectrow_array("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
4336 | " FROM records WHERE record_id = ?",
|
---|
4337 | undef, ($args{id}) ) or return;
|
---|
4338 | $type = ($args{revrec} eq 'n' ? 'domain' : 'revzone');
|
---|
4339 | }
|
---|
4340 | my ($result) = $dbh->selectrow_array("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
|
---|
4341 | undef, ($tmpid) );
|
---|
4342 | return $result;
|
---|
4343 | }
|
---|
4344 | # should be impossible to get here with even remotely sane arguments
|
---|
4345 | return;
|
---|
4346 | } # end parentID()
|
---|
4347 |
|
---|
4348 |
|
---|
4349 | ## DNSDB::isParent()
|
---|
4350 | # Returns true if $id1 is a parent of $id2, false otherwise
|
---|
4351 | sub isParent {
|
---|
4352 | my $self = shift;
|
---|
4353 | my $dbh = $self->{dbh};
|
---|
4354 | my $id1 = shift;
|
---|
4355 | my $type1 = shift;
|
---|
4356 | my $id2 = shift;
|
---|
4357 | my $type2 = shift;
|
---|
4358 | ##todo: immediate, secondary, full (default)
|
---|
4359 |
|
---|
4360 | # Return false on invalid types
|
---|
4361 | return 0 if !grep /^$type1$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
4362 | return 0 if !grep /^$type2$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
4363 |
|
---|
4364 | # Return false on impossible relations
|
---|
4365 | return 0 if $type1 eq 'record'; # nothing may be a child of a record
|
---|
4366 | return 0 if $type1 eq 'defrec'; # nothing may be a child of a record
|
---|
4367 | return 0 if $type1 eq 'defrevrec'; # nothing may be a child of a record
|
---|
4368 | return 0 if $type1 eq 'user'; # nothing may be child of a user
|
---|
4369 | return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record
|
---|
4370 | return 0 if $type1 eq 'revzone' && $type2 ne 'record';# reverse zone may not be a parent of anything other than a record
|
---|
4371 |
|
---|
4372 | # ennnhhhh.... if we're passed an id of 0, it will never be found. usual
|
---|
4373 | # case would be the UI creating a new <thing>, and so we don't have an ID for
|
---|
4374 | # <thing> to look up yet. in that case the UI should check the parent as well.
|
---|
4375 | return 0 if $id1 == 0; # nothing can have a parent id of 0
|
---|
4376 | return 1 if $id2 == 0; # anything could have a child id of 0 (or "unknown")
|
---|
4377 |
|
---|
4378 | # group 1 is the ultimate root parent
|
---|
4379 | return 1 if $type1 eq 'group' && $id1 == 1;
|
---|
4380 |
|
---|
4381 | # groups are always (a) parent of themselves
|
---|
4382 | return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2;
|
---|
4383 |
|
---|
4384 | my $id = $id2;
|
---|
4385 | my $type = $type2;
|
---|
4386 | my $foundparent = 0;
|
---|
4387 |
|
---|
4388 | # Records are the only entity with two possible parents. We need to split the parent checks on
|
---|
4389 | # domain/rdns.
|
---|
4390 | if ($type eq 'record') {
|
---|
4391 | my ($dom,$rdns) = $dbh->selectrow_array("SELECT domain_id,rdns_id FROM records WHERE record_id=?",
|
---|
4392 | undef, ($id));
|
---|
4393 | # check immediate parent against request
|
---|
4394 | return 1 if $type1 eq 'domain' && $id1 == $dom;
|
---|
4395 | return 1 if $type1 eq 'revzone' && $id1 == $rdns;
|
---|
4396 | # if request is group, check *both* parents. Only check if the parent is nonzero though.
|
---|
4397 | return 1 if $dom && $self->isParent($id1, $type1, $dom, 'domain');
|
---|
4398 | return 1 if $rdns && $self->isParent($id1, $type1, $rdns, 'revzone');
|
---|
4399 | # exit here since we've executed the loop below by proxy in the above recursive calls.
|
---|
4400 | return 0;
|
---|
4401 | }
|
---|
4402 |
|
---|
4403 | # almost the same loop as getParents() above
|
---|
4404 | my $limiter = 0;
|
---|
4405 | while (1) {
|
---|
4406 | my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
|
---|
4407 | my $result = $dbh->selectrow_hashref($sql,
|
---|
4408 | undef, ($id) );
|
---|
4409 | if (!$result) {
|
---|
4410 | $limiter++;
|
---|
4411 | ##fixme: how often will this happen on a live site? fail at max limiter <n>?
|
---|
4412 | # 2013/10/22 only seems to happen when you request an entity that doesn't exist.
|
---|
4413 | warn "no results looking for $sql with id $id (depth $limiter)\n";
|
---|
4414 | last;
|
---|
4415 | }
|
---|
4416 | if ($result && $result->{$par_col{$type}} == $id1) {
|
---|
4417 | $foundparent = 1;
|
---|
4418 | last;
|
---|
4419 | } else {
|
---|
4420 | ##fixme: do we care about trying to return a "no such record/domain/user/group" error?
|
---|
4421 | # should be impossible to create an inconsistent DB just with API calls.
|
---|
4422 | warn $dbh->errstr." $sql, $id" if $dbh->errstr;
|
---|
4423 | }
|
---|
4424 | # group 1 is its own parent. need this here more to break strange loops than for detecting a parent
|
---|
4425 | last if $result->{$par_col{$type}} == 1;
|
---|
4426 | $id = $result->{$par_col{$type}};
|
---|
4427 | $type = $par_type{$type};
|
---|
4428 | }
|
---|
4429 |
|
---|
4430 | return $foundparent;
|
---|
4431 | } # end isParent()
|
---|
4432 |
|
---|
4433 |
|
---|
4434 | ## DNSDB::zoneStatus()
|
---|
4435 | # Returns and optionally sets a zone's status
|
---|
4436 | # Takes a database handle, domain/revzone ID, forward/reverse flag, and optionally a status argument
|
---|
4437 | # Returns status, or undef on errors.
|
---|
4438 | sub zoneStatus {
|
---|
4439 | my $self = shift;
|
---|
4440 | my $dbh = $self->{dbh};
|
---|
4441 | my $id = shift;
|
---|
4442 | my $revrec = shift;
|
---|
4443 | my $newstatus = shift || 'mu';
|
---|
4444 |
|
---|
4445 | return undef if $id !~ /^\d+$/;
|
---|
4446 |
|
---|
4447 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
4448 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
4449 | local $dbh->{AutoCommit} = 0;
|
---|
4450 | local $dbh->{RaiseError} = 1;
|
---|
4451 |
|
---|
4452 | if ($newstatus ne 'mu') {
|
---|
4453 | # ooo, fun! let's see what we were passed for status
|
---|
4454 | eval {
|
---|
4455 | $newstatus = 0 if $newstatus eq 'domoff';
|
---|
4456 | $newstatus = 1 if $newstatus eq 'domon';
|
---|
4457 | $dbh->do("UPDATE ".($revrec eq 'n' ? 'domains' : 'revzones')." SET status=? WHERE ".
|
---|
4458 | ($revrec eq 'n' ? 'domain_id' : 'rdns_id')."=?", undef, ($newstatus,$id) );
|
---|
4459 |
|
---|
4460 | ##fixme switch to more consise "Enabled <domain"/"Disabled <domain>" as with users?
|
---|
4461 | $resultstr = "Changed ".($revrec eq 'n' ? $self->domainName($id) : $self->revName($id)).
|
---|
4462 | " state to ".($newstatus ? 'active' : 'inactive');
|
---|
4463 |
|
---|
4464 | my %loghash;
|
---|
4465 | $loghash{domain_id} = $id if $revrec eq 'n';
|
---|
4466 | $loghash{rdns_id} = $id if $revrec eq 'y';
|
---|
4467 | $loghash{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec);
|
---|
4468 | $loghash{entry} = $resultstr;
|
---|
4469 | $self->_log(%loghash);
|
---|
4470 |
|
---|
4471 | $dbh->commit;
|
---|
4472 | };
|
---|
4473 | if ($@) {
|
---|
4474 | my $msg = $@;
|
---|
4475 | eval { $dbh->rollback; };
|
---|
4476 | $resultstr = '';
|
---|
4477 | $errstr = $msg;
|
---|
4478 | return;
|
---|
4479 | }
|
---|
4480 | }
|
---|
4481 |
|
---|
4482 | my ($status) = $dbh->selectrow_array("SELECT status FROM ".
|
---|
4483 | ($revrec eq 'n' ? "domains WHERE domain_id=?" : "revzones WHERE rdns_id=?"),
|
---|
4484 | undef, ($id) );
|
---|
4485 | return $status;
|
---|
4486 | } # end zoneStatus()
|
---|
4487 |
|
---|
4488 |
|
---|
4489 | ## DNSDB::getZonesByCIDR()
|
---|
4490 | # Get a list of zone names and IDs that records for a passed CIDR block are within.
|
---|
4491 | sub getZonesByCIDR {
|
---|
4492 | my $self = shift;
|
---|
4493 | my $dbh = $self->{dbh};
|
---|
4494 | my %args = @_;
|
---|
4495 |
|
---|
4496 | my $result = $dbh->selectall_arrayref("SELECT rdns_id,revnet FROM revzones WHERE revnet >>= ? OR revnet <<= ?",
|
---|
4497 | { Slice => {} }, ($args{cidr}, $args{cidr}) );
|
---|
4498 | return $result;
|
---|
4499 | } # end getZonesByCIDR()
|
---|
4500 |
|
---|
4501 |
|
---|
4502 | ## DNSDB::importAXFR
|
---|
4503 | # Import a domain via AXFR
|
---|
4504 | # Takes AXFR host, domain to transfer, group to put the domain in,
|
---|
4505 | # and an optional hash containing:
|
---|
4506 | # status - active/inactive state flag (defaults to active)
|
---|
4507 | # rwsoa - overwrite-SOA flag (defaults to off)
|
---|
4508 | # rwns - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
|
---|
4509 | # merge - flag to automerge A or AAAA records with matching PTR records
|
---|
4510 | # Returns a status code (OK, WARN, or FAIL) and message - message should be blank
|
---|
4511 | # if status is OK, but WARN includes conditions that are not fatal but should
|
---|
4512 | # really be reported.
|
---|
4513 | sub importAXFR {
|
---|
4514 | my $self = shift;
|
---|
4515 | my $dbh = $self->{dbh};
|
---|
4516 | my $ifrom_in = shift;
|
---|
4517 | my $zone = shift;
|
---|
4518 | my $group = shift;
|
---|
4519 |
|
---|
4520 | my %args = @_;
|
---|
4521 |
|
---|
4522 | ##fixme: add mode to delete&replace, merge+overwrite, merge new?
|
---|
4523 |
|
---|
4524 | $args{status} = (defined($args{status}) ? $args{status} : 0);
|
---|
4525 | $args{status} = 1 if $args{status} eq 'on';
|
---|
4526 |
|
---|
4527 | my $nrecs = 0;
|
---|
4528 | my $soaflag = 0;
|
---|
4529 | my $nsflag = 0;
|
---|
4530 | my $warnmsg = '';
|
---|
4531 | my $ifrom;
|
---|
4532 |
|
---|
4533 | my $rev = 'n';
|
---|
4534 | my $code = 'OK';
|
---|
4535 | my $msg = 'foobar?';
|
---|
4536 |
|
---|
4537 | # choke on possible bad setting in ifrom
|
---|
4538 | # IPv4 and v6, and valid hostnames!
|
---|
4539 | ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
4540 | return ('FAIL', "Bad AXFR source host $ifrom")
|
---|
4541 | unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
4542 |
|
---|
4543 | my $errmsg;
|
---|
4544 |
|
---|
4545 | my $zone_id;
|
---|
4546 | my $domain_id = 0;
|
---|
4547 | my $rdns_id = 0;
|
---|
4548 | my $cidr;
|
---|
4549 |
|
---|
4550 | # magic happens! detect if we're importing a domain or a reverse zone
|
---|
4551 | # while we're at it, figure out what the CIDR netblock is (if we got a .arpa)
|
---|
4552 | # or what the formal .arpa zone is (if we got a CIDR netblock)
|
---|
4553 | # Handles sub-octet v4 zones in the format specified in the Cricket Book, 2nd Ed, p217-218
|
---|
4554 |
|
---|
4555 | if ($zone =~ m{(?:\.arpa\.?|/\d+)$}) {
|
---|
4556 | # we seem to have a reverse zone
|
---|
4557 | $rev = 'y';
|
---|
4558 |
|
---|
4559 | if ($zone =~ /\.arpa\.?$/) {
|
---|
4560 | # we have a formal reverse zone. call _zone2cidr and get the CIDR block.
|
---|
4561 | ($code,$msg) = _zone2cidr($zone);
|
---|
4562 | return ($code, $msg) if $code eq 'FAIL';
|
---|
4563 | $cidr = $msg;
|
---|
4564 | } elsif ($zone =~ m|^[\d.]+/\d+$|) {
|
---|
4565 | # v4 revzone, CIDR netblock
|
---|
4566 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
4567 | $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
4568 | } elsif ($zone =~ m|^[a-fA-F\d:]+/\d+$|) {
|
---|
4569 | # v6 revzone, CIDR netblock
|
---|
4570 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
4571 | return ('FAIL', "$zone is not a nibble-aligned block") if $cidr->masklen % 4 != 0;
|
---|
4572 | $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.');
|
---|
4573 | } else {
|
---|
4574 | # there is. no. else!
|
---|
4575 | return ('FAIL', "Unknown zone name format");
|
---|
4576 | }
|
---|
4577 |
|
---|
4578 | # quick check to start to see if we've already got one
|
---|
4579 |
|
---|
4580 | ($zone_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?",
|
---|
4581 | undef, ("$cidr"));
|
---|
4582 | $rdns_id = $zone_id;
|
---|
4583 | } else {
|
---|
4584 | # default to domain
|
---|
4585 | ($zone_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
4586 | undef, ($zone));
|
---|
4587 | $domain_id = $zone_id;
|
---|
4588 | }
|
---|
4589 |
|
---|
4590 | return ('FAIL', ($rev eq 'n' ? 'Domain' : 'Reverse zone')." already exists") if $zone_id;
|
---|
4591 |
|
---|
4592 | # little local utility sub to swap $val and $host for revzone records.
|
---|
4593 | sub _revswap {
|
---|
4594 | my $rechost = shift;
|
---|
4595 | my $recdata = shift;
|
---|
4596 |
|
---|
4597 | if ($rechost =~ /\.in-addr\.arpa\.?$/) {
|
---|
4598 | $rechost =~ s/\.in-addr\.arpa\.?$//;
|
---|
4599 | $rechost = join '.', reverse split /\./, $rechost;
|
---|
4600 | } else {
|
---|
4601 | $rechost =~ s/\.ip6\.arpa\.?$//;
|
---|
4602 | my @nibs = reverse split /\./, $rechost;
|
---|
4603 | $rechost = '';
|
---|
4604 | my $nc;
|
---|
4605 | foreach (@nibs) {
|
---|
4606 | $rechost.= $_;
|
---|
4607 | $rechost .= ":" if ++$nc % 4 == 0 && $nc < 32;
|
---|
4608 | }
|
---|
4609 | $rechost .= ":" if $nc < 32 && $rechost !~ /\*$/; # close netblock records?
|
---|
4610 | ##fixme: there's a case that ends up with a partial entry here:
|
---|
4611 | # ip:add:re:ss::
|
---|
4612 | # can't reproduce after letting it sit overnight after discovery. :(
|
---|
4613 | #print "$rechost\n";
|
---|
4614 | # canonicalize with NetAddr::IP
|
---|
4615 | $rechost = NetAddr::IP->new($rechost)->addr unless $rechost =~ /\*$/;
|
---|
4616 | }
|
---|
4617 | return ($recdata,$rechost)
|
---|
4618 | }
|
---|
4619 |
|
---|
4620 |
|
---|
4621 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
4622 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
4623 | local $dbh->{AutoCommit} = 0;
|
---|
4624 | local $dbh->{RaiseError} = 1;
|
---|
4625 |
|
---|
4626 | my $sth;
|
---|
4627 | eval {
|
---|
4628 |
|
---|
4629 | if ($rev eq 'n') {
|
---|
4630 | ##fixme: serial
|
---|
4631 | $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef,
|
---|
4632 | ($zone, $group, $args{status}) );
|
---|
4633 | # get domain id so we can do the records
|
---|
4634 | ($zone_id) = $dbh->selectrow_array("SELECT currval('domains_domain_id_seq')");
|
---|
4635 | $domain_id = $zone_id;
|
---|
4636 | $self->_log(group_id => $group, domain_id => $domain_id,
|
---|
4637 | entry => "[Added ".($args{status} ? 'active' : 'inactive')." domain $zone via AXFR]");
|
---|
4638 | } else {
|
---|
4639 | ##fixme: serial
|
---|
4640 | $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef,
|
---|
4641 | ($cidr,$group,$args{status}) );
|
---|
4642 | # get revzone id so we can do the records
|
---|
4643 | ($zone_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
4644 | $rdns_id = $zone_id;
|
---|
4645 | $self->_log(group_id => $group, rdns_id => $rdns_id,
|
---|
4646 | entry => "[Added ".($args{status} ? 'active' : 'inactive')." reverse zone $cidr via AXFR]");
|
---|
4647 | }
|
---|
4648 |
|
---|
4649 | ## bizarre DBI<->Net::DNS interaction bug:
|
---|
4650 | ## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
|
---|
4651 | ## fixed, apparently I was doing *something* odd, but not certain what it was that
|
---|
4652 | ## caused a commit instead of barfing
|
---|
4653 |
|
---|
4654 | my $res = Net::DNS::Resolver->new;
|
---|
4655 | $res->nameservers($ifrom);
|
---|
4656 | $res->axfr_start($zone)
|
---|
4657 | or die "Couldn't begin AXFR\n";
|
---|
4658 |
|
---|
4659 | $sth = $dbh->prepare("INSERT INTO records (domain_id,rdns_id,host,type,val,distance,weight,port,ttl)".
|
---|
4660 | " VALUES (?,?,?,?,?,?,?,?,?)");
|
---|
4661 |
|
---|
4662 | # Stash info about sub-octet v4 revzones here so we don't have
|
---|
4663 | # to store the CNAMEs used to delegate a suboctet zone
|
---|
4664 | # $suboct{zone}{ns}[] -> array of nameservers
|
---|
4665 | # $suboct{zone}{cname}[] -> array of extant CNAMEs (Just In Case someone did something bizarre)
|
---|
4666 | ## commented pending actual use of this data. for now, we'll just
|
---|
4667 | ## auto-(re)create the CNAMEs in revzones on export
|
---|
4668 | # my %suboct;
|
---|
4669 |
|
---|
4670 | while (my $rr = $res->axfr_next()) {
|
---|
4671 |
|
---|
4672 | my $val;
|
---|
4673 | my $distance = 0;
|
---|
4674 | my $weight = 0;
|
---|
4675 | my $port = 0;
|
---|
4676 | my $logfrag = '';
|
---|
4677 |
|
---|
4678 | my $type = $rr->type;
|
---|
4679 | my $ttl = ($newttl ? $newttl : $rr->ttl); # allow force-override TTLs
|
---|
4680 | my $host = $rr->name;
|
---|
4681 | my $ttl = ($args{newttl} ? $args{newttl} : $rr->ttl); # allow force-override TTLs
|
---|
4682 |
|
---|
4683 | $soaflag = 1 if $type eq 'SOA';
|
---|
4684 | $nsflag = 1 if $type eq 'NS';
|
---|
4685 |
|
---|
4686 | # "Primary" types:
|
---|
4687 | # A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
|
---|
4688 | # maybe KEY
|
---|
4689 |
|
---|
4690 | # BIND supports:
|
---|
4691 | # [standard]
|
---|
4692 | # A AAAA CNAME MX NS PTR SOA TXT
|
---|
4693 | # [variously experimental, obsolete, or obscure]
|
---|
4694 | # 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
|
---|
4695 | # ... if one can ever find the right magic to format them correctly
|
---|
4696 |
|
---|
4697 | # Net::DNS supports:
|
---|
4698 | # RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
|
---|
4699 | # EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
|
---|
4700 | # DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
|
---|
4701 |
|
---|
4702 | # nasty big ugly case-like thing here, since we have to do *some* different
|
---|
4703 | # processing depending on the record. le sigh.
|
---|
4704 |
|
---|
4705 | ##fixme: what record types other than TXT can/will have >255-byte payloads?
|
---|
4706 |
|
---|
4707 | if ($type eq 'A') {
|
---|
4708 | $val = $rr->address;
|
---|
4709 | } elsif ($type eq 'NS') {
|
---|
4710 | # hmm. should we warn here if subdomain NS'es are left alone?
|
---|
4711 | next if ($args{rwns} && ($rr->name eq $zone));
|
---|
4712 | if ($rev eq 'y') {
|
---|
4713 | # revzones have records more or less reversed from forward zones.
|
---|
4714 | my ($tmpcode,$tmpmsg) = _zone2cidr($host);
|
---|
4715 | die "Error converting NS record: $tmpmsg\n" if $tmpcode eq 'FAIL'; # hmm. may not make sense...
|
---|
4716 | $val = "$tmpmsg";
|
---|
4717 | $host = $rr->nsdname;
|
---|
4718 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
4719 | # Tag and preserve. For now this is commented for a no-op, but we have Ideas for
|
---|
4720 | # another custom storage type ("DELEGATE") that will use these subzone-delegation records
|
---|
4721 | #if ($val ne "$cidr") {
|
---|
4722 | # push @{$suboct{$val}{ns}}, $host;
|
---|
4723 | #}
|
---|
4724 | } else {
|
---|
4725 | $val = $rr->nsdname;
|
---|
4726 | }
|
---|
4727 | $nsflag = 1;
|
---|
4728 | } elsif ($type eq 'CNAME') {
|
---|
4729 | if ($rev eq 'y') {
|
---|
4730 | # hmm. do we even want to bother with storing these at this level? Sub-octet delegation
|
---|
4731 | # by CNAME is essentially a record-publication hack, and we want to just represent the
|
---|
4732 | # "true" logical intentions as far down the stack as we can from the UI.
|
---|
4733 | ($host,$val) = _revswap($host,$rr->cname);
|
---|
4734 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
4735 | # Tag and preserve in case we want to commit them as-is later, but mostly we don't care.
|
---|
4736 | # Commented pending actually doing something with possibly new type DELEGATE
|
---|
4737 | #my $tmprev = $host;
|
---|
4738 | #$tmprev =~ s/^\d+\.//;
|
---|
4739 | #($code,$tmprev) = _zone2cidr($tmprev);
|
---|
4740 | #push @{$suboct{"$tmprev"}{cname}}, $val;
|
---|
4741 | # Silently skip CNAMEs in revzones.
|
---|
4742 | next;
|
---|
4743 | } else {
|
---|
4744 | $val = $rr->cname;
|
---|
4745 | }
|
---|
4746 | } elsif ($type eq 'SOA') {
|
---|
4747 | next if $args{rwsoa};
|
---|
4748 | $host = $rr->rname.":".$rr->mname;
|
---|
4749 | $val = $rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum;
|
---|
4750 | $soaflag = 1;
|
---|
4751 | } elsif ($type eq 'PTR') {
|
---|
4752 | ($host,$val) = _revswap($host,$rr->ptrdname);
|
---|
4753 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
4754 | # hmm. PTR records should not be in forward zones.
|
---|
4755 | } elsif ($type eq 'MX') {
|
---|
4756 | $val = $rr->exchange;
|
---|
4757 | $distance = $rr->preference;
|
---|
4758 | } elsif ($type eq 'TXT') {
|
---|
4759 | ##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
|
---|
4760 | ## but don't really seem enthusiastic about it.
|
---|
4761 | #print "should use rdatastr:\n\t".$rr->rdatastr."\n or char_str_list:\n\t".join(' ',$rr->char_str_list())."\n";
|
---|
4762 | # rdatastr returns a BIND-targetted logical string, including opening and closing quotes
|
---|
4763 | # char_str_list returns a list of the individual string fragments in the record
|
---|
4764 | # txtdata returns the more useful all-in-one form (since we want to push such protocol
|
---|
4765 | # details as far down the stack as we can)
|
---|
4766 | # NB: this may turn out to be more troublesome if we ever have need of >512-byte TXT records.
|
---|
4767 | if ($rev eq 'y') {
|
---|
4768 | ($host,$val) = _revswap($host,$rr->txtdata);
|
---|
4769 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
4770 | } else {
|
---|
4771 | $val = $rr->txtdata;
|
---|
4772 | }
|
---|
4773 | } elsif ($type eq 'SPF') {
|
---|
4774 | ##fixme: and the same caveat here, since it is apparently a clone of ::TXT
|
---|
4775 | $val = $rr->txtdata;
|
---|
4776 | } elsif ($type eq 'AAAA') {
|
---|
4777 | $val = $rr->address;
|
---|
4778 | } elsif ($type eq 'SRV') {
|
---|
4779 | $val = $rr->target;
|
---|
4780 | $distance = $rr->priority;
|
---|
4781 | $weight = $rr->weight;
|
---|
4782 | $port = $rr->port;
|
---|
4783 | } elsif ($type eq 'KEY') {
|
---|
4784 | # we don't actually know what to do with these...
|
---|
4785 | $val = $rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname;
|
---|
4786 | } else {
|
---|
4787 | $val = $rr->rdatastr;
|
---|
4788 | # Finding a different record type is not fatal.... just problematic.
|
---|
4789 | # We may not be able to export it correctly.
|
---|
4790 | $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
|
---|
4791 | }
|
---|
4792 |
|
---|
4793 | my $logentry = "[AXFR ".($rev eq 'n' ? $zone : $cidr)."] ";
|
---|
4794 |
|
---|
4795 | if ($args{merge}) {
|
---|
4796 | if ($rev eq 'n') {
|
---|
4797 | # importing a domain; we have A and AAAA records that could be merged with matching PTR records
|
---|
4798 | my $etype;
|
---|
4799 | my ($erdns,$erid,$ettl) = $dbh->selectrow_array("SELECT rdns_id,record_id,ttl FROM records ".
|
---|
4800 | "WHERE host=? AND val=? AND type=12",
|
---|
4801 | undef, ($host, $val) );
|
---|
4802 | if ($erid) {
|
---|
4803 | if ($type eq 'A') { # PTR -> A+PTR
|
---|
4804 | $etype = 65280;
|
---|
4805 | $logentry .= "Merged A record with existing PTR record '$host A+PTR $val', TTL $ettl";
|
---|
4806 | }
|
---|
4807 | if ($type eq 'AAAA') { # PTR -> AAAA+PTR
|
---|
4808 | $etype = 65281;
|
---|
4809 | $logentry .= "Merged AAAA record with existing PTR record '$host AAAA+PTR $val', TTL $ettl";
|
---|
4810 | }
|
---|
4811 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
4812 | $dbh->do("UPDATE records SET domain_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
4813 | ($domain_id, $ettl, $etype, $erid));
|
---|
4814 | $nrecs++;
|
---|
4815 | $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $erdns, entry => $logentry);
|
---|
4816 | next; # while axfr_next
|
---|
4817 | }
|
---|
4818 | } # $rev eq 'n'
|
---|
4819 | else {
|
---|
4820 | # importing a revzone, we have PTR records that could be merged with matching A/AAAA records
|
---|
4821 | my ($domid,$erid,$ettl,$etype) = $dbh->selectrow_array("SELECT domain_id,record_id,ttl,type FROM records ".
|
---|
4822 | "WHERE host=? AND val=? AND (type=1 OR type=28)",
|
---|
4823 | undef, ($host, $val) );
|
---|
4824 | if ($erid) {
|
---|
4825 | if ($etype == 1) { # A -> A+PTR
|
---|
4826 | $etype = 65280;
|
---|
4827 | $logentry .= "Merged PTR record with existing matching A record '$host A+PTR $val', TTL $ettl";
|
---|
4828 | }
|
---|
4829 | if ($etype == 28) { # AAAA -> AAAA+PTR
|
---|
4830 | $etype = 65281;
|
---|
4831 | $logentry .= "Merged PTR record with existing matching AAAA record '$host AAAA+PTR $val', TTL $ettl";
|
---|
4832 | }
|
---|
4833 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
4834 | $dbh->do("UPDATE records SET rdns_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
4835 | ($rdns_id, $ettl, $etype, $erid));
|
---|
4836 | $nrecs++;
|
---|
4837 | $self->_log(group_id => $group, domain_id => $domid, rdns_id => $rdns_id, entry => $logentry);
|
---|
4838 | next; # while axfr_next
|
---|
4839 | }
|
---|
4840 | } # $rev eq 'y'
|
---|
4841 | } # if $args{merge}
|
---|
4842 |
|
---|
4843 | # Insert the new record
|
---|
4844 | $sth->execute($domain_id, $rdns_id, $host, $reverse_typemap{$type}, $val,
|
---|
4845 | $distance, $weight, $port, $ttl);
|
---|
4846 |
|
---|
4847 | $nrecs++;
|
---|
4848 |
|
---|
4849 | if ($type eq 'SOA') {
|
---|
4850 | # also !$args{rwsoa}, but if that's set, it should be impossible to get here.
|
---|
4851 | my @tmp1 = split /:/, $host;
|
---|
4852 | my @tmp2 = split /:/, $val;
|
---|
4853 | $logentry .= "Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
4854 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl";
|
---|
4855 | } elsif ($logfrag) {
|
---|
4856 | # special case for log entries we need to meddle with a little.
|
---|
4857 | $logentry .= $logfrag;
|
---|
4858 | } else {
|
---|
4859 | $logentry .= "Added record '$host $type";
|
---|
4860 | $logentry .= " [distance $distance]" if $type eq 'MX';
|
---|
4861 | $logentry .= " [priority $distance] [weight $weight] [port $port]" if $type eq 'SRV';
|
---|
4862 | $logentry .= " $val', TTL $ttl";
|
---|
4863 | }
|
---|
4864 | $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $rdns_id, entry => $logentry);
|
---|
4865 |
|
---|
4866 | } # while axfr_next
|
---|
4867 |
|
---|
4868 | # Detect and handle delegated subzones
|
---|
4869 | # Placeholder for when we decide what to actually do with this, see previous comments in NS and CNAME handling.
|
---|
4870 | #foreach (keys %suboct) {
|
---|
4871 | # print "found ".($suboct{$_}{ns} ? @{$suboct{$_}{ns}} : '0')." NS records and ".
|
---|
4872 | # ($suboct{$_}{cname} ? @{$suboct{$_}{cname}} : '0')." CNAMEs for $_\n";
|
---|
4873 | #}
|
---|
4874 |
|
---|
4875 | # Overwrite SOA record
|
---|
4876 | if ($args{rwsoa}) {
|
---|
4877 | $soaflag = 1;
|
---|
4878 | my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
|
---|
4879 | my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
4880 | $sthgetsoa->execute($group,$reverse_typemap{SOA});
|
---|
4881 | while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
|
---|
4882 | $host =~ s/DOMAIN/$zone/g;
|
---|
4883 | $val =~ s/DOMAIN/$zone/g;
|
---|
4884 | $sthputsoa->execute($zone_id,$host,$reverse_typemap{SOA},$val,$ttl);
|
---|
4885 | }
|
---|
4886 | }
|
---|
4887 |
|
---|
4888 | # Overwrite NS records
|
---|
4889 | if ($args{rwns}) {
|
---|
4890 | $nsflag = 1;
|
---|
4891 | my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
|
---|
4892 | my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
4893 | $sthgetns->execute($group,$reverse_typemap{NS});
|
---|
4894 | while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
|
---|
4895 | $host =~ s/DOMAIN/$zone/g;
|
---|
4896 | $val =~ s/DOMAIN/$zone/g;
|
---|
4897 | $sthputns->execute($zone_id,$host,$reverse_typemap{NS},$val,$ttl);
|
---|
4898 | }
|
---|
4899 | }
|
---|
4900 |
|
---|
4901 | die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
|
---|
4902 | die "Bad zone: No SOA record!\n" if !$soaflag;
|
---|
4903 | die "Bad zone: No NS records!\n" if !$nsflag;
|
---|
4904 |
|
---|
4905 | $dbh->commit;
|
---|
4906 |
|
---|
4907 | };
|
---|
4908 |
|
---|
4909 | if ($@) {
|
---|
4910 | my $msg = $@;
|
---|
4911 | eval { $dbh->rollback; };
|
---|
4912 | return ('FAIL',$msg." $warnmsg");
|
---|
4913 | } else {
|
---|
4914 | return ('WARN', $warnmsg) if $warnmsg;
|
---|
4915 | return ('OK',"Imported OK");
|
---|
4916 | }
|
---|
4917 |
|
---|
4918 | # it should be impossible to get here.
|
---|
4919 | return ('WARN',"OOOK!");
|
---|
4920 | } # end importAXFR()
|
---|
4921 |
|
---|
4922 |
|
---|
4923 | ## DNSDB::importBIND()
|
---|
4924 | sub importBIND {
|
---|
4925 | } # end importBIND()
|
---|
4926 |
|
---|
4927 |
|
---|
4928 | ## DNSDB::import_tinydns()
|
---|
4929 | sub import_tinydns {
|
---|
4930 | } # end import_tinydns()
|
---|
4931 |
|
---|
4932 |
|
---|
4933 | ## DNSDB::export()
|
---|
4934 | # Export the DNS database, or a part of it
|
---|
4935 | # Takes a string indicating the export type, plus optional arguments depending on type
|
---|
4936 | # Writes zone data to targets as appropriate for type
|
---|
4937 | sub export {
|
---|
4938 | my $self = shift;
|
---|
4939 | my $target = shift;
|
---|
4940 |
|
---|
4941 | if ($target eq 'tiny') {
|
---|
4942 | $self->__export_tiny(@_);
|
---|
4943 | }
|
---|
4944 | # elsif ($target eq 'foo') {
|
---|
4945 | # __export_foo(@_);
|
---|
4946 | #}
|
---|
4947 | # etc
|
---|
4948 |
|
---|
4949 | } # end export()
|
---|
4950 |
|
---|
4951 |
|
---|
4952 | ## DNSDB::__export_tiny
|
---|
4953 | # Internal sub to implement tinyDNS (compatible) export
|
---|
4954 | # Takes filehandle to write export to, optional argument(s)
|
---|
4955 | # to determine which data gets exported
|
---|
4956 | sub __export_tiny {
|
---|
4957 | my $self = shift;
|
---|
4958 | my $dbh = $self->{dbh};
|
---|
4959 | my $datafile = shift;
|
---|
4960 |
|
---|
4961 | ##fixme: slurp up further options to specify particular zone(s) to export
|
---|
4962 |
|
---|
4963 | ##fixme: fail if $datafile isn't an open, writable file
|
---|
4964 |
|
---|
4965 | # easy case - export all evarything
|
---|
4966 | # not-so-easy case - export item(s) specified
|
---|
4967 | # todo: figure out what kind of list we use to export items
|
---|
4968 |
|
---|
4969 | # raw packet in unknown format: first byte indicates length
|
---|
4970 | # of remaining data, allows up to 255 raw bytes
|
---|
4971 |
|
---|
4972 | # Locations/views - worth including in the caching setup?
|
---|
4973 | my $lochash = $dbh->selectall_hashref("SELECT location,iplist FROM locations", 'location');
|
---|
4974 | foreach my $location (keys %$lochash) {
|
---|
4975 | foreach my $ipprefix (split /[,\s]+/, $lochash->{$location}{iplist}) {
|
---|
4976 | $ipprefix =~ s/\s+//g;
|
---|
4977 | $ipprefix = new NetAddr::IP $ipprefix;
|
---|
4978 | ##fixme: how to handle IPv6?
|
---|
4979 | next if $ipprefix->{isv6};
|
---|
4980 | # have to account for /nn CIDR entries. tinydns only speaks octet-sliced prefix.
|
---|
4981 | if ($ipprefix->masklen <= 8) {
|
---|
4982 | foreach ($ipprefix->split(8)) {
|
---|
4983 | my $tmp = $_->addr;
|
---|
4984 | $tmp =~ s/\.\d+\.\d+\.\d+$//;
|
---|
4985 | print $datafile "%$location:$tmp\n";
|
---|
4986 | }
|
---|
4987 | } elsif ($ipprefix->masklen <= 16) {
|
---|
4988 | foreach ($ipprefix->split(16)) {
|
---|
4989 | my $tmp = $_->addr;
|
---|
4990 | $tmp =~ s/\.\d+\.\d+$//;
|
---|
4991 | print $datafile "%$location:$tmp\n";
|
---|
4992 | }
|
---|
4993 | } elsif ($ipprefix->masklen <= 24) {
|
---|
4994 | foreach ($ipprefix->split(24)) {
|
---|
4995 | my $tmp = $_->addr;
|
---|
4996 | $tmp =~ s/\.\d+$//;
|
---|
4997 | print $datafile "%$location:$tmp\n";
|
---|
4998 | }
|
---|
4999 | } else {
|
---|
5000 | foreach ($ipprefix->split(32)) {
|
---|
5001 | print $datafile "%$location:".$_->addr."\n";
|
---|
5002 | }
|
---|
5003 | }
|
---|
5004 | }
|
---|
5005 | print $datafile "%$location\n" if !$lochash->{$location}{iplist};
|
---|
5006 | }
|
---|
5007 |
|
---|
5008 | # tracking hash so we don't double-export A+PTR or AAAA+PTR records.
|
---|
5009 | my %recflags;
|
---|
5010 |
|
---|
5011 | # For reasons unknown, we can't sanely UNION these statements. Feh.
|
---|
5012 | # Supposedly it should work though (note last 3 lines):
|
---|
5013 | ## PG manual
|
---|
5014 | #UNION Clause
|
---|
5015 | #
|
---|
5016 | #The UNION clause has this general form:
|
---|
5017 | #
|
---|
5018 | # select_statement UNION [ ALL ] select_statement
|
---|
5019 | #
|
---|
5020 | #select_statement is any SELECT statement without an ORDER BY, LIMIT, FOR UPDATE, or FOR SHARE clause. (ORDER BY
|
---|
5021 | #and LIMIT can be attached to a subexpression if it is enclosed in parentheses. Without parentheses, these
|
---|
5022 | #clauses will be taken to apply to the result of the UNION, not to its right-hand input expression.)
|
---|
5023 | my $soasth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
5024 | "FROM records WHERE rdns_id=? AND type=6");
|
---|
5025 | my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location,extract(epoch from stamp),expires,stampactive ".
|
---|
5026 | "FROM records WHERE rdns_id=? AND not type=6 ".
|
---|
5027 | "ORDER BY masklen(CAST(val AS inet)) DESC, CAST(val AS inet)");
|
---|
5028 | my $revsth = $dbh->prepare("SELECT rdns_id,revnet,status,changed FROM revzones WHERE status=1 ".
|
---|
5029 | "ORDER BY masklen(revnet) DESC");
|
---|
5030 | my $zonesth = $dbh->prepare("UPDATE revzones SET changed='n' WHERE rdns_id=?");
|
---|
5031 | $revsth->execute();
|
---|
5032 | while (my ($revid,$revzone,$revstat,$changed) = $revsth->fetchrow_array) {
|
---|
5033 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
5034 | # O_NOFOLLOW
|
---|
5035 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
5036 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
5037 | # still be followed.
|
---|
5038 | # but that doesn't help other platforms. :/
|
---|
5039 | my $tmpzone = NetAddr::IP->new($revzone);
|
---|
5040 | ##fixme: locations/views? subnet mask? need to avoid possible collisions with zone/superzone
|
---|
5041 | ## (eg /20 vs /24, starting on .0.0)
|
---|
5042 | my $cz = $tmpzone->network->addr."-".$tmpzone->masklen;
|
---|
5043 | my $cachefile = "$self->{exportcache}/$cz";
|
---|
5044 | my $tmpcache = "$self->{exportcache}/tmp.$cz.$$";
|
---|
5045 | eval {
|
---|
5046 |
|
---|
5047 | # only update the cache file if the zone has changed, or if the cache file has nothing in it.
|
---|
5048 | if ($self->{force_refresh} || $changed || !-e $cachefile || -z $cachefile) {
|
---|
5049 | open ZONECACHE, ">$tmpcache" or die "Error creating temporary file $tmpcache: $!\n";
|
---|
5050 |
|
---|
5051 | # need to fetch this separately since the rest of the records all (should) have real IPs in val
|
---|
5052 | $soasth->execute($revid);
|
---|
5053 | my (@zsoa) = $soasth->fetchrow_array();
|
---|
5054 | _printrec_tiny(*ZONECACHE,'y',\%recflags,$revzone,
|
---|
5055 | $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],'');
|
---|
5056 |
|
---|
5057 | $recsth->execute($revid);
|
---|
5058 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc,$stamp,$expires,$stampactive) = $recsth->fetchrow_array) {
|
---|
5059 | next if $recflags{$recid};
|
---|
5060 |
|
---|
5061 | # not sure this is necessary for revzones.
|
---|
5062 | # # Spaces are evil.
|
---|
5063 | # $val =~ s/^\s+//;
|
---|
5064 | # $val =~ s/\s+$//;
|
---|
5065 | # if ($typemap{$type} ne 'TXT') {
|
---|
5066 | # # Leading or trailng spaces could be legit in TXT records.
|
---|
5067 | # $host =~ s/^\s+//;
|
---|
5068 | # $host =~ s/\s+$//;
|
---|
5069 | # }
|
---|
5070 |
|
---|
5071 | _printrec_tiny(*ZONECACHE, 'y', \%recflags, $revzone,
|
---|
5072 | $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp, $expires, $stampactive)
|
---|
5073 | if *ZONECACHE;
|
---|
5074 |
|
---|
5075 | $recflags{$recid} = 1;
|
---|
5076 |
|
---|
5077 | } # while ($recsth)
|
---|
5078 |
|
---|
5079 | close ZONECACHE; # force the file to be written
|
---|
5080 |
|
---|
5081 | # catch obvious write errors that leave an empty temp file
|
---|
5082 | if (-s $tmpcache) {
|
---|
5083 | rename $tmpcache, $cachefile
|
---|
5084 | or die "Error overwriting cache file $cachefile with temporary file: $!\n";
|
---|
5085 | }
|
---|
5086 |
|
---|
5087 | } # if $changed or cache filesize is 0
|
---|
5088 |
|
---|
5089 | };
|
---|
5090 | if ($@) {
|
---|
5091 | print "error writing new data for $revzone: $@\n";
|
---|
5092 | # error! something borked, and we should be able to fall back on the old cache file
|
---|
5093 | # report the error, somehow.
|
---|
5094 | } else {
|
---|
5095 | # mark zone as unmodified. Only do this if no errors, that way
|
---|
5096 | # export failures should recover a little more automatically.
|
---|
5097 | $zonesth->execute($revid);
|
---|
5098 | }
|
---|
5099 | # Always stream the cache (even if stale or obsolete due to errors creating the new cache)
|
---|
5100 | open CACHE, "<$cachefile";
|
---|
5101 | print $datafile $_ while <CACHE>;
|
---|
5102 | close CACHE;
|
---|
5103 |
|
---|
5104 | } # while ($revsth)
|
---|
5105 |
|
---|
5106 | my $domsth = $dbh->prepare("SELECT domain_id,domain,status,changed FROM domains WHERE status=1");
|
---|
5107 | $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location,extract(epoch from stamp),expires,stampactive ".
|
---|
5108 | "FROM records WHERE domain_id=?"); # Just exclude all types relating to rDNS
|
---|
5109 | # "FROM records WHERE domain_id=? AND type < 65280"); # Just exclude all types relating to rDNS
|
---|
5110 | $zonesth = $dbh->prepare("UPDATE domains SET changed='n' WHERE domain_id=?");
|
---|
5111 | $domsth->execute();
|
---|
5112 | while (my ($domid,$dom,$domstat,$changed) = $domsth->fetchrow_array) {
|
---|
5113 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
5114 | # O_NOFOLLOW
|
---|
5115 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
5116 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
5117 | # still be followed.
|
---|
5118 | # but that doesn't help other platforms. :/
|
---|
5119 | my $cachefile = "$self->{exportcache}/$dom";
|
---|
5120 | my $tmpcache = "$self->{exportcache}/tmp.$dom.$$";
|
---|
5121 | eval {
|
---|
5122 |
|
---|
5123 | # only update the cache file if the zone has changed, or if the cache file has nothing in it.
|
---|
5124 | if ($self->{force_refresh} || $changed || !-e $cachefile || -z $cachefile) {
|
---|
5125 | open ZONECACHE, ">$tmpcache" or die "Error creating temporary file $tmpcache: $!\n";
|
---|
5126 |
|
---|
5127 | $recsth->execute($domid);
|
---|
5128 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc,$stamp,$expires,$stampactive) = $recsth->fetchrow_array) {
|
---|
5129 | next if $recflags{$recid};
|
---|
5130 |
|
---|
5131 | # Spaces are evil.
|
---|
5132 | $host =~ s/^\s+//;
|
---|
5133 | $host =~ s/\s+$//;
|
---|
5134 | if ($typemap{$type} ne 'TXT') {
|
---|
5135 | # Leading or trailng spaces could be legit in TXT records.
|
---|
5136 | $val =~ s/^\s+//;
|
---|
5137 | $val =~ s/\s+$//;
|
---|
5138 | }
|
---|
5139 |
|
---|
5140 | _printrec_tiny(*ZONECACHE, 'n', \%recflags,
|
---|
5141 | $dom, $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp, $expires, $stampactive)
|
---|
5142 | if *ZONECACHE;
|
---|
5143 |
|
---|
5144 | $recflags{$recid} = 1;
|
---|
5145 |
|
---|
5146 | } # while ($recsth)
|
---|
5147 |
|
---|
5148 | close ZONECACHE; # force the file to be written
|
---|
5149 |
|
---|
5150 | # catch obvious write errors that leave an empty temp file
|
---|
5151 | if (-s $tmpcache) {
|
---|
5152 | rename $tmpcache, $cachefile
|
---|
5153 | or die "Error overwriting cache file $cachefile with temporary file: $!\n";
|
---|
5154 | }
|
---|
5155 |
|
---|
5156 | } # if $changed or cache filesize is 0
|
---|
5157 |
|
---|
5158 | };
|
---|
5159 | if ($@) {
|
---|
5160 | print "error writing new data for $dom: $@\n";
|
---|
5161 | # error! something borked, and we should be able to fall back on the old cache file
|
---|
5162 | # report the error, somehow.
|
---|
5163 | } else {
|
---|
5164 | # mark domain as unmodified. Only do this if no errors, that way
|
---|
5165 | # export failures should recover a little more automatically.
|
---|
5166 | $zonesth->execute($domid);
|
---|
5167 | }
|
---|
5168 | # Always stream the cache (even if stale or obsolete due to errors creating the new cache)
|
---|
5169 | open CACHE, "<$cachefile";
|
---|
5170 | print $datafile $_ while <CACHE>;
|
---|
5171 | close CACHE;
|
---|
5172 |
|
---|
5173 | } # while ($domsth)
|
---|
5174 |
|
---|
5175 | } # end __export_tiny()
|
---|
5176 |
|
---|
5177 |
|
---|
5178 | # Utility sub for __export_tiny above
|
---|
5179 | sub _printrec_tiny {
|
---|
5180 | my ($datafile,$revrec,$recflags,$zone,$host,$type,$val,$dist,$weight,$port,$ttl,$loc,$stamp,$expires,$stampactive) = @_;
|
---|
5181 |
|
---|
5182 | $loc = '' if !$loc; # de-nullify - just in case
|
---|
5183 | ##fixme: handle case of record-with-location-that-doesn't-exist better.
|
---|
5184 | # note this currently fails safe (tested) - records with a location that
|
---|
5185 | # doesn't exist will not be sent to any client
|
---|
5186 | # $loc = '' if !$lochash->{$loc};
|
---|
5187 |
|
---|
5188 |
|
---|
5189 | ## Records that are valid only before or after a set time
|
---|
5190 |
|
---|
5191 | # record due to expire sometime is the complex case. we don't want to just
|
---|
5192 | # rely on tinydns' auto-adjusting TTLs, because the default TTL in that case
|
---|
5193 | # is one day instead of the SOA minttl as BIND might do.
|
---|
5194 |
|
---|
5195 | # consider the case where a record is set to expire a week ahead, but the next
|
---|
5196 | # day later you want to change it NOW (or as NOWish as you get with your DNS
|
---|
5197 | # management practice). but now you're stuck, because someone, somewhere,
|
---|
5198 | # has just done a lookup before your latest change was published, and they'll
|
---|
5199 | # be caching that old, broken record for 1 day instead of your zone default
|
---|
5200 | # TTL.
|
---|
5201 |
|
---|
5202 | # $stamp-$ttl is the *latest* we can publish the record with the defined TTL
|
---|
5203 | # to still have the expiry happen as scheduled, but we need to find some
|
---|
5204 | # *earlier* point. We can maybe guess, and 2x TTL is probably reasonable,
|
---|
5205 | # but we need info on the export frequency.
|
---|
5206 |
|
---|
5207 | # export the normal, non-expiring record up until $stamp-<guesstimate>, then
|
---|
5208 | # switch to exporting a record with the TAI64 stamp and a 0 TTL so tinydns
|
---|
5209 | # takes over TTL management.
|
---|
5210 |
|
---|
5211 | if ($stampactive) {
|
---|
5212 | if ($expires) {
|
---|
5213 | # record expires at $stamp; decide if we need to keep the TTL and ignore
|
---|
5214 | # the stamp for a time or if we need to change the TTL to 0 and convert
|
---|
5215 | # $stamp to TAI64 so tinydns can use $stamp to autoadjust the TTL on the fly.
|
---|
5216 | # extra hack, optimally needs more knowledge of data export frequency
|
---|
5217 | # smack the idiot customer who insists on 0 TTLs; they can suck up and
|
---|
5218 | # deal with a 10-minute TTL. especially on scheduled changes. note this
|
---|
5219 | # should be (export freq * 2), but we don't know the actual export frequency.
|
---|
5220 | $ttl = 300 if $ttl == 0; #hack phtui
|
---|
5221 | my $ahead = (86400 < $ttl*2 ? 86400 : $ttl*2);
|
---|
5222 | if ((time() + $ahead) < $stamp) {
|
---|
5223 | # more than 2x TTL OR more than one day (whichever is less) from expiry time; publish normal record
|
---|
5224 | $stamp = '';
|
---|
5225 | } else {
|
---|
5226 | # less than 2x TTL from expiry time, let tinydns take over TTL management and publish the TAI64 stamp.
|
---|
5227 | $ttl = 0;
|
---|
5228 | $stamp = unixtai64($stamp);
|
---|
5229 | $stamp =~ s/\@//;
|
---|
5230 | }
|
---|
5231 | } else {
|
---|
5232 | # record is "active after"; convert epoch from database to TAI64, publish, and collect $200.
|
---|
5233 | $stamp = unixtai64($stamp);
|
---|
5234 | $stamp =~ s/\@//;
|
---|
5235 | }
|
---|
5236 | } else {
|
---|
5237 | # flag for active timestamp is false; don't actually put a timestamp in the output
|
---|
5238 | $stamp = '';
|
---|
5239 | }
|
---|
5240 |
|
---|
5241 | # support tinydns' auto-TTL
|
---|
5242 | $ttl = '' if $ttl == -1;
|
---|
5243 | # these are WAY FREAKING HIGH - higher even than most TLD registry TTLs!
|
---|
5244 | # NS 259200 => 3d
|
---|
5245 | # all others 86400 => 1d
|
---|
5246 |
|
---|
5247 | if ($revrec eq 'y') {
|
---|
5248 | $val = $zone if $val eq '@';
|
---|
5249 | } else {
|
---|
5250 | $host = $zone if $host eq '@';
|
---|
5251 | }
|
---|
5252 |
|
---|
5253 | ## Convert a bare number into an octal-coded pair of octets.
|
---|
5254 | # Take optional arg to indicate a decimal or hex input. Defaults to hex.
|
---|
5255 | sub octalize {
|
---|
5256 | my $tmp = shift;
|
---|
5257 | my $srctype = shift || 'h'; # default assumes hex string
|
---|
5258 | $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
|
---|
5259 | $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
|
---|
5260 | my @o = ($tmp =~ /^(..)(..)$/); # split into octets
|
---|
5261 | return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);;
|
---|
5262 | }
|
---|
5263 |
|
---|
5264 | ## WARNING: This works to export even the whole Internet's worth of IP space...
|
---|
5265 | ## if you have the disk/RAM to handle the dataset, and you call this sub based on /16-sized chunks
|
---|
5266 | ## A /16 took ~3 seconds with a handful of separate records; adding a /8 pushed export time out to ~13m:40s
|
---|
5267 | ## 0/0 is estimated to take ~54 hours and ~256G of disk
|
---|
5268 | ## RAM usage depends on how many non-template entries you have in the set.
|
---|
5269 | ## This should probably be done on record addition rather than export; large blocks may need to be done in a
|
---|
5270 | ## forked process
|
---|
5271 | sub __publish_subnet {
|
---|
5272 | my $sub = shift;
|
---|
5273 | my $recflags = shift;
|
---|
5274 | my $hpat = shift;
|
---|
5275 | my $fh = shift;
|
---|
5276 | my $ttl = shift;
|
---|
5277 | my $stamp = shift;
|
---|
5278 | my $loc = shift;
|
---|
5279 | my $ptronly = shift || 0;
|
---|
5280 |
|
---|
5281 | my $iplist = $sub->splitref(32);
|
---|
5282 | foreach (@$iplist) {
|
---|
5283 | my $ip = $_->addr;
|
---|
5284 | # make as if we split the non-octet-aligned block into octet-aligned blocks as with SOA
|
---|
5285 | next if $ip =~ /\.(0|255)$/;
|
---|
5286 | next if $$recflags{$ip};
|
---|
5287 | $$recflags{$ip}++;
|
---|
5288 | next if $hpat eq '%blank%'; # Allows blanking a subnet so no records are published.
|
---|
5289 | my $rec = $hpat; # start fresh with the template for each IP
|
---|
5290 | _template4_expand(\$rec, $ip);
|
---|
5291 | print $fh ($ptronly ? "^"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$rec" : "=$rec:$ip").
|
---|
5292 | ":$ttl:$stamp:$loc\n";
|
---|
5293 | }
|
---|
5294 | }
|
---|
5295 |
|
---|
5296 | ##fixme? append . to all host/val hostnames
|
---|
5297 | if ($typemap{$type} eq 'SOA') {
|
---|
5298 |
|
---|
5299 | # host contains pri-ns:responsible
|
---|
5300 | # val is abused to contain refresh:retry:expire:minttl
|
---|
5301 | ##fixme: "manual" serial vs tinydns-autoserial
|
---|
5302 | # let's be explicit about abusing $host and $val
|
---|
5303 | my ($email, $primary) = (split /:/, $host)[0,1];
|
---|
5304 | my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
|
---|
5305 | if ($revrec eq 'y') {
|
---|
5306 | ##fixme: have to publish SOA records for each v4 /24 in sub-/16, and each /16 in sub-/8
|
---|
5307 | # what about v6?
|
---|
5308 | # -> only need SOA for local chunks offset from reverse delegation boundaries, so v6 is fine
|
---|
5309 | $zone = NetAddr::IP->new($zone);
|
---|
5310 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
5311 | if (!$zone->{isv6} && ($zone->masklen < 24) && ($zone->masklen % 8 != 0)) {
|
---|
5312 | foreach my $szone ($zone->split($zone->masklen + (8 - $zone->masklen % 8))) {
|
---|
5313 | $szone = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
5314 | print $datafile "Z$szone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
|
---|
5315 | }
|
---|
5316 | return; # skips "default" bits just below
|
---|
5317 | }
|
---|
5318 | $zone = _ZONE($zone, 'ZONE', 'r', '.').($zone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
5319 | }
|
---|
5320 | print $datafile "Z$zone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
|
---|
5321 |
|
---|
5322 | } elsif ($typemap{$type} eq 'A') {
|
---|
5323 |
|
---|
5324 | print $datafile "+$host:$val:$ttl:$stamp:$loc\n";
|
---|
5325 |
|
---|
5326 | } elsif ($typemap{$type} eq 'NS') {
|
---|
5327 |
|
---|
5328 | if ($revrec eq 'y') {
|
---|
5329 | $val = NetAddr::IP->new($val);
|
---|
5330 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
5331 | if (!$val->{isv6} && ($val->masklen < 24) && ($val->masklen % 8 != 0)) {
|
---|
5332 | foreach my $szone ($val->split($val->masklen + (8 - $val->masklen % 8))) {
|
---|
5333 | my $szone2 = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
5334 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
5335 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n";
|
---|
5336 | $$recflags{$szone2} = $val->masklen;
|
---|
5337 | }
|
---|
5338 | } elsif ($val->{isv6} && ($val->masklen < 64) && ($val->masklen % 4 !=0)) {
|
---|
5339 | foreach my $szone ($val->split($val->masklen + (4 - $val->masklen % 4))) {
|
---|
5340 | my $szone2 = _ZONE($szone, 'ZONE.ip6.arpa', 'r', '.');
|
---|
5341 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
5342 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n";
|
---|
5343 | $$recflags{$szone2} = $val->masklen;
|
---|
5344 | }
|
---|
5345 | } else {
|
---|
5346 | my $val2 = _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
5347 | print $datafile "\&$val2"."::$host:$ttl:$stamp:$loc\n";
|
---|
5348 | $$recflags{$val2} = $val->masklen;
|
---|
5349 | }
|
---|
5350 | } else {
|
---|
5351 | print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n";
|
---|
5352 | }
|
---|
5353 |
|
---|
5354 | } elsif ($typemap{$type} eq 'AAAA') {
|
---|
5355 |
|
---|
5356 | print $datafile ":$host:28:";
|
---|
5357 | my $altgrp = 0;
|
---|
5358 | my @altconv;
|
---|
5359 | # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
|
---|
5360 | foreach (split /:/, $val) {
|
---|
5361 | if (/^$/) {
|
---|
5362 | # flag blank entry; this is a series of 0's of (currently) unknown length
|
---|
5363 | $altconv[$altgrp++] = 's';
|
---|
5364 | } else {
|
---|
5365 | # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
|
---|
5366 | $altconv[$altgrp++] = octalize($_)
|
---|
5367 | }
|
---|
5368 | }
|
---|
5369 | foreach my $octet (@altconv) {
|
---|
5370 | # if not 's', output
|
---|
5371 | print $datafile $octet unless $octet =~ /^s$/;
|
---|
5372 | # if 's', output (9-array length)x literal '\000\000'
|
---|
5373 | print $datafile '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
|
---|
5374 | }
|
---|
5375 | print $datafile ":$ttl:$stamp:$loc\n";
|
---|
5376 |
|
---|
5377 | } elsif ($typemap{$type} eq 'MX') {
|
---|
5378 |
|
---|
5379 | print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n";
|
---|
5380 |
|
---|
5381 | } elsif ($typemap{$type} eq 'TXT') {
|
---|
5382 |
|
---|
5383 | ##fixme: split v-e-r-y long TXT strings? will need to do so for BIND export, at least
|
---|
5384 | if ($revrec eq 'n') {
|
---|
5385 | $val =~ s/:/\\072/g; # may need to replace other symbols
|
---|
5386 | print $datafile "'$host:$val:$ttl:$stamp:$loc\n";
|
---|
5387 | } else {
|
---|
5388 | $host =~ s/:/\\072/g; # may need to replace other symbols
|
---|
5389 | my $val2 = NetAddr::IP->new($val);
|
---|
5390 | print $datafile "'"._ZONE($val2, 'ZONE', 'r', '.').($val2->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
5391 | ":$host:$ttl:$stamp:$loc\n";
|
---|
5392 | }
|
---|
5393 |
|
---|
5394 | # by-hand TXT
|
---|
5395 | #:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
|
---|
5396 | #@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
|
---|
5397 | #'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
|
---|
5398 |
|
---|
5399 | #txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
|
---|
5400 | #: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
|
---|
5401 |
|
---|
5402 | # very long TXT record as brought in by axfr-get
|
---|
5403 | # note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
|
---|
5404 | # also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
|
---|
5405 | #:longtxt.deepnet.cx:16:
|
---|
5406 | #\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
|
---|
5407 | #\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.
|
---|
5408 | #\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.
|
---|
5409 | #:3600
|
---|
5410 |
|
---|
5411 | } elsif ($typemap{$type} eq 'CNAME') {
|
---|
5412 |
|
---|
5413 | if ($revrec eq 'n') {
|
---|
5414 | print $datafile "C$host:$val:$ttl:$stamp:$loc\n";
|
---|
5415 | } else {
|
---|
5416 | my $val2 = NetAddr::IP->new($val);
|
---|
5417 | print $datafile "C"._ZONE($val2, 'ZONE', 'r', '.').($val2->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
5418 | ":$host:$ttl:$stamp:$loc\n";
|
---|
5419 | }
|
---|
5420 |
|
---|
5421 | } elsif ($typemap{$type} eq 'SRV') {
|
---|
5422 |
|
---|
5423 | # data is two-byte values for priority, weight, port, in that order,
|
---|
5424 | # followed by length/string data
|
---|
5425 |
|
---|
5426 | print $datafile ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
|
---|
5427 |
|
---|
5428 | $val .= '.' if $val !~ /\.$/;
|
---|
5429 | foreach (split /\./, $val) {
|
---|
5430 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
5431 | }
|
---|
5432 | print $datafile "\\000:$ttl:$stamp:$loc\n";
|
---|
5433 |
|
---|
5434 | } elsif ($typemap{$type} eq 'RP') {
|
---|
5435 |
|
---|
5436 | # RP consists of two mostly free-form strings.
|
---|
5437 | # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
|
---|
5438 | # The second is the "hostname" of a TXT record with more info.
|
---|
5439 | print $datafile ":$host:17:";
|
---|
5440 | my ($who,$what) = split /\s/, $val;
|
---|
5441 | foreach (split /\./, $who) {
|
---|
5442 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
5443 | }
|
---|
5444 | print $datafile '\000';
|
---|
5445 | foreach (split /\./, $what) {
|
---|
5446 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
5447 | }
|
---|
5448 | print $datafile "\\000:$ttl:$stamp:$loc\n";
|
---|
5449 |
|
---|
5450 | } elsif ($typemap{$type} eq 'PTR') {
|
---|
5451 |
|
---|
5452 | $zone = NetAddr::IP->new($zone);
|
---|
5453 | $$recflags{$val}++;
|
---|
5454 | if (!$zone->{isv6} && $zone->masklen > 24) {
|
---|
5455 | ($val) = ($val =~ /\.(\d+)$/);
|
---|
5456 | print $datafile "^$val."._ZONE($zone, 'ZONE', 'r', '.').'.in-addr.arpa'.
|
---|
5457 | ":$host:ttl:$stamp:$loc\n";
|
---|
5458 | } else {
|
---|
5459 | $val = NetAddr::IP->new($val);
|
---|
5460 | print $datafile "^".
|
---|
5461 | _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
5462 | ":$host:$ttl:$stamp:$loc\n";
|
---|
5463 | }
|
---|
5464 |
|
---|
5465 | } elsif ($type == 65280) { # A+PTR
|
---|
5466 |
|
---|
5467 | $$recflags{$val}++;
|
---|
5468 | print $datafile "=$host:$val:$ttl:$stamp:$loc\n";
|
---|
5469 |
|
---|
5470 | } elsif ($type == 65281) { # AAAA+PTR
|
---|
5471 |
|
---|
5472 | $$recflags{$val}++;
|
---|
5473 | # treat these as two separate records. since tinydns doesn't have
|
---|
5474 | # a native combined type, we have to create them separately anyway.
|
---|
5475 | # print both; a dangling record is harmless, and impossible via web
|
---|
5476 | # UI anyway
|
---|
5477 | _printrec_tiny($datafile,$revrec,$recflags,$zone,$host,28,$val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
5478 | _printrec_tiny($datafile,$revrec,$recflags,$zone,$host,12,$val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
5479 | ##fixme: add a config flag to indicate use of the patch from http://www.fefe.de/dns/
|
---|
5480 | # type 6 is for AAAA+PTR, type 3 is for AAAA
|
---|
5481 |
|
---|
5482 | } elsif ($type == 65282) { # PTR template
|
---|
5483 |
|
---|
5484 | # only useful for v4 with standard DNS software, since this expands all
|
---|
5485 | # IPs in $zone (or possibly $val?) with autogenerated records
|
---|
5486 | $val = NetAddr::IP->new($val);
|
---|
5487 | return if $val->{isv6};
|
---|
5488 |
|
---|
5489 | if ($val->masklen <= 16) {
|
---|
5490 | foreach my $sub ($val->split(16)) {
|
---|
5491 | __publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, 1);
|
---|
5492 | }
|
---|
5493 | } else {
|
---|
5494 | __publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, 1);
|
---|
5495 | }
|
---|
5496 |
|
---|
5497 | } elsif ($type == 65283) { # A+PTR template
|
---|
5498 |
|
---|
5499 | $val = NetAddr::IP->new($val);
|
---|
5500 | # Just In Case. An A+PTR should be impossible to add to a v6 revzone via API.
|
---|
5501 | return if $val->{isv6};
|
---|
5502 |
|
---|
5503 | if ($val->masklen <= 16) {
|
---|
5504 | foreach my $sub ($val->split(16)) {
|
---|
5505 | __publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, 0);
|
---|
5506 | }
|
---|
5507 | } else {
|
---|
5508 | __publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, 0);
|
---|
5509 | }
|
---|
5510 |
|
---|
5511 | } elsif ($type == 65284) { # AAAA+PTR template
|
---|
5512 | # Stub for completeness. Could be exported to DNS software that supports
|
---|
5513 | # some degree of internal automagic in generic-record-creation
|
---|
5514 | # (eg http://search.cpan.org/dist/AllKnowingDNS/ )
|
---|
5515 |
|
---|
5516 | } elsif ($type == 65285) { # Delegation
|
---|
5517 | # This is intended for reverse zones, but may prove useful in forward zones.
|
---|
5518 |
|
---|
5519 | # All delegations need to create one or more NS records. The NS record handler knows what to do.
|
---|
5520 | _printrec_tiny($datafile,$revrec,$recflags,$zone,$host,$reverse_typemap{'NS'},
|
---|
5521 | $val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
5522 | if ($revrec eq 'y') {
|
---|
5523 | # In the case of a sub-/24 v4 reverse delegation, we need to generate CNAMEs
|
---|
5524 | # to redirect all of the individual IP lookups as well.
|
---|
5525 | # Not sure how this would actually resolve if a /24 or larger was delegated
|
---|
5526 | # one way, and a sub-/24 in that >=/24 was delegated elsewhere...
|
---|
5527 | my $dblock = NetAddr::IP->new($val);
|
---|
5528 | if (!$dblock->{isv6} && $dblock->masklen > 24) {
|
---|
5529 | my @subs = $dblock->split;
|
---|
5530 | foreach (@subs) {
|
---|
5531 | next if $$recflags{"$_"};
|
---|
5532 | my ($oct) = ($_->addr =~ /(\d+)$/);
|
---|
5533 | print $datafile "C"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$oct.".
|
---|
5534 | _ZONE($dblock, 'ZONE.in-addr.arpa', 'r', '.').":$ttl:$stamp:$loc\n";
|
---|
5535 | $$recflags{"$_"}++;
|
---|
5536 | }
|
---|
5537 | }
|
---|
5538 | }
|
---|
5539 |
|
---|
5540 | ##
|
---|
5541 | ## Uncommon types. These will need better UI support Any Day Sometime Maybe(TM).
|
---|
5542 | ##
|
---|
5543 |
|
---|
5544 | } elsif ($type == 44) { # SSHFP
|
---|
5545 | my ($algo,$fpt,$fp) = split /\s+/, $val;
|
---|
5546 |
|
---|
5547 | my $rec = sprintf ":$host:44:\\%0.3o\\%0.3o", $algo, $fpt;
|
---|
5548 | while (my ($byte) = ($fp =~ /^(..)/) ) {
|
---|
5549 | $rec .= sprintf "\\%0.3o", hex($byte);
|
---|
5550 | $fp =~ s/^..//;
|
---|
5551 | }
|
---|
5552 | print $datafile "$rec:$ttl:$stamp:$loc\n";
|
---|
5553 |
|
---|
5554 | } else {
|
---|
5555 | # raw record. we don't know what's in here, so we ASS-U-ME the user has
|
---|
5556 | # put it in correctly, since either the user is messing directly with the
|
---|
5557 | # database, or the record was imported via AXFR
|
---|
5558 | # <split by char>
|
---|
5559 | # convert anything not a-zA-Z0-9.- to octal coding
|
---|
5560 |
|
---|
5561 | ##fixme: add flag to export "unknown" record types - note we'll probably end up
|
---|
5562 | # mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
|
---|
5563 | #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
|
---|
5564 |
|
---|
5565 | } # record type if-else
|
---|
5566 |
|
---|
5567 | } # end _printrec_tiny()
|
---|
5568 |
|
---|
5569 |
|
---|
5570 | ## DNSDB::mailNotify()
|
---|
5571 | # Sends notification mail to recipients regarding a DNSDB operation
|
---|
5572 | sub mailNotify {
|
---|
5573 | my $self = shift;
|
---|
5574 | my $dbh = $self->{dbh};
|
---|
5575 | my ($subj,$message) = @_;
|
---|
5576 |
|
---|
5577 | return if $self->{mailhost} eq 'smtp.example.com'; # do nothing if still using default SMTP host.
|
---|
5578 |
|
---|
5579 | my $mailer = Net::SMTP->new($self->{mailhost}, Hello => "dnsadmin.$self->{domain}");
|
---|
5580 |
|
---|
5581 | my $mailsender = ($self->{mailsender} ? $self->{mailsender} : $self->{mailnotify});
|
---|
5582 |
|
---|
5583 | $mailer->mail($mailsender);
|
---|
5584 | $mailer->to($self->{mailnotify});
|
---|
5585 | $mailer->data("From: \"$self->{mailname}\" <$mailsender>\n",
|
---|
5586 | "To: <$self->{mailnotify}>\n",
|
---|
5587 | "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
|
---|
5588 | "Subject: $subj\n",
|
---|
5589 | "X-Mailer: DNSAdmin v".$DNSDB::VERSION." Notify\n",
|
---|
5590 | "Organization: $self->{orgname}\n",
|
---|
5591 | "\n$message\n");
|
---|
5592 | $mailer->quit;
|
---|
5593 | }
|
---|
5594 |
|
---|
5595 | # shut Perl up
|
---|
5596 | 1;
|
---|