1 | # dns/trunk/DNSDB.pm
|
---|
2 | # Abstraction functions for DNS administration
|
---|
3 | ##
|
---|
4 | # $Id: DNSDB.pm 514 2013-05-22 21:55:29Z 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 qw(:lower);
|
---|
31 | use POSIX;
|
---|
32 | use Fcntl qw(:flock);
|
---|
33 |
|
---|
34 | use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
|
---|
35 |
|
---|
36 | $VERSION = 1.1; ##VERSION##
|
---|
37 | @ISA = qw(Exporter);
|
---|
38 | @EXPORT_OK = qw(
|
---|
39 | &initGlobals &login &initActionLog
|
---|
40 | &getPermissions &changePermissions &comparePermissions
|
---|
41 | &changeGroup
|
---|
42 | &loadConfig &connectDB &finish
|
---|
43 | &addDomain &delZone &domainName &revName &domainID &revID &addRDNS
|
---|
44 | &getZoneCount &getZoneList &getZoneLocation
|
---|
45 | &addGroup &delGroup &getChildren &groupName
|
---|
46 | &getGroupCount &getGroupList
|
---|
47 | &addUser &updateUser &delUser &userFullName &userStatus &getUserData
|
---|
48 | &getUserCount &getUserList &getUserDropdown
|
---|
49 | &addLoc &updateLoc &delLoc &getLoc
|
---|
50 | &getLocCount &getLocList &getLocDropdown
|
---|
51 | &getSOA &updateSOA &getRecLine &getRecList &getRecCount
|
---|
52 | &addRec &updateRec &delRec
|
---|
53 | &getLogCount &getLogEntries
|
---|
54 | &getRevPattern
|
---|
55 | &getTypelist
|
---|
56 | &parentID
|
---|
57 | &isParent
|
---|
58 | &zoneStatus &getZonesByCIDR &importAXFR
|
---|
59 | &export
|
---|
60 | &mailNotify
|
---|
61 | %typemap %reverse_typemap %config
|
---|
62 | @permtypes $permlist %permchains
|
---|
63 | );
|
---|
64 |
|
---|
65 | @EXPORT = qw(%typemap %reverse_typemap @permtypes $permlist %permchains);
|
---|
66 | %EXPORT_TAGS = ( ALL => [qw(
|
---|
67 | &initGlobals &login &initActionLog
|
---|
68 | &getPermissions &changePermissions &comparePermissions
|
---|
69 | &changeGroup
|
---|
70 | &loadConfig &connectDB &finish
|
---|
71 | &addDomain &delZone &domainName &revName &domainID &revID &addRDNS
|
---|
72 | &getZoneCount &getZoneList &getZoneLocation
|
---|
73 | &addGroup &delGroup &getChildren &groupName
|
---|
74 | &getGroupCount &getGroupList
|
---|
75 | &addUser &updateUser &delUser &userFullName &userStatus &getUserData
|
---|
76 | &getUserCount &getUserList &getUserDropdown
|
---|
77 | &addLoc &updateLoc &delLoc &getLoc
|
---|
78 | &getLocCount &getLocList &getLocDropdown
|
---|
79 | &getSOA &updateSOA &getRecLine &getRecList &getRecCount
|
---|
80 | &addRec &updateRec &delRec
|
---|
81 | &getLogCount &getLogEntries
|
---|
82 | &getRevPattern
|
---|
83 | &getTypelist
|
---|
84 | &parentID
|
---|
85 | &isParent
|
---|
86 | &zoneStatus &getZonesByCIDR &importAXFR
|
---|
87 | &export
|
---|
88 | &mailNotify
|
---|
89 | %typemap %reverse_typemap %config
|
---|
90 | @permtypes $permlist %permchains
|
---|
91 | )]
|
---|
92 | );
|
---|
93 |
|
---|
94 | our $errstr = '';
|
---|
95 | our $resultstr = '';
|
---|
96 |
|
---|
97 | # Halfway sane defaults for SOA, TTL, etc.
|
---|
98 | # serial defaults to 0 for convenience.
|
---|
99 | # value will be either YYYYMMDDNN for BIND/etc, or auto-internal for tinydns
|
---|
100 | our %def = qw (
|
---|
101 | contact hostmaster.DOMAIN
|
---|
102 | prins ns1.myserver.com
|
---|
103 | serial 0
|
---|
104 | soattl 86400
|
---|
105 | refresh 10800
|
---|
106 | retry 3600
|
---|
107 | expire 604800
|
---|
108 | minttl 10800
|
---|
109 | ttl 10800
|
---|
110 | );
|
---|
111 |
|
---|
112 | # Arguably defined wholly in the db, but little reason to change without supporting code changes
|
---|
113 | # group_view, user_view permissions? separate rDNS permission(s)?
|
---|
114 | our @permtypes = qw (
|
---|
115 | group_edit group_create group_delete
|
---|
116 | user_edit user_create user_delete
|
---|
117 | domain_edit domain_create domain_delete
|
---|
118 | record_edit record_create record_delete record_locchg
|
---|
119 | location_edit location_create location_delete location_view
|
---|
120 | self_edit admin
|
---|
121 | );
|
---|
122 | our $permlist = join(',',@permtypes);
|
---|
123 |
|
---|
124 | # Some permissions more or less require certain others.
|
---|
125 | our %permchains = (
|
---|
126 | user_edit => 'self_edit',
|
---|
127 | location_edit => 'location_view',
|
---|
128 | location_create => 'location_view',
|
---|
129 | location_delete => 'location_view',
|
---|
130 | record_locchg => 'location_view',
|
---|
131 | );
|
---|
132 |
|
---|
133 | # DNS record type map and reverse map.
|
---|
134 | # loaded from the database, from http://www.iana.org/assignments/dns-parameters
|
---|
135 | our %typemap;
|
---|
136 | our %reverse_typemap;
|
---|
137 |
|
---|
138 | # Prepopulate a basic config. Note some of these *will* cause errors if left unset.
|
---|
139 | # note: add appropriate stanzas in loadConfig to parse these
|
---|
140 | our %config = (
|
---|
141 | # Database connection info
|
---|
142 | dbname => 'dnsdb',
|
---|
143 | dbuser => 'dnsdb',
|
---|
144 | dbpass => 'secret',
|
---|
145 | dbhost => '',
|
---|
146 |
|
---|
147 | # Email notice settings
|
---|
148 | mailhost => 'smtp.example.com',
|
---|
149 | mailnotify => 'dnsdb@example.com', # to
|
---|
150 | mailsender => 'dnsdb@example.com', # from
|
---|
151 | mailname => 'DNS Administration',
|
---|
152 | orgname => 'Example Corp',
|
---|
153 | domain => 'example.com',
|
---|
154 |
|
---|
155 | # Template directory
|
---|
156 | templatedir => 'templates/',
|
---|
157 | # fmeh. this is a real web path, not a logical internal one. hm..
|
---|
158 | # cssdir => 'templates/',
|
---|
159 | sessiondir => 'session/',
|
---|
160 | exportcache => 'cache/',
|
---|
161 |
|
---|
162 | # Session params
|
---|
163 | timeout => '3600', # 1 hour default
|
---|
164 |
|
---|
165 | # Other miscellanea
|
---|
166 | log_failures => 1, # log all evarthing by default
|
---|
167 | perpage => 15,
|
---|
168 | maxfcgi => 100, # reasonable default?
|
---|
169 | );
|
---|
170 |
|
---|
171 | ## (Semi)private variables
|
---|
172 |
|
---|
173 | # Hash of functions for validating record types. Filled in initGlobals() since
|
---|
174 | # it relies on visibility flags from the rectypes table in the DB
|
---|
175 | my %validators;
|
---|
176 |
|
---|
177 | # Entity-relationship reference hashes.
|
---|
178 | my %par_tbl = (
|
---|
179 | group => 'groups',
|
---|
180 | user => 'users',
|
---|
181 | defrec => 'default_records',
|
---|
182 | defrevrec => 'default_rev_records',
|
---|
183 | domain => 'domains',
|
---|
184 | revzone => 'revzones',
|
---|
185 | record => 'records'
|
---|
186 | );
|
---|
187 | my %id_col = (
|
---|
188 | group => 'group_id',
|
---|
189 | user => 'user_id',
|
---|
190 | defrec => 'record_id',
|
---|
191 | defrevrec => 'record_id',
|
---|
192 | domain => 'domain_id',
|
---|
193 | revzone => 'rdns_id',
|
---|
194 | record => 'record_id'
|
---|
195 | );
|
---|
196 | my %par_col = (
|
---|
197 | group => 'parent_group_id',
|
---|
198 | user => 'group_id',
|
---|
199 | defrec => 'group_id',
|
---|
200 | defrevrec => 'group_id',
|
---|
201 | domain => 'group_id',
|
---|
202 | revzone => 'group_id',
|
---|
203 | record => 'domain_id'
|
---|
204 | );
|
---|
205 | my %par_type = (
|
---|
206 | group => 'group',
|
---|
207 | user => 'group',
|
---|
208 | defrec => 'group',
|
---|
209 | defrevrec => 'group',
|
---|
210 | domain => 'group',
|
---|
211 | revzone => 'group',
|
---|
212 | record => 'domain'
|
---|
213 | );
|
---|
214 |
|
---|
215 | ##
|
---|
216 | ## Constructor and destructor
|
---|
217 | ##
|
---|
218 |
|
---|
219 | sub new {
|
---|
220 | my $this = shift;
|
---|
221 | my $class = ref($this) || $this;
|
---|
222 | my %args = @_;
|
---|
223 | ##fixme? to ponder: do we do some magic if the caller sets eg dbname to prevent parsing of the config file?
|
---|
224 | if (!loadConfig(basename => $args{configfile})) {
|
---|
225 | warn "Using default configuration; unable to load custom settings: $errstr\n";
|
---|
226 | }
|
---|
227 | my $self = \%config;
|
---|
228 | $self->{configfile} = $args{configfile};
|
---|
229 | bless $self, $class;
|
---|
230 | $self->{dbh} = connectDB($self->{dbname}, $self->{dbuser}, $self->{dbpass}, $self->{dbhost}) or return;
|
---|
231 | $self->initGlobals();
|
---|
232 |
|
---|
233 | return $self;
|
---|
234 | }
|
---|
235 |
|
---|
236 | sub DESTROY {
|
---|
237 | my $self = shift;
|
---|
238 | $self->{dbh}->disconnect;
|
---|
239 | }
|
---|
240 |
|
---|
241 | sub errstr { $DNSDB::errstr; }
|
---|
242 |
|
---|
243 | ##
|
---|
244 | ## utility functions
|
---|
245 | ##
|
---|
246 |
|
---|
247 | ## DNSDB::_rectable()
|
---|
248 | # Takes default+rdns flags, returns appropriate table name
|
---|
249 | sub _rectable {
|
---|
250 | my $def = shift;
|
---|
251 | my $rev = shift;
|
---|
252 |
|
---|
253 | return 'records' if $def ne 'y';
|
---|
254 | return 'default_records' if $rev ne 'y';
|
---|
255 | return 'default_rev_records';
|
---|
256 | } # end _rectable()
|
---|
257 |
|
---|
258 | ## DNSDB::_recparent()
|
---|
259 | # Takes default+rdns flags, returns appropriate parent-id column name
|
---|
260 | sub _recparent {
|
---|
261 | my $def = shift;
|
---|
262 | my $rev = shift;
|
---|
263 |
|
---|
264 | return 'group_id' if $def eq 'y';
|
---|
265 | return 'rdns_id' if $rev eq 'y';
|
---|
266 | return 'domain_id';
|
---|
267 | } # end _recparent()
|
---|
268 |
|
---|
269 | ## DNSDB::_ipparent()
|
---|
270 | # Check an IP to be added in a reverse zone to see if it's really in the requested parent.
|
---|
271 | # Takes default and reverse flags, IP (fragment) to check, parent zone ID,
|
---|
272 | # and a reference to a NetAddr::IP object (also used to pass back a fully-reconstructed IP for
|
---|
273 | # database insertion)
|
---|
274 | sub _ipparent {
|
---|
275 | my $self = shift;
|
---|
276 | my $dbh = $self->{dbh};
|
---|
277 | my $defrec = shift;
|
---|
278 | my $revrec = shift;
|
---|
279 | my $val = shift;
|
---|
280 | my $id = shift;
|
---|
281 | my $addr = shift;
|
---|
282 |
|
---|
283 | return if $revrec ne 'y'; # this sub not useful in forward zones
|
---|
284 |
|
---|
285 | $$addr = NetAddr::IP->new($$val); #necessary?
|
---|
286 |
|
---|
287 | # subsub to split, reverse, and overlay an IP fragment on a netblock
|
---|
288 | sub __rev_overlay {
|
---|
289 | my $splitme = shift; # ':' or '.', m'lud?
|
---|
290 | my $parnet = shift;
|
---|
291 | my $val = shift;
|
---|
292 | my $addr = shift;
|
---|
293 |
|
---|
294 | my $joinme = $splitme;
|
---|
295 | $splitme = '\.' if $splitme eq '.';
|
---|
296 | my @working = reverse(split($splitme, $parnet->addr));
|
---|
297 | my @parts = reverse(split($splitme, $$val));
|
---|
298 | for (my $i = 0; $i <= $#parts; $i++) {
|
---|
299 | $working[$i] = $parts[$i];
|
---|
300 | }
|
---|
301 | my $checkme = NetAddr::IP->new(join($joinme, reverse(@working))) or return 0;
|
---|
302 | return 0 unless $checkme->within($parnet);
|
---|
303 | $$addr = $checkme; # force "correct" IP to be recorded.
|
---|
304 | return 1;
|
---|
305 | }
|
---|
306 |
|
---|
307 | my ($parstr) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id = ?", undef, ($id));
|
---|
308 | my $parnet = NetAddr::IP->new($parstr);
|
---|
309 |
|
---|
310 | # Fail early on v6-in-v4 or v4-in-v6. We're not accepting these ATM.
|
---|
311 | return 0 if $parnet->addr =~ /\./ && $$val =~ /:/;
|
---|
312 | return 0 if $parnet->addr =~ /:/ && $$val =~ /\./;
|
---|
313 |
|
---|
314 | if ($$addr && ($$val =~ /^[\da-fA-F][\da-fA-F:]+[\da-fA-F]$/ || $$val =~ m|/\d+$|)) {
|
---|
315 | # the only case where NetAddr::IP's acceptance of legitimate IPs is "correct" is for a proper IPv6 address,
|
---|
316 | # or a netblock (only expected on templates)
|
---|
317 | # the rest we have to restructure before fiddling. *sigh*
|
---|
318 | return 1 if $$addr->within($parnet);
|
---|
319 | } else {
|
---|
320 | # We don't have a complete IP in $$val (yet)... unless we have a netblock
|
---|
321 | if ($parnet->addr =~ /:/) {
|
---|
322 | $$val =~ s/^:+//; # gotta strip'em all...
|
---|
323 | return __rev_overlay(':', $parnet, $val, $addr);
|
---|
324 | }
|
---|
325 | if ($parnet->addr =~ /\./) {
|
---|
326 | $$val =~ s/^\.+//;
|
---|
327 | return __rev_overlay('.', $parnet, $val, $addr);
|
---|
328 | }
|
---|
329 | # should be impossible to get here...
|
---|
330 | }
|
---|
331 | # ... and here.
|
---|
332 | # can't do nuttin' in forward zones
|
---|
333 | } # end _ipparent()
|
---|
334 |
|
---|
335 | ## DNSDB::_hostparent()
|
---|
336 | # A little different than _ipparent above; this tries to *find* the parent zone of a hostname
|
---|
337 | # Takes a hostname.
|
---|
338 | # Returns the domain ID of the parent domain if one was found.
|
---|
339 | sub _hostparent {
|
---|
340 | my $self = shift;
|
---|
341 | my $dbh = $self->{dbh};
|
---|
342 | my $hname = shift;
|
---|
343 |
|
---|
344 | $hname =~ s/^\*\.//; # this should be impossible to find in the domains table.
|
---|
345 | my @hostbits = split /\./, $hname;
|
---|
346 | my $sth = $dbh->prepare("SELECT count(*),domain_id FROM domains WHERE lower(domain) = lower(?) GROUP BY domain_id");
|
---|
347 | foreach (@hostbits) {
|
---|
348 | $sth->execute($hname);
|
---|
349 | my ($found, $parid) = $sth->fetchrow_array;
|
---|
350 | if ($found) {
|
---|
351 | return $parid;
|
---|
352 | }
|
---|
353 | $hname =~ s/^$_\.//;
|
---|
354 | }
|
---|
355 | } # end _hostparent()
|
---|
356 |
|
---|
357 | ## DNSDB::_log()
|
---|
358 | # Log an action
|
---|
359 | # Takes a log entry hash containing at least:
|
---|
360 | # group_id, log entry
|
---|
361 | # and optionally one or more of:
|
---|
362 | # domain_id, rdns_id
|
---|
363 | # The %userdata hash provides the user ID, username, and fullname
|
---|
364 | sub _log {
|
---|
365 | my $self = shift;
|
---|
366 | my $dbh = $self->{dbh};
|
---|
367 |
|
---|
368 | my %args = @_;
|
---|
369 |
|
---|
370 | $args{rdns_id} = 0 if !$args{rdns_id};
|
---|
371 | $args{domain_id} = 0 if !$args{domain_id};
|
---|
372 |
|
---|
373 | ##fixme: farm out the actual logging to different subs for file, syslog, internal, etc based on config
|
---|
374 | # if ($config{log_channel} eq 'sql') {
|
---|
375 | $dbh->do("INSERT INTO log (domain_id,rdns_id,group_id,entry,user_id,email,name) VALUES (?,?,?,?,?,?,?)",
|
---|
376 | undef,
|
---|
377 | ($args{domain_id}, $args{rdns_id}, $args{group_id}, $args{entry},
|
---|
378 | $self->{loguserid}, $self->{logusername}, $self->{logfullname}) );
|
---|
379 | # } elsif ($config{log_channel} eq 'file') {
|
---|
380 | # } elsif ($config{log_channel} eq 'syslog') {
|
---|
381 | # }
|
---|
382 | } # end _log
|
---|
383 |
|
---|
384 |
|
---|
385 | ##
|
---|
386 | ## Record validation subs.
|
---|
387 | ##
|
---|
388 |
|
---|
389 | ## All of these subs take substantially the same arguments:
|
---|
390 | # a hash containing at least the following keys:
|
---|
391 | # - defrec (default/live flag)
|
---|
392 | # - revrec (forward/reverse flag)
|
---|
393 | # - id (parent entity ID)
|
---|
394 | # - host (hostname)
|
---|
395 | # - rectype
|
---|
396 | # - val (IP, hostname [CNAME/MX/SRV] or text)
|
---|
397 | # - addr (NetAddr::IP object from val. May be undef.)
|
---|
398 | # MX and SRV record validation also expect distance, and SRV records expect weight and port as well.
|
---|
399 | # host, rectype, and addr should be references as these may be modified in validation
|
---|
400 |
|
---|
401 | # A record
|
---|
402 | sub _validate_1 {
|
---|
403 | my $self = shift;
|
---|
404 | my $dbh = $self->{dbh};
|
---|
405 |
|
---|
406 | my %args = @_;
|
---|
407 |
|
---|
408 | return ('FAIL', 'Reverse zones cannot contain A records') if $args{revrec} eq 'y';
|
---|
409 |
|
---|
410 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
411 | # or the intended parent domain for live records.
|
---|
412 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
413 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
414 |
|
---|
415 | # Check IP is well-formed, and that it's a v4 address
|
---|
416 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
|
---|
417 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
418 | unless ${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/;
|
---|
419 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
420 | unless $args{addr} && !$args{addr}->{isv6};
|
---|
421 | # coerce IP/value to normalized form for storage
|
---|
422 | ${$args{val}} = $args{addr}->addr;
|
---|
423 |
|
---|
424 | return ('OK','OK');
|
---|
425 | } # done A record
|
---|
426 |
|
---|
427 | # NS record
|
---|
428 | sub _validate_2 {
|
---|
429 | my $self = shift;
|
---|
430 | my $dbh = $self->{dbh};
|
---|
431 |
|
---|
432 | my %args = @_;
|
---|
433 |
|
---|
434 | # Check that the target of the record is within the parent.
|
---|
435 | # Yes, host<->val are mixed up here; can't see a way to avoid it. :(
|
---|
436 | if ($args{defrec} eq 'n') {
|
---|
437 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
438 | if ($args{revrec} eq 'y') {
|
---|
439 | my $tmpip = NetAddr::IP->new(${$args{val}});
|
---|
440 | my $pname = $self->revName($args{id});
|
---|
441 | return ('FAIL',"${$args{val}} not within $pname")
|
---|
442 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$tmpip);
|
---|
443 | # Sub the returned thing for ZONE? This could get stupid if you have typos...
|
---|
444 | ${$args{val}} =~ s/ZONE/$tmpip->address/;
|
---|
445 | } else {
|
---|
446 | my $pname = $self->domainName($args{id});
|
---|
447 | ${$args{host}} = $pname if ${$args{host}} !~ /\.$pname$/;
|
---|
448 | }
|
---|
449 | } else {
|
---|
450 | # Default reverse NS records should always refer to the implied parent
|
---|
451 | ${$args{host}} = 'DOMAIN' if $args{revrec} eq 'n';
|
---|
452 | ${$args{val}} = 'ZONE' if $args{revrec} eq 'y';
|
---|
453 | }
|
---|
454 |
|
---|
455 | # Let this lie for now. Needs more magic.
|
---|
456 | # # Check IP is well-formed, and that it's a v4 address
|
---|
457 | # return ('FAIL',"A record must be a valid IPv4 address")
|
---|
458 | # unless $addr && !$addr->{isv6};
|
---|
459 | # # coerce IP/value to normalized form for storage
|
---|
460 | # $$val = $addr->addr;
|
---|
461 |
|
---|
462 | return ('OK','OK');
|
---|
463 | } # done NS record
|
---|
464 |
|
---|
465 | # CNAME record
|
---|
466 | sub _validate_5 {
|
---|
467 | my $self = shift;
|
---|
468 | my $dbh = $self->{dbh};
|
---|
469 |
|
---|
470 | my %args = @_;
|
---|
471 |
|
---|
472 | # Not really true, but these are only useful for delegating smaller-than-/24 IP blocks.
|
---|
473 | # This is fundamentally a messy operation and should really just be taken care of by the
|
---|
474 | # export process, not manual maintenance of the necessary records.
|
---|
475 | return ('FAIL', 'Reverse zones cannot contain CNAME records') if $args{revrec} eq 'y';
|
---|
476 |
|
---|
477 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
478 | # or the intended parent domain for live records.
|
---|
479 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
480 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
481 |
|
---|
482 | return ('OK','OK');
|
---|
483 | } # done CNAME record
|
---|
484 |
|
---|
485 | # SOA record
|
---|
486 | sub _validate_6 {
|
---|
487 | # Smart monkeys won't stick their fingers in here; we have
|
---|
488 | # separate dedicated routines to deal with SOA records.
|
---|
489 | return ('OK','OK');
|
---|
490 | } # done SOA record
|
---|
491 |
|
---|
492 | # PTR record
|
---|
493 | sub _validate_12 {
|
---|
494 | my $self = shift;
|
---|
495 | my $dbh = $self->{dbh};
|
---|
496 |
|
---|
497 | my %args = @_;
|
---|
498 |
|
---|
499 | if ($args{revrec} eq 'y') {
|
---|
500 | if ($args{defrec} eq 'n') {
|
---|
501 | return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
502 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
503 | ${$args{val}} = $args{addr}->addr;
|
---|
504 | } else {
|
---|
505 | if (${$args{val}} =~ /\./) {
|
---|
506 | # looks like a v4 or fragment
|
---|
507 | if (${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/) {
|
---|
508 | # woo! a complete IP! validate it and normalize, or fail.
|
---|
509 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
510 | or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
|
---|
511 | ${$args{val}} = $args{addr}->addr;
|
---|
512 | } else {
|
---|
513 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
514 | }
|
---|
515 | } elsif (${$args{val}} =~ /[a-f:]/) {
|
---|
516 | # looks like a v6 or fragment
|
---|
517 | ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
|
---|
518 | if ($args{addr}) {
|
---|
519 | if ($args{addr}->addr =~ /^0/) {
|
---|
520 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
521 | } else {
|
---|
522 | ${$args{val}} = $args{addr}->addr;
|
---|
523 | }
|
---|
524 | }
|
---|
525 | } else {
|
---|
526 | # bare number (probably). These could be v4 or v6, so we'll
|
---|
527 | # expand on these on creation of a reverse zone.
|
---|
528 | ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
|
---|
529 | }
|
---|
530 | ${$args{host}} =~ s/\.*$/\.$config{domain}/ if ${$args{host}} !~ /(?:$config{domain}|ADMINDOMAIN)$/;
|
---|
531 | }
|
---|
532 |
|
---|
533 | # Multiple PTR records do NOT generally do what most people believe they do,
|
---|
534 | # and tend to fail in the most awkward way possible. Check and warn.
|
---|
535 | # We use $val instead of $addr->addr since we may be in a defrec, and may have eg "ZONE::42" or "ZONE.12"
|
---|
536 |
|
---|
537 | my @checkvals = (${$args{val}});
|
---|
538 | if (${$args{val}} =~ /,/) {
|
---|
539 | # push . and :: variants into checkvals if val has ,
|
---|
540 | my $tmp;
|
---|
541 | ($tmp = ${$args{val}}) =~ s/,/./;
|
---|
542 | push @checkvals, $tmp;
|
---|
543 | ($tmp = ${$args{val}}) =~ s/,/::/;
|
---|
544 | push @checkvals, $tmp;
|
---|
545 | }
|
---|
546 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ?");
|
---|
547 | foreach my $checkme (@checkvals) {
|
---|
548 | if ($args{update}) {
|
---|
549 | # Record update. There should usually be an existing PTR (the record being updated)
|
---|
550 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
551 | " WHERE val = ?", undef, ($checkme)) };
|
---|
552 | return ('WARN', "PTR record for $checkme already exists; adding another will probably not do what you want")
|
---|
553 | if @ptrs && (!grep /^$args{update}$/, @ptrs);
|
---|
554 | } else {
|
---|
555 | # New record. Always warn if a PTR exists
|
---|
556 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
557 | " WHERE val = ?", undef, ($checkme));
|
---|
558 | return ('WARN', "PTR record for $checkme already exists; adding another will probably not do what you want")
|
---|
559 | if $ptrcount;
|
---|
560 | }
|
---|
561 | }
|
---|
562 |
|
---|
563 | } else {
|
---|
564 | # Not absolutely true but only useful if you hack things up for sub-/24 v4 reverse delegations
|
---|
565 | # Simpler to just create the reverse zone and grant access for the customer to edit it, and create direct
|
---|
566 | # PTR records on export
|
---|
567 | return ('FAIL',"Forward zones cannot contain PTR records");
|
---|
568 | }
|
---|
569 |
|
---|
570 | return ('OK','OK');
|
---|
571 | } # done PTR record
|
---|
572 |
|
---|
573 | # MX record
|
---|
574 | sub _validate_15 {
|
---|
575 | my $self = shift;
|
---|
576 | my $dbh = $self->{dbh};
|
---|
577 |
|
---|
578 | my %args = @_;
|
---|
579 |
|
---|
580 | # Not absolutely true but WTF use is an MX record for a reverse zone?
|
---|
581 | return ('FAIL', 'Reverse zones cannot contain MX records') if $args{revrec} eq 'y';
|
---|
582 |
|
---|
583 | return ('FAIL', "Distance is required for MX records") unless defined(${$args{dist}});
|
---|
584 | ${$args{dist}} =~ s/\s*//g;
|
---|
585 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
|
---|
586 |
|
---|
587 | ${$args{fields}} = "distance,";
|
---|
588 | push @{$args{vallist}}, ${$args{dist}};
|
---|
589 |
|
---|
590 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
591 | # or the intended parent domain for live records.
|
---|
592 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
593 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
594 |
|
---|
595 | # hmm.. this might work. except possibly for something pointing to "deadbeef.ca". <g>
|
---|
596 | # if ($type == $reverse_typemap{NS} || $type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
|
---|
597 | # if ($val =~ /^\s*[\da-f:.]+\s*$/) {
|
---|
598 | # return ('FAIL',"$val is not a valid IP address") if !$addr;
|
---|
599 | # }
|
---|
600 | # }
|
---|
601 |
|
---|
602 | return ('OK','OK');
|
---|
603 | } # done MX record
|
---|
604 |
|
---|
605 | # TXT record
|
---|
606 | sub _validate_16 {
|
---|
607 | # Could arguably put a WARN return here on very long (>512) records
|
---|
608 | return ('OK','OK');
|
---|
609 | } # done TXT record
|
---|
610 |
|
---|
611 | # RP record
|
---|
612 | sub _validate_17 {
|
---|
613 | # Probably have to validate these some day
|
---|
614 | return ('OK','OK');
|
---|
615 | } # done RP record
|
---|
616 |
|
---|
617 | # AAAA record
|
---|
618 | sub _validate_28 {
|
---|
619 | my $self = shift;
|
---|
620 | my $dbh = $self->{dbh};
|
---|
621 |
|
---|
622 | my %args = @_;
|
---|
623 |
|
---|
624 | return ('FAIL', 'Reverse zones cannot contain AAAA records') if $args{revrec} eq 'y';
|
---|
625 |
|
---|
626 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
627 | # or the intended parent domain for live records.
|
---|
628 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
629 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
630 |
|
---|
631 | # Check IP is well-formed, and that it's a v6 address
|
---|
632 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
|
---|
633 | unless $args{addr} && $args{addr}->{isv6};
|
---|
634 | # coerce IP/value to normalized form for storage
|
---|
635 | ${$args{val}} = $args{addr}->addr;
|
---|
636 |
|
---|
637 | return ('OK','OK');
|
---|
638 | } # done AAAA record
|
---|
639 |
|
---|
640 | # SRV record
|
---|
641 | sub _validate_33 {
|
---|
642 | my $self = shift;
|
---|
643 | my $dbh = $self->{dbh};
|
---|
644 |
|
---|
645 | my %args = @_;
|
---|
646 |
|
---|
647 | # Not absolutely true but WTF use is an SRV record for a reverse zone?
|
---|
648 | return ('FAIL', 'Reverse zones cannot contain SRV records') if $args{revrec} eq 'y';
|
---|
649 |
|
---|
650 | return ('FAIL', "Distance is required for SRV records") unless defined(${$args{dist}});
|
---|
651 | ${$args{dist}} =~ s/\s*//g;
|
---|
652 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
|
---|
653 |
|
---|
654 | return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]")
|
---|
655 | unless ${$args{host}} =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/;
|
---|
656 | return ('FAIL',"Port and weight are required for SRV records")
|
---|
657 | unless defined(${$args{weight}}) && defined(${$args{port}});
|
---|
658 | ${$args{weight}} =~ s/\s*//g;
|
---|
659 | ${$args{port}} =~ s/\s*//g;
|
---|
660 |
|
---|
661 | return ('FAIL',"Port and weight are required, and must be numeric")
|
---|
662 | unless ${$args{weight}} =~ /^\d+$/ && ${$args{port}} =~ /^\d+$/;
|
---|
663 |
|
---|
664 | ${$args{fields}} = "distance,weight,port,";
|
---|
665 | push @{$args{vallist}}, (${$args{dist}}, ${$args{weight}}, ${$args{port}});
|
---|
666 |
|
---|
667 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
668 | # or the intended parent domain for live records.
|
---|
669 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
670 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
671 |
|
---|
672 | return ('OK','OK');
|
---|
673 | } # done SRV record
|
---|
674 |
|
---|
675 | # Now the custom types
|
---|
676 |
|
---|
677 | # A+PTR record. With a very little bit of magic we can also use this sub to validate AAAA+PTR. Whee!
|
---|
678 | sub _validate_65280 {
|
---|
679 | my $self = shift;
|
---|
680 | my $dbh = $self->{dbh};
|
---|
681 |
|
---|
682 | my %args = @_;
|
---|
683 |
|
---|
684 | my $code = 'OK';
|
---|
685 | my $msg = 'OK';
|
---|
686 |
|
---|
687 | if ($args{defrec} eq 'n') {
|
---|
688 | # live record; revrec determines whether we validate the PTR or A component first.
|
---|
689 |
|
---|
690 | if ($args{revrec} eq 'y') {
|
---|
691 | ($code,$msg) = $self->_validate_12(%args);
|
---|
692 | return ($code,$msg) if $code eq 'FAIL';
|
---|
693 |
|
---|
694 | # check A+PTR is really v4
|
---|
695 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
696 | if ${$args{rectype}} == 65280 && $args{addr}->{isv6};
|
---|
697 | # check AAAA+PTR is really v6
|
---|
698 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
|
---|
699 | if ${$args{rectype}} == 65281 && !$args{addr}->{isv6};
|
---|
700 |
|
---|
701 | # Check if the reqested domain exists. If not, coerce the type down to PTR and warn.
|
---|
702 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) {
|
---|
703 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
704 | " as PTR instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
705 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
706 | $msg = $addmsg if $code eq 'OK';
|
---|
707 | ${$args{rectype}} = $reverse_typemap{PTR};
|
---|
708 | return ('WARN', $msg);
|
---|
709 | }
|
---|
710 |
|
---|
711 | # Add domain ID to field list and values
|
---|
712 | ${$args{fields}} .= "domain_id,";
|
---|
713 | push @{$args{vallist}}, ${$args{domid}};
|
---|
714 |
|
---|
715 | } else {
|
---|
716 | ($code,$msg) = $self->_validate_1(%args) if ${$args{rectype}} == 65280;
|
---|
717 | ($code,$msg) = $self->_validate_28(%args) if ${$args{rectype}} == 65281;
|
---|
718 | return ($code,$msg) if $code eq 'FAIL';
|
---|
719 |
|
---|
720 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
721 | # work here since we don't *know* which parent to put it in.
|
---|
722 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
723 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
724 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
725 | if (!$revid) {
|
---|
726 | $msg = "Record ".($args{update} ? 'updated' : 'added')." as ".(${$args{rectype}} == 65280 ? 'A' : 'AAAA').
|
---|
727 | " instead of $typemap{${$args{rectype}}}; reverse zone not found for ${$args{val}}";
|
---|
728 | ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
729 | return ('WARN', $msg);
|
---|
730 | }
|
---|
731 |
|
---|
732 | # Check for duplicate PTRs. Note we don't have to play games with $code and $msg, because
|
---|
733 | # by definition there can't be duplicate PTRs if the reverse zone isn't managed here.
|
---|
734 | if ($args{update}) {
|
---|
735 | # Record update. There should usually be an existing PTR (the record being updated)
|
---|
736 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
737 | " WHERE val = ?", undef, (${$args{val}})) };
|
---|
738 | if (@ptrs && (!grep /^$args{update}$/, @ptrs)) {
|
---|
739 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
|
---|
740 | $code = 'WARN';
|
---|
741 | }
|
---|
742 | } else {
|
---|
743 | # New record. Always warn if a PTR exists
|
---|
744 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
745 | " WHERE val = ?", undef, (${$args{val}}));
|
---|
746 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want"
|
---|
747 | if $ptrcount;
|
---|
748 | $code = 'WARN' if $ptrcount;
|
---|
749 | }
|
---|
750 |
|
---|
751 | # my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
752 | # " WHERE val = ?", undef, ${$args{val}});
|
---|
753 | # if ($ptrcount) {
|
---|
754 | # my $curid = $dbh->selectrow_array("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
755 | # " WHERE val = ?
|
---|
756 | # $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
|
---|
757 | # $code = 'WARN';
|
---|
758 | # }
|
---|
759 |
|
---|
760 | ${$args{fields}} .= "rdns_id,";
|
---|
761 | push @{$args{vallist}}, $revid;
|
---|
762 | }
|
---|
763 |
|
---|
764 | } else { # defrec eq 'y'
|
---|
765 | if ($args{revrec} eq 'y') {
|
---|
766 | ($code,$msg) = $self->_validate_12(%args);
|
---|
767 | return ($code,$msg) if $code eq 'FAIL';
|
---|
768 | if (${$args{rectype}} == 65280) {
|
---|
769 | return ('FAIL',"A+PTR record must be a valid IPv4 address or fragment")
|
---|
770 | if ${$args{val}} =~ /:/;
|
---|
771 | ${$args{val}} =~ s/^ZONE,/ZONE./; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
772 | } elsif (${$args{rectype}} == 65281) {
|
---|
773 | return ('FAIL',"AAAA+PTR record must be a valid IPv6 address or fragment")
|
---|
774 | if ${$args{val}} =~ /\./;
|
---|
775 | ${$args{val}} =~ s/^ZONE,/ZONE::/; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
776 | }
|
---|
777 | } else {
|
---|
778 | # This is easy. I also can't see a real use-case for A/AAAA+PTR in *all* forward
|
---|
779 | # domains, since you wouldn't be able to substitute both domain and reverse zone
|
---|
780 | # sanely, and you'd end up with guaranteed over-replicated PTR records that would
|
---|
781 | # confuse the hell out of pretty much anything that uses them.
|
---|
782 | ##fixme: make this a config flag?
|
---|
783 | return ('FAIL', "$typemap{${$args{rectype}}} records not allowed in default domains");
|
---|
784 | }
|
---|
785 | }
|
---|
786 |
|
---|
787 | return ($code, $msg);
|
---|
788 | } # done A+PTR record
|
---|
789 |
|
---|
790 | # AAAA+PTR record
|
---|
791 | # A+PTR above has been magicked to handle AAAA+PTR as well.
|
---|
792 | sub _validate_65281 {
|
---|
793 | return _validate_65280(@_);
|
---|
794 | } # done AAAA+PTR record
|
---|
795 |
|
---|
796 | # PTR template record
|
---|
797 | sub _validate_65282 {
|
---|
798 | my $self = shift;
|
---|
799 | my $dbh = $self->{dbh};
|
---|
800 |
|
---|
801 | my %args = @_;
|
---|
802 |
|
---|
803 | # we're *this* >.< close to being able to just call _validate_12... unfortunately we can't, quite.
|
---|
804 | if ($args{revrec} eq 'y') {
|
---|
805 | if ($args{defrec} eq 'n') {
|
---|
806 | return ('FAIL', "Template block ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
807 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
808 | ##fixme: warn if $args{val} is not /31 or larger block?
|
---|
809 | ${$args{val}} = "$args{addr}";
|
---|
810 | } else {
|
---|
811 | if (${$args{val}} =~ /\./) {
|
---|
812 | # looks like a v4 or fragment
|
---|
813 | if (${$args{val}} =~ m|^\d+\.\d+\.\d+\.\d+(?:/\d+)?$|) {
|
---|
814 | # woo! a complete IP! validate it and normalize, or fail.
|
---|
815 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
816 | or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
|
---|
817 | ${$args{val}} = "$args{addr}";
|
---|
818 | } else {
|
---|
819 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
820 | }
|
---|
821 | } elsif (${$args{val}} =~ /[a-f:]/) {
|
---|
822 | # looks like a v6 or fragment
|
---|
823 | ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
|
---|
824 | if ($args{addr}) {
|
---|
825 | if ($args{addr}->addr =~ /^0/) {
|
---|
826 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
827 | } else {
|
---|
828 | ${$args{val}} = "$args{addr}";
|
---|
829 | }
|
---|
830 | }
|
---|
831 | } else {
|
---|
832 | # bare number (probably). These could be v4 or v6, so we'll
|
---|
833 | # expand on these on creation of a reverse zone.
|
---|
834 | ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
|
---|
835 | }
|
---|
836 | }
|
---|
837 | ##fixme: validate %-patterns?
|
---|
838 |
|
---|
839 | # Unlike single PTR records, there is absolutely no way to sanely support multiple
|
---|
840 | # PTR templates for the same block, since they expect to expand to all the individual
|
---|
841 | # IPs on export. Nested templates should be supported though.
|
---|
842 |
|
---|
843 | my @checkvals = (${$args{val}});
|
---|
844 | if (${$args{val}} =~ /,/) {
|
---|
845 | # push . and :: variants into checkvals if val has ,
|
---|
846 | my $tmp;
|
---|
847 | ($tmp = ${$args{val}}) =~ s/,/./;
|
---|
848 | push @checkvals, $tmp;
|
---|
849 | ($tmp = ${$args{val}}) =~ s/,/::/;
|
---|
850 | push @checkvals, $tmp;
|
---|
851 | }
|
---|
852 | ##fixme: this feels wrong still - need to restrict template pseudorecords to One Of Each
|
---|
853 | # Per Netblock such that they don't conflict on export
|
---|
854 | my $typeck;
|
---|
855 | # type 65282 -> ptr template -> look for any of 65282, 65283, 65284
|
---|
856 | $typeck = 'type=65283 OR type=65284' if ${$args{rectype}} == 65282;
|
---|
857 | # type 65283 -> a+ptr template -> v4 -> look for 65282 or 65283
|
---|
858 | $typeck = 'type=65283' if ${$args{rectype}} == 65282;
|
---|
859 | # type 65284 -> aaaa+ptr template -> v6 -> look for 65282 or 65284
|
---|
860 | $typeck = 'type=65284' if ${$args{rectype}} == 65282;
|
---|
861 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ? ".
|
---|
862 | "AND (type=65282 OR $typeck)");
|
---|
863 | foreach my $checkme (@checkvals) {
|
---|
864 | $pcsth->execute($checkme);
|
---|
865 | my ($rc) = $pcsth->fetchrow_array;
|
---|
866 | return ('FAIL', "Only one template pseudorecord may exist for a given IP block") if $rc > 1;
|
---|
867 | }
|
---|
868 |
|
---|
869 | } else {
|
---|
870 | return ('FAIL', "Forward zones cannot contain PTR records");
|
---|
871 | }
|
---|
872 |
|
---|
873 | return ('OK','OK');
|
---|
874 | } # done PTR template record
|
---|
875 |
|
---|
876 | # A+PTR template record
|
---|
877 | sub _validate_65283 {
|
---|
878 | my $self = shift;
|
---|
879 | my $dbh = $self->{dbh};
|
---|
880 |
|
---|
881 | my %args = @_;
|
---|
882 |
|
---|
883 | my ($code,$msg) = ('OK','OK');
|
---|
884 |
|
---|
885 | ##fixme: need to fiddle things since A+PTR templates are acceptable in live
|
---|
886 | # forward zones but not default records
|
---|
887 | if ($args{defrec} eq 'n') {
|
---|
888 | if ($args{revrec} eq 'n') {
|
---|
889 | ($code,$msg) = $self->_validate_1(%args) if ${$args{rectype}} == 65280;
|
---|
890 | ($code,$msg) = $self->_validate_28(%args) if ${$args{rectype}} == 65281;
|
---|
891 | return ($code,$msg) if $code eq 'FAIL';
|
---|
892 |
|
---|
893 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
894 | # work here since we don't *know* which parent to put it in.
|
---|
895 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
896 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
897 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
898 | # Fail if no match; we can't coerce a PTR-template type down to not include the PTR bit currently.
|
---|
899 | if (!$revid) {
|
---|
900 | $msg = "Can't ".($args{update} ? 'update' : 'add')." ${$args{host}}/${$args{val}} as ".
|
---|
901 | "$typemap{${$args{rectype}}}: reverse zone not found for ${$args{val}}";
|
---|
902 | ##fixme: add A template, AAAA template types?
|
---|
903 | # ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
904 | return ('FAIL', $msg);
|
---|
905 | }
|
---|
906 |
|
---|
907 | # Add reverse zone ID to field list and values
|
---|
908 | ${$args{fields}} .= "rdns_id,";
|
---|
909 | push @{$args{vallist}}, $revid;
|
---|
910 |
|
---|
911 | } else {
|
---|
912 | return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
913 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
914 | ${$args{val}} = "$args{addr}";
|
---|
915 |
|
---|
916 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) {
|
---|
917 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
918 | " as PTR template instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
919 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
920 | $msg = $addmsg if $code eq 'OK';
|
---|
921 | ${$args{rectype}} = 65282;
|
---|
922 | return ('WARN', $msg);
|
---|
923 | }
|
---|
924 |
|
---|
925 | # Add domain ID to field list and values
|
---|
926 | ${$args{fields}} .= "domain_id,";
|
---|
927 | push @{$args{vallist}}, ${$args{domid}};
|
---|
928 | }
|
---|
929 |
|
---|
930 | } else {
|
---|
931 | my ($code,$msg) = $self->_validate_65282(%args);
|
---|
932 | return ($code, $msg) if $code eq 'FAIL';
|
---|
933 | # get domain, check against ${$args{name}}
|
---|
934 | }
|
---|
935 |
|
---|
936 | return ('OK','OK');
|
---|
937 | } # done AAAA+PTR template record
|
---|
938 |
|
---|
939 | # AAAA+PTR template record
|
---|
940 | sub _validate_65284 {
|
---|
941 | return ('OK','OK');
|
---|
942 | } # done AAAA+PTR template record
|
---|
943 |
|
---|
944 | # Delegation record
|
---|
945 | # This is essentially a specialized clone of the NS record, primarily useful
|
---|
946 | # for delegating IPv4 sub-/24 reverse blocks
|
---|
947 | sub _validate_65285 {
|
---|
948 | my $self = shift;
|
---|
949 | my $dbh = $self->{dbh};
|
---|
950 |
|
---|
951 | my %args = @_;
|
---|
952 |
|
---|
953 | # Almost, but not quite, identical to NS record validation.
|
---|
954 |
|
---|
955 | # Check that the target of the record is within the parent.
|
---|
956 | # Yes, host<->val are mixed up here; can't see a way to avoid it. :(
|
---|
957 | if ($args{defrec} eq 'n') {
|
---|
958 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
959 | if ($args{revrec} eq 'y') {
|
---|
960 | my $tmpip = NetAddr::IP->new(${$args{val}});
|
---|
961 | my $pname = $self->revName($args{id});
|
---|
962 | return ('FAIL',"${$args{val}} not within $pname")
|
---|
963 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$tmpip);
|
---|
964 | # Normalize
|
---|
965 | ${$args{val}} = "$tmpip";
|
---|
966 | } else {
|
---|
967 | my $pname = $self->domainName($args{id});
|
---|
968 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
969 | }
|
---|
970 | } else {
|
---|
971 | return ('FAIL',"Delegation records are not permitted in default record sets");
|
---|
972 | }
|
---|
973 | return ('OK','OK');
|
---|
974 | }
|
---|
975 |
|
---|
976 |
|
---|
977 | ##
|
---|
978 | ## Record data substitution subs
|
---|
979 | ##
|
---|
980 |
|
---|
981 | # Replace ZONE in hostname, or create (most of) the actual proper zone name
|
---|
982 | sub _ZONE {
|
---|
983 | my $zone = shift;
|
---|
984 | my $string = shift;
|
---|
985 | my $fr = shift || 'f'; # flag for forward/reverse order? nb: ignored for IP
|
---|
986 | my $sep = shift || '-'; # Separator character - unlikely we'll ever need more than . or -
|
---|
987 |
|
---|
988 | my $prefix;
|
---|
989 |
|
---|
990 | $string =~ s/,/./ if !$zone->{isv6};
|
---|
991 | $string =~ s/,/::/ if $zone->{isv6};
|
---|
992 |
|
---|
993 | # Subbing ZONE in the host. We need to properly ID the netblock range
|
---|
994 | # The subbed text should have "network IP with trailing zeros stripped" for
|
---|
995 | # blocks lined up on octet (for v4) or hex-quad (for v6) boundaries
|
---|
996 | # For blocks that do NOT line up on these boundaries, we take the most
|
---|
997 | # significant octet or 16-bit chunk of the "broadcast" IP and append it
|
---|
998 | # after a double-dash
|
---|
999 | # ie:
|
---|
1000 | # 8.0.0.0/6 -> 8.0.0.0 -> 11.255.255.255; sub should be 8--11
|
---|
1001 | # 10.0.0.0/12 -> 10.0.0.0 -> 10.0.0.0 -> 10.15.255.255; sub should be 10-0--15
|
---|
1002 | # 192.168.4.0/22 -> 192.168.4.0 -> 192.168.7.255; sub should be 192-168-4--7
|
---|
1003 | # 192.168.0.8/29 -> 192.168.0.8 -> 192.168.0.15; sub should be 192-168-0-8--15
|
---|
1004 | # Similar for v6
|
---|
1005 |
|
---|
1006 | if (!$zone->{isv6}) { # IPv4
|
---|
1007 |
|
---|
1008 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
1009 | # a funky subnet that had host bits set.
|
---|
1010 | my $bc = $zone->broadcast->addr;
|
---|
1011 |
|
---|
1012 | if ($zone->masklen > 24) {
|
---|
1013 | $bc =~ s/^\d+\.\d+\.\d+\.//;
|
---|
1014 | } elsif ($zone->masklen > 16) {
|
---|
1015 | $prefix =~ s/\.0$//;
|
---|
1016 | $bc =~ s/^\d+\.\d+\.//;
|
---|
1017 | } elsif ($zone->masklen > 8) {
|
---|
1018 | $bc =~ s/^\d+\.//;
|
---|
1019 | $prefix =~ s/\.0\.0$//;
|
---|
1020 | } else {
|
---|
1021 | $prefix =~ s/\.0\.0\.0$//;
|
---|
1022 | }
|
---|
1023 | if ($zone->masklen % 8) {
|
---|
1024 | $bc =~ s/(\.255)+$//;
|
---|
1025 | $prefix .= "--$bc"; #"--".zone->masklen; # use range or mask length?
|
---|
1026 | }
|
---|
1027 | if ($fr eq 'f') {
|
---|
1028 | $prefix =~ s/\.+/$sep/g;
|
---|
1029 | } else {
|
---|
1030 | $prefix = join($sep, reverse(split(/\./, $prefix)));
|
---|
1031 | }
|
---|
1032 |
|
---|
1033 | } else { # IPv6
|
---|
1034 |
|
---|
1035 | if ($fr eq 'f') {
|
---|
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 | if (($zone->masklen % 16) != 0) {
|
---|
1041 | # Strip trailing :0 off $prefix, and :ffff off the broadcast IP
|
---|
1042 | for (my $i=0; $i<(7-int($zone->masklen / 16)); $i++) {
|
---|
1043 | $prefix =~ s/:0$//;
|
---|
1044 | $bc =~ s/:ffff$//;
|
---|
1045 | }
|
---|
1046 | # Strip the leading 16-bit chunks off the front of the broadcast IP
|
---|
1047 | $bc =~ s/^([a-f0-9]+:)+//;
|
---|
1048 | # Append the remaining 16-bit chunk to the prefix after "--"
|
---|
1049 | $prefix .= "--$bc";
|
---|
1050 | } else {
|
---|
1051 | # Strip off :0 from the end until we reach the netblock length.
|
---|
1052 | for (my $i=0; $i<(8-$zone->masklen / 16); $i++) {
|
---|
1053 | $prefix =~ s/:0$//;
|
---|
1054 | }
|
---|
1055 | }
|
---|
1056 | # Actually deal with the separator
|
---|
1057 | $prefix =~ s/:/$sep/g;
|
---|
1058 |
|
---|
1059 | } else { # $fr eq 'f'
|
---|
1060 |
|
---|
1061 | $prefix = $zone->network->full; # Just In Case someone managed to slip in
|
---|
1062 | # a funky subnet that had host bits set.
|
---|
1063 | my $bc = $zone->broadcast->full;
|
---|
1064 | $prefix =~ s/://g; # clean these out since they're not spaced right for this case
|
---|
1065 | $bc =~ s/://g;
|
---|
1066 | # Strip trailing 0 off $prefix, and f off the broadcast IP, to match the mask length
|
---|
1067 | for (my $i=0; $i<(31-int($zone->masklen / 4)); $i++) {
|
---|
1068 | $prefix =~ s/0$//;
|
---|
1069 | $bc =~ s/f$//;
|
---|
1070 | }
|
---|
1071 | # Split and reverse the order of the nibbles in the network/broadcast IPs
|
---|
1072 | # trim another 0 for nibble-aligned blocks first, but only if we really have a block, not an IP
|
---|
1073 | $prefix =~ s/0$// if $zone->masklen % 4 == 0 && $zone->masklen != 128;
|
---|
1074 | my @nbits = reverse split //, $prefix;
|
---|
1075 | my @bbits = reverse split //, $bc;
|
---|
1076 | # Handle the sub-nibble case. Eww. I feel dirty supporting this...
|
---|
1077 | $nbits[0] = "$nbits[0]-$bbits[0]" if ($zone->masklen % 4) != 0;
|
---|
1078 | # Glue it back together
|
---|
1079 | $prefix = join($sep, @nbits);
|
---|
1080 |
|
---|
1081 | } # $fr ne 'f'
|
---|
1082 |
|
---|
1083 | } # $zone->{isv6}
|
---|
1084 |
|
---|
1085 | # Do the substitution, finally
|
---|
1086 | $string =~ s/ZONE/$prefix/;
|
---|
1087 | $string =~ s/--/-/ if $sep ne '-'; # - as separator needs extra help for sub-octet v4 netblocks
|
---|
1088 | return $string;
|
---|
1089 | } # done _ZONE()
|
---|
1090 |
|
---|
1091 | # Not quite a substitution sub, but placed here as it's basically the inverse of above;
|
---|
1092 | # given the .arpa zone name, return the CIDR netblock the zone is for.
|
---|
1093 | # Supports v4 non-octet/non-classful netblocks as per the method outlined in the Grasshopper Book (2nd Ed p217-218)
|
---|
1094 | # Does NOT support non-quad v6 netblocks via the same scheme; it shouldn't ever be necessary.
|
---|
1095 | # Takes a nominal .arpa zone name, returns a success code and NetAddr::IP, or a fail code and message
|
---|
1096 | sub _zone2cidr {
|
---|
1097 | my $zone = shift;
|
---|
1098 |
|
---|
1099 | my $cidr;
|
---|
1100 | my $tmpcidr;
|
---|
1101 | my $warnmsg = '';
|
---|
1102 |
|
---|
1103 | if ($zone =~ /\.in-addr\.arpa\.?$/) {
|
---|
1104 | # v4 revzone, formal zone name type
|
---|
1105 | my $tmpzone = $zone;
|
---|
1106 | $tmpzone =~ s/\.in-addr\.arpa\.?//;
|
---|
1107 | return ('FAIL', "Non-numerics in apparent IPv4 reverse zone name") if $tmpzone !~ /^(?:\d+-)?[\d\.]+$/;
|
---|
1108 |
|
---|
1109 | # Snag the octet pieces
|
---|
1110 | my @octs = split /\./, $tmpzone;
|
---|
1111 |
|
---|
1112 | # Map result of a range manipulation to a mask length change. Cheaper than finding the 2-root of $octets[0]+1.
|
---|
1113 | # Note we will not support /31 blocks, mostly due to issues telling "24-31" -> .24/29 apart from
|
---|
1114 | # "24-31" -> .24/31", with a litte bit of "/31 is icky".
|
---|
1115 | my %maskmap = ( 3 => 2, 7 => 3, 15 => 4, 31 => 5, 63 => 6, 127 => 7,
|
---|
1116 | 30 => 2, 29 => 3, 28 => 4, 27 => 5, 26 => 6, 25 => 7
|
---|
1117 | );
|
---|
1118 |
|
---|
1119 | # Handle "range" blocks, eg, 80-83.168.192.in-addr.arpa (192.168.80.0/22)
|
---|
1120 | # Need to take the size of the range to offset the basic octet-based mask length,
|
---|
1121 | # and make sure the first number in the range gets used as the network address for the block
|
---|
1122 | # Alternate form: The second number is actually the real netmask, not the end of the range.
|
---|
1123 | my $masklen = 0;
|
---|
1124 | if ($octs[0] =~ /^((\d+)-(\d+))$/) { # take the range...
|
---|
1125 | if (24 < $3 && $3 < 31) {
|
---|
1126 | # we have a real netmask
|
---|
1127 | $masklen = -$maskmap{$3};
|
---|
1128 | } else {
|
---|
1129 | # we have a range. NB: only real CIDR ranges are supported
|
---|
1130 | $masklen -= $maskmap{-(eval $1)}; # find the mask base...
|
---|
1131 | }
|
---|
1132 | $octs[0] = $2; # set the base octet of the range...
|
---|
1133 | }
|
---|
1134 | @octs = reverse @octs; # We can reverse the octet pieces now that we've extracted and munged any ranges
|
---|
1135 |
|
---|
1136 | # arguably we should only allow sub-octet range/mask in-addr.arpa
|
---|
1137 | # specifications in the least significant octet, but the code is
|
---|
1138 | # simpler if we deal with sub-octet delegations at any level.
|
---|
1139 |
|
---|
1140 | # Now we find the "true" mask with the aid of the "base" calculated above
|
---|
1141 | if ($#octs == 0) {
|
---|
1142 | $masklen += 8;
|
---|
1143 | $tmpcidr = "$octs[0].0.0.0/$masklen"; # really hope we don't see one of these very often.
|
---|
1144 | } elsif ($#octs == 1) {
|
---|
1145 | $masklen += 16;
|
---|
1146 | $tmpcidr = "$octs[0].$octs[1].0.0/$masklen";
|
---|
1147 | } elsif ($#octs == 2) {
|
---|
1148 | $masklen += 24;
|
---|
1149 | $tmpcidr = "$octs[0].$octs[1].$octs[2].0/$masklen";
|
---|
1150 | } else {
|
---|
1151 | $masklen += 32;
|
---|
1152 | $tmpcidr = "$octs[0].$octs[1].$octs[2].$octs[3]/$masklen";
|
---|
1153 | }
|
---|
1154 |
|
---|
1155 | } elsif ($zone =~ /\.ip6\.arpa$/) {
|
---|
1156 | # v6 revzone, formal zone name type
|
---|
1157 | my $tmpzone = $zone;
|
---|
1158 | $tmpzone =~ s/\.ip6\.arpa\.?//;
|
---|
1159 | ##fixme: if-n-when we decide we can support sub-nibble v6 zone names, we'll need to change this segment
|
---|
1160 | return ('FAIL', "Non-hexadecimals in apparent IPv6 reverse zone name") if $tmpzone !~ /^[a-fA-F\d\.]+$/;
|
---|
1161 | my @quads = reverse(split(/\./, $tmpzone));
|
---|
1162 | $warnmsg .= "Apparent sub-/64 IPv6 reverse zone\n" if $#quads > 15;
|
---|
1163 | my $nc;
|
---|
1164 | foreach (@quads) {
|
---|
1165 | $tmpcidr .= $_;
|
---|
1166 | $tmpcidr .= ":" if ++$nc % 4 == 0;
|
---|
1167 | }
|
---|
1168 | my $nq = 1 if $nc % 4 != 0;
|
---|
1169 | my $mask = $nc * 4; # need to do this here because we probably increment it below
|
---|
1170 | while ($nc++ % 4 != 0) {
|
---|
1171 | $tmpcidr .= "0";
|
---|
1172 | }
|
---|
1173 | $tmpcidr .= ($nq ? '::' : ':')."/$mask";
|
---|
1174 | }
|
---|
1175 |
|
---|
1176 | # Just to be sure, use NetAddr::IP to validate. Saves a lot of nasty regex watching for valid octet values.
|
---|
1177 | return ('FAIL', "Invalid zone $zone (apparent netblock $tmpcidr)")
|
---|
1178 | unless $cidr = NetAddr::IP->new($tmpcidr);
|
---|
1179 |
|
---|
1180 | if ($warnmsg) {
|
---|
1181 | $errstr = $warnmsg;
|
---|
1182 | return ('WARN', $cidr);
|
---|
1183 | }
|
---|
1184 | return ('OK', $cidr);
|
---|
1185 | } # done _zone2cidr()
|
---|
1186 |
|
---|
1187 | # Record template %-parameter expansion, IPv4. Note that IPv6 doesn't
|
---|
1188 | # really have a sane way to handle this type of expansion at the moment
|
---|
1189 | # due to the size of the address space.
|
---|
1190 | # Takes a reference to a template string to be expanded, and an IP to use in the replacement.
|
---|
1191 | sub _template4_expand {
|
---|
1192 | my $tmpl = shift;
|
---|
1193 | my $ip = shift;
|
---|
1194 |
|
---|
1195 | my @ipparts = split /\./, $ip;
|
---|
1196 | my @iphex;
|
---|
1197 | my @ippad;
|
---|
1198 | for (@ipparts) {
|
---|
1199 | push @iphex, sprintf("%x", $_);
|
---|
1200 | push @ippad, sprintf("%0.3u", $_);
|
---|
1201 | }
|
---|
1202 |
|
---|
1203 | # IP substitutions in template records:
|
---|
1204 | #major patterns:
|
---|
1205 | #dashed IP, forward and reverse
|
---|
1206 | #dotted IP, forward and reverse (even if forward is... dumb)
|
---|
1207 | # -> %r for reverse, %i for forward, leading - or . to indicate separator, defaults to -
|
---|
1208 | # %r or %-r => %4d-%3d-%2d-%1d
|
---|
1209 | # %.r => %4d.%3d.%2d.%1d
|
---|
1210 | # %i or %-i => %1d-%2d-%3d-%4d
|
---|
1211 | # %.i => %1d.%2d.%3d.%4d
|
---|
1212 | $$tmpl =~ s/\%r/\%4d-\%3d-\%2d-\%1d/g;
|
---|
1213 | $$tmpl =~ s/\%([-.])r/\%4d$1\%3d$1\%2d$1\%1d/g;
|
---|
1214 | $$tmpl =~ s/\%i/\%1d-\%2d-\%3d-\%4d/g;
|
---|
1215 | $$tmpl =~ s/\%([-.])i/\%1d$1\%2d$1\%3d$1\%4d/g;
|
---|
1216 |
|
---|
1217 | #hex-coded IP
|
---|
1218 | # %h
|
---|
1219 | $$tmpl =~ s/\%h/$iphex[0]$iphex[1]$iphex[2]$iphex[3]/g;
|
---|
1220 |
|
---|
1221 | #IP as decimal-coded 32-bit value
|
---|
1222 | # %d
|
---|
1223 | my $iptmp = $ipparts[0]*256*256*256 + $ipparts[1]*256*256 + $ipparts[2]*256 + $ipparts[3];
|
---|
1224 | $$tmpl =~ s/\%d/$iptmp/g;
|
---|
1225 |
|
---|
1226 | #minor patterns (per-octet)
|
---|
1227 | # %[1234][dh0]
|
---|
1228 | #octet
|
---|
1229 | #hex-coded octet
|
---|
1230 | #0-padded octet
|
---|
1231 | $$tmpl =~ s/\%([1234])d/$ipparts[$1-1]/g;
|
---|
1232 | $$tmpl =~ s/\%([1234])h/$iphex[$1-1]/g;
|
---|
1233 | $$tmpl =~ s/\%([1234])0/$ippad[$1-1]/g;
|
---|
1234 | } # _template4_expand()
|
---|
1235 |
|
---|
1236 |
|
---|
1237 | ##
|
---|
1238 | ## Initialization and cleanup subs
|
---|
1239 | ##
|
---|
1240 |
|
---|
1241 | ## DNSDB::loadConfig()
|
---|
1242 | # Load the minimum required initial state (DB connect info) from a config file
|
---|
1243 | # Load misc other bits while we're at it.
|
---|
1244 | # Takes an optional hash that may contain:
|
---|
1245 | # - basename and config path to look for
|
---|
1246 | # Populates the %config and %def hashes
|
---|
1247 | sub loadConfig {
|
---|
1248 | my %args = @_;
|
---|
1249 | $args{configfile} = '' if !$args{configfile};
|
---|
1250 |
|
---|
1251 | ##fixme this is *intended* to load a system-default config template, and allow
|
---|
1252 | # overriding on a per-tool or per-web-UI-instance basis with a secondary config
|
---|
1253 | # file. The "default" config file can't be deleted in the current form.
|
---|
1254 |
|
---|
1255 | my $deferr = ''; # place to put error from default config file in case we can't find either one
|
---|
1256 |
|
---|
1257 | my $configroot = "/etc/dnsdb"; ##CFG_LEAF##
|
---|
1258 | $configroot = '' if $args{configfile} =~ m|^/|; # allow passed siteconfig to specify an arbitrary absolute path
|
---|
1259 | $args{configfile} .= ".conf" if $args{configfile} !~ /\.conf$/;
|
---|
1260 | my $defconfig = "$configroot/dnsdb.conf";
|
---|
1261 | my $siteconfig = "$configroot/$args{configfile}";
|
---|
1262 |
|
---|
1263 | # System defaults
|
---|
1264 | __cfgload("$defconfig") or $deferr = $errstr;
|
---|
1265 |
|
---|
1266 | # Per-site-ish settings.
|
---|
1267 | if ($args{configfile} ne '.conf') {
|
---|
1268 | unless (__cfgload("$siteconfig")) {
|
---|
1269 | $errstr = ($deferr ? "Error opening default config file $defconfig: $deferr\n" : '').
|
---|
1270 | "Error opening site config file $siteconfig";
|
---|
1271 | return;
|
---|
1272 | }
|
---|
1273 | }
|
---|
1274 |
|
---|
1275 | # Munge log_failures.
|
---|
1276 | if ($config{log_failures} ne '1' && $config{log_failures} ne '0') {
|
---|
1277 | # true/false, on/off, yes/no all valid.
|
---|
1278 | if ($config{log_failures} =~ /^(?:true|false|on|off|yes|no)$/) {
|
---|
1279 | if ($config{log_failures} =~ /(?:true|on|yes)/) {
|
---|
1280 | $config{log_failures} = 1;
|
---|
1281 | } else {
|
---|
1282 | $config{log_failures} = 0;
|
---|
1283 | }
|
---|
1284 | } else {
|
---|
1285 | $errstr = "Bad log_failures setting $config{log_failures}";
|
---|
1286 | $config{log_failures} = 1;
|
---|
1287 | # Bad setting shouldn't be fatal.
|
---|
1288 | # return 2;
|
---|
1289 | }
|
---|
1290 | }
|
---|
1291 |
|
---|
1292 | # All good, clear the error and go home.
|
---|
1293 | $errstr = '';
|
---|
1294 | return 1;
|
---|
1295 | } # end loadConfig()
|
---|
1296 |
|
---|
1297 |
|
---|
1298 | ## DNSDB::__cfgload()
|
---|
1299 | # Private sub to parse a config file and load it into %config
|
---|
1300 | # Takes a filename
|
---|
1301 | sub __cfgload {
|
---|
1302 | $errstr = '';
|
---|
1303 | my $cfgfile = shift;
|
---|
1304 |
|
---|
1305 | if (open CFG, "<$cfgfile") {
|
---|
1306 | while (<CFG>) {
|
---|
1307 | chomp;
|
---|
1308 | s/^\s*//;
|
---|
1309 | next if /^#/;
|
---|
1310 | next if /^$/;
|
---|
1311 | # hmm. more complex bits in this file might require [heading] headers, maybe?
|
---|
1312 | # $mode = $1 if /^\[(a-z)+]/;
|
---|
1313 | # DB connect info
|
---|
1314 | $config{dbname} = $1 if /^dbname\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1315 | $config{dbuser} = $1 if /^dbuser\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1316 | $config{dbpass} = $1 if /^dbpass\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1317 | $config{dbhost} = $1 if /^dbhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1318 | # SOA defaults
|
---|
1319 | $def{contact} = $1 if /^contact\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1320 | $def{prins} = $1 if /^prins\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1321 | $def{soattl} = $1 if /^soattl\s*=\s*(\d+)/i;
|
---|
1322 | $def{refresh} = $1 if /^refresh\s*=\s*(\d+)/i;
|
---|
1323 | $def{retry} = $1 if /^retry\s*=\s*(\d+)/i;
|
---|
1324 | $def{expire} = $1 if /^expire\s*=\s*(\d+)/i;
|
---|
1325 | $def{minttl} = $1 if /^minttl\s*=\s*(\d+)/i;
|
---|
1326 | $def{ttl} = $1 if /^ttl\s*=\s*(\d+)/i;
|
---|
1327 | # Mail settings
|
---|
1328 | $config{mailhost} = $1 if /^mailhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1329 | $config{mailnotify} = $1 if /^mailnotify\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
1330 | $config{mailsender} = $1 if /^mailsender\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
1331 | $config{mailname} = $1 if /^mailname\s*=\s*([a-z0-9\s_.-]+)/i;
|
---|
1332 | $config{orgname} = $1 if /^orgname\s*=\s*([a-z0-9\s_.,'-]+)/i;
|
---|
1333 | $config{domain} = $1 if /^domain\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1334 | # session - note this is fed directly to CGI::Session
|
---|
1335 | $config{timeout} = $1 if /^[tT][iI][mM][eE][oO][uU][tT]\s*=\s*(\d+[smhdwMy]?)/;
|
---|
1336 | $config{sessiondir} = $1 if m{^sessiondir\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
1337 | # misc
|
---|
1338 | $config{log_failures} = $1 if /^log_failures\s*=\s*([a-z01]+)/i;
|
---|
1339 | $config{perpage} = $1 if /^perpage\s*=\s*(\d+)/i;
|
---|
1340 | $config{exportcache} = $1 if m{^exportcache\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
1341 | # RPC options
|
---|
1342 | $config{rpcmode} = $1 if /^rpc_mode\s*=\s*(socket|HTTP|XMLRPC)\s*$/i;
|
---|
1343 | $config{maxfcgi} = $1 if /^max_fcgi_requests\s*=\s*(\d+)\s*$/i;
|
---|
1344 | if (my ($tmp) = /^rpc_iplist\s*=\s*(.+)/i) {
|
---|
1345 | my @ips = split /[,\s]+/, $tmp;
|
---|
1346 | my $rpcsys = shift @ips;
|
---|
1347 | push @{$config{rpcacl}{$rpcsys}}, @ips;
|
---|
1348 | }
|
---|
1349 | }
|
---|
1350 | close CFG;
|
---|
1351 | } else {
|
---|
1352 | $errstr = $!;
|
---|
1353 | return;
|
---|
1354 | }
|
---|
1355 | return 1;
|
---|
1356 | } # end __cfgload()
|
---|
1357 |
|
---|
1358 |
|
---|
1359 | ## DNSDB::connectDB()
|
---|
1360 | # Creates connection to DNS database.
|
---|
1361 | # Requires the database name, username, and password.
|
---|
1362 | # Returns a handle to the db or undef on failure.
|
---|
1363 | # Set up for a PostgreSQL db; could be any transactional DBMS with the
|
---|
1364 | # right changes.
|
---|
1365 | # Called by new(); not intended to be called publicly.
|
---|
1366 | sub connectDB {
|
---|
1367 | $errstr = '';
|
---|
1368 | my $dbname = shift;
|
---|
1369 | my $user = shift;
|
---|
1370 | my $pass = shift;
|
---|
1371 | my $dbh;
|
---|
1372 | my $DSN = "DBI:Pg:dbname=$dbname";
|
---|
1373 |
|
---|
1374 | my $host = shift;
|
---|
1375 | $DSN .= ";host=$host" if $host;
|
---|
1376 |
|
---|
1377 | # Note that we want to autocommit by default, and we will turn it off locally as necessary.
|
---|
1378 | # We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
|
---|
1379 | $dbh = DBI->connect($DSN, $user, $pass, {
|
---|
1380 | AutoCommit => 1,
|
---|
1381 | PrintError => 0
|
---|
1382 | });
|
---|
1383 | if (!$dbh) {
|
---|
1384 | $errstr = $DBI::errstr;
|
---|
1385 | return;
|
---|
1386 | }
|
---|
1387 | #) if(!$dbh);
|
---|
1388 |
|
---|
1389 | local $dbh->{RaiseError} = 1;
|
---|
1390 |
|
---|
1391 | eval {
|
---|
1392 | ##fixme: initialize the DB if we can't find the table (since, by definition, there's
|
---|
1393 | # nothing there if we can't select from it...)
|
---|
1394 | my $tblsth = $dbh->prepare("SELECT count(*) FROM pg_catalog.pg_class WHERE relkind='r' AND relname=?");
|
---|
1395 | my ($tblcount) = $dbh->selectrow_array($tblsth, undef, ('misc'));
|
---|
1396 | # return (undef,$DBI::errstr) if $dbh->err;
|
---|
1397 |
|
---|
1398 | #if ($tblcount == 0) {
|
---|
1399 | # # create tables one at a time, checking for each.
|
---|
1400 | # return (undef, "check table misc missing");
|
---|
1401 | #}
|
---|
1402 |
|
---|
1403 | # Return here if we can't select.
|
---|
1404 | # This should retrieve the dbversion key.
|
---|
1405 | my $sth = $dbh->prepare("SELECT key,value FROM misc WHERE misc_id=1");
|
---|
1406 | $sth->execute();
|
---|
1407 | # return (undef,$DBI::errstr) if ($sth->err);
|
---|
1408 |
|
---|
1409 | ##fixme: do stuff to the DB on version mismatch
|
---|
1410 | # x.y series should upgrade on $DNSDB::VERSION > misc(key=>version)
|
---|
1411 | # DB should be downward-compatible; column defaults should give sane (if possibly
|
---|
1412 | # useless-and-needs-help) values in columns an older software stack doesn't know about.
|
---|
1413 |
|
---|
1414 | # See if the select returned anything (or null data). This should
|
---|
1415 | # succeed if the select executed, but...
|
---|
1416 | $sth->fetchrow();
|
---|
1417 | # return (undef,$DBI::errstr) if ($sth->err);
|
---|
1418 |
|
---|
1419 | $sth->finish;
|
---|
1420 |
|
---|
1421 | }; # wrapped DB checks
|
---|
1422 | if ($@) {
|
---|
1423 | $errstr = $@;
|
---|
1424 | return;
|
---|
1425 | }
|
---|
1426 |
|
---|
1427 | # If we get here, we should be OK.
|
---|
1428 | return $dbh;
|
---|
1429 | } # end connectDB
|
---|
1430 |
|
---|
1431 |
|
---|
1432 | ## DNSDB::finish()
|
---|
1433 | # Cleans up after database handles and so on.
|
---|
1434 | # Requires a database handle
|
---|
1435 | sub finish {
|
---|
1436 | my $self = shift;
|
---|
1437 | $self->{dbh}->disconnect;
|
---|
1438 | } # end finish
|
---|
1439 |
|
---|
1440 |
|
---|
1441 | ## DNSDB::initGlobals()
|
---|
1442 | # Initialize global variables
|
---|
1443 | # NB: this does NOT include web-specific session variables!
|
---|
1444 | sub initGlobals {
|
---|
1445 | my $self = shift;
|
---|
1446 | my $dbh = $self->{dbh};
|
---|
1447 |
|
---|
1448 | # load record types from database
|
---|
1449 | my $sth = $dbh->prepare("SELECT val,name,stdflag FROM rectypes");
|
---|
1450 | $sth->execute;
|
---|
1451 | while (my ($recval,$recname,$stdflag) = $sth->fetchrow_array()) {
|
---|
1452 | $typemap{$recval} = $recname;
|
---|
1453 | $reverse_typemap{$recname} = $recval;
|
---|
1454 | # now we fill the record validation function hash
|
---|
1455 | if ($stdflag < 5) {
|
---|
1456 | my $fn = "_validate_$recval";
|
---|
1457 | $validators{$recval} = \&$fn;
|
---|
1458 | } else {
|
---|
1459 | my $fn = "sub { return ('FAIL','Type $recval ($recname) not supported'); }";
|
---|
1460 | $validators{$recval} = eval $fn;
|
---|
1461 | }
|
---|
1462 | }
|
---|
1463 | } # end initGlobals
|
---|
1464 |
|
---|
1465 |
|
---|
1466 | ## DNSDB::initRPC()
|
---|
1467 | # Takes a remote username and remote fullname.
|
---|
1468 | # Sets up the RPC logging-pseudouser if needed.
|
---|
1469 | # Sets the %userdata hash for logging.
|
---|
1470 | # Returns undef on failure
|
---|
1471 | sub initRPC {
|
---|
1472 | my $self = shift;
|
---|
1473 | my $dbh = $self->{dbh};
|
---|
1474 | my %args = @_;
|
---|
1475 |
|
---|
1476 | return if !$args{username};
|
---|
1477 | return if !$args{fullname};
|
---|
1478 |
|
---|
1479 | $args{username} = "$args{username}/$args{rpcsys}";
|
---|
1480 |
|
---|
1481 | my $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
|
---|
1482 | " FROM users WHERE username=?", undef, ($args{username}) );
|
---|
1483 | if (!$tmpuser) {
|
---|
1484 | $dbh->do("INSERT INTO users (username,password,firstname,type) VALUES (?,'RPC',?,'R')", undef,
|
---|
1485 | ($args{username}, $args{fullname}) );
|
---|
1486 | $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
|
---|
1487 | " FROM users WHERE username=?", undef, ($args{username}) );
|
---|
1488 | }
|
---|
1489 | $tmpuser->{lastname} = '' if !$tmpuser->{lastname};
|
---|
1490 | $self->{loguserid} = $tmpuser->{userid};
|
---|
1491 | $self->{logusername} = $tmpuser->{username};
|
---|
1492 | $self->{logfullname} = "$tmpuser->{firstname} $tmpuser->{lastname} ($args{rpcsys})";
|
---|
1493 | return 1 if $tmpuser;
|
---|
1494 | } # end initRPC()
|
---|
1495 |
|
---|
1496 |
|
---|
1497 | ## DNSDB::login()
|
---|
1498 | # Takes a database handle, username and password
|
---|
1499 | # Returns a userdata hash (UID, GID, username, fullname parts) if username exists,
|
---|
1500 | # password matches the one on file, and account is not disabled
|
---|
1501 | # Returns undef otherwise
|
---|
1502 | sub login {
|
---|
1503 | my $self = shift;
|
---|
1504 | my $dbh = $self->{dbh};
|
---|
1505 | my $user = shift;
|
---|
1506 | my $pass = shift;
|
---|
1507 |
|
---|
1508 | my $userinfo = $dbh->selectrow_hashref("SELECT user_id,group_id,password,firstname,lastname,status".
|
---|
1509 | " FROM users WHERE username=?",
|
---|
1510 | undef, ($user) );
|
---|
1511 | return if !$userinfo;
|
---|
1512 | return if !$userinfo->{status};
|
---|
1513 |
|
---|
1514 | if ($userinfo->{password} =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
|
---|
1515 | # native passwords (crypt-md5)
|
---|
1516 | return if $userinfo->{password} ne unix_md5_crypt($pass,$1);
|
---|
1517 | } elsif ($userinfo->{password} =~ /^[0-9a-f]{32}$/) {
|
---|
1518 | # VegaDNS import (hex-coded MD5)
|
---|
1519 | return if $userinfo->{password} ne md5_hex($pass);
|
---|
1520 | } else {
|
---|
1521 | # plaintext (convenient now and then)
|
---|
1522 | return if $userinfo->{password} ne $pass;
|
---|
1523 | }
|
---|
1524 |
|
---|
1525 | return $userinfo;
|
---|
1526 | } # end login()
|
---|
1527 |
|
---|
1528 |
|
---|
1529 | ## DNSDB::initActionLog()
|
---|
1530 | # Set up action logging. Takes a database handle and user ID
|
---|
1531 | # Sets some internal globals and Does The Right Thing to set up a logging channel.
|
---|
1532 | # This sets up _log() to spew out log entries to the defined channel without worrying
|
---|
1533 | # about having to open a file or a syslog channel
|
---|
1534 | ##fixme Need to call _initActionLog_blah() for various logging channels, configured
|
---|
1535 | # via dnsdb.conf, in $config{log_channel} or something
|
---|
1536 | # See https://secure.deepnet.cx/trac/dnsadmin/ticket/21
|
---|
1537 | sub initActionLog {
|
---|
1538 | my $self = shift;
|
---|
1539 | my $dbh = $self->{dbh};
|
---|
1540 | my $uid = shift;
|
---|
1541 |
|
---|
1542 | return if !$uid;
|
---|
1543 |
|
---|
1544 | # snag user info for logging. there's got to be a way to not have to pass this back
|
---|
1545 | # and forth from a caller, but web usage means no persistence we can rely on from
|
---|
1546 | # the server side.
|
---|
1547 | my ($username,$fullname) = $dbh->selectrow_array("SELECT username, firstname || ' ' || lastname".
|
---|
1548 | " FROM users WHERE user_id=?", undef, ($uid));
|
---|
1549 | ##fixme: errors are unpossible!
|
---|
1550 |
|
---|
1551 | $self->{logusername} = $username;
|
---|
1552 | $self->{loguserid} = $uid;
|
---|
1553 | $self->{logfullname} = $fullname;
|
---|
1554 |
|
---|
1555 | # convert to real check once we have other logging channels
|
---|
1556 | # if ($config{log_channel} eq 'sql') {
|
---|
1557 | # Open Log, Sez Me!
|
---|
1558 | # }
|
---|
1559 |
|
---|
1560 | } # end initActionLog
|
---|
1561 |
|
---|
1562 |
|
---|
1563 | ## DNSDB::getPermissions()
|
---|
1564 | # Get permissions from DB
|
---|
1565 | # Requires DB handle, group or user flag, ID, and hashref.
|
---|
1566 | sub getPermissions {
|
---|
1567 | my $self = shift;
|
---|
1568 | my $dbh = $self->{dbh};
|
---|
1569 |
|
---|
1570 | my $type = shift;
|
---|
1571 | my $id = shift;
|
---|
1572 | my $hash = shift;
|
---|
1573 |
|
---|
1574 | my $sql = qq(
|
---|
1575 | SELECT
|
---|
1576 | p.admin,p.self_edit,
|
---|
1577 | p.group_create,p.group_edit,p.group_delete,
|
---|
1578 | p.user_create,p.user_edit,p.user_delete,
|
---|
1579 | p.domain_create,p.domain_edit,p.domain_delete,
|
---|
1580 | p.record_create,p.record_edit,p.record_delete,p.record_locchg,
|
---|
1581 | p.location_create,p.location_edit,p.location_delete,p.location_view
|
---|
1582 | FROM permissions p
|
---|
1583 | );
|
---|
1584 | if ($type eq 'group') {
|
---|
1585 | $sql .= qq(
|
---|
1586 | JOIN groups g ON g.permission_id=p.permission_id
|
---|
1587 | WHERE g.group_id=?
|
---|
1588 | );
|
---|
1589 | } else {
|
---|
1590 | $sql .= qq(
|
---|
1591 | JOIN users u ON u.permission_id=p.permission_id
|
---|
1592 | WHERE u.user_id=?
|
---|
1593 | );
|
---|
1594 | }
|
---|
1595 |
|
---|
1596 | my $sth = $dbh->prepare($sql);
|
---|
1597 |
|
---|
1598 | ##fixme? we don't trap other plain SELECT errors
|
---|
1599 | $sth->execute($id);
|
---|
1600 |
|
---|
1601 | # my $permref = $sth->fetchrow_hashref;
|
---|
1602 | # return $permref;
|
---|
1603 | # $hash = $permref;
|
---|
1604 | # Eww. Need to learn how to forcibly drop a hashref onto an existing hash.
|
---|
1605 | ($hash->{admin},$hash->{self_edit},
|
---|
1606 | $hash->{group_create},$hash->{group_edit},$hash->{group_delete},
|
---|
1607 | $hash->{user_create},$hash->{user_edit},$hash->{user_delete},
|
---|
1608 | $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete},
|
---|
1609 | $hash->{record_create},$hash->{record_edit},$hash->{record_delete},$hash->{record_locchg},
|
---|
1610 | $hash->{location_create},$hash->{location_edit},$hash->{location_delete},$hash->{location_view}
|
---|
1611 | ) = $sth->fetchrow_array;
|
---|
1612 |
|
---|
1613 | } # end getPermissions()
|
---|
1614 |
|
---|
1615 |
|
---|
1616 | ## DNSDB::changePermissions()
|
---|
1617 | # Update an ACL entry
|
---|
1618 | # Takes a db handle, type, owner-id, and hashref for the changed permissions.
|
---|
1619 | sub changePermissions {
|
---|
1620 | my $self = shift;
|
---|
1621 | my $dbh = $self->{dbh};
|
---|
1622 | my $type = shift;
|
---|
1623 | my $id = shift;
|
---|
1624 | my $newperms = shift;
|
---|
1625 | my $inherit = shift || 0;
|
---|
1626 |
|
---|
1627 | my $resultmsg = '';
|
---|
1628 |
|
---|
1629 | # see if we're switching from inherited to custom. for bonus points,
|
---|
1630 | # snag the permid and parent permid anyway, since we'll need the permid
|
---|
1631 | # to set/alter custom perms, and both if we're switching from custom to
|
---|
1632 | # inherited.
|
---|
1633 | my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id,".
|
---|
1634 | ($type eq 'user' ? 'u.group_id,u.username' : 'u.parent_group_id,u.group_name').
|
---|
1635 | " FROM ".($type eq 'user' ? 'users' : 'groups')." u ".
|
---|
1636 | " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ".
|
---|
1637 | " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?");
|
---|
1638 | $sth->execute($id);
|
---|
1639 |
|
---|
1640 | my ($wasinherited,$permid,$parpermid,$parid,$name) = $sth->fetchrow_array;
|
---|
1641 |
|
---|
1642 | # hack phtoui
|
---|
1643 | # group id 1 is "special" in that it's it's own parent (err... possibly.)
|
---|
1644 | # may make its parent id 0 which doesn't exist, and as a bonus is Perl-false.
|
---|
1645 | $wasinherited = 0 if ($type eq 'group' && $id == 1);
|
---|
1646 |
|
---|
1647 | local $dbh->{AutoCommit} = 0;
|
---|
1648 | local $dbh->{RaiseError} = 1;
|
---|
1649 |
|
---|
1650 | # Wrap all the SQL in a transaction
|
---|
1651 | eval {
|
---|
1652 | if ($inherit) {
|
---|
1653 |
|
---|
1654 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ".
|
---|
1655 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) );
|
---|
1656 | $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) );
|
---|
1657 |
|
---|
1658 | } else {
|
---|
1659 |
|
---|
1660 | if ($wasinherited) { # munge new permission entry in if we're switching from inherited perms
|
---|
1661 | ##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users
|
---|
1662 | # ... if'n'when we have groups with fully inherited permissions.
|
---|
1663 | # SQL is coo
|
---|
1664 | $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ".
|
---|
1665 | "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) );
|
---|
1666 | ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ".
|
---|
1667 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) );
|
---|
1668 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ".
|
---|
1669 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) );
|
---|
1670 | }
|
---|
1671 |
|
---|
1672 | # and now set the permissions we were passed
|
---|
1673 | foreach (@permtypes) {
|
---|
1674 | if (defined ($newperms->{$_})) {
|
---|
1675 | $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) );
|
---|
1676 | }
|
---|
1677 | }
|
---|
1678 |
|
---|
1679 | } # (inherited->)? custom
|
---|
1680 |
|
---|
1681 | if ($type eq 'user') {
|
---|
1682 | $resultmsg = "Updated permissions for user $name";
|
---|
1683 | } else {
|
---|
1684 | $resultmsg = "Updated default permissions for group $name";
|
---|
1685 | }
|
---|
1686 | $self->_log(group_id => ($type eq 'user' ? $parid : $id), entry => $resultmsg);
|
---|
1687 | $dbh->commit;
|
---|
1688 | }; # end eval
|
---|
1689 | if ($@) {
|
---|
1690 | my $msg = $@;
|
---|
1691 | eval { $dbh->rollback; };
|
---|
1692 | return ('FAIL',"Error changing permissions: $msg");
|
---|
1693 | }
|
---|
1694 |
|
---|
1695 | return ('OK',$resultmsg);
|
---|
1696 | } # end changePermissions()
|
---|
1697 |
|
---|
1698 |
|
---|
1699 | ## DNSDB::comparePermissions()
|
---|
1700 | # Compare two permission hashes
|
---|
1701 | # Returns '>', '<', '=', '!'
|
---|
1702 | sub comparePermissions {
|
---|
1703 | my $p1 = shift;
|
---|
1704 | my $p2 = shift;
|
---|
1705 |
|
---|
1706 | my $retval = '='; # assume equality until proven otherwise
|
---|
1707 |
|
---|
1708 | no warnings "uninitialized";
|
---|
1709 |
|
---|
1710 | foreach (@permtypes) {
|
---|
1711 | next if $p1->{$_} == $p2->{$_}; # equal is good
|
---|
1712 | if ($p1->{$_} && !$p2->{$_}) {
|
---|
1713 | if ($retval eq '<') { # if we've already found an unequal pair where
|
---|
1714 | $retval = '!'; # $p2 has more access, and we now find a pair
|
---|
1715 | last; # where $p1 has more access, the overall access
|
---|
1716 | } # is neither greater or lesser, it's unequal.
|
---|
1717 | $retval = '>';
|
---|
1718 | }
|
---|
1719 | if (!$p1->{$_} && $p2->{$_}) {
|
---|
1720 | if ($retval eq '>') { # if we've already found an unequal pair where
|
---|
1721 | $retval = '!'; # $p1 has more access, and we now find a pair
|
---|
1722 | last; # where $p2 has more access, the overall access
|
---|
1723 | } # is neither greater or lesser, it's unequal.
|
---|
1724 | $retval = '<';
|
---|
1725 | }
|
---|
1726 | }
|
---|
1727 | return $retval;
|
---|
1728 | } # end comparePermissions()
|
---|
1729 |
|
---|
1730 |
|
---|
1731 | ## DNSDB::changeGroup()
|
---|
1732 | # Change group ID of an entity
|
---|
1733 | # Takes a database handle, entity type, entity ID, and new group ID
|
---|
1734 | sub changeGroup {
|
---|
1735 | my $self = shift;
|
---|
1736 | my $dbh = $self->{dbh};
|
---|
1737 | my $type = shift;
|
---|
1738 | my $id = shift;
|
---|
1739 | my $newgrp = shift;
|
---|
1740 |
|
---|
1741 | ##fixme: fail on not enough args
|
---|
1742 | #return ('FAIL', "Missing
|
---|
1743 |
|
---|
1744 | return ('FAIL', "Can't change the group of a $type")
|
---|
1745 | unless grep /^$type$/, ('domain','revzone','user','group'); # could be extended for defrecs?
|
---|
1746 |
|
---|
1747 | # Collect some names for logging and messages
|
---|
1748 | my $entname;
|
---|
1749 | if ($type eq 'domain') {
|
---|
1750 | $entname = $self->domainName($id);
|
---|
1751 | } elsif ($type eq 'revzone') {
|
---|
1752 | $entname = $self->revName($id);
|
---|
1753 | } elsif ($type eq 'user') {
|
---|
1754 | $entname = $self->userFullName($id, '%u');
|
---|
1755 | } elsif ($type eq 'group') {
|
---|
1756 | $entname = $self->groupName($id);
|
---|
1757 | }
|
---|
1758 |
|
---|
1759 | my ($oldgid) = $dbh->selectrow_array("SELECT group_id FROM $par_tbl{$type} WHERE $id_col{$type}=?",
|
---|
1760 | undef, ($id));
|
---|
1761 | my $oldgname = $self->groupName($oldgid);
|
---|
1762 | my $newgname = $self->groupName($newgrp);
|
---|
1763 |
|
---|
1764 | return ('FAIL', "Can't move things into a group that doesn't exist") if !$newgname;
|
---|
1765 |
|
---|
1766 | return ('WARN', "Nothing to do, new group is the same as the old group") if $oldgid == $newgrp;
|
---|
1767 |
|
---|
1768 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
1769 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
1770 | local $dbh->{AutoCommit} = 0;
|
---|
1771 | local $dbh->{RaiseError} = 1;
|
---|
1772 |
|
---|
1773 | eval {
|
---|
1774 | $dbh->do("UPDATE $par_tbl{$type} SET group_id=? WHERE $id_col{$type}=?", undef, ($newgrp, $id));
|
---|
1775 | # Log the change in both the old and new groups
|
---|
1776 | $self->_log(group_id => $oldgid, entry => "Moved $type $entname from $oldgname to $newgname");
|
---|
1777 | $self->_log(group_id => $newgrp, entry => "Moved $type $entname from $oldgname to $newgname");
|
---|
1778 | $dbh->commit;
|
---|
1779 | };
|
---|
1780 | if ($@) {
|
---|
1781 | my $msg = $@;
|
---|
1782 | eval { $dbh->rollback; };
|
---|
1783 | if ($config{log_failures}) {
|
---|
1784 | $self->_log(group_id => $oldgid, entry => "Error moving $type $entname to $newgname: $msg");
|
---|
1785 | $dbh->commit; # since we enabled transactions earlier
|
---|
1786 | }
|
---|
1787 | return ('FAIL',"Error moving $type $entname to $newgname: $msg");
|
---|
1788 | }
|
---|
1789 |
|
---|
1790 | return ('OK',"Moved $type $entname from $oldgname to $newgname");
|
---|
1791 | } # end changeGroup()
|
---|
1792 |
|
---|
1793 |
|
---|
1794 | ##
|
---|
1795 | ## Processing subs
|
---|
1796 | ##
|
---|
1797 |
|
---|
1798 | ## DNSDB::addDomain()
|
---|
1799 | # Add a domain
|
---|
1800 | # Takes a database handle, domain name, numeric group, boolean(ish) state (active/inactive),
|
---|
1801 | # and user info hash (for logging).
|
---|
1802 | # Returns a status code and message
|
---|
1803 | sub addDomain {
|
---|
1804 | $errstr = '';
|
---|
1805 | my $self = shift;
|
---|
1806 | my $dbh = $self->{dbh};
|
---|
1807 | my $domain = shift;
|
---|
1808 | return ('FAIL',"Domain must not be blank\n") if !$domain;
|
---|
1809 | my $group = shift;
|
---|
1810 | return ('FAIL',"Group must be specified\n") if !defined($group);
|
---|
1811 | my $state = shift;
|
---|
1812 | return ('FAIL',"Domain status must be specified\n") if !defined($state);
|
---|
1813 |
|
---|
1814 | $state = 1 if $state =~ /^active$/;
|
---|
1815 | $state = 1 if $state =~ /^on$/;
|
---|
1816 | $state = 0 if $state =~ /^inactive$/;
|
---|
1817 | $state = 0 if $state =~ /^off$/;
|
---|
1818 |
|
---|
1819 | return ('FAIL',"Invalid domain status") if $state !~ /^\d+$/;
|
---|
1820 |
|
---|
1821 | return ('FAIL', "Invalid characters in domain") if $domain !~ /^[a-zA-Z0-9_.-]+$/;
|
---|
1822 |
|
---|
1823 | my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)");
|
---|
1824 | my $dom_id;
|
---|
1825 |
|
---|
1826 | # quick check to start to see if we've already got one
|
---|
1827 | $sth->execute($domain);
|
---|
1828 | ($dom_id) = $sth->fetchrow_array;
|
---|
1829 |
|
---|
1830 | return ('FAIL', "Domain already exists") if $dom_id;
|
---|
1831 |
|
---|
1832 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
1833 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
1834 | local $dbh->{AutoCommit} = 0;
|
---|
1835 | local $dbh->{RaiseError} = 1;
|
---|
1836 |
|
---|
1837 | # Wrap all the SQL in a transaction
|
---|
1838 | eval {
|
---|
1839 | # insert the domain...
|
---|
1840 | $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef, ($domain, $group, $state));
|
---|
1841 |
|
---|
1842 | # get the ID...
|
---|
1843 | ($dom_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
1844 | undef, ($domain));
|
---|
1845 |
|
---|
1846 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
1847 | entry => "Added ".($state ? 'active' : 'inactive')." domain $domain");
|
---|
1848 |
|
---|
1849 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
1850 | my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
1851 | my $sth_in = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,distance,weight,port,ttl)".
|
---|
1852 | " VALUES ($dom_id,?,?,?,?,?,?,?)");
|
---|
1853 | $sth->execute($group);
|
---|
1854 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $sth->fetchrow_array()) {
|
---|
1855 | $host =~ s/DOMAIN/$domain/g;
|
---|
1856 | $val =~ s/DOMAIN/$domain/g;
|
---|
1857 | $sth_in->execute($host,$type,$val,$dist,$weight,$port,$ttl);
|
---|
1858 | if ($typemap{$type} eq 'SOA') {
|
---|
1859 | my @tmp1 = split /:/, $host;
|
---|
1860 | my @tmp2 = split /:/, $val;
|
---|
1861 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
1862 | entry => "[new $domain] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
1863 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl");
|
---|
1864 | } else {
|
---|
1865 | my $logentry = "[new $domain] Added record '$host $typemap{$type}";
|
---|
1866 | $logentry .= " [distance $dist]" if $typemap{$type} eq 'MX';
|
---|
1867 | $logentry .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$type} eq 'SRV';
|
---|
1868 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
1869 | entry => $logentry." $val', TTL $ttl");
|
---|
1870 | }
|
---|
1871 | }
|
---|
1872 |
|
---|
1873 | # once we get here, we should have suceeded.
|
---|
1874 | $dbh->commit;
|
---|
1875 | }; # end eval
|
---|
1876 |
|
---|
1877 | if ($@) {
|
---|
1878 | my $msg = $@;
|
---|
1879 | eval { $dbh->rollback; };
|
---|
1880 | $self->_log(group_id => $group, entry => "Failed adding domain $domain ($msg)")
|
---|
1881 | if $config{log_failures};
|
---|
1882 | $dbh->commit; # since we enabled transactions earlier
|
---|
1883 | return ('FAIL',$msg);
|
---|
1884 | } else {
|
---|
1885 | return ('OK',$dom_id);
|
---|
1886 | }
|
---|
1887 | } # end addDomain
|
---|
1888 |
|
---|
1889 |
|
---|
1890 | ## DNSDB::delZone()
|
---|
1891 | # Delete a forward or reverse zone.
|
---|
1892 | # Takes a database handle, zone ID, and forward/reverse flag.
|
---|
1893 | # for now, just delete the records, then the domain.
|
---|
1894 | # later we may want to archive it in some way instead (status code 2, for example?)
|
---|
1895 | sub delZone {
|
---|
1896 | my $self = shift;
|
---|
1897 | my $dbh = $self->{dbh};
|
---|
1898 | my $zoneid = shift;
|
---|
1899 | my $revrec = shift;
|
---|
1900 |
|
---|
1901 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
1902 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
1903 | local $dbh->{AutoCommit} = 0;
|
---|
1904 | local $dbh->{RaiseError} = 1;
|
---|
1905 |
|
---|
1906 | my $msg = '';
|
---|
1907 | my $failmsg = '';
|
---|
1908 | my $zone = ($revrec eq 'n' ? $self->domainName($zoneid) : $self->revName($zoneid));
|
---|
1909 |
|
---|
1910 | return ('FAIL', ($revrec eq 'n' ? 'Domain' : 'Reverse zone')." ID $zoneid doesn't exist") if !$zone;
|
---|
1911 |
|
---|
1912 | # Set this up here since we may use if if $config{log_failures} is enabled
|
---|
1913 | my %loghash;
|
---|
1914 | $loghash{domain_id} = $zoneid if $revrec eq 'n';
|
---|
1915 | $loghash{rdns_id} = $zoneid if $revrec eq 'y';
|
---|
1916 | $loghash{group_id} = $self->parentID(
|
---|
1917 | id => $zoneid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec);
|
---|
1918 |
|
---|
1919 | # Wrap all the SQL in a transaction
|
---|
1920 | eval {
|
---|
1921 | # Disentangle custom record types before removing the
|
---|
1922 | # ones that are only in the zone to be deleted
|
---|
1923 | if ($revrec eq 'n') {
|
---|
1924 | my $sth = $dbh->prepare("UPDATE records SET type=?,domain_id=0 WHERE domain_id=? AND type=?");
|
---|
1925 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
1926 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65280);
|
---|
1927 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65281);
|
---|
1928 | $sth->execute(65282, $zoneid, 65283);
|
---|
1929 | $sth->execute(65282, $zoneid, 65284);
|
---|
1930 | $failmsg = "Failure removing domain records";
|
---|
1931 | $dbh->do("DELETE FROM records WHERE domain_id=?", undef, ($zoneid));
|
---|
1932 | $failmsg = "Failure removing domain";
|
---|
1933 | $dbh->do("DELETE FROM domains WHERE domain_id=?", undef, ($zoneid));
|
---|
1934 | } else {
|
---|
1935 | my $sth = $dbh->prepare("UPDATE records SET type=?,rdns_id=0 WHERE rdns_id=? AND type=?");
|
---|
1936 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
1937 | $sth->execute($reverse_typemap{A}, $zoneid, 65280);
|
---|
1938 | $sth->execute($reverse_typemap{AAAA}, $zoneid, 65281);
|
---|
1939 | # We don't have an "A template" or "AAAA template" type, although it might be useful for symmetry.
|
---|
1940 | # $sth->execute(65286?, $zoneid, 65283);
|
---|
1941 | # $sth->execute(65286?, $zoneid, 65284);
|
---|
1942 | $failmsg = "Failure removing reverse records";
|
---|
1943 | $dbh->do("DELETE FROM records WHERE rdns_id=?", undef, ($zoneid));
|
---|
1944 | $failmsg = "Failure removing reverse zone";
|
---|
1945 | $dbh->do("DELETE FROM revzones WHERE rdns_id=?", undef, ($zoneid));
|
---|
1946 | }
|
---|
1947 |
|
---|
1948 | $msg = "Deleted ".($revrec eq 'n' ? 'domain' : 'reverse zone')." $zone";
|
---|
1949 | $loghash{entry} = $msg;
|
---|
1950 | $self->_log(%loghash);
|
---|
1951 |
|
---|
1952 | # once we get here, we should have suceeded.
|
---|
1953 | $dbh->commit;
|
---|
1954 | }; # end eval
|
---|
1955 |
|
---|
1956 | if ($@) {
|
---|
1957 | $msg = $@;
|
---|
1958 | eval { $dbh->rollback; };
|
---|
1959 | $loghash{entry} = "Error deleting $zone: $msg ($failmsg)";
|
---|
1960 | if ($config{log_failures}) {
|
---|
1961 | $self->_log(%loghash);
|
---|
1962 | $dbh->commit; # since we enabled transactions earlier
|
---|
1963 | }
|
---|
1964 | return ('FAIL', $loghash{entry});
|
---|
1965 | } else {
|
---|
1966 | return ('OK', $msg);
|
---|
1967 | }
|
---|
1968 |
|
---|
1969 | } # end delZone()
|
---|
1970 |
|
---|
1971 |
|
---|
1972 | ## DNSDB::domainName()
|
---|
1973 | # Return the domain name based on a domain ID
|
---|
1974 | # Takes a database handle and the domain ID
|
---|
1975 | # Returns the domain name or undef on failure
|
---|
1976 | sub domainName {
|
---|
1977 | $errstr = '';
|
---|
1978 | my $self = shift;
|
---|
1979 | my $dbh = $self->{dbh};
|
---|
1980 | my $domid = shift;
|
---|
1981 | my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
|
---|
1982 | $errstr = $DBI::errstr if !$domname;
|
---|
1983 | return $domname if $domname;
|
---|
1984 | } # end domainName()
|
---|
1985 |
|
---|
1986 |
|
---|
1987 | ## DNSDB::revName()
|
---|
1988 | # Return the reverse zone name based on an rDNS ID
|
---|
1989 | # Takes a database handle and the rDNS ID
|
---|
1990 | # Returns the reverse zone name or undef on failure
|
---|
1991 | sub revName {
|
---|
1992 | $errstr = '';
|
---|
1993 | my $self = shift;
|
---|
1994 | my $dbh = $self->{dbh};
|
---|
1995 | my $revid = shift;
|
---|
1996 | my ($revname) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id=?", undef, ($revid) );
|
---|
1997 | $errstr = $DBI::errstr if !$revname;
|
---|
1998 | return $revname if $revname;
|
---|
1999 | } # end revName()
|
---|
2000 |
|
---|
2001 |
|
---|
2002 | ## DNSDB::domainID()
|
---|
2003 | # Takes a database handle and domain name
|
---|
2004 | # Returns the domain ID number
|
---|
2005 | sub domainID {
|
---|
2006 | $errstr = '';
|
---|
2007 | my $self = shift;
|
---|
2008 | my $dbh = $self->{dbh};
|
---|
2009 | my $domain = shift;
|
---|
2010 | my ($domid) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
2011 | undef, ($domain) );
|
---|
2012 | if (!$domid) {
|
---|
2013 | if ($dbh->err) {
|
---|
2014 | $errstr = $DBI::errstr;
|
---|
2015 | } else {
|
---|
2016 | $errstr = "Domain $domain not present";
|
---|
2017 | }
|
---|
2018 | }
|
---|
2019 | return $domid if $domid;
|
---|
2020 | } # end domainID()
|
---|
2021 |
|
---|
2022 |
|
---|
2023 | ## DNSDB::revID()
|
---|
2024 | # Takes a database handle and reverse zone name
|
---|
2025 | # Returns the rDNS ID number
|
---|
2026 | sub revID {
|
---|
2027 | $errstr = '';
|
---|
2028 | my $self = shift;
|
---|
2029 | my $dbh = $self->{dbh};
|
---|
2030 | my $revzone = shift;
|
---|
2031 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ($revzone) );
|
---|
2032 | if (!$revid) {
|
---|
2033 | if ($dbh->err) {
|
---|
2034 | $errstr = $DBI::errstr;
|
---|
2035 | } else {
|
---|
2036 | $errstr = "Reverse zone $revzone not present";
|
---|
2037 | }
|
---|
2038 | }
|
---|
2039 | return $revid if $revid;
|
---|
2040 | } # end revID()
|
---|
2041 |
|
---|
2042 |
|
---|
2043 | ## DNSDB::addRDNS
|
---|
2044 | # Adds a reverse DNS zone
|
---|
2045 | # Takes a database handle, CIDR block, reverse DNS pattern, numeric group,
|
---|
2046 | # and boolean(ish) state (active/inactive)
|
---|
2047 | # Returns a status code and message
|
---|
2048 | sub addRDNS {
|
---|
2049 | my $self = shift;
|
---|
2050 | my $dbh = $self->{dbh};
|
---|
2051 | my $zone = NetAddr::IP->new(shift);
|
---|
2052 |
|
---|
2053 | return ('FAIL',"Zone name must be a valid CIDR netblock") unless ($zone && $zone->addr !~ /^0/);
|
---|
2054 | my $revpatt = shift; # construct a custom (A/AAAA+)? PTR template record
|
---|
2055 | my $group = shift;
|
---|
2056 | my $state = shift;
|
---|
2057 | my $defloc = shift || '';
|
---|
2058 |
|
---|
2059 | $state = 1 if $state =~ /^active$/;
|
---|
2060 | $state = 1 if $state =~ /^on$/;
|
---|
2061 | $state = 0 if $state =~ /^inactive$/;
|
---|
2062 | $state = 0 if $state =~ /^off$/;
|
---|
2063 |
|
---|
2064 | return ('FAIL',"Invalid zone status") if $state !~ /^\d+$/;
|
---|
2065 |
|
---|
2066 | # quick check to start to see if we've already got one
|
---|
2067 | my ($rdns_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ("$zone"));
|
---|
2068 |
|
---|
2069 | return ('FAIL', "Zone already exists") if $rdns_id;
|
---|
2070 |
|
---|
2071 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
2072 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
2073 | local $dbh->{AutoCommit} = 0;
|
---|
2074 | local $dbh->{RaiseError} = 1;
|
---|
2075 |
|
---|
2076 | my $warnstr = '';
|
---|
2077 | my $defttl = 3600; # 1 hour should be reasonable. And unless things have gone horribly
|
---|
2078 | # wrong, we should have a value to override this anyway.
|
---|
2079 |
|
---|
2080 | # Wrap all the SQL in a transaction
|
---|
2081 | eval {
|
---|
2082 | # insert the zone...
|
---|
2083 | $dbh->do("INSERT INTO revzones (revnet,group_id,status,default_location) VALUES (?,?,?,?)", undef,
|
---|
2084 | ($zone, $group, $state, $defloc) );
|
---|
2085 |
|
---|
2086 | # get the ID...
|
---|
2087 | ($rdns_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
2088 |
|
---|
2089 | $self->_log(rdns_id => $rdns_id, group_id => $group,
|
---|
2090 | entry => "Added ".($state ? 'active' : 'inactive')." reverse zone $zone");
|
---|
2091 |
|
---|
2092 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
2093 | my $sth = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
2094 | my $sth_in = $dbh->prepare("INSERT INTO records (rdns_id,domain_id,host,type,val,ttl,location)".
|
---|
2095 | " VALUES ($rdns_id,?,?,?,?,?,?)");
|
---|
2096 | $sth->execute($group);
|
---|
2097 | while (my ($host,$type,$val,$ttl) = $sth->fetchrow_array()) {
|
---|
2098 | # Silently skip v4/v6 mismatches. This is not an error, this is expected.
|
---|
2099 | if ($zone->{isv6}) {
|
---|
2100 | next if ($type == 65280 || $type == 65283);
|
---|
2101 | } else {
|
---|
2102 | next if ($type == 65281 || $type == 65284);
|
---|
2103 | }
|
---|
2104 |
|
---|
2105 | $host =~ s/ADMINDOMAIN/$config{domain}/g;
|
---|
2106 |
|
---|
2107 | # Check to make sure the IP stubs will fit in the zone. Under most usage failures here should be rare.
|
---|
2108 | # On failure, tack a note on to a warning string and continue without adding this record.
|
---|
2109 | # While we're at it, we substitute $zone for ZONE in the value.
|
---|
2110 | if ($val eq 'ZONE') {
|
---|
2111 | # If we've got a pattern, we skip the default record version on (A+)PTR-template types
|
---|
2112 | next if $revpatt && ($type == 65282 || $type == 65283);
|
---|
2113 | ##fixme? do we care if we have multiple whole-zone templates?
|
---|
2114 | $val = $zone->network;
|
---|
2115 | } elsif ($val =~ /ZONE/) {
|
---|
2116 | my $tmpval = $val;
|
---|
2117 | $tmpval =~ s/ZONE//;
|
---|
2118 | # Bend the rules and allow single-trailing-number PTR or PTR template records to be inserted
|
---|
2119 | # as either v4 or v6. May make this an off-by-default config flag
|
---|
2120 | # Note that the origin records that may trigger this **SHOULD** already have ZONE,\d
|
---|
2121 | if ($type == 12 || $type == 65282) {
|
---|
2122 | $tmpval =~ s/[,.]/::/ if ($tmpval =~ /^[,.]\d+$/ && $zone->{isv6});
|
---|
2123 | $tmpval =~ s/[,:]+/./ if ($tmpval =~ /^(?:,|::)\d+$/ && !$zone->{isv6});
|
---|
2124 | }
|
---|
2125 | my $addr;
|
---|
2126 | if ($self->_ipparent('n', 'y', \$tmpval, $rdns_id, \$addr)) {
|
---|
2127 | $val = $addr->addr;
|
---|
2128 | } else {
|
---|
2129 | $warnstr .= "\nDefault record '$val $typemap{$type} $host' doesn't fit in $zone, skipping";
|
---|
2130 | next;
|
---|
2131 | }
|
---|
2132 | }
|
---|
2133 |
|
---|
2134 | # Substitute $zone for ZONE in the hostname, but only for non-NS records.
|
---|
2135 | # NS records get this substitution on the value instead.
|
---|
2136 | $host = _ZONE($zone, $host) if $type != 2;
|
---|
2137 |
|
---|
2138 | # Fill in the forward domain ID if we can find it, otherwise:
|
---|
2139 | # Coerce type down to PTR or PTR template if we can't
|
---|
2140 | my $domid = 0;
|
---|
2141 | if ($type >= 65280) {
|
---|
2142 | if (!($domid = $self->_hostparent($host))) {
|
---|
2143 | $warnstr .= "\nRecord added as PTR instead of $typemap{$type}; domain not found for $host";
|
---|
2144 | $type = $reverse_typemap{PTR};
|
---|
2145 | $domid = 0; # just to be explicit.
|
---|
2146 | }
|
---|
2147 | }
|
---|
2148 |
|
---|
2149 | $sth_in->execute($domid,$host,$type,$val,$ttl,$defloc);
|
---|
2150 |
|
---|
2151 | if ($typemap{$type} eq 'SOA') {
|
---|
2152 | my @tmp1 = split /:/, $host;
|
---|
2153 | my @tmp2 = split /:/, $val;
|
---|
2154 | $self->_log(rdns_id => $rdns_id, group_id => $group,
|
---|
2155 | entry => "[new $zone] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
2156 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl");
|
---|
2157 | $defttl = $tmp2[3];
|
---|
2158 | } else {
|
---|
2159 | my $logentry = "[new $zone] Added record '$host $typemap{$type} $val', TTL $ttl";
|
---|
2160 | $logentry .= ", default location ".$self->getLoc($defloc)->{description} if $defloc;
|
---|
2161 | $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group, entry => $logentry);
|
---|
2162 | }
|
---|
2163 | }
|
---|
2164 |
|
---|
2165 | # Generate record based on provided pattern.
|
---|
2166 | if ($revpatt) {
|
---|
2167 | my $host;
|
---|
2168 | my $type = ($zone->{isv6} ? 65284 : 65283);
|
---|
2169 | my $val = $zone->network;
|
---|
2170 |
|
---|
2171 | # Substitute $zone for ZONE in the hostname.
|
---|
2172 | $host = _ZONE($zone, $revpatt);
|
---|
2173 |
|
---|
2174 | my $domid = 0;
|
---|
2175 | if (!($domid = $self->_hostparent($host))) {
|
---|
2176 | $warnstr .= "\nDefault pattern added as PTR template instead of $typemap{$type}; domain not found for $host";
|
---|
2177 | $type = 65282;
|
---|
2178 | $domid = 0; # just to be explicit.
|
---|
2179 | }
|
---|
2180 |
|
---|
2181 | $sth_in->execute($domid,$host,$type,$val,$defttl,$defloc);
|
---|
2182 | my $logentry = "[new $zone] Added record '$host $typemap{$type}";
|
---|
2183 | $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group,
|
---|
2184 | entry => $logentry." $val', TTL $defttl from pattern");
|
---|
2185 | }
|
---|
2186 |
|
---|
2187 | # If there are warnings (presumably about default records skipped for cause) log them
|
---|
2188 | $self->_log(rdns_id => $rdns_id, group_id => $group, entry => "Warning(s) adding $zone:$warnstr")
|
---|
2189 | if $warnstr;
|
---|
2190 |
|
---|
2191 | # once we get here, we should have suceeded.
|
---|
2192 | $dbh->commit;
|
---|
2193 | }; # end eval
|
---|
2194 |
|
---|
2195 | if ($@) {
|
---|
2196 | my $msg = $@;
|
---|
2197 | eval { $dbh->rollback; };
|
---|
2198 | $self->_log(group_id => $group, entry => "Failed adding reverse zone $zone ($msg)")
|
---|
2199 | if $config{log_failures};
|
---|
2200 | $dbh->commit; # since we enabled transactions earlier
|
---|
2201 | return ('FAIL',$msg);
|
---|
2202 | } else {
|
---|
2203 | my $retcode = 'OK';
|
---|
2204 | if ($warnstr) {
|
---|
2205 | $resultstr = $warnstr;
|
---|
2206 | $retcode = 'WARN';
|
---|
2207 | }
|
---|
2208 | return ($retcode, $rdns_id);
|
---|
2209 | }
|
---|
2210 |
|
---|
2211 | } # end addRDNS()
|
---|
2212 |
|
---|
2213 |
|
---|
2214 | ## DNSDB::getZoneCount
|
---|
2215 | # Get count of zones in group or groups
|
---|
2216 | # Takes a database handle and hash containing:
|
---|
2217 | # - the "current" group
|
---|
2218 | # - an array of "acceptable" groups
|
---|
2219 | # - a flag for forward/reverse zones
|
---|
2220 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
2221 | # Returns an integer count of the resulting zone list.
|
---|
2222 | sub getZoneCount {
|
---|
2223 | my $self = shift;
|
---|
2224 | my $dbh = $self->{dbh};
|
---|
2225 |
|
---|
2226 | my %args = @_;
|
---|
2227 |
|
---|
2228 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
2229 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
2230 | $errstr = "Bad or missing curgroup argument";
|
---|
2231 | return;
|
---|
2232 | }
|
---|
2233 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
2234 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
2235 | $errstr = "Bad childlist argument";
|
---|
2236 | return;
|
---|
2237 | }
|
---|
2238 |
|
---|
2239 | my @filterargs;
|
---|
2240 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
2241 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
2242 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
2243 | push @filterargs, $args{filter} if $args{filter};
|
---|
2244 |
|
---|
2245 | my $sql;
|
---|
2246 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
2247 | if ($args{revrec} eq 'n') {
|
---|
2248 | $sql = "SELECT count(*) FROM domains".
|
---|
2249 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
2250 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
2251 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
2252 | } else {
|
---|
2253 | $sql = "SELECT count(*) FROM revzones".
|
---|
2254 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
2255 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
|
---|
2256 | ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
2257 | }
|
---|
2258 | my ($count) = $dbh->selectrow_array($sql, undef, @filterargs);
|
---|
2259 | return $count;
|
---|
2260 | } # end getZoneCount()
|
---|
2261 |
|
---|
2262 |
|
---|
2263 | ## DNSDB::getZoneList()
|
---|
2264 | # Get a list of zones in the specified group(s)
|
---|
2265 | # Takes the same arguments as getZoneCount() above
|
---|
2266 | # Returns a reference to an array of hashrefs suitable for feeding to HTML::Template
|
---|
2267 | sub getZoneList {
|
---|
2268 | my $self = shift;
|
---|
2269 | my $dbh = $self->{dbh};
|
---|
2270 |
|
---|
2271 | my %args = @_;
|
---|
2272 |
|
---|
2273 | my @zonelist;
|
---|
2274 |
|
---|
2275 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
2276 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
2277 |
|
---|
2278 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
2279 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
2280 | $errstr = "Bad or missing curgroup argument";
|
---|
2281 | return;
|
---|
2282 | }
|
---|
2283 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
2284 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
2285 | $errstr = "Bad childlist argument";
|
---|
2286 | return;
|
---|
2287 | }
|
---|
2288 |
|
---|
2289 | my @filterargs;
|
---|
2290 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
2291 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
2292 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
2293 | push @filterargs, $args{filter} if $args{filter};
|
---|
2294 |
|
---|
2295 | my $sql;
|
---|
2296 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
2297 | if ($args{revrec} eq 'n') {
|
---|
2298 | $args{sortby} = 'domain' if !$args{sortby} || !grep /^$args{sortby}$/, ('domain','group','status');
|
---|
2299 | $sql = "SELECT domain_id,domain,status,groups.group_name AS group FROM domains".
|
---|
2300 | " INNER JOIN groups ON domains.group_id=groups.group_id".
|
---|
2301 | " WHERE domains.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
2302 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
2303 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
2304 | } else {
|
---|
2305 | ##fixme: arguably startwith here is irrelevant. depends on the UI though.
|
---|
2306 | $args{sortby} = 'revnet' if !$args{sortby} || !grep /^$args{sortby}$/, ('revnet','group','status');
|
---|
2307 | $sql = "SELECT rdns_id,revnet,status,groups.group_name AS group FROM revzones".
|
---|
2308 | " INNER JOIN groups ON revzones.group_id=groups.group_id".
|
---|
2309 | " WHERE revzones.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
2310 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
|
---|
2311 | ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
2312 | }
|
---|
2313 | # A common tail.
|
---|
2314 | $sql .= " ORDER BY ".($args{sortby} eq 'group' ? 'groups.group_name' : $args{sortby})." $args{sortorder} ".
|
---|
2315 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage}".
|
---|
2316 | " OFFSET ".$args{offset}*$config{perpage});
|
---|
2317 | my $sth = $dbh->prepare($sql);
|
---|
2318 | $sth->execute(@filterargs);
|
---|
2319 | my $rownum = 0;
|
---|
2320 |
|
---|
2321 | while (my @data = $sth->fetchrow_array) {
|
---|
2322 | my %row;
|
---|
2323 | $row{domain_id} = $data[0];
|
---|
2324 | $row{domain} = $data[1];
|
---|
2325 | $row{status} = $data[2];
|
---|
2326 | $row{group} = $data[3];
|
---|
2327 | push @zonelist, \%row;
|
---|
2328 | }
|
---|
2329 |
|
---|
2330 | return \@zonelist;
|
---|
2331 | } # end getZoneList()
|
---|
2332 |
|
---|
2333 |
|
---|
2334 | ## DNSDB::getZoneLocation()
|
---|
2335 | # Retrieve the default location for a zone.
|
---|
2336 | # Takes a database handle, forward/reverse flag, and zone ID
|
---|
2337 | sub getZoneLocation {
|
---|
2338 | my $self = shift;
|
---|
2339 | my $dbh = $self->{dbh};
|
---|
2340 | my $revrec = shift;
|
---|
2341 | my $zoneid = shift;
|
---|
2342 |
|
---|
2343 | my ($loc) = $dbh->selectrow_array("SELECT default_location FROM ".
|
---|
2344 | ($revrec eq 'n' ? 'domains WHERE domain_id = ?' : 'revzones WHERE rdns_id = ?'),
|
---|
2345 | undef, ($zoneid));
|
---|
2346 | return $loc;
|
---|
2347 | } # end getZoneLocation()
|
---|
2348 |
|
---|
2349 |
|
---|
2350 | ## DNSDB::addGroup()
|
---|
2351 | # Add a group
|
---|
2352 | # Takes a database handle, group name, parent group, hashref for permissions,
|
---|
2353 | # and optional template-vs-cloneme flag for the default records
|
---|
2354 | # Returns a status code and message
|
---|
2355 | sub addGroup {
|
---|
2356 | $errstr = '';
|
---|
2357 | my $self = shift;
|
---|
2358 | my $dbh = $self->{dbh};
|
---|
2359 | my $groupname = shift;
|
---|
2360 | my $pargroup = shift;
|
---|
2361 | my $permissions = shift;
|
---|
2362 |
|
---|
2363 | # 0 indicates "custom", hardcoded.
|
---|
2364 | # Any other value clones that group's default records, if it exists.
|
---|
2365 | my $inherit = shift || 0;
|
---|
2366 | ##fixme: need a flag to indicate clone records or <?> ?
|
---|
2367 |
|
---|
2368 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
2369 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
2370 | local $dbh->{AutoCommit} = 0;
|
---|
2371 | local $dbh->{RaiseError} = 1;
|
---|
2372 |
|
---|
2373 | my ($group_id) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($groupname));
|
---|
2374 |
|
---|
2375 | return ('FAIL', "Group already exists") if $group_id;
|
---|
2376 |
|
---|
2377 | # Wrap all the SQL in a transaction
|
---|
2378 | eval {
|
---|
2379 | $dbh->do("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)", undef, ($pargroup, $groupname) );
|
---|
2380 |
|
---|
2381 | my ($groupid) = $dbh->selectrow_array("SELECT currval('groups_group_id_seq')");
|
---|
2382 |
|
---|
2383 | # We work through the whole set of permissions instead of specifying them so
|
---|
2384 | # that when we add a new permission, we don't have to change the code anywhere
|
---|
2385 | # that doesn't explicitly deal with that specific permission.
|
---|
2386 | my @permvals;
|
---|
2387 | foreach (@permtypes) {
|
---|
2388 | if (!defined ($permissions->{$_})) {
|
---|
2389 | push @permvals, 0;
|
---|
2390 | } else {
|
---|
2391 | push @permvals, $permissions->{$_};
|
---|
2392 | }
|
---|
2393 | }
|
---|
2394 | $dbh->do("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")",
|
---|
2395 | undef, ($groupid, @permvals) );
|
---|
2396 | my ($permid) = $dbh->selectrow_array("SELECT currval('permissions_permission_id_seq')");
|
---|
2397 | $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
|
---|
2398 |
|
---|
2399 | # Default records
|
---|
2400 | my $sthf = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
|
---|
2401 | "VALUES ($groupid,?,?,?,?,?,?,?)");
|
---|
2402 | my $sthr = $dbh->prepare("INSERT INTO default_rev_records (group_id,host,type,val,ttl) ".
|
---|
2403 | "VALUES ($groupid,?,?,?,?)");
|
---|
2404 | if ($inherit) {
|
---|
2405 | # Duplicate records from parent. Actually relying on inherited records feels
|
---|
2406 | # very fragile, and it would be problematic to roll over at a later time.
|
---|
2407 | my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
2408 | $sth2->execute($pargroup);
|
---|
2409 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
2410 | $sthf->execute(@clonedata);
|
---|
2411 | }
|
---|
2412 | # And now the reverse records
|
---|
2413 | $sth2 = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
2414 | $sth2->execute($pargroup);
|
---|
2415 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
2416 | $sthr->execute(@clonedata);
|
---|
2417 | }
|
---|
2418 | } else {
|
---|
2419 | ##fixme: Hardcoding is Bad, mmmmkaaaay?
|
---|
2420 | # reasonable basic defaults for SOA, MX, NS, and minimal hosting
|
---|
2421 | # could load from a config file, but somewhere along the line we need hardcoded bits.
|
---|
2422 | $sthf->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
|
---|
2423 | $sthf->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
|
---|
2424 | $sthf->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
|
---|
2425 | $sthf->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
|
---|
2426 | $sthf->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
|
---|
2427 | $sthf->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
|
---|
2428 | # reasonable basic defaults for generic reverse zone. Same as initial SQL tabledef.
|
---|
2429 | $sthr->execute('hostmaster.ADMINDOMAIN:ns1.ADMINDOMAIN', 6, '10800:3600:604800:10800', 86400);
|
---|
2430 | $sthr->execute('unused-%r.ADMINDOMAIN', 65283, 'ZONE', 3600);
|
---|
2431 | }
|
---|
2432 |
|
---|
2433 | $self->_log(group_id => $pargroup, entry => "Added group $groupname");
|
---|
2434 |
|
---|
2435 | # once we get here, we should have suceeded.
|
---|
2436 | $dbh->commit;
|
---|
2437 | }; # end eval
|
---|
2438 |
|
---|
2439 | if ($@) {
|
---|
2440 | my $msg = $@;
|
---|
2441 | eval { $dbh->rollback; };
|
---|
2442 | if ($config{log_failures}) {
|
---|
2443 | $self->_log(group_id => $pargroup, entry => "Failed to add group $groupname: $msg");
|
---|
2444 | $dbh->commit;
|
---|
2445 | }
|
---|
2446 | return ('FAIL',$msg);
|
---|
2447 | }
|
---|
2448 |
|
---|
2449 | return ('OK','OK');
|
---|
2450 | } # end addGroup()
|
---|
2451 |
|
---|
2452 |
|
---|
2453 | ## DNSDB::delGroup()
|
---|
2454 | # Delete a group.
|
---|
2455 | # Takes a group ID
|
---|
2456 | # Returns a status code and message
|
---|
2457 | sub delGroup {
|
---|
2458 | my $self = shift;
|
---|
2459 | my $dbh = $self->{dbh};
|
---|
2460 | my $groupid = shift;
|
---|
2461 |
|
---|
2462 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
2463 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
2464 | local $dbh->{AutoCommit} = 0;
|
---|
2465 | local $dbh->{RaiseError} = 1;
|
---|
2466 |
|
---|
2467 | ##fixme: locate "knowable" error conditions and deal with them before the eval
|
---|
2468 | # ... or inside, whatever.
|
---|
2469 | # -> domains still exist in group
|
---|
2470 | # -> ...
|
---|
2471 | my $failmsg = '';
|
---|
2472 | my $resultmsg = '';
|
---|
2473 |
|
---|
2474 | # collect some pieces for logging and error messages
|
---|
2475 | my $groupname = $self->groupName($groupid);
|
---|
2476 | my $parid = $self->parentID(id => $groupid, type => 'group');
|
---|
2477 |
|
---|
2478 | # Wrap all the SQL in a transaction
|
---|
2479 | eval {
|
---|
2480 | # Check for Things in the group
|
---|
2481 | $failmsg = "Can't remove group $groupname";
|
---|
2482 | my ($grpcnt) = $dbh->selectrow_array("SELECT count(*) FROM groups WHERE parent_group_id=?", undef, ($groupid));
|
---|
2483 | die "$grpcnt groups still in group\n" if $grpcnt;
|
---|
2484 | my ($domcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($groupid));
|
---|
2485 | die "$domcnt domains still in group\n" if $domcnt;
|
---|
2486 | my ($revcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($groupid));
|
---|
2487 | die "$revcnt reverse zones still in group\n" if $revcnt;
|
---|
2488 | my ($usercnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($groupid));
|
---|
2489 | die "$usercnt users still in group\n" if $usercnt;
|
---|
2490 |
|
---|
2491 | $failmsg = "Failed to delete default records for $groupname";
|
---|
2492 | $dbh->do("DELETE from default_records WHERE group_id=?", undef, ($groupid));
|
---|
2493 | $failmsg = "Failed to delete default reverse records for $groupname";
|
---|
2494 | $dbh->do("DELETE from default_rev_records WHERE group_id=?", undef, ($groupid));
|
---|
2495 | $failmsg = "Failed to remove group $groupname";
|
---|
2496 | $dbh->do("DELETE from groups WHERE group_id=?", undef, ($groupid));
|
---|
2497 |
|
---|
2498 | $self->_log(group_id => $parid, entry => "Deleted group $groupname");
|
---|
2499 | $resultmsg = "Deleted group $groupname";
|
---|
2500 |
|
---|
2501 | # once we get here, we should have suceeded.
|
---|
2502 | $dbh->commit;
|
---|
2503 | }; # end eval
|
---|
2504 |
|
---|
2505 | if ($@) {
|
---|
2506 | my $msg = $@;
|
---|
2507 | eval { $dbh->rollback; };
|
---|
2508 | if ($config{log_failures}) {
|
---|
2509 | $self->_log(group_id => $parid, entry => "$failmsg: $msg");
|
---|
2510 | $dbh->commit; # since we enabled transactions earlier
|
---|
2511 | }
|
---|
2512 | return ('FAIL',"$failmsg: $msg");
|
---|
2513 | }
|
---|
2514 |
|
---|
2515 | return ('OK',$resultmsg);
|
---|
2516 | } # end delGroup()
|
---|
2517 |
|
---|
2518 |
|
---|
2519 | ## DNSDB::getChildren()
|
---|
2520 | # Get a list of all groups whose parent^n is group <n>
|
---|
2521 | # Takes a database handle, group ID, reference to an array to put the group IDs in,
|
---|
2522 | # and an optional flag to return only immediate children or all children-of-children
|
---|
2523 | # default to returning all children
|
---|
2524 | # Calls itself
|
---|
2525 | sub getChildren {
|
---|
2526 | $errstr = '';
|
---|
2527 | my $self = shift;
|
---|
2528 | my $dbh = $self->{dbh};
|
---|
2529 | my $rootgroup = shift;
|
---|
2530 | my $groupdest = shift;
|
---|
2531 | my $immed = shift || 'all';
|
---|
2532 |
|
---|
2533 | # special break for default group; otherwise we get stuck.
|
---|
2534 | if ($rootgroup == 1) {
|
---|
2535 | # by definition, group 1 is the Root Of All Groups
|
---|
2536 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
|
---|
2537 | ($immed ne 'all' ? " AND parent_group_id=1" : '')." ORDER BY group_name");
|
---|
2538 | $sth->execute;
|
---|
2539 | while (my @this = $sth->fetchrow_array) {
|
---|
2540 | push @$groupdest, @this;
|
---|
2541 | }
|
---|
2542 | } else {
|
---|
2543 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=? ORDER BY group_name");
|
---|
2544 | $sth->execute($rootgroup);
|
---|
2545 | return if $sth->rows == 0;
|
---|
2546 | my @grouplist;
|
---|
2547 | while (my ($group) = $sth->fetchrow_array) {
|
---|
2548 | push @$groupdest, $group;
|
---|
2549 | $self->getChildren($group, $groupdest) if $immed eq 'all';
|
---|
2550 | }
|
---|
2551 | }
|
---|
2552 | } # end getChildren()
|
---|
2553 |
|
---|
2554 |
|
---|
2555 | ## DNSDB::groupName()
|
---|
2556 | # Return the group name based on a group ID
|
---|
2557 | # Takes a database handle and the group ID
|
---|
2558 | # Returns the group name or undef on failure
|
---|
2559 | sub groupName {
|
---|
2560 | $errstr = '';
|
---|
2561 | my $self = shift;
|
---|
2562 | my $dbh = $self->{dbh};
|
---|
2563 | my $groupid = shift;
|
---|
2564 | my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
|
---|
2565 | $sth->execute($groupid);
|
---|
2566 | my ($groupname) = $sth->fetchrow_array();
|
---|
2567 | $errstr = $DBI::errstr if !$groupname;
|
---|
2568 | return $groupname if $groupname;
|
---|
2569 | } # end groupName
|
---|
2570 |
|
---|
2571 |
|
---|
2572 | ## DNSDB::getGroupCount()
|
---|
2573 | # Get count of subgroups in group or groups
|
---|
2574 | # Takes a database handle and hash containing:
|
---|
2575 | # - the "current" group
|
---|
2576 | # - an array of "acceptable" groups
|
---|
2577 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
2578 | # Returns an integer count of the resulting group list.
|
---|
2579 | sub getGroupCount {
|
---|
2580 | my $self = shift;
|
---|
2581 | my $dbh = $self->{dbh};
|
---|
2582 |
|
---|
2583 | my %args = @_;
|
---|
2584 |
|
---|
2585 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
2586 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
2587 | $errstr = "Bad or missing curgroup argument";
|
---|
2588 | return;
|
---|
2589 | }
|
---|
2590 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
2591 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
2592 | $errstr = "Bad childlist argument";
|
---|
2593 | return;
|
---|
2594 | }
|
---|
2595 |
|
---|
2596 | my @filterargs;
|
---|
2597 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
2598 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
2599 | push @filterargs, $args{filter} if $args{filter};
|
---|
2600 |
|
---|
2601 | my $sql = "SELECT count(*) FROM groups ".
|
---|
2602 | "WHERE parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
2603 | ($args{startwith} ? " AND group_name ~* ?" : '').
|
---|
2604 | ($args{filter} ? " AND group_name ~* ?" : '');
|
---|
2605 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
2606 | $errstr = $dbh->errstr if !$count;
|
---|
2607 | return $count;
|
---|
2608 | } # end getGroupCount
|
---|
2609 |
|
---|
2610 |
|
---|
2611 | ## DNSDB::getGroupList()
|
---|
2612 | # Get a list of sub^n-groups in the specified group(s)
|
---|
2613 | # Takes the same arguments as getGroupCount() above
|
---|
2614 | # Returns an arrayref containing hashrefs suitable for feeding straight to HTML::Template
|
---|
2615 | sub getGroupList {
|
---|
2616 | my $self = shift;
|
---|
2617 | my $dbh = $self->{dbh};
|
---|
2618 |
|
---|
2619 | my %args = @_;
|
---|
2620 |
|
---|
2621 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
2622 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
2623 | $errstr = "Bad or missing curgroup argument";
|
---|
2624 | return;
|
---|
2625 | }
|
---|
2626 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
2627 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
2628 | $errstr = "Bad childlist argument";
|
---|
2629 | return;
|
---|
2630 | }
|
---|
2631 |
|
---|
2632 | my @filterargs;
|
---|
2633 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
2634 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
2635 | push @filterargs, $args{filter} if $args{filter};
|
---|
2636 |
|
---|
2637 | # protection against bad or missing arguments
|
---|
2638 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
2639 | $args{sortby} = 'group' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
2640 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
2641 |
|
---|
2642 | # munge sortby for columns in database
|
---|
2643 | $args{sortby} = 'g.group_name' if $args{sortby} eq 'group';
|
---|
2644 | $args{sortby} = 'g2.group_name' if $args{sortby} eq 'parent';
|
---|
2645 |
|
---|
2646 | my $sql = q(SELECT g.group_id AS groupid, g.group_name AS groupname, g2.group_name AS pgroup
|
---|
2647 | FROM groups g
|
---|
2648 | INNER JOIN groups g2 ON g2.group_id=g.parent_group_id
|
---|
2649 | ).
|
---|
2650 | " WHERE g.parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
2651 | ($args{startwith} ? " AND g.group_name ~* ?" : '').
|
---|
2652 | ($args{filter} ? " AND g.group_name ~* ?" : '').
|
---|
2653 | " GROUP BY g.group_id, g.group_name, g2.group_name ".
|
---|
2654 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
2655 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
2656 | my $glist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
2657 | $errstr = $dbh->errstr if !$glist;
|
---|
2658 |
|
---|
2659 | # LEFT JOINs make the result set balloon beyond sanity just to include counts;
|
---|
2660 | # this means there's lots of crunching needed to trim the result set back down.
|
---|
2661 | # So instead we track the order of the groups, and push the counts into the
|
---|
2662 | # arrayref result separately.
|
---|
2663 | ##fixme: put this whole sub in a transaction? might be
|
---|
2664 | # needed for accurate results on very busy systems.
|
---|
2665 | ##fixme: large group lists need prepared statements?
|
---|
2666 | #my $ucsth = $dbh->prepare("SELECT count(*) FROM users WHERE group_id=?");
|
---|
2667 | #my $dcsth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
|
---|
2668 | #my $rcsth = $dbh->prepare("SELECT count(*) FROM revzones WHERE group_id=?");
|
---|
2669 | foreach (@{$glist}) {
|
---|
2670 | my ($ucnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($$_{groupid}));
|
---|
2671 | $$_{nusers} = $ucnt;
|
---|
2672 | my ($dcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($$_{groupid}));
|
---|
2673 | $$_{ndomains} = $dcnt;
|
---|
2674 | my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($$_{groupid}));
|
---|
2675 | $$_{nrevzones} = $rcnt;
|
---|
2676 | }
|
---|
2677 |
|
---|
2678 | return $glist;
|
---|
2679 | } # end getGroupList
|
---|
2680 |
|
---|
2681 |
|
---|
2682 | ## DNSDB::groupID()
|
---|
2683 | # Return the group ID based on the group name
|
---|
2684 | # Takes a database handle and the group name
|
---|
2685 | # Returns the group ID or undef on failure
|
---|
2686 | sub groupID {
|
---|
2687 | $errstr = '';
|
---|
2688 | my $self = shift;
|
---|
2689 | my $dbh = $self->{dbh};
|
---|
2690 | my $group = shift;
|
---|
2691 | my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($group) );
|
---|
2692 | $errstr = $DBI::errstr if !$grpid;
|
---|
2693 | return $grpid if $grpid;
|
---|
2694 | } # end groupID()
|
---|
2695 |
|
---|
2696 |
|
---|
2697 | ## DNSDB::addUser()
|
---|
2698 | # Add a user.
|
---|
2699 | # Takes a DB handle, username, group ID, password, state (active/inactive).
|
---|
2700 | # Optionally accepts:
|
---|
2701 | # user type (user/admin) - defaults to user
|
---|
2702 | # permissions string - defaults to inherit from group
|
---|
2703 | # three valid forms:
|
---|
2704 | # i - Inherit permissions
|
---|
2705 | # c:<user_id> - Clone permissions from <user_id>
|
---|
2706 | # C:<permission list> - Set these specific permissions
|
---|
2707 | # first name - defaults to username
|
---|
2708 | # last name - defaults to blank
|
---|
2709 | # phone - defaults to blank (could put other data within column def)
|
---|
2710 | # Returns (OK,<uid>) on success, (FAIL,<message>) on failure
|
---|
2711 | sub addUser {
|
---|
2712 | $errstr = '';
|
---|
2713 | my $self = shift;
|
---|
2714 | my $dbh = $self->{dbh};
|
---|
2715 | my $username = shift;
|
---|
2716 | my $group = shift;
|
---|
2717 | my $pass = shift;
|
---|
2718 | my $state = shift;
|
---|
2719 |
|
---|
2720 | return ('FAIL', "Missing one or more required entries") if !defined($state);
|
---|
2721 | return ('FAIL', "Username must not be blank") if !$username;
|
---|
2722 |
|
---|
2723 | # Munge in some alternate state values
|
---|
2724 | $state = 1 if $state =~ /^active$/;
|
---|
2725 | $state = 1 if $state =~ /^on$/;
|
---|
2726 | $state = 0 if $state =~ /^inactive$/;
|
---|
2727 | $state = 0 if $state =~ /^off$/;
|
---|
2728 |
|
---|
2729 | my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
|
---|
2730 |
|
---|
2731 | my $permstring = shift || 'i'; # default is to inhert permissions from group
|
---|
2732 |
|
---|
2733 | my $fname = shift || $username;
|
---|
2734 | my $lname = shift || '';
|
---|
2735 | my $phone = shift || ''; # not going format-check
|
---|
2736 |
|
---|
2737 | my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
|
---|
2738 | my $user_id;
|
---|
2739 |
|
---|
2740 | # quick check to start to see if we've already got one
|
---|
2741 | $sth->execute($username);
|
---|
2742 | ($user_id) = $sth->fetchrow_array;
|
---|
2743 |
|
---|
2744 | return ('FAIL', "User already exists") if $user_id;
|
---|
2745 |
|
---|
2746 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
2747 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
2748 | local $dbh->{AutoCommit} = 0;
|
---|
2749 | local $dbh->{RaiseError} = 1;
|
---|
2750 |
|
---|
2751 | # Wrap all the SQL in a transaction
|
---|
2752 | eval {
|
---|
2753 | # insert the user... note we set inherited perms by default since
|
---|
2754 | # it's simple and cleans up some other bits of state
|
---|
2755 | my $sth = $dbh->prepare("INSERT INTO users ".
|
---|
2756 | "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
|
---|
2757 | "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
|
---|
2758 | $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);
|
---|
2759 |
|
---|
2760 | # get the ID...
|
---|
2761 | ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");
|
---|
2762 |
|
---|
2763 | # Permissions! Gotta set'em all!
|
---|
2764 | die "Invalid permission string $permstring\n"
|
---|
2765 | if $permstring !~ /^(?:
|
---|
2766 | i # inherit
|
---|
2767 | |c:\d+ # clone
|
---|
2768 | # custom. no, the leading , is not a typo
|
---|
2769 | |C:(?:,(?:group|user|domain|record|location|self)_(?:edit|create|delete|locchg|view))*
|
---|
2770 | )$/x;
|
---|
2771 | # bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
|
---|
2772 | if ($permstring ne 'i') {
|
---|
2773 | # for cloned or custom permissions, we have to create a new permissions entry.
|
---|
2774 | my $clonesrc = $group;
|
---|
2775 | if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
|
---|
2776 | $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
|
---|
2777 | "SELECT $permlist,? FROM permissions WHERE permission_id=".
|
---|
2778 | "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
|
---|
2779 | undef, ($user_id,$clonesrc) );
|
---|
2780 | $dbh->do("UPDATE users SET permission_id=".
|
---|
2781 | "(SELECT permission_id FROM permissions WHERE user_id=?) ".
|
---|
2782 | "WHERE user_id=?", undef, ($user_id, $user_id) );
|
---|
2783 | }
|
---|
2784 | if ($permstring =~ /^C:/) {
|
---|
2785 | # finally for custom permissions, we set the passed-in permissions (and unset
|
---|
2786 | # any that might have been brought in by the clone operation above)
|
---|
2787 | my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
|
---|
2788 | undef, ($user_id) );
|
---|
2789 | foreach (@permtypes) {
|
---|
2790 | if ($permstring =~ /,$_/) {
|
---|
2791 | $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
|
---|
2792 | } else {
|
---|
2793 | $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
|
---|
2794 | }
|
---|
2795 | }
|
---|
2796 | }
|
---|
2797 |
|
---|
2798 | $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
|
---|
2799 |
|
---|
2800 | ##fixme: add another table to hold name/email for log table?
|
---|
2801 |
|
---|
2802 | $self->_log(group_id => $group, entry => "Added user $username ($fname $lname)");
|
---|
2803 | # once we get here, we should have suceeded.
|
---|
2804 | $dbh->commit;
|
---|
2805 | }; # end eval
|
---|
2806 |
|
---|
2807 | if ($@) {
|
---|
2808 | my $msg = $@;
|
---|
2809 | eval { $dbh->rollback; };
|
---|
2810 | if ($config{log_failures}) {
|
---|
2811 | $self->_log(group_id => $group, entry => "Error adding user $username: $msg");
|
---|
2812 | $dbh->commit; # since we enabled transactions earlier
|
---|
2813 | }
|
---|
2814 | return ('FAIL',"Error adding user $username: $msg");
|
---|
2815 | }
|
---|
2816 |
|
---|
2817 | return ('OK',"User $username ($fname $lname) added");
|
---|
2818 | } # end addUser
|
---|
2819 |
|
---|
2820 |
|
---|
2821 | ## DNSDB::getUserCount()
|
---|
2822 | # Get count of users in group
|
---|
2823 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
2824 | # - a reference list of secondary groups
|
---|
2825 | # - a filter string
|
---|
2826 | # - a "Starts with" string
|
---|
2827 | sub getUserCount {
|
---|
2828 | my $self = shift;
|
---|
2829 | my $dbh = $self->{dbh};
|
---|
2830 |
|
---|
2831 | my %args = @_;
|
---|
2832 |
|
---|
2833 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
2834 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
2835 | $errstr = "Bad or missing curgroup argument";
|
---|
2836 | return;
|
---|
2837 | }
|
---|
2838 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
2839 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
2840 | $errstr = "Bad childlist argument";
|
---|
2841 | return;
|
---|
2842 | }
|
---|
2843 |
|
---|
2844 | my @filterargs;
|
---|
2845 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
2846 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
2847 | push @filterargs, $args{filter} if $args{filter};
|
---|
2848 |
|
---|
2849 | my $sql = "SELECT count(*) FROM users ".
|
---|
2850 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
2851 | ($args{startwith} ? " AND username ~* ?" : '').
|
---|
2852 | ($args{filter} ? " AND username ~* ?" : '');
|
---|
2853 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
2854 | $errstr = $dbh->errstr if !$count;
|
---|
2855 | return $count;
|
---|
2856 | } # end getUserCount()
|
---|
2857 |
|
---|
2858 |
|
---|
2859 | ## DNSDB::getUserList()
|
---|
2860 | # Get list of users
|
---|
2861 | # Takes the same arguments as getUserCount() above, plus optional:
|
---|
2862 | # - sort field
|
---|
2863 | # - sort order
|
---|
2864 | # - offset/return-all-everything flag (defaults to $perpage records)
|
---|
2865 | sub getUserList {
|
---|
2866 | my $self = shift;
|
---|
2867 | my $dbh = $self->{dbh};
|
---|
2868 |
|
---|
2869 | my %args = @_;
|
---|
2870 |
|
---|
2871 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
2872 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
2873 | $errstr = "Bad or missing curgroup argument";
|
---|
2874 | return;
|
---|
2875 | }
|
---|
2876 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
2877 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
2878 | $errstr = "Bad childlist argument";
|
---|
2879 | return;
|
---|
2880 | }
|
---|
2881 |
|
---|
2882 | my @filterargs;
|
---|
2883 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
2884 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
2885 | push @filterargs, $args{filter} if $args{filter};
|
---|
2886 |
|
---|
2887 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
2888 | my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
2889 | fname => 'fname');
|
---|
2890 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
2891 |
|
---|
2892 | # protection against bad or missing arguments
|
---|
2893 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
2894 | $args{sortby} = 'u.username' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
2895 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
2896 |
|
---|
2897 | my $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ".
|
---|
2898 | "FROM users u ".
|
---|
2899 | "INNER JOIN groups g ON u.group_id=g.group_id ".
|
---|
2900 | "WHERE u.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
2901 | ($args{startwith} ? " AND u.username ~* ?" : '').
|
---|
2902 | ($args{filter} ? " AND u.username ~* ?" : '').
|
---|
2903 | " AND NOT u.type = 'R' ".
|
---|
2904 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
2905 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
2906 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
2907 | $errstr = $dbh->errstr if !$ulist;
|
---|
2908 | return $ulist;
|
---|
2909 | } # end getUserList()
|
---|
2910 |
|
---|
2911 |
|
---|
2912 | ## DNSDB::getUserDropdown()
|
---|
2913 | # Get a list of usernames for use in a dropdown menu.
|
---|
2914 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
2915 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
2916 | sub getUserDropdown {
|
---|
2917 | my $self = shift;
|
---|
2918 | my $dbh = $self->{dbh};
|
---|
2919 | my $grp = shift;
|
---|
2920 | my $sel = shift || 0;
|
---|
2921 |
|
---|
2922 | my $sth = $dbh->prepare("SELECT username,user_id FROM users WHERE group_id=?");
|
---|
2923 | $sth->execute($grp);
|
---|
2924 |
|
---|
2925 | my @userlist;
|
---|
2926 | while (my ($username,$uid) = $sth->fetchrow_array) {
|
---|
2927 | my %row = (
|
---|
2928 | username => $username,
|
---|
2929 | uid => $uid,
|
---|
2930 | selected => ($sel == $uid ? 1 : 0)
|
---|
2931 | );
|
---|
2932 | push @userlist, \%row;
|
---|
2933 | }
|
---|
2934 | return \@userlist;
|
---|
2935 | } # end getUserDropdown()
|
---|
2936 |
|
---|
2937 |
|
---|
2938 | ## DNSDB:: updateUser()
|
---|
2939 | # Update general data about user
|
---|
2940 | sub updateUser {
|
---|
2941 | my $self = shift;
|
---|
2942 | my $dbh = $self->{dbh};
|
---|
2943 |
|
---|
2944 | ##fixme: tweak calling convention so that we can update any given bit of data
|
---|
2945 | my $uid = shift;
|
---|
2946 | my $username = shift;
|
---|
2947 | my $group = shift;
|
---|
2948 | my $pass = shift;
|
---|
2949 | my $state = shift;
|
---|
2950 | my $type = shift || 'u';
|
---|
2951 | my $fname = shift || $username;
|
---|
2952 | my $lname = shift || '';
|
---|
2953 | my $phone = shift || ''; # not going format-check
|
---|
2954 |
|
---|
2955 | my $resultmsg = '';
|
---|
2956 |
|
---|
2957 | # Munge in some alternate state values
|
---|
2958 | $state = 1 if $state =~ /^active$/;
|
---|
2959 | $state = 1 if $state =~ /^on$/;
|
---|
2960 | $state = 0 if $state =~ /^inactive$/;
|
---|
2961 | $state = 0 if $state =~ /^off$/;
|
---|
2962 |
|
---|
2963 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
2964 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
2965 | local $dbh->{AutoCommit} = 0;
|
---|
2966 | local $dbh->{RaiseError} = 1;
|
---|
2967 |
|
---|
2968 | my $sth;
|
---|
2969 |
|
---|
2970 | # Password can be left blank; if so we assume there's one on file.
|
---|
2971 | # Actual blank passwords are bad, mm'kay?
|
---|
2972 | if (!$pass) {
|
---|
2973 | ($pass) = $dbh->selectrow_array("SELECT password FROM users WHERE user_id=?", undef, ($uid));
|
---|
2974 | } else {
|
---|
2975 | $pass = unix_md5_crypt($pass);
|
---|
2976 | }
|
---|
2977 |
|
---|
2978 | eval {
|
---|
2979 | $dbh->do("UPDATE users SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?".
|
---|
2980 | " WHERE user_id=?", undef, ($username, $pass, $fname, $lname, $phone, $type, $state, $uid));
|
---|
2981 | $resultmsg = "Updated user info for $username ($fname $lname)";
|
---|
2982 | $self->_log(group_id => $group, entry => $resultmsg);
|
---|
2983 | $dbh->commit;
|
---|
2984 | };
|
---|
2985 | if ($@) {
|
---|
2986 | my $msg = $@;
|
---|
2987 | eval { $dbh->rollback; };
|
---|
2988 | if ($config{log_failures}) {
|
---|
2989 | $self->_log(group_id => $group, entry => "Error updating user $username: $msg");
|
---|
2990 | $dbh->commit; # since we enabled transactions earlier
|
---|
2991 | }
|
---|
2992 | return ('FAIL',"Error updating user $username: $msg");
|
---|
2993 | }
|
---|
2994 |
|
---|
2995 | return ('OK',$resultmsg);
|
---|
2996 | } # end updateUser()
|
---|
2997 |
|
---|
2998 |
|
---|
2999 | ## DNSDB::delUser()
|
---|
3000 | # Delete a user.
|
---|
3001 | # Takes a database handle and user ID
|
---|
3002 | # Returns a success/failure code and matching message
|
---|
3003 | sub delUser {
|
---|
3004 | my $self = shift;
|
---|
3005 | my $dbh = $self->{dbh};
|
---|
3006 | my $userid = shift;
|
---|
3007 |
|
---|
3008 | return ('FAIL',"Bad userid") if !defined($userid);
|
---|
3009 |
|
---|
3010 | my $userdata = $self->getUserData($userid);
|
---|
3011 |
|
---|
3012 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
3013 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
3014 | local $dbh->{AutoCommit} = 0;
|
---|
3015 | local $dbh->{RaiseError} = 1;
|
---|
3016 |
|
---|
3017 | eval {
|
---|
3018 | $dbh->do("DELETE FROM users WHERE user_id=?", undef, ($userid));
|
---|
3019 | $self->_log(group_id => $userdata->{group_id},
|
---|
3020 | entry => "Deleted user ID $userid/".$userdata->{username}.
|
---|
3021 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")");
|
---|
3022 | $dbh->commit;
|
---|
3023 | };
|
---|
3024 | if ($@) {
|
---|
3025 | my $msg = $@;
|
---|
3026 | eval { $dbh->rollback; };
|
---|
3027 | if ($config{log_failures}) {
|
---|
3028 | $self->_log(group_id => $userdata->{group_id}, entry => "Error deleting user ID ".
|
---|
3029 | "$userid/".$userdata->{username}.": $msg");
|
---|
3030 | $dbh->commit;
|
---|
3031 | }
|
---|
3032 | return ('FAIL',"Error deleting user $userid/".$userdata->{username}.": $msg");
|
---|
3033 | }
|
---|
3034 |
|
---|
3035 | return ('OK',"Deleted user ".$userdata->{username}." (".$userdata->{firstname}." ".$userdata->{lastname}.")");
|
---|
3036 | } # end delUser
|
---|
3037 |
|
---|
3038 |
|
---|
3039 | ## DNSDB::userFullName()
|
---|
3040 | # Return a pretty string!
|
---|
3041 | # Takes a user_id and optional printf-ish string to indicate which pieces where:
|
---|
3042 | # %u for the username
|
---|
3043 | # %f for the first name
|
---|
3044 | # %l for the last name
|
---|
3045 | # All other text in the passed string will be left as-is.
|
---|
3046 | ##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
|
---|
3047 | sub userFullName {
|
---|
3048 | $errstr = '';
|
---|
3049 | my $self = shift;
|
---|
3050 | my $dbh = $self->{dbh};
|
---|
3051 | my $userid = shift;
|
---|
3052 | my $fullformat = shift || '%f %l (%u)';
|
---|
3053 | my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
|
---|
3054 | $sth->execute($userid);
|
---|
3055 | my ($uname,$fname,$lname) = $sth->fetchrow_array();
|
---|
3056 | $errstr = $DBI::errstr if !$uname;
|
---|
3057 |
|
---|
3058 | $fullformat =~ s/\%u/$uname/g;
|
---|
3059 | $fullformat =~ s/\%f/$fname/g;
|
---|
3060 | $fullformat =~ s/\%l/$lname/g;
|
---|
3061 |
|
---|
3062 | return $fullformat;
|
---|
3063 | } # end userFullName
|
---|
3064 |
|
---|
3065 |
|
---|
3066 | ## DNSDB::userStatus()
|
---|
3067 | # Sets and/or returns a user's status
|
---|
3068 | # Takes a database handle, user ID and optionally a status argument
|
---|
3069 | # Returns undef on errors.
|
---|
3070 | sub userStatus {
|
---|
3071 | my $self = shift;
|
---|
3072 | my $dbh = $self->{dbh};
|
---|
3073 | my $id = shift;
|
---|
3074 | my $newstatus = shift || 'mu';
|
---|
3075 |
|
---|
3076 | return undef if $id !~ /^\d+$/;
|
---|
3077 |
|
---|
3078 | my $userdata = $self->getUserData($id);
|
---|
3079 |
|
---|
3080 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
3081 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
3082 | local $dbh->{AutoCommit} = 0;
|
---|
3083 | local $dbh->{RaiseError} = 1;
|
---|
3084 |
|
---|
3085 | if ($newstatus ne 'mu') {
|
---|
3086 | # ooo, fun! let's see what we were passed for status
|
---|
3087 | eval {
|
---|
3088 | $newstatus = 0 if $newstatus eq 'useroff';
|
---|
3089 | $newstatus = 1 if $newstatus eq 'useron';
|
---|
3090 | $dbh->do("UPDATE users SET status=? WHERE user_id=?", undef, ($newstatus, $id));
|
---|
3091 |
|
---|
3092 | $resultstr = ($newstatus ? 'Enabled' : 'Disabled')." user ".$userdata->{username}.
|
---|
3093 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")";
|
---|
3094 |
|
---|
3095 | my %loghash;
|
---|
3096 | $loghash{group_id} = $self->parentID(id => $id, type => 'user');
|
---|
3097 | $loghash{entry} = $resultstr;
|
---|
3098 | $self->_log(%loghash);
|
---|
3099 |
|
---|
3100 | $dbh->commit;
|
---|
3101 | };
|
---|
3102 | if ($@) {
|
---|
3103 | my $msg = $@;
|
---|
3104 | eval { $dbh->rollback; };
|
---|
3105 | $resultstr = '';
|
---|
3106 | $errstr = $msg;
|
---|
3107 | ##fixme: failure logging?
|
---|
3108 | return;
|
---|
3109 | }
|
---|
3110 | }
|
---|
3111 |
|
---|
3112 | my ($status) = $dbh->selectrow_array("SELECT status FROM users WHERE user_id=?", undef, ($id));
|
---|
3113 | return $status;
|
---|
3114 | } # end userStatus()
|
---|
3115 |
|
---|
3116 |
|
---|
3117 | ## DNSDB::getUserData()
|
---|
3118 | # Get misc user data for display
|
---|
3119 | sub getUserData {
|
---|
3120 | my $self = shift;
|
---|
3121 | my $dbh = $self->{dbh};
|
---|
3122 | my $uid = shift;
|
---|
3123 |
|
---|
3124 | my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
|
---|
3125 | "FROM users WHERE user_id=?");
|
---|
3126 | $sth->execute($uid);
|
---|
3127 | return $sth->fetchrow_hashref();
|
---|
3128 | } # end getUserData()
|
---|
3129 |
|
---|
3130 |
|
---|
3131 | ## DNSDB::addLoc()
|
---|
3132 | # Add a new location.
|
---|
3133 | # Takes a database handle, group ID, short and long description, and a comma-separated
|
---|
3134 | # list of IP addresses.
|
---|
3135 | # Returns ('OK',<location>) on success, ('FAIL',<failmsg>) on failure
|
---|
3136 | sub addLoc {
|
---|
3137 | my $self = shift;
|
---|
3138 | my $dbh = $self->{dbh};
|
---|
3139 | my $grp = shift;
|
---|
3140 | my $shdesc = shift;
|
---|
3141 | my $comments = shift;
|
---|
3142 | my $iplist = shift;
|
---|
3143 |
|
---|
3144 | # $shdesc gets set to the generated location ID if possible, but these can be de-undefined here.
|
---|
3145 | $comments = '' if !$comments;
|
---|
3146 | $iplist = '' if !$iplist;
|
---|
3147 |
|
---|
3148 | my $loc;
|
---|
3149 |
|
---|
3150 | # Generate a location ID. This is, by spec, a two-character widget. We'll use [a-z][a-z]
|
---|
3151 | # for now; 676 locations should satisfy all but the largest of the huge networks.
|
---|
3152 | # Not sure whether these are case-sensitive, or what other rules might apply - in any case
|
---|
3153 | # the absolute maximum is 16K (256*256) since it's parsed by tinydns as a two-character field.
|
---|
3154 |
|
---|
3155 | # add just after "my $origloc = $loc;":
|
---|
3156 | # # These expand the possible space from 26^2 to 52^2 [* note in testing only 2052 were achieved],
|
---|
3157 | # # and wrap it around.
|
---|
3158 | # # Yes, they skip a couple of possibles. No, I don't care.
|
---|
3159 | # $loc = 'aA' if $loc eq 'zz';
|
---|
3160 | # $loc = 'Aa' if $loc eq 'zZ';
|
---|
3161 | # $loc = 'ZA' if $loc eq 'Zz';
|
---|
3162 | # $loc = 'aa' if $loc eq 'ZZ';
|
---|
3163 |
|
---|
3164 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
3165 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
3166 | local $dbh->{AutoCommit} = 0;
|
---|
3167 | local $dbh->{RaiseError} = 1;
|
---|
3168 |
|
---|
3169 | ##fixme: There is probably a far better way to do this. Sequential increments
|
---|
3170 | # are marginally less stupid that pure random generation though, and the existence
|
---|
3171 | # check makes sure we don't stomp on an imported one.
|
---|
3172 |
|
---|
3173 | eval {
|
---|
3174 | # Get the "last" location. Note this is the only use for loc_id, because selecting on location Does Funky Things
|
---|
3175 | ($loc) = $dbh->selectrow_array("SELECT location FROM locations ORDER BY loc_id DESC LIMIT 1");
|
---|
3176 | ($loc) = ($loc =~ /^(..)/) if $loc;
|
---|
3177 | my $origloc = $loc;
|
---|
3178 | $loc = 'aa' if !$loc;
|
---|
3179 | # Make a change...
|
---|
3180 | $loc++;
|
---|
3181 | # ... and keep changing if it exists
|
---|
3182 | while ($dbh->selectrow_array("SELECT count(*) FROM locations WHERE location LIKE ?", undef, ($loc.'%'))) {
|
---|
3183 | $loc++;
|
---|
3184 | ($loc) = ($loc =~ /^(..)/);
|
---|
3185 | die "too many locations in use, can't add another one\n" if $loc eq $origloc;
|
---|
3186 | ##fixme: really need to handle this case faster somehow
|
---|
3187 | #if $loc eq $origloc die "<thwap> bad admin: all locations used, your network is too fragmented";
|
---|
3188 | }
|
---|
3189 | # And now we should have a unique location. tinydns fundamentally limits the
|
---|
3190 | # number of these but there's no doc on what characters are valid.
|
---|
3191 | $shdesc = $loc if !$shdesc;
|
---|
3192 | $dbh->do("INSERT INTO locations (location, group_id, iplist, description, comments) VALUES (?,?,?,?,?)",
|
---|
3193 | undef, ($loc, $grp, $iplist, $shdesc, $comments) );
|
---|
3194 | $self->_log(entry => "Added location ($shdesc, '$iplist')");
|
---|
3195 | $dbh->commit;
|
---|
3196 | };
|
---|
3197 | if ($@) {
|
---|
3198 | my $msg = $@;
|
---|
3199 | eval { $dbh->rollback; };
|
---|
3200 | if ($config{log_failures}) {
|
---|
3201 | $shdesc = $loc if !$shdesc;
|
---|
3202 | $self->_log(entry => "Failed adding location ($shdesc, '$iplist'): $msg");
|
---|
3203 | $dbh->commit;
|
---|
3204 | }
|
---|
3205 | return ('FAIL',$msg);
|
---|
3206 | }
|
---|
3207 |
|
---|
3208 | return ('OK',$loc);
|
---|
3209 | } # end addLoc()
|
---|
3210 |
|
---|
3211 |
|
---|
3212 | ## DNSDB::updateLoc()
|
---|
3213 | # Update details of a location.
|
---|
3214 | # Takes a database handle, location ID, group ID, short description,
|
---|
3215 | # long comments/notes, and comma/space-separated IP list
|
---|
3216 | # Returns a result code and message
|
---|
3217 | sub updateLoc {
|
---|
3218 | my $self = shift;
|
---|
3219 | my $dbh = $self->{dbh};
|
---|
3220 | my $loc = shift;
|
---|
3221 | my $grp = shift;
|
---|
3222 | my $shdesc = shift;
|
---|
3223 | my $comments = shift;
|
---|
3224 | my $iplist = shift;
|
---|
3225 |
|
---|
3226 | $shdesc = '' if !$shdesc;
|
---|
3227 | $comments = '' if !$comments;
|
---|
3228 | $iplist = '' if !$iplist;
|
---|
3229 |
|
---|
3230 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
3231 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
3232 | local $dbh->{AutoCommit} = 0;
|
---|
3233 | local $dbh->{RaiseError} = 1;
|
---|
3234 |
|
---|
3235 | my $oldloc = $self->getLoc($loc);
|
---|
3236 | my $okmsg = "Updated location (".$oldloc->{description}.", '".$oldloc->{iplist}."') to ($shdesc, '$iplist')";
|
---|
3237 |
|
---|
3238 | eval {
|
---|
3239 | $dbh->do("UPDATE locations SET group_id=?,iplist=?,description=?,comments=? WHERE location=?",
|
---|
3240 | undef, ($grp, $iplist, $shdesc, $comments, $loc) );
|
---|
3241 | $self->_log(entry => $okmsg);
|
---|
3242 | $dbh->commit;
|
---|
3243 | };
|
---|
3244 | if ($@) {
|
---|
3245 | my $msg = $@;
|
---|
3246 | eval { $dbh->rollback; };
|
---|
3247 | if ($config{log_failures}) {
|
---|
3248 | $shdesc = $loc if !$shdesc;
|
---|
3249 | $self->_log(entry => "Failed updating location ($shdesc, '$iplist'): $msg");
|
---|
3250 | $dbh->commit;
|
---|
3251 | }
|
---|
3252 | return ('FAIL',$msg);
|
---|
3253 | }
|
---|
3254 |
|
---|
3255 | return ('OK',$okmsg);
|
---|
3256 | } # end updateLoc()
|
---|
3257 |
|
---|
3258 |
|
---|
3259 | ## DNSDB::delLoc()
|
---|
3260 | sub delLoc {
|
---|
3261 | my $self = shift;
|
---|
3262 | my $dbh = $self->{dbh};
|
---|
3263 | my $loc = shift;
|
---|
3264 |
|
---|
3265 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
3266 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
3267 | local $dbh->{AutoCommit} = 0;
|
---|
3268 | local $dbh->{RaiseError} = 1;
|
---|
3269 |
|
---|
3270 | my $oldloc = $self->getLoc($loc);
|
---|
3271 | my $olddesc = ($oldloc->{description} ? $oldloc->{description} : $loc);
|
---|
3272 | my $okmsg = "Deleted location ($olddesc, '".$oldloc->{iplist}."')";
|
---|
3273 |
|
---|
3274 | eval {
|
---|
3275 | # Check for records with this location first. Deleting a location without deleting records
|
---|
3276 | # tagged for that location will render them unpublished without other warning.
|
---|
3277 | my ($r) = $dbh->selectrow_array("SELECT record_id FROM records WHERE location=? LIMIT 1", undef, ($loc) );
|
---|
3278 | die "Records still exist in location $olddesc\n" if $r;
|
---|
3279 | $dbh->do("DELETE FROM locations WHERE location=?", undef, ($loc) );
|
---|
3280 | $self->_log(entry => $okmsg);
|
---|
3281 | $dbh->commit;
|
---|
3282 | };
|
---|
3283 | if ($@) {
|
---|
3284 | my $msg = $@;
|
---|
3285 | eval { $dbh->rollback; };
|
---|
3286 | if ($config{log_failures}) {
|
---|
3287 | $self->_log(entry => "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
|
---|
3288 | $dbh->commit;
|
---|
3289 | }
|
---|
3290 | return ('FAIL', "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
|
---|
3291 | }
|
---|
3292 |
|
---|
3293 | return ('OK',$okmsg);
|
---|
3294 | } # end delLoc()
|
---|
3295 |
|
---|
3296 |
|
---|
3297 | ## DNSDB::getLoc()
|
---|
3298 | # Get details about a location/view
|
---|
3299 | # Takes a database handle and location ID.
|
---|
3300 | # Returns a reference to a hash containing the group ID, IP list, description, and comments/notes
|
---|
3301 | sub getLoc {
|
---|
3302 | my $self = shift;
|
---|
3303 | my $dbh = $self->{dbh};
|
---|
3304 | my $loc = shift;
|
---|
3305 |
|
---|
3306 | my $sth = $dbh->prepare("SELECT group_id,iplist,description,comments FROM locations WHERE location=?");
|
---|
3307 | $sth->execute($loc);
|
---|
3308 | return $sth->fetchrow_hashref();
|
---|
3309 | } # end getLoc()
|
---|
3310 |
|
---|
3311 |
|
---|
3312 | ## DNSDB::getLocCount()
|
---|
3313 | # Get count of locations/views
|
---|
3314 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
3315 | # - a reference list of secondary groups
|
---|
3316 | # - a filter string
|
---|
3317 | # - a "Starts with" string
|
---|
3318 | sub getLocCount {
|
---|
3319 | my $self = shift;
|
---|
3320 | my $dbh = $self->{dbh};
|
---|
3321 |
|
---|
3322 | my %args = @_;
|
---|
3323 |
|
---|
3324 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
3325 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
3326 | $errstr = "Bad or missing curgroup argument";
|
---|
3327 | return;
|
---|
3328 | }
|
---|
3329 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
3330 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
3331 | $errstr = "Bad childlist argument";
|
---|
3332 | return;
|
---|
3333 | }
|
---|
3334 |
|
---|
3335 | my @filterargs;
|
---|
3336 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
3337 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
3338 | push @filterargs, $args{filter} if $args{filter};
|
---|
3339 |
|
---|
3340 | my $sql = "SELECT count(*) FROM locations ".
|
---|
3341 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
3342 | ($args{startwith} ? " AND description ~* ?" : '').
|
---|
3343 | ($args{filter} ? " AND description ~* ?" : '');
|
---|
3344 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
3345 | $errstr = $dbh->errstr if !$count;
|
---|
3346 | return $count;
|
---|
3347 | } # end getLocCount()
|
---|
3348 |
|
---|
3349 |
|
---|
3350 | ## DNSDB::getLocList()
|
---|
3351 | sub getLocList {
|
---|
3352 | my $self = shift;
|
---|
3353 | my $dbh = $self->{dbh};
|
---|
3354 |
|
---|
3355 | my %args = @_;
|
---|
3356 |
|
---|
3357 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
3358 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
3359 | $errstr = "Bad or missing curgroup argument";
|
---|
3360 | return;
|
---|
3361 | }
|
---|
3362 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
3363 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
3364 | $errstr = "Bad childlist argument";
|
---|
3365 | return;
|
---|
3366 | }
|
---|
3367 |
|
---|
3368 | my @filterargs;
|
---|
3369 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
3370 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
3371 | push @filterargs, $args{filter} if $args{filter};
|
---|
3372 |
|
---|
3373 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
3374 | # my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
3375 | # fname => 'fname');
|
---|
3376 | # $args{sortby} = $sortmap{$args{sortby}};
|
---|
3377 |
|
---|
3378 | # protection against bad or missing arguments
|
---|
3379 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
3380 | $args{sortby} = 'l.description' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
3381 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
3382 |
|
---|
3383 | my $sql = "SELECT l.location, l.description, l.iplist, g.group_name ".
|
---|
3384 | "FROM locations l ".
|
---|
3385 | "INNER JOIN groups g ON l.group_id=g.group_id ".
|
---|
3386 | "WHERE l.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
3387 | ($args{startwith} ? " AND l.description ~* ?" : '').
|
---|
3388 | ($args{filter} ? " AND l.description ~* ?" : '').
|
---|
3389 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
3390 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
3391 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
3392 | $errstr = $dbh->errstr if !$ulist;
|
---|
3393 | return $ulist;
|
---|
3394 | } # end getLocList()
|
---|
3395 |
|
---|
3396 |
|
---|
3397 | ## DNSDB::getLocDropdown()
|
---|
3398 | # Get a list of location names for use in a dropdown menu.
|
---|
3399 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
3400 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
3401 | sub getLocDropdown {
|
---|
3402 | my $self = shift;
|
---|
3403 | my $dbh = $self->{dbh};
|
---|
3404 | my $grp = shift;
|
---|
3405 | my $sel = shift || '';
|
---|
3406 |
|
---|
3407 | my $sth = $dbh->prepare(qq(
|
---|
3408 | SELECT description,location FROM locations
|
---|
3409 | WHERE group_id=?
|
---|
3410 | ORDER BY description
|
---|
3411 | ) );
|
---|
3412 | $sth->execute($grp);
|
---|
3413 |
|
---|
3414 | my @loclist;
|
---|
3415 | push @loclist, { locname => "(Default/All)", loc => '', selected => ($sel ? 0 : ($sel eq '' ? 1 : 0)) };
|
---|
3416 | while (my ($locname, $loc) = $sth->fetchrow_array) {
|
---|
3417 | my %row = (
|
---|
3418 | locname => $locname,
|
---|
3419 | loc => $loc,
|
---|
3420 | selected => ($sel eq $loc ? 1 : 0)
|
---|
3421 | );
|
---|
3422 | push @loclist, \%row;
|
---|
3423 | }
|
---|
3424 | return \@loclist;
|
---|
3425 | } # end getLocDropdown()
|
---|
3426 |
|
---|
3427 |
|
---|
3428 | ## DNSDB::getSOA()
|
---|
3429 | # Return all suitable fields from an SOA record in separate elements of a hash
|
---|
3430 | # Takes a database handle, default/live flag, domain/reverse flag, and parent ID
|
---|
3431 | sub getSOA {
|
---|
3432 | $errstr = '';
|
---|
3433 | my $self = shift;
|
---|
3434 | my $dbh = $self->{dbh};
|
---|
3435 | my $def = shift;
|
---|
3436 | my $rev = shift;
|
---|
3437 | my $id = shift;
|
---|
3438 |
|
---|
3439 | # (ab)use distance and weight columns to store SOA data? can't for default_rev_records...
|
---|
3440 | # - should really attach serial to the zone parent somewhere
|
---|
3441 |
|
---|
3442 | my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev).
|
---|
3443 | " WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}";
|
---|
3444 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
3445 | return if !$ret;
|
---|
3446 | ##fixme: stick a flag somewhere if the record doesn't exist. by the API, this is an impossible case, but...
|
---|
3447 |
|
---|
3448 | ($ret->{contact},$ret->{prins}) = split /:/, $ret->{host};
|
---|
3449 | delete $ret->{host};
|
---|
3450 | ($ret->{refresh},$ret->{retry},$ret->{expire},$ret->{minttl}) = split /:/, $ret->{val};
|
---|
3451 | delete $ret->{val};
|
---|
3452 |
|
---|
3453 | return $ret;
|
---|
3454 | } # end getSOA()
|
---|
3455 |
|
---|
3456 |
|
---|
3457 | ## DNSDB::updateSOA()
|
---|
3458 | # Update the specified SOA record
|
---|
3459 | # Takes a database handle, default/live flag, forward/reverse flag, and SOA data hash
|
---|
3460 | # Returns a two-element list with a result code and message
|
---|
3461 | sub updateSOA {
|
---|
3462 | my $self = shift;
|
---|
3463 | my $dbh = $self->{dbh};
|
---|
3464 | my $defrec = shift;
|
---|
3465 | my $revrec = shift;
|
---|
3466 |
|
---|
3467 | my %soa = @_;
|
---|
3468 |
|
---|
3469 | my $oldsoa = $self->getSOA($defrec, $revrec, $soa{id});
|
---|
3470 |
|
---|
3471 | my $msg;
|
---|
3472 | my %logdata;
|
---|
3473 | if ($defrec eq 'n') {
|
---|
3474 | $logdata{domain_id} = $soa{id} if $revrec eq 'n';
|
---|
3475 | $logdata{rdns_id} = $soa{id} if $revrec eq 'y';
|
---|
3476 | $logdata{group_id} = $self->parentID(id => $soa{id}, revrec => $revrec,
|
---|
3477 | type => ($revrec eq 'n' ? 'domain' : 'revzone') );
|
---|
3478 | } else {
|
---|
3479 | $logdata{group_id} = $soa{id};
|
---|
3480 | }
|
---|
3481 | my $parname = ($defrec eq 'y' ? $self->groupName($soa{id}) :
|
---|
3482 | ($revrec eq 'n' ? $self->domainName($soa{id}) : $self->revName($soa{id})) );
|
---|
3483 |
|
---|
3484 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
3485 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
3486 | local $dbh->{AutoCommit} = 0;
|
---|
3487 | local $dbh->{RaiseError} = 1;
|
---|
3488 |
|
---|
3489 | eval {
|
---|
3490 | my $sql = "UPDATE "._rectable($defrec, $revrec)." SET host=?, val=?, ttl=? WHERE record_id=? AND type=6";
|
---|
3491 | $dbh->do($sql, undef, ("$soa{contact}:$soa{prins}", "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}",
|
---|
3492 | $soa{ttl}, $oldsoa->{record_id}) );
|
---|
3493 | $msg = "Updated ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse ' : 'default ') : '').
|
---|
3494 | "SOA for $parname: ".
|
---|
3495 | "(ns $oldsoa->{prins}, contact $oldsoa->{contact}, refresh $oldsoa->{refresh},".
|
---|
3496 | " retry $oldsoa->{retry}, expire $oldsoa->{expire}, minTTL $oldsoa->{minttl}, TTL $oldsoa->{ttl}) to ".
|
---|
3497 | "(ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
|
---|
3498 | " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})";
|
---|
3499 |
|
---|
3500 | $logdata{entry} = $msg;
|
---|
3501 | $self->_log(%logdata);
|
---|
3502 |
|
---|
3503 | $dbh->commit;
|
---|
3504 | };
|
---|
3505 | if ($@) {
|
---|
3506 | $msg = $@;
|
---|
3507 | eval { $dbh->rollback; };
|
---|
3508 | $logdata{entry} = "Error updating ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse zone ' : 'default ') : '').
|
---|
3509 | "SOA record for $parname: $msg";
|
---|
3510 | if ($config{log_failures}) {
|
---|
3511 | $self->_log(%logdata);
|
---|
3512 | $dbh->commit;
|
---|
3513 | }
|
---|
3514 | return ('FAIL', $logdata{entry});
|
---|
3515 | } else {
|
---|
3516 | return ('OK', $msg);
|
---|
3517 | }
|
---|
3518 | } # end updateSOA()
|
---|
3519 |
|
---|
3520 |
|
---|
3521 | ## DNSDB::getRecLine()
|
---|
3522 | # Return all data fields for a zone record in separate elements of a hash
|
---|
3523 | # Takes a database handle, default/live flag, forward/reverse flag, and record ID
|
---|
3524 | sub getRecLine {
|
---|
3525 | $errstr = '';
|
---|
3526 | my $self = shift;
|
---|
3527 | my $dbh = $self->{dbh};
|
---|
3528 | my $defrec = shift;
|
---|
3529 | my $revrec = shift;
|
---|
3530 | my $id = shift;
|
---|
3531 |
|
---|
3532 | my $sql = "SELECT record_id,host,type,val,ttl".
|
---|
3533 | ($defrec eq 'n' ? ',location' : '').
|
---|
3534 | ($revrec eq 'n' ? ',distance,weight,port' : '').
|
---|
3535 | (($defrec eq 'y') ? ',group_id FROM ' : ',domain_id,rdns_id FROM ').
|
---|
3536 | _rectable($defrec,$revrec)." WHERE record_id=?";
|
---|
3537 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
3538 |
|
---|
3539 | if ($dbh->err) {
|
---|
3540 | $errstr = $DBI::errstr;
|
---|
3541 | return undef;
|
---|
3542 | }
|
---|
3543 |
|
---|
3544 | if (!$ret) {
|
---|
3545 | $errstr = "No such record";
|
---|
3546 | return undef;
|
---|
3547 | }
|
---|
3548 |
|
---|
3549 | # explicitly set a parent id
|
---|
3550 | if ($defrec eq 'y') {
|
---|
3551 | $ret->{parid} = $ret->{group_id};
|
---|
3552 | } else {
|
---|
3553 | $ret->{parid} = (($revrec eq 'n') ? $ret->{domain_id} : $ret->{rdns_id});
|
---|
3554 | # and a secondary if we have a custom type that lives in both a forward and reverse zone
|
---|
3555 | $ret->{secid} = (($revrec eq 'y') ? $ret->{domain_id} : $ret->{rdns_id}) if $ret->{type} > 65279;
|
---|
3556 | }
|
---|
3557 | $ret->{address} = $ret->{val}; # because.
|
---|
3558 |
|
---|
3559 | return $ret;
|
---|
3560 | }
|
---|
3561 |
|
---|
3562 |
|
---|
3563 | ##fixme: should use above (getRecLine()) to get lines for below?
|
---|
3564 | ## DNSDB::getRecList()
|
---|
3565 | # Return records for a group or zone
|
---|
3566 | # Takes a default/live flag, group or zone ID, start,
|
---|
3567 | # number of records, sort field, and sort order
|
---|
3568 | # Returns a reference to an array of hashes
|
---|
3569 | sub getRecList {
|
---|
3570 | $errstr = '';
|
---|
3571 | my $self = shift;
|
---|
3572 | my $dbh = $self->{dbh};
|
---|
3573 |
|
---|
3574 | my %args = @_;
|
---|
3575 |
|
---|
3576 | my @filterargs;
|
---|
3577 |
|
---|
3578 | push @filterargs, $args{filter} if $args{filter};
|
---|
3579 |
|
---|
3580 | # protection against bad or missing arguments
|
---|
3581 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
3582 | my $defsort;
|
---|
3583 | $defsort = 'host' if $args{revrec} eq 'n'; # default sort by host on domain record list
|
---|
3584 | $defsort = 'val' if $args{revrec} eq 'y'; # default sort by IP on revzone record list
|
---|
3585 | $args{sortby} = '' if !$args{sortby};
|
---|
3586 | $args{sortby} = $defsort if !$args{revrec};
|
---|
3587 | $args{sortby} = $defsort if $args{sortby} !~ /^[\w_,.]+$/;
|
---|
3588 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
3589 | my $perpage = ($args{nrecs} ? $args{nrecs} : $config{perpage});
|
---|
3590 |
|
---|
3591 | # sort reverse zones on IP, correctly
|
---|
3592 | # do other fiddling with $args{sortby} while we're at it.
|
---|
3593 | # whee! multisort means just passing comma-separated fields in sortby!
|
---|
3594 | my $newsort = '';
|
---|
3595 | foreach my $sf (split /,/, $args{sortby}) {
|
---|
3596 | $sf = "r.$sf";
|
---|
3597 | $sf =~ s/r\.val/CAST (r.val AS inet)/
|
---|
3598 | if $args{revrec} eq 'y' && $args{defrec} eq 'n';
|
---|
3599 | $sf =~ s/r\.type/t.alphaorder/;
|
---|
3600 | $newsort .= ",$sf";
|
---|
3601 | }
|
---|
3602 | $newsort =~ s/^,//;
|
---|
3603 |
|
---|
3604 | my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.ttl";
|
---|
3605 | $sql .= ",l.description AS locname" if $args{defrec} eq 'n';
|
---|
3606 | $sql .= ",r.distance,r.weight,r.port" if $args{revrec} eq 'n';
|
---|
3607 | $sql .= " FROM "._rectable($args{defrec},$args{revrec})." r ";
|
---|
3608 | $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
|
---|
3609 | $sql .= "LEFT JOIN locations l ON r.location=l.location " if $args{defrec} eq 'n';
|
---|
3610 | $sql .= "WHERE "._recparent($args{defrec},$args{revrec})." = ?";
|
---|
3611 | $sql .= " AND NOT r.type=$reverse_typemap{SOA}";
|
---|
3612 | $sql .= " AND (r.host ~* ? OR r.val ~* ?)" if $args{filter};
|
---|
3613 | $sql .= " ORDER BY $newsort $args{sortorder}";
|
---|
3614 | # ensure consistent ordering by sorting on record_id too
|
---|
3615 | $sql .= ", record_id $args{sortorder}";
|
---|
3616 | $sql .= ($args{offset} eq 'all' ? '' : " LIMIT $perpage OFFSET ".$args{offset}*$perpage);
|
---|
3617 |
|
---|
3618 | my @bindvars = ($args{id});
|
---|
3619 | push @bindvars, ($args{filter},$args{filter}) if $args{filter};
|
---|
3620 |
|
---|
3621 | my $ret = $dbh->selectall_arrayref($sql, { Slice => {} }, (@bindvars) );
|
---|
3622 | $errstr = "Error retrieving records: ".$dbh->errstr if !$ret;
|
---|
3623 | return $ret;
|
---|
3624 | } # end getRecList()
|
---|
3625 |
|
---|
3626 |
|
---|
3627 | ## DNSDB::getRecCount()
|
---|
3628 | # Return count of non-SOA records in zone (or default records in a group)
|
---|
3629 | # Takes a database handle, default/live flag, reverse/forward flag, group/domain ID,
|
---|
3630 | # and optional filtering modifier
|
---|
3631 | # Returns the count
|
---|
3632 | sub getRecCount {
|
---|
3633 | my $self = shift;
|
---|
3634 | my $dbh = $self->{dbh};
|
---|
3635 | my $defrec = shift;
|
---|
3636 | my $revrec = shift;
|
---|
3637 | my $id = shift;
|
---|
3638 | my $filter = shift || '';
|
---|
3639 |
|
---|
3640 | # keep the nasties down, since we can't ?-sub this bit. :/
|
---|
3641 | # note this is chars allowed in DNS hostnames
|
---|
3642 | $filter =~ s/[^a-zA-Z0-9_.:-]//g;
|
---|
3643 |
|
---|
3644 | my @bindvars = ($id);
|
---|
3645 | push @bindvars, $filter if $filter;
|
---|
3646 | my $sql = "SELECT count(*) FROM ".
|
---|
3647 | _rectable($defrec,$revrec).
|
---|
3648 | " WHERE "._recparent($defrec,$revrec)."=? ".
|
---|
3649 | "AND NOT type=$reverse_typemap{SOA}".
|
---|
3650 | ($filter ? " AND host ~* ?" : '');
|
---|
3651 | my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) );
|
---|
3652 |
|
---|
3653 | return $count;
|
---|
3654 |
|
---|
3655 | } # end getRecCount()
|
---|
3656 |
|
---|
3657 |
|
---|
3658 | ## DNSDB::addRec()
|
---|
3659 | # Add a new record to a domain or a group's default records
|
---|
3660 | # Takes a database handle, default/live flag, group/domain ID,
|
---|
3661 | # host, type, value, and TTL
|
---|
3662 | # Some types require additional detail: "distance" for MX and SRV,
|
---|
3663 | # and weight/port for SRV
|
---|
3664 | # Returns a status code and detail message in case of error
|
---|
3665 | ##fixme: pass a hash with the record data, not a series of separate values
|
---|
3666 | sub addRec {
|
---|
3667 | $errstr = '';
|
---|
3668 | my $self = shift;
|
---|
3669 | my $dbh = $self->{dbh};
|
---|
3670 | my $defrec = shift;
|
---|
3671 | my $revrec = shift;
|
---|
3672 | my $id = shift; # parent (group_id for defrecs, rdns_id for reverse records,
|
---|
3673 | # domain_id for domain records)
|
---|
3674 |
|
---|
3675 | my $host = shift;
|
---|
3676 | my $rectype = shift; # reference so we can coerce it if "+"-types can't find both zones
|
---|
3677 | my $val = shift;
|
---|
3678 | my $ttl = shift;
|
---|
3679 | my $location = shift;
|
---|
3680 | $location = '' if !$location;
|
---|
3681 |
|
---|
3682 | # Spaces are evil.
|
---|
3683 | $$host =~ s/^\s+//;
|
---|
3684 | $$host =~ s/\s+$//;
|
---|
3685 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
3686 | # Leading or trailng spaces could be legit in TXT records.
|
---|
3687 | $$val =~ s/^\s+//;
|
---|
3688 | $$val =~ s/\s+$//;
|
---|
3689 | }
|
---|
3690 |
|
---|
3691 | # prep for validation
|
---|
3692 | my $addr = NetAddr::IP->new($$val);
|
---|
3693 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
3694 |
|
---|
3695 | my $domid = 0;
|
---|
3696 | my $revid = 0;
|
---|
3697 |
|
---|
3698 | my $retcode = 'OK'; # assume everything will go OK
|
---|
3699 | my $retmsg = '';
|
---|
3700 |
|
---|
3701 | # do simple validation first
|
---|
3702 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
|
---|
3703 |
|
---|
3704 | # Quick check on hostname parts. Note the regex is more forgiving than the error message;
|
---|
3705 | # domain names technically are case-insensitive, and we use printf-like % codes for a couple
|
---|
3706 | # of types. Other things may also be added to validate default records of several flavours.
|
---|
3707 | return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z . _)")
|
---|
3708 | if $defrec eq 'n' && ($revrec eq 'y' ? $$rectype != $reverse_typemap{TXT} : 1) &&
|
---|
3709 | $$host !~ /^[0-9a-z_%.-]+$/i;
|
---|
3710 |
|
---|
3711 | # Collect these even if we're only doing a simple A record so we can call *any* validation sub
|
---|
3712 | my $dist = shift;
|
---|
3713 | my $weight = shift;
|
---|
3714 | my $port = shift;
|
---|
3715 |
|
---|
3716 | my $fields;
|
---|
3717 | my @vallist;
|
---|
3718 |
|
---|
3719 | # Call the validation sub for the type requested.
|
---|
3720 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec, id => $id,
|
---|
3721 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
3722 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
3723 | fields => \$fields, vallist => \@vallist);
|
---|
3724 |
|
---|
3725 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
3726 |
|
---|
3727 | # Set up database fields and bind parameters
|
---|
3728 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
3729 | push @vallist, ($$host,$$rectype,$$val,$ttl,$id);
|
---|
3730 |
|
---|
3731 | # locations are not for default records, silly coder!
|
---|
3732 | if ($defrec eq 'n') {
|
---|
3733 | $fields .= ",location";
|
---|
3734 | push @vallist, $location;
|
---|
3735 | }
|
---|
3736 | my $vallen = '?'.(',?'x$#vallist);
|
---|
3737 |
|
---|
3738 | # Put together the success log entry. We have to use this horrible kludge
|
---|
3739 | # because domain_id and rdns_id may or may not be present, and if they are,
|
---|
3740 | # they're not at a guaranteed consistent index in the array. wheee!
|
---|
3741 | my %logdata;
|
---|
3742 | my @ftmp = split /,/, $fields;
|
---|
3743 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
3744 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
3745 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
3746 | }
|
---|
3747 | $logdata{group_id} = $id if $defrec eq 'y';
|
---|
3748 | $logdata{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec)
|
---|
3749 | if $defrec eq 'n';
|
---|
3750 | $logdata{entry} = "Added ".($defrec eq 'y' ? 'default record' : 'record');
|
---|
3751 | # NS records for revzones get special treatment
|
---|
3752 | if ($revrec eq 'y' && $$rectype == 2) {
|
---|
3753 | $logdata{entry} .= " '$$val $typemap{$$rectype} $$host";
|
---|
3754 | } else {
|
---|
3755 | $logdata{entry} .= " '$$host $typemap{$$rectype} $$val";
|
---|
3756 | }
|
---|
3757 |
|
---|
3758 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
3759 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]"
|
---|
3760 | if $typemap{$$rectype} eq 'SRV';
|
---|
3761 | $logdata{entry} .= "', TTL $ttl";
|
---|
3762 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location;
|
---|
3763 |
|
---|
3764 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
3765 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
3766 | local $dbh->{AutoCommit} = 0;
|
---|
3767 | local $dbh->{RaiseError} = 1;
|
---|
3768 |
|
---|
3769 | eval {
|
---|
3770 | $dbh->do("INSERT INTO "._rectable($defrec, $revrec)." ($fields) VALUES ($vallen)",
|
---|
3771 | undef, @vallist);
|
---|
3772 | $self->_log(%logdata);
|
---|
3773 | $dbh->commit;
|
---|
3774 | };
|
---|
3775 | if ($@) {
|
---|
3776 | my $msg = $@;
|
---|
3777 | eval { $dbh->rollback; };
|
---|
3778 | if ($config{log_failures}) {
|
---|
3779 | $logdata{entry} = "Failed adding ".($defrec eq 'y' ? 'default ' : '').
|
---|
3780 | "record '$$host $typemap{$$rectype} $$val', TTL $ttl ($msg)";
|
---|
3781 | $self->_log(%logdata);
|
---|
3782 | $dbh->commit;
|
---|
3783 | }
|
---|
3784 | return ('FAIL',$msg);
|
---|
3785 | }
|
---|
3786 |
|
---|
3787 | $resultstr = $logdata{entry};
|
---|
3788 | return ($retcode, $retmsg);
|
---|
3789 |
|
---|
3790 | } # end addRec()
|
---|
3791 |
|
---|
3792 |
|
---|
3793 | ## DNSDB::updateRec()
|
---|
3794 | # Update a record
|
---|
3795 | # Takes a database handle, default and reverse flags, record ID, immediate parent ID, and new record data.
|
---|
3796 | # Returns a status code and message
|
---|
3797 | sub updateRec {
|
---|
3798 | $errstr = '';
|
---|
3799 |
|
---|
3800 | my $self = shift;
|
---|
3801 | my $dbh = $self->{dbh};
|
---|
3802 | my $defrec = shift;
|
---|
3803 | my $revrec = shift;
|
---|
3804 | my $id = shift;
|
---|
3805 | my $parid = shift; # immediate parent entity that we're descending from to update the record
|
---|
3806 |
|
---|
3807 | # all records have these
|
---|
3808 | my $host = shift;
|
---|
3809 | my $hostbk = $$host; # Keep a backup copy of the original, so we can WARN if the update mangles the domain
|
---|
3810 | my $rectype = shift;
|
---|
3811 | my $val = shift;
|
---|
3812 | my $ttl = shift;
|
---|
3813 | my $location = shift; # may be empty/null/undef depending on caller
|
---|
3814 | $location = '' if !$location;
|
---|
3815 |
|
---|
3816 | # just set it to an empty string; failures will be caught later.
|
---|
3817 | $$host = '' if !$$host;
|
---|
3818 |
|
---|
3819 | # Spaces are evil.
|
---|
3820 | $$host =~ s/^\s+//;
|
---|
3821 | $$host =~ s/\s+$//;
|
---|
3822 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
3823 | # Leading or trailng spaces could be legit in TXT records.
|
---|
3824 | $$val =~ s/^\s+//;
|
---|
3825 | $$val =~ s/\s+$//;
|
---|
3826 | }
|
---|
3827 |
|
---|
3828 | # prep for validation
|
---|
3829 | my $addr = NetAddr::IP->new($$val);
|
---|
3830 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
3831 |
|
---|
3832 | my $domid = 0;
|
---|
3833 | my $revid = 0;
|
---|
3834 |
|
---|
3835 | my $retcode = 'OK'; # assume everything will go OK
|
---|
3836 | my $retmsg = '';
|
---|
3837 |
|
---|
3838 | # do simple validation first
|
---|
3839 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
|
---|
3840 |
|
---|
3841 | # Quick check on hostname parts. Note the regex is more forgiving than the error message;
|
---|
3842 | # domain names technically are case-insensitive, and we use printf-like % codes for a couple
|
---|
3843 | # of types. Other things may also be added to validate default records of several flavours.
|
---|
3844 | return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z - . _)")
|
---|
3845 | if $defrec eq 'n' && ($revrec eq 'y' ? $$rectype != $reverse_typemap{TXT} : 1) &&
|
---|
3846 | $$host !~ /^[0-9a-z_%.-]+$/i;
|
---|
3847 |
|
---|
3848 | # only MX and SRV will use these
|
---|
3849 | my $dist = shift || 0;
|
---|
3850 | my $weight = shift || 0;
|
---|
3851 | my $port = shift || 0;
|
---|
3852 |
|
---|
3853 | my $fields;
|
---|
3854 | my @vallist;
|
---|
3855 |
|
---|
3856 | # get old record data so we have the right parent ID
|
---|
3857 | # and for logging (eventually)
|
---|
3858 | my $oldrec = $self->getRecLine($defrec, $revrec, $id);
|
---|
3859 |
|
---|
3860 | # Call the validation sub for the type requested.
|
---|
3861 | # Note the ID to pass here is the *parent*, not the record
|
---|
3862 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec,
|
---|
3863 | id => ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})),
|
---|
3864 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
3865 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
3866 | fields => \$fields, vallist => \@vallist,
|
---|
3867 | update => $id);
|
---|
3868 |
|
---|
3869 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
3870 |
|
---|
3871 | # Set up database fields and bind parameters. Note only the optional fields
|
---|
3872 | # (distance, weight, port, secondary parent ID) are added in the validation call above
|
---|
3873 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
3874 | push @vallist, ($$host,$$rectype,$$val,$ttl,
|
---|
3875 | ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})) );
|
---|
3876 |
|
---|
3877 | # locations are not for default records, silly coder!
|
---|
3878 | if ($defrec eq 'n') {
|
---|
3879 | $fields .= ",location";
|
---|
3880 | push @vallist, $location;
|
---|
3881 | }
|
---|
3882 |
|
---|
3883 | # hack hack PTHUI
|
---|
3884 | # need to forcibly make sure we disassociate a record with a parent it's no longer related to.
|
---|
3885 | # eg, PTR records may not have a domain parent, or A/AAAA records may not have a revzone parent.
|
---|
3886 | # mainly needed for crossover types that got coerced down to "standard" types
|
---|
3887 | if ($defrec eq 'n') {
|
---|
3888 | if ($$rectype == $reverse_typemap{PTR}) {
|
---|
3889 | $fields .= ",domain_id";
|
---|
3890 | push @vallist, 0;
|
---|
3891 | }
|
---|
3892 | if ($$rectype == $reverse_typemap{A} || $$rectype == $reverse_typemap{AAAA}) {
|
---|
3893 | $fields .= ",rdns_id";
|
---|
3894 | push @vallist, 0;
|
---|
3895 | }
|
---|
3896 | }
|
---|
3897 | # fix fat-finger-originated record type changes
|
---|
3898 | if ($$rectype == 65285) {
|
---|
3899 | $fields .= ",rdns_id" if $revrec eq 'n';
|
---|
3900 | $fields .= ",domain_id" if $revrec eq 'y';
|
---|
3901 | push @vallist, 0;
|
---|
3902 | }
|
---|
3903 | if ($defrec eq 'n') {
|
---|
3904 | $domid = $parid if $revrec eq 'n';
|
---|
3905 | $revid = $parid if $revrec eq 'y';
|
---|
3906 | }
|
---|
3907 |
|
---|
3908 | # Put together the success log entry. Horrible kludge from addRec() copied as-is since
|
---|
3909 | # we don't know whether the passed arguments or retrieved values for domain_id and rdns_id
|
---|
3910 | # will be maintained (due to "not-in-zone" validation changes)
|
---|
3911 | my %logdata;
|
---|
3912 | $logdata{domain_id} = $domid;
|
---|
3913 | $logdata{rdns_id} = $revid;
|
---|
3914 | my @ftmp = split /,/, $fields;
|
---|
3915 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
3916 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
3917 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
3918 | }
|
---|
3919 | $logdata{group_id} = $parid if $defrec eq 'y';
|
---|
3920 | $logdata{group_id} = $self->parentID(id => $parid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec)
|
---|
3921 | if $defrec eq 'n';
|
---|
3922 | $logdata{entry} = "Updated ".($defrec eq 'y' ? 'default record' : 'record')." from\n";
|
---|
3923 | # NS records for revzones get special treatment
|
---|
3924 | if ($revrec eq 'y' && $$rectype == 2) {
|
---|
3925 | $logdata{entry} .= " '$oldrec->{val} $typemap{$oldrec->{type}} $oldrec->{host}";
|
---|
3926 | } else {
|
---|
3927 | $logdata{entry} .= " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
3928 | }
|
---|
3929 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
3930 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
3931 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
3932 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
3933 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location};
|
---|
3934 | $logdata{entry} .= "\nto\n";
|
---|
3935 | # More NS special
|
---|
3936 | if ($revrec eq 'y' && $$rectype == 2) {
|
---|
3937 | $logdata{entry} .= "'$$val $typemap{$$rectype} $$host";
|
---|
3938 | } else {
|
---|
3939 | $logdata{entry} .= "'$$host $typemap{$$rectype} $$val";
|
---|
3940 | }
|
---|
3941 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
3942 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$$rectype} eq 'SRV';
|
---|
3943 | $logdata{entry} .= "', TTL $ttl";
|
---|
3944 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location;
|
---|
3945 |
|
---|
3946 | local $dbh->{AutoCommit} = 0;
|
---|
3947 | local $dbh->{RaiseError} = 1;
|
---|
3948 |
|
---|
3949 | # Fiddle the field list into something suitable for updates
|
---|
3950 | $fields =~ s/,/=?,/g;
|
---|
3951 | $fields .= "=?";
|
---|
3952 |
|
---|
3953 | eval {
|
---|
3954 | $dbh->do("UPDATE "._rectable($defrec,$revrec)." SET $fields WHERE record_id=?", undef, (@vallist, $id) );
|
---|
3955 | $self->_log(%logdata);
|
---|
3956 | $dbh->commit;
|
---|
3957 | };
|
---|
3958 | if ($@) {
|
---|
3959 | my $msg = $@;
|
---|
3960 | eval { $dbh->rollback; };
|
---|
3961 | if ($config{log_failures}) {
|
---|
3962 | $logdata{entry} = "Failed updating ".($defrec eq 'y' ? 'default ' : '').
|
---|
3963 | "record '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
3964 | $self->_log(%logdata);
|
---|
3965 | $dbh->commit;
|
---|
3966 | }
|
---|
3967 | return ('FAIL', $msg);
|
---|
3968 | }
|
---|
3969 |
|
---|
3970 | $resultstr = $logdata{entry};
|
---|
3971 | return ($retcode, $retmsg);
|
---|
3972 | } # end updateRec()
|
---|
3973 |
|
---|
3974 |
|
---|
3975 | ## DNSDB::downconvert()
|
---|
3976 | # A mostly internal (not exported) semiutilty sub to downconvert from pseudotype <x>
|
---|
3977 | # to a compatible component type. Only a handful of operations are valid, anything
|
---|
3978 | # else is a null-op.
|
---|
3979 | # Takes the record ID and the new type. Returns boolean.
|
---|
3980 | sub downconvert {
|
---|
3981 | my $self = shift;
|
---|
3982 | my $dbh = $self->{dbh};
|
---|
3983 | my $recid = shift;
|
---|
3984 | my $newtype = shift;
|
---|
3985 |
|
---|
3986 | # also, only work on live records; little to no value trying to do this on default records.
|
---|
3987 | my $rec = $self->getRecLine('n', 'y', $recid);
|
---|
3988 |
|
---|
3989 | # hm?
|
---|
3990 | #return 1 if !$rec;
|
---|
3991 |
|
---|
3992 | return 1 if $rec->{type} < 65000; # Only the reverse-record pseudotypes can be downconverted
|
---|
3993 | return 1 if $rec->{type} == 65282; # Nowhere to go
|
---|
3994 |
|
---|
3995 | my $delpar;
|
---|
3996 | my @sqlargs;
|
---|
3997 | if ($rec->{type} == 65280) {
|
---|
3998 | return 1 if $newtype != 1 && $newtype != 12;
|
---|
3999 | $delpar = ($newtype == 1 ? 'rdns_id' : 'domain_id');
|
---|
4000 | push @sqlargs, 0, $newtype, $recid;
|
---|
4001 | } elsif ($rec->{type} == 65281) {
|
---|
4002 | return 1 if $newtype != 28 && $newtype != 12;
|
---|
4003 | $delpar = ($newtype == 28 ? 'rdns_id' : 'domain_id');
|
---|
4004 | push @sqlargs, 0, $newtype, $recid;
|
---|
4005 | } elsif ($rec->{type} == 65283) {
|
---|
4006 | return 1 if $newtype != 65282;
|
---|
4007 | $delpar = 'rdns_id';
|
---|
4008 | } elsif ($rec->{type} == 65284) {
|
---|
4009 | return 1 if $newtype != 65282;
|
---|
4010 | $delpar = 'rdns_id';
|
---|
4011 | } else {
|
---|
4012 | # Your llama is on fire.
|
---|
4013 | }
|
---|
4014 |
|
---|
4015 | local $dbh->{AutoCommit} = 0;
|
---|
4016 | local $dbh->{RaiseError} = 1;
|
---|
4017 |
|
---|
4018 | eval {
|
---|
4019 | $dbh->do("UPDATE records SET $delpar = ?, type = ? WHERE record_id = ?", undef, @sqlargs);
|
---|
4020 | $dbh->commit;
|
---|
4021 | };
|
---|
4022 | if ($@) {
|
---|
4023 | $errstr = $@;
|
---|
4024 | eval { $dbh->rollback; };
|
---|
4025 | return 0;
|
---|
4026 | }
|
---|
4027 | return 1;
|
---|
4028 | } # end downconvert()
|
---|
4029 |
|
---|
4030 |
|
---|
4031 | ## DNSDB::delRec()
|
---|
4032 | # Delete a record.
|
---|
4033 | sub delRec {
|
---|
4034 | $errstr = '';
|
---|
4035 | my $self = shift;
|
---|
4036 | my $dbh = $self->{dbh};
|
---|
4037 | my $defrec = shift;
|
---|
4038 | my $revrec = shift;
|
---|
4039 | my $id = shift;
|
---|
4040 |
|
---|
4041 | my $oldrec = $self->getRecLine($defrec, $revrec, $id);
|
---|
4042 |
|
---|
4043 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
4044 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
4045 | local $dbh->{AutoCommit} = 0;
|
---|
4046 | local $dbh->{RaiseError} = 1;
|
---|
4047 |
|
---|
4048 | # Put together the log entry
|
---|
4049 | my %logdata;
|
---|
4050 | $logdata{domain_id} = $oldrec->{domain_id};
|
---|
4051 | $logdata{rdns_id} = $oldrec->{rdns_id};
|
---|
4052 | $logdata{group_id} = $oldrec->{group_id} if $defrec eq 'y';
|
---|
4053 | $logdata{group_id} = $self->parentID(id => $oldrec->{domain_id}, type => ($revrec eq 'n' ? 'domain' : 'revzone'),
|
---|
4054 | revrec => $revrec)
|
---|
4055 | if $defrec eq 'n';
|
---|
4056 | $logdata{entry} = "Deleted ".($defrec eq 'y' ? 'default record ' : 'record ').
|
---|
4057 | "'$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
4058 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
4059 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
4060 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
4061 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
4062 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location};
|
---|
4063 |
|
---|
4064 | eval {
|
---|
4065 | my $sth = $dbh->do("DELETE FROM "._rectable($defrec,$revrec)." WHERE record_id=?", undef, ($id));
|
---|
4066 | $self->_log(%logdata);
|
---|
4067 | $dbh->commit;
|
---|
4068 | };
|
---|
4069 | if ($@) {
|
---|
4070 | my $msg = $@;
|
---|
4071 | eval { $dbh->rollback; };
|
---|
4072 | if ($config{log_failures}) {
|
---|
4073 | $logdata{entry} = "Error deleting ".($defrec eq 'y' ? 'default record' : 'record').
|
---|
4074 | " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
4075 | $self->_log(%logdata);
|
---|
4076 | $dbh->commit;
|
---|
4077 | }
|
---|
4078 | return ('FAIL', $msg);
|
---|
4079 | }
|
---|
4080 |
|
---|
4081 | return ('OK',$logdata{entry});
|
---|
4082 | } # end delRec()
|
---|
4083 |
|
---|
4084 |
|
---|
4085 | ## DNSDB::getLogCount()
|
---|
4086 | # Get a count of log entries
|
---|
4087 | # Takes a database handle and a hash containing at least:
|
---|
4088 | # - Entity ID and entity type as the primary log "slice"
|
---|
4089 | sub getLogCount {
|
---|
4090 | my $self = shift;
|
---|
4091 | my $dbh = $self->{dbh};
|
---|
4092 |
|
---|
4093 | my %args = @_;
|
---|
4094 |
|
---|
4095 | my @filterargs;
|
---|
4096 | ##fixme: which fields do we want to filter on?
|
---|
4097 | # push @filterargs,
|
---|
4098 |
|
---|
4099 | $errstr = 'Missing primary parent ID and/or type';
|
---|
4100 | # fail early if we don't have a "prime" ID to look for log entries for
|
---|
4101 | return if !$args{id};
|
---|
4102 |
|
---|
4103 | # or if the prime id type is missing or invalid
|
---|
4104 | return if !$args{logtype};
|
---|
4105 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
4106 | $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
|
---|
4107 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
|
---|
4108 |
|
---|
4109 | my $sql = "SELECT count(*) FROM log ".
|
---|
4110 | "WHERE $id_col{$args{logtype}}=?".
|
---|
4111 | ($args{filter} ? " AND entry ~* ?" : '');
|
---|
4112 | my ($count) = $dbh->selectrow_array($sql, undef, ($args{id}, @filterargs) );
|
---|
4113 | $errstr = $dbh->errstr if !$count;
|
---|
4114 | return $count;
|
---|
4115 | } # end getLogCount()
|
---|
4116 |
|
---|
4117 |
|
---|
4118 | ## DNSDB::getLogEntries()
|
---|
4119 | # Get a list of log entries
|
---|
4120 | # Takes arguments as with getLogCount() above, plus optional:
|
---|
4121 | # - sort field
|
---|
4122 | # - sort order
|
---|
4123 | # - offset for pagination
|
---|
4124 | sub getLogEntries {
|
---|
4125 | my $self = shift;
|
---|
4126 | my $dbh = $self->{dbh};
|
---|
4127 |
|
---|
4128 | my %args = @_;
|
---|
4129 |
|
---|
4130 | my @filterargs;
|
---|
4131 |
|
---|
4132 | # fail early if we don't have a "prime" ID to look for log entries for
|
---|
4133 | return if !$args{id};
|
---|
4134 |
|
---|
4135 | # or if the prime id type is missing or invalid
|
---|
4136 | return if !$args{logtype};
|
---|
4137 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
4138 | $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
|
---|
4139 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
|
---|
4140 |
|
---|
4141 | # Sorting defaults
|
---|
4142 | $args{sortorder} = 'DESC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
4143 | $args{sortby} = 'stamp' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
4144 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
4145 |
|
---|
4146 | my %sortmap = (fname => 'name', username => 'email', entry => 'entry', stamp => 'stamp');
|
---|
4147 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
4148 |
|
---|
4149 | my $sql = "SELECT user_id AS userid, email AS useremail, name AS userfname, entry AS logentry, ".
|
---|
4150 | "date_trunc('second',stamp) AS logtime ".
|
---|
4151 | "FROM log ".
|
---|
4152 | "WHERE $id_col{$args{logtype}}=?".
|
---|
4153 | ($args{filter} ? " AND entry ~* ?" : '').
|
---|
4154 | " ORDER BY $args{sortby} $args{sortorder}, log_id $args{sortorder}".
|
---|
4155 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
4156 | my $loglist = $dbh->selectall_arrayref($sql, { Slice => {} }, ($args{id}, @filterargs) );
|
---|
4157 | $errstr = $dbh->errstr if !$loglist;
|
---|
4158 | return $loglist;
|
---|
4159 | } # end getLogEntries()
|
---|
4160 |
|
---|
4161 |
|
---|
4162 | ## IPDB::getRevPattern()
|
---|
4163 | # Get the narrowest template pattern applicable to a passed CIDR address (may be a netblock or an IP)
|
---|
4164 | sub getRevPattern {
|
---|
4165 | my $self = shift;
|
---|
4166 | my $dbh = $self->{dbh};
|
---|
4167 | my $cidr = shift;
|
---|
4168 | my $group = shift || 1; # just in case
|
---|
4169 |
|
---|
4170 | # for speed! Casting and comparing even ~7K records takes ~2.5s, so narrow it down to one revzone first.
|
---|
4171 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >>= ? AND group_id = ?",
|
---|
4172 | undef, ($cidr, $group) );
|
---|
4173 |
|
---|
4174 | ##fixme? may need to narrow things down more by octet-chopping and doing text comparisons before casting.
|
---|
4175 | my ($revpatt) = $dbh->selectrow_array("SELECT host FROM records ".
|
---|
4176 | "WHERE (type in (12,65280,65281,65282,65283,65284)) AND rdns_id = ? AND CAST (val AS inet) >>= ? ".
|
---|
4177 | "ORDER BY CAST (val AS inet) DESC LIMIT 1", undef, ($revid, $cidr) );
|
---|
4178 | return $revpatt;
|
---|
4179 | } # end getRevPattern()
|
---|
4180 |
|
---|
4181 |
|
---|
4182 | ## DNSDB::getTypelist()
|
---|
4183 | # Get a list of record types for various UI dropdowns
|
---|
4184 | # Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A)
|
---|
4185 | # Returns an arrayref to list of hashrefs perfect for HTML::Template
|
---|
4186 | sub getTypelist {
|
---|
4187 | my $self = shift;
|
---|
4188 | my $dbh = $self->{dbh};
|
---|
4189 | my $recgroup = shift;
|
---|
4190 | my $type = shift || $reverse_typemap{A};
|
---|
4191 |
|
---|
4192 | # also accepting $webvar{revrec}!
|
---|
4193 | $recgroup = 'f' if $recgroup eq 'n';
|
---|
4194 | $recgroup = 'r' if $recgroup eq 'y';
|
---|
4195 |
|
---|
4196 | my $sql = "SELECT val,name FROM rectypes WHERE ";
|
---|
4197 | if ($recgroup eq 'r') {
|
---|
4198 | # reverse zone types
|
---|
4199 | $sql .= "stdflag=2 OR stdflag=3";
|
---|
4200 | } elsif ($recgroup eq 'l') {
|
---|
4201 | # DNS lookup types. Note we avoid our custom types >= 65280, since those are entirely internal.
|
---|
4202 | $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280";
|
---|
4203 | } else {
|
---|
4204 | # default; forward zone types. technically $type eq 'f' but not worth the error message.
|
---|
4205 | $sql .= "stdflag=1 OR stdflag=2";
|
---|
4206 | $sql .= " AND val < 65280" if $recgroup eq 'fo'; # An extra flag to trim off the pseudotypes as well.
|
---|
4207 | }
|
---|
4208 | $sql .= " ORDER BY listorder";
|
---|
4209 |
|
---|
4210 | my $sth = $dbh->prepare($sql);
|
---|
4211 | $sth->execute;
|
---|
4212 | my @typelist;
|
---|
4213 | while (my ($rval,$rname) = $sth->fetchrow_array()) {
|
---|
4214 | my %row = ( recval => $rval, recname => $rname );
|
---|
4215 | $row{tselect} = 1 if $rval == $type;
|
---|
4216 | push @typelist, \%row;
|
---|
4217 | }
|
---|
4218 |
|
---|
4219 | # Add SOA on lookups since it's not listed in other dropdowns.
|
---|
4220 | if ($recgroup eq 'l') {
|
---|
4221 | my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
|
---|
4222 | $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
|
---|
4223 | push @typelist, \%row;
|
---|
4224 | }
|
---|
4225 |
|
---|
4226 | return \@typelist;
|
---|
4227 | } # end getTypelist()
|
---|
4228 |
|
---|
4229 |
|
---|
4230 | ## DNSDB::parentID()
|
---|
4231 | # Get ID of entity that is nearest parent to requested id
|
---|
4232 | # Takes a database handle and a hash of entity ID, entity type, optional parent type flag
|
---|
4233 | # (domain/reverse zone or group), and optional default/live and forward/reverse flags
|
---|
4234 | # Returns the ID or undef on failure
|
---|
4235 | sub parentID {
|
---|
4236 | my $self = shift;
|
---|
4237 | my $dbh = $self->{dbh};
|
---|
4238 |
|
---|
4239 | my %args = @_;
|
---|
4240 |
|
---|
4241 | # clean up the parent-type. Set it to group if not set; coerce revzone to domain for simpler logic
|
---|
4242 | $args{partype} = 'group' if !$args{partype};
|
---|
4243 | $args{partype} = 'domain' if $args{partype} eq 'revzone';
|
---|
4244 |
|
---|
4245 | # clean up defrec and revrec. default to live record, forward zone
|
---|
4246 | $args{defrec} = 'n' if !$args{defrec};
|
---|
4247 | $args{revrec} = 'n' if !$args{revrec};
|
---|
4248 |
|
---|
4249 | if ($par_type{$args{partype}} eq 'domain') {
|
---|
4250 | # only live records can have a domain/zone parent
|
---|
4251 | return unless ($args{type} eq 'record' && $args{defrec} eq 'n');
|
---|
4252 | my $result = $dbh->selectrow_hashref("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
4253 | " FROM records WHERE record_id = ?",
|
---|
4254 | undef, ($args{id}) ) or return;
|
---|
4255 | return $result;
|
---|
4256 | } else {
|
---|
4257 | # snag some arguments that will either fall through or be overwritten to save some code duplication
|
---|
4258 | my $tmpid = $args{id};
|
---|
4259 | my $type = $args{type};
|
---|
4260 | if ($type eq 'record' && $args{defrec} eq 'n') {
|
---|
4261 | # Live records go through the records table first.
|
---|
4262 | ($tmpid) = $dbh->selectrow_array("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
4263 | " FROM records WHERE record_id = ?",
|
---|
4264 | undef, ($args{id}) ) or return;
|
---|
4265 | $type = ($args{revrec} eq 'n' ? 'domain' : 'revzone');
|
---|
4266 | }
|
---|
4267 | my ($result) = $dbh->selectrow_array("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
|
---|
4268 | undef, ($tmpid) );
|
---|
4269 | return $result;
|
---|
4270 | }
|
---|
4271 | # should be impossible to get here with even remotely sane arguments
|
---|
4272 | return;
|
---|
4273 | } # end parentID()
|
---|
4274 |
|
---|
4275 |
|
---|
4276 | ## DNSDB::isParent()
|
---|
4277 | # Returns true if $id1 is a parent of $id2, false otherwise
|
---|
4278 | sub isParent {
|
---|
4279 | my $self = shift;
|
---|
4280 | my $dbh = $self->{dbh};
|
---|
4281 | my $id1 = shift;
|
---|
4282 | my $type1 = shift;
|
---|
4283 | my $id2 = shift;
|
---|
4284 | my $type2 = shift;
|
---|
4285 | ##todo: immediate, secondary, full (default)
|
---|
4286 |
|
---|
4287 | # Return false on invalid types
|
---|
4288 | return 0 if !grep /^$type1$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
4289 | return 0 if !grep /^$type2$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
4290 |
|
---|
4291 | # Return false on impossible relations
|
---|
4292 | return 0 if $type1 eq 'record'; # nothing may be a child of a record
|
---|
4293 | return 0 if $type1 eq 'defrec'; # nothing may be a child of a record
|
---|
4294 | return 0 if $type1 eq 'defrevrec'; # nothing may be a child of a record
|
---|
4295 | return 0 if $type1 eq 'user'; # nothing may be child of a user
|
---|
4296 | return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record
|
---|
4297 | return 0 if $type1 eq 'revzone' && $type2 ne 'record';# reverse zone may not be a parent of anything other than a record
|
---|
4298 |
|
---|
4299 | # ennnhhhh.... if we're passed an id of 0, it will never be found. usual
|
---|
4300 | # case would be the UI creating a new <thing>, and so we don't have an ID for
|
---|
4301 | # <thing> to look up yet. in that case the UI should check the parent as well.
|
---|
4302 | return 0 if $id1 == 0; # nothing can have a parent id of 0
|
---|
4303 | return 1 if $id2 == 0; # anything could have a child id of 0 (or "unknown")
|
---|
4304 |
|
---|
4305 | # group 1 is the ultimate root parent
|
---|
4306 | return 1 if $type1 eq 'group' && $id1 == 1;
|
---|
4307 |
|
---|
4308 | # groups are always (a) parent of themselves
|
---|
4309 | return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2;
|
---|
4310 |
|
---|
4311 | my $id = $id2;
|
---|
4312 | my $type = $type2;
|
---|
4313 | my $foundparent = 0;
|
---|
4314 |
|
---|
4315 | # Records are the only entity with two possible parents. We need to split the parent checks on
|
---|
4316 | # domain/rdns.
|
---|
4317 | if ($type eq 'record') {
|
---|
4318 | my ($dom,$rdns) = $dbh->selectrow_array("SELECT domain_id,rdns_id FROM records WHERE record_id=?",
|
---|
4319 | undef, ($id));
|
---|
4320 | # check immediate parent against request
|
---|
4321 | return 1 if $type1 eq 'domain' && $id1 == $dom;
|
---|
4322 | return 1 if $type1 eq 'revzone' && $id1 == $rdns;
|
---|
4323 | # if request is group, check *both* parents. Only check if the parent is nonzero though.
|
---|
4324 | return 1 if $dom && $self->isParent($id1, $type1, $dom, 'domain');
|
---|
4325 | return 1 if $rdns && $self->isParent($id1, $type1, $rdns, 'revzone');
|
---|
4326 | # exit here since we've executed the loop below by proxy in the above recursive calls.
|
---|
4327 | return 0;
|
---|
4328 | }
|
---|
4329 |
|
---|
4330 | # almost the same loop as getParents() above
|
---|
4331 | my $limiter = 0;
|
---|
4332 | while (1) {
|
---|
4333 | my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
|
---|
4334 | my $result = $dbh->selectrow_hashref($sql,
|
---|
4335 | undef, ($id) );
|
---|
4336 | if (!$result) {
|
---|
4337 | $limiter++;
|
---|
4338 | ##fixme: how often will this happen on a live site? fail at max limiter <n>?
|
---|
4339 | warn "no results looking for $sql with id $id (depth $limiter)\n";
|
---|
4340 | last;
|
---|
4341 | }
|
---|
4342 | if ($result && $result->{$par_col{$type}} == $id1) {
|
---|
4343 | $foundparent = 1;
|
---|
4344 | last;
|
---|
4345 | } else {
|
---|
4346 | ##fixme: do we care about trying to return a "no such record/domain/user/group" error?
|
---|
4347 | # should be impossible to create an inconsistent DB just with API calls.
|
---|
4348 | warn $dbh->errstr." $sql, $id" if $dbh->errstr;
|
---|
4349 | }
|
---|
4350 | # group 1 is its own parent. need this here more to break strange loops than for detecting a parent
|
---|
4351 | last if $result->{$par_col{$type}} == 1;
|
---|
4352 | $id = $result->{$par_col{$type}};
|
---|
4353 | $type = $par_type{$type};
|
---|
4354 | }
|
---|
4355 |
|
---|
4356 | return $foundparent;
|
---|
4357 | } # end isParent()
|
---|
4358 |
|
---|
4359 |
|
---|
4360 | ## DNSDB::zoneStatus()
|
---|
4361 | # Returns and optionally sets a zone's status
|
---|
4362 | # Takes a database handle, domain/revzone ID, forward/reverse flag, and optionally a status argument
|
---|
4363 | # Returns status, or undef on errors.
|
---|
4364 | sub zoneStatus {
|
---|
4365 | my $self = shift;
|
---|
4366 | my $dbh = $self->{dbh};
|
---|
4367 | my $id = shift;
|
---|
4368 | my $revrec = shift;
|
---|
4369 | my $newstatus = shift || 'mu';
|
---|
4370 |
|
---|
4371 | return undef if $id !~ /^\d+$/;
|
---|
4372 |
|
---|
4373 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
4374 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
4375 | local $dbh->{AutoCommit} = 0;
|
---|
4376 | local $dbh->{RaiseError} = 1;
|
---|
4377 |
|
---|
4378 | if ($newstatus ne 'mu') {
|
---|
4379 | # ooo, fun! let's see what we were passed for status
|
---|
4380 | eval {
|
---|
4381 | $newstatus = 0 if $newstatus eq 'domoff';
|
---|
4382 | $newstatus = 1 if $newstatus eq 'domon';
|
---|
4383 | $dbh->do("UPDATE ".($revrec eq 'n' ? 'domains' : 'revzones')." SET status=? WHERE ".
|
---|
4384 | ($revrec eq 'n' ? 'domain_id' : 'rdns_id')."=?", undef, ($newstatus,$id) );
|
---|
4385 |
|
---|
4386 | ##fixme switch to more consise "Enabled <domain"/"Disabled <domain>" as with users?
|
---|
4387 | $resultstr = "Changed ".($revrec eq 'n' ? $self->domainName($id) : $self->revName($id)).
|
---|
4388 | " state to ".($newstatus ? 'active' : 'inactive');
|
---|
4389 |
|
---|
4390 | my %loghash;
|
---|
4391 | $loghash{domain_id} = $id if $revrec eq 'n';
|
---|
4392 | $loghash{rdns_id} = $id if $revrec eq 'y';
|
---|
4393 | $loghash{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec);
|
---|
4394 | $loghash{entry} = $resultstr;
|
---|
4395 | $self->_log(%loghash);
|
---|
4396 |
|
---|
4397 | $dbh->commit;
|
---|
4398 | };
|
---|
4399 | if ($@) {
|
---|
4400 | my $msg = $@;
|
---|
4401 | eval { $dbh->rollback; };
|
---|
4402 | $resultstr = '';
|
---|
4403 | $errstr = $msg;
|
---|
4404 | return;
|
---|
4405 | }
|
---|
4406 | }
|
---|
4407 |
|
---|
4408 | my ($status) = $dbh->selectrow_array("SELECT status FROM ".
|
---|
4409 | ($revrec eq 'n' ? "domains WHERE domain_id=?" : "revzones WHERE rdns_id=?"),
|
---|
4410 | undef, ($id) );
|
---|
4411 | return $status;
|
---|
4412 | } # end zoneStatus()
|
---|
4413 |
|
---|
4414 |
|
---|
4415 | ## DNSDB::getZonesByCIDR()
|
---|
4416 | # Get a list of zone names and IDs that records for a passed CIDR block are within.
|
---|
4417 | sub getZonesByCIDR {
|
---|
4418 | my $self = shift;
|
---|
4419 | my $dbh = $self->{dbh};
|
---|
4420 | my %args = @_;
|
---|
4421 |
|
---|
4422 | my $result = $dbh->selectall_arrayref("SELECT rdns_id,revnet FROM revzones WHERE revnet >>= ? OR revnet <<= ?",
|
---|
4423 | { Slice => {} }, ($args{cidr}, $args{cidr}) );
|
---|
4424 | return $result;
|
---|
4425 | } # end getZonesByCIDR()
|
---|
4426 |
|
---|
4427 |
|
---|
4428 | ## DNSDB::importAXFR
|
---|
4429 | # Import a domain via AXFR
|
---|
4430 | # Takes AXFR host, domain to transfer, group to put the domain in,
|
---|
4431 | # and an optional hash containing:
|
---|
4432 | # status - active/inactive state flag (defaults to active)
|
---|
4433 | # rwsoa - overwrite-SOA flag (defaults to off)
|
---|
4434 | # rwns - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
|
---|
4435 | # merge - flag to automerge A or AAAA records with matching PTR records
|
---|
4436 | # Returns a status code (OK, WARN, or FAIL) and message - message should be blank
|
---|
4437 | # if status is OK, but WARN includes conditions that are not fatal but should
|
---|
4438 | # really be reported.
|
---|
4439 | sub importAXFR {
|
---|
4440 | my $self = shift;
|
---|
4441 | my $dbh = $self->{dbh};
|
---|
4442 | my $ifrom_in = shift;
|
---|
4443 | my $zone = shift;
|
---|
4444 | my $group = shift;
|
---|
4445 |
|
---|
4446 | my %args = @_;
|
---|
4447 |
|
---|
4448 | ##fixme: add mode to delete&replace, merge+overwrite, merge new?
|
---|
4449 |
|
---|
4450 | $args{status} = (defined($args{status}) ? $args{status} : 0);
|
---|
4451 | $args{status} = 1 if $args{status} eq 'on';
|
---|
4452 |
|
---|
4453 | my $nrecs = 0;
|
---|
4454 | my $soaflag = 0;
|
---|
4455 | my $nsflag = 0;
|
---|
4456 | my $warnmsg = '';
|
---|
4457 | my $ifrom;
|
---|
4458 |
|
---|
4459 | my $rev = 'n';
|
---|
4460 | my $code = 'OK';
|
---|
4461 | my $msg = 'foobar?';
|
---|
4462 |
|
---|
4463 | # choke on possible bad setting in ifrom
|
---|
4464 | # IPv4 and v6, and valid hostnames!
|
---|
4465 | ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
4466 | return ('FAIL', "Bad AXFR source host $ifrom")
|
---|
4467 | unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
4468 |
|
---|
4469 | my $errmsg;
|
---|
4470 |
|
---|
4471 | my $zone_id;
|
---|
4472 | my $domain_id = 0;
|
---|
4473 | my $rdns_id = 0;
|
---|
4474 | my $cidr;
|
---|
4475 |
|
---|
4476 | # magic happens! detect if we're importing a domain or a reverse zone
|
---|
4477 | # while we're at it, figure out what the CIDR netblock is (if we got a .arpa)
|
---|
4478 | # or what the formal .arpa zone is (if we got a CIDR netblock)
|
---|
4479 | # Handles sub-octet v4 zones in the format specified in the Cricket Book, 2nd Ed, p217-218
|
---|
4480 |
|
---|
4481 | if ($zone =~ m{(?:\.arpa\.?|/\d+)$}) {
|
---|
4482 | # we seem to have a reverse zone
|
---|
4483 | $rev = 'y';
|
---|
4484 |
|
---|
4485 | if ($zone =~ /\.arpa\.?$/) {
|
---|
4486 | # we have a formal reverse zone. call _zone2cidr and get the CIDR block.
|
---|
4487 | ($code,$msg) = _zone2cidr($zone);
|
---|
4488 | return ($code, $msg) if $code eq 'FAIL';
|
---|
4489 | $cidr = $msg;
|
---|
4490 | } elsif ($zone =~ m|^[\d.]+/\d+$|) {
|
---|
4491 | # v4 revzone, CIDR netblock
|
---|
4492 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
4493 | $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
4494 | } elsif ($zone =~ m|^[a-fA-F\d:]+/\d+$|) {
|
---|
4495 | # v6 revzone, CIDR netblock
|
---|
4496 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
4497 | return ('FAIL', "$zone is not a nibble-aligned block") if $cidr->masklen % 4 != 0;
|
---|
4498 | $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.');
|
---|
4499 | } else {
|
---|
4500 | # there is. no. else!
|
---|
4501 | return ('FAIL', "Unknown zone name format");
|
---|
4502 | }
|
---|
4503 |
|
---|
4504 | # quick check to start to see if we've already got one
|
---|
4505 |
|
---|
4506 | ($zone_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?",
|
---|
4507 | undef, ("$cidr"));
|
---|
4508 | $rdns_id = $zone_id;
|
---|
4509 | } else {
|
---|
4510 | # default to domain
|
---|
4511 | ($zone_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
4512 | undef, ($zone));
|
---|
4513 | $domain_id = $zone_id;
|
---|
4514 | }
|
---|
4515 |
|
---|
4516 | return ('FAIL', ($rev eq 'n' ? 'Domain' : 'Reverse zone')." already exists") if $zone_id;
|
---|
4517 |
|
---|
4518 | # little local utility sub to swap $val and $host for revzone records.
|
---|
4519 | sub _revswap {
|
---|
4520 | my $rechost = shift;
|
---|
4521 | my $recdata = shift;
|
---|
4522 |
|
---|
4523 | if ($rechost =~ /\.in-addr\.arpa\.?$/) {
|
---|
4524 | $rechost =~ s/\.in-addr\.arpa\.?$//;
|
---|
4525 | $rechost = join '.', reverse split /\./, $rechost;
|
---|
4526 | } else {
|
---|
4527 | $rechost =~ s/\.ip6\.arpa\.?$//;
|
---|
4528 | my @nibs = reverse split /\./, $rechost;
|
---|
4529 | $rechost = '';
|
---|
4530 | my $nc;
|
---|
4531 | foreach (@nibs) {
|
---|
4532 | $rechost.= $_;
|
---|
4533 | $rechost .= ":" if ++$nc % 4 == 0 && $nc < 32;
|
---|
4534 | }
|
---|
4535 | $rechost .= ":" if $nc < 32 && $rechost !~ /\*$/; # close netblock records?
|
---|
4536 | ##fixme: there's a case that ends up with a partial entry here:
|
---|
4537 | # ip:add:re:ss::
|
---|
4538 | # can't reproduce after letting it sit overnight after discovery. :(
|
---|
4539 | #print "$rechost\n";
|
---|
4540 | # canonicalize with NetAddr::IP
|
---|
4541 | $rechost = NetAddr::IP->new($rechost)->addr unless $rechost =~ /\*$/;
|
---|
4542 | }
|
---|
4543 | return ($recdata,$rechost)
|
---|
4544 | }
|
---|
4545 |
|
---|
4546 |
|
---|
4547 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
4548 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
4549 | local $dbh->{AutoCommit} = 0;
|
---|
4550 | local $dbh->{RaiseError} = 1;
|
---|
4551 |
|
---|
4552 | my $sth;
|
---|
4553 | eval {
|
---|
4554 |
|
---|
4555 | if ($rev eq 'n') {
|
---|
4556 | ##fixme: serial
|
---|
4557 | $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef,
|
---|
4558 | ($zone, $group, $args{status}) );
|
---|
4559 | # get domain id so we can do the records
|
---|
4560 | ($zone_id) = $dbh->selectrow_array("SELECT currval('domains_domain_id_seq')");
|
---|
4561 | $domain_id = $zone_id;
|
---|
4562 | $self->_log(group_id => $group, domain_id => $domain_id,
|
---|
4563 | entry => "[Added ".($args{status} ? 'active' : 'inactive')." domain $zone via AXFR]");
|
---|
4564 | } else {
|
---|
4565 | ##fixme: serial
|
---|
4566 | $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef,
|
---|
4567 | ($cidr,$group,$args{status}) );
|
---|
4568 | # get revzone id so we can do the records
|
---|
4569 | ($zone_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
4570 | $rdns_id = $zone_id;
|
---|
4571 | $self->_log(group_id => $group, rdns_id => $rdns_id,
|
---|
4572 | entry => "[Added ".($args{status} ? 'active' : 'inactive')." reverse zone $cidr via AXFR]");
|
---|
4573 | }
|
---|
4574 |
|
---|
4575 | ## bizarre DBI<->Net::DNS interaction bug:
|
---|
4576 | ## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
|
---|
4577 | ## fixed, apparently I was doing *something* odd, but not certain what it was that
|
---|
4578 | ## caused a commit instead of barfing
|
---|
4579 |
|
---|
4580 | my $res = Net::DNS::Resolver->new;
|
---|
4581 | $res->nameservers($ifrom);
|
---|
4582 | $res->axfr_start($zone)
|
---|
4583 | or die "Couldn't begin AXFR\n";
|
---|
4584 |
|
---|
4585 | $sth = $dbh->prepare("INSERT INTO records (domain_id,rdns_id,host,type,val,distance,weight,port,ttl)".
|
---|
4586 | " VALUES (?,?,?,?,?,?,?,?,?)");
|
---|
4587 |
|
---|
4588 | # Stash info about sub-octet v4 revzones here so we don't have
|
---|
4589 | # to store the CNAMEs used to delegate a suboctet zone
|
---|
4590 | # $suboct{zone}{ns}[] -> array of nameservers
|
---|
4591 | # $suboct{zone}{cname}[] -> array of extant CNAMEs (Just In Case someone did something bizarre)
|
---|
4592 | ## commented pending actual use of this data. for now, we'll just
|
---|
4593 | ## auto-(re)create the CNAMEs in revzones on export
|
---|
4594 | # my %suboct;
|
---|
4595 |
|
---|
4596 | while (my $rr = $res->axfr_next()) {
|
---|
4597 |
|
---|
4598 | my $val;
|
---|
4599 | my $distance = 0;
|
---|
4600 | my $weight = 0;
|
---|
4601 | my $port = 0;
|
---|
4602 | my $logfrag = '';
|
---|
4603 |
|
---|
4604 | my $type = $rr->type;
|
---|
4605 | my $host = $rr->name;
|
---|
4606 | my $ttl = ($args{newttl} ? $args{newttl} : $rr->ttl); # allow force-override TTLs
|
---|
4607 |
|
---|
4608 | $soaflag = 1 if $type eq 'SOA';
|
---|
4609 | $nsflag = 1 if $type eq 'NS';
|
---|
4610 |
|
---|
4611 | # "Primary" types:
|
---|
4612 | # A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
|
---|
4613 | # maybe KEY
|
---|
4614 |
|
---|
4615 | # BIND supports:
|
---|
4616 | # [standard]
|
---|
4617 | # A AAAA CNAME MX NS PTR SOA TXT
|
---|
4618 | # [variously experimental, obsolete, or obscure]
|
---|
4619 | # 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
|
---|
4620 | # ... if one can ever find the right magic to format them correctly
|
---|
4621 |
|
---|
4622 | # Net::DNS supports:
|
---|
4623 | # RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
|
---|
4624 | # EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
|
---|
4625 | # DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
|
---|
4626 |
|
---|
4627 | # nasty big ugly case-like thing here, since we have to do *some* different
|
---|
4628 | # processing depending on the record. le sigh.
|
---|
4629 |
|
---|
4630 | ##fixme: what record types other than TXT can/will have >255-byte payloads?
|
---|
4631 |
|
---|
4632 | if ($type eq 'A') {
|
---|
4633 | $val = $rr->address;
|
---|
4634 | } elsif ($type eq 'NS') {
|
---|
4635 | # hmm. should we warn here if subdomain NS'es are left alone?
|
---|
4636 | next if ($args{rwns} && ($rr->name eq $zone));
|
---|
4637 | if ($rev eq 'y') {
|
---|
4638 | # revzones have records more or less reversed from forward zones.
|
---|
4639 | my ($tmpcode,$tmpmsg) = _zone2cidr($host);
|
---|
4640 | die "Error converting NS record: $tmpmsg\n" if $tmpcode eq 'FAIL'; # hmm. may not make sense...
|
---|
4641 | $val = "$tmpmsg";
|
---|
4642 | $host = $rr->nsdname;
|
---|
4643 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
4644 | # Tag and preserve. For now this is commented for a no-op, but we have Ideas for
|
---|
4645 | # another custom storage type ("DELEGATE") that will use these subzone-delegation records
|
---|
4646 | #if ($val ne "$cidr") {
|
---|
4647 | # push @{$suboct{$val}{ns}}, $host;
|
---|
4648 | #}
|
---|
4649 | } else {
|
---|
4650 | $val = $rr->nsdname;
|
---|
4651 | }
|
---|
4652 | $nsflag = 1;
|
---|
4653 | } elsif ($type eq 'CNAME') {
|
---|
4654 | if ($rev eq 'y') {
|
---|
4655 | # hmm. do we even want to bother with storing these at this level? Sub-octet delegation
|
---|
4656 | # by CNAME is essentially a record-publication hack, and we want to just represent the
|
---|
4657 | # "true" logical intentions as far down the stack as we can from the UI.
|
---|
4658 | ($host,$val) = _revswap($host,$rr->cname);
|
---|
4659 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
4660 | # Tag and preserve in case we want to commit them as-is later, but mostly we don't care.
|
---|
4661 | # Commented pending actually doing something with possibly new type DELEGATE
|
---|
4662 | #my $tmprev = $host;
|
---|
4663 | #$tmprev =~ s/^\d+\.//;
|
---|
4664 | #($code,$tmprev) = _zone2cidr($tmprev);
|
---|
4665 | #push @{$suboct{"$tmprev"}{cname}}, $val;
|
---|
4666 | # Silently skip CNAMEs in revzones.
|
---|
4667 | next;
|
---|
4668 | } else {
|
---|
4669 | $val = $rr->cname;
|
---|
4670 | }
|
---|
4671 | } elsif ($type eq 'SOA') {
|
---|
4672 | next if $args{rwsoa};
|
---|
4673 | $host = $rr->rname.":".$rr->mname;
|
---|
4674 | $val = $rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum;
|
---|
4675 | $soaflag = 1;
|
---|
4676 | } elsif ($type eq 'PTR') {
|
---|
4677 | ($host,$val) = _revswap($host,$rr->ptrdname);
|
---|
4678 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
4679 | # hmm. PTR records should not be in forward zones.
|
---|
4680 | } elsif ($type eq 'MX') {
|
---|
4681 | $val = $rr->exchange;
|
---|
4682 | $distance = $rr->preference;
|
---|
4683 | } elsif ($type eq 'TXT') {
|
---|
4684 | ##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
|
---|
4685 | ## but don't really seem enthusiastic about it.
|
---|
4686 | #print "should use rdatastr:\n\t".$rr->rdatastr."\n or char_str_list:\n\t".join(' ',$rr->char_str_list())."\n";
|
---|
4687 | # rdatastr returns a BIND-targetted logical string, including opening and closing quotes
|
---|
4688 | # char_str_list returns a list of the individual string fragments in the record
|
---|
4689 | # txtdata returns the more useful all-in-one form (since we want to push such protocol
|
---|
4690 | # details as far down the stack as we can)
|
---|
4691 | # NB: this may turn out to be more troublesome if we ever have need of >512-byte TXT records.
|
---|
4692 | if ($rev eq 'y') {
|
---|
4693 | ($host,$val) = _revswap($host,$rr->txtdata);
|
---|
4694 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
4695 | } else {
|
---|
4696 | $val = $rr->txtdata;
|
---|
4697 | }
|
---|
4698 | } elsif ($type eq 'SPF') {
|
---|
4699 | ##fixme: and the same caveat here, since it is apparently a clone of ::TXT
|
---|
4700 | $val = $rr->txtdata;
|
---|
4701 | } elsif ($type eq 'AAAA') {
|
---|
4702 | $val = $rr->address;
|
---|
4703 | } elsif ($type eq 'SRV') {
|
---|
4704 | $val = $rr->target;
|
---|
4705 | $distance = $rr->priority;
|
---|
4706 | $weight = $rr->weight;
|
---|
4707 | $port = $rr->port;
|
---|
4708 | } elsif ($type eq 'KEY') {
|
---|
4709 | # we don't actually know what to do with these...
|
---|
4710 | $val = $rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname;
|
---|
4711 | } else {
|
---|
4712 | $val = $rr->rdatastr;
|
---|
4713 | # Finding a different record type is not fatal.... just problematic.
|
---|
4714 | # We may not be able to export it correctly.
|
---|
4715 | $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
|
---|
4716 | }
|
---|
4717 |
|
---|
4718 | my $logentry = "[AXFR ".($rev eq 'n' ? $zone : $cidr)."] ";
|
---|
4719 |
|
---|
4720 | if ($args{merge}) {
|
---|
4721 | if ($rev eq 'n') {
|
---|
4722 | # importing a domain; we have A and AAAA records that could be merged with matching PTR records
|
---|
4723 | my $etype;
|
---|
4724 | my ($erdns,$erid,$ettl) = $dbh->selectrow_array("SELECT rdns_id,record_id,ttl FROM records ".
|
---|
4725 | "WHERE host=? AND val=? AND type=12",
|
---|
4726 | undef, ($host, $val) );
|
---|
4727 | if ($erid) {
|
---|
4728 | if ($type eq 'A') { # PTR -> A+PTR
|
---|
4729 | $etype = 65280;
|
---|
4730 | $logentry .= "Merged A record with existing PTR record '$host A+PTR $val', TTL $ettl";
|
---|
4731 | }
|
---|
4732 | if ($type eq 'AAAA') { # PTR -> AAAA+PTR
|
---|
4733 | $etype = 65281;
|
---|
4734 | $logentry .= "Merged AAAA record with existing PTR record '$host AAAA+PTR $val', TTL $ettl";
|
---|
4735 | }
|
---|
4736 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
4737 | $dbh->do("UPDATE records SET domain_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
4738 | ($domain_id, $ettl, $etype, $erid));
|
---|
4739 | $nrecs++;
|
---|
4740 | $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $erdns, entry => $logentry);
|
---|
4741 | next; # while axfr_next
|
---|
4742 | }
|
---|
4743 | } # $rev eq 'n'
|
---|
4744 | else {
|
---|
4745 | # importing a revzone, we have PTR records that could be merged with matching A/AAAA records
|
---|
4746 | my ($domid,$erid,$ettl,$etype) = $dbh->selectrow_array("SELECT domain_id,record_id,ttl,type FROM records ".
|
---|
4747 | "WHERE host=? AND val=? AND (type=1 OR type=28)",
|
---|
4748 | undef, ($host, $val) );
|
---|
4749 | if ($erid) {
|
---|
4750 | if ($etype == 1) { # A -> A+PTR
|
---|
4751 | $etype = 65280;
|
---|
4752 | $logentry .= "Merged PTR record with existing matching A record '$host A+PTR $val', TTL $ettl";
|
---|
4753 | }
|
---|
4754 | if ($etype == 28) { # AAAA -> AAAA+PTR
|
---|
4755 | $etype = 65281;
|
---|
4756 | $logentry .= "Merged PTR record with existing matching AAAA record '$host AAAA+PTR $val', TTL $ettl";
|
---|
4757 | }
|
---|
4758 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
4759 | $dbh->do("UPDATE records SET rdns_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
4760 | ($rdns_id, $ettl, $etype, $erid));
|
---|
4761 | $nrecs++;
|
---|
4762 | $self->_log(group_id => $group, domain_id => $domid, rdns_id => $rdns_id, entry => $logentry);
|
---|
4763 | next; # while axfr_next
|
---|
4764 | }
|
---|
4765 | } # $rev eq 'y'
|
---|
4766 | } # if $args{merge}
|
---|
4767 |
|
---|
4768 | # Insert the new record
|
---|
4769 | $sth->execute($domain_id, $rdns_id, $host, $reverse_typemap{$type}, $val,
|
---|
4770 | $distance, $weight, $port, $ttl);
|
---|
4771 |
|
---|
4772 | $nrecs++;
|
---|
4773 |
|
---|
4774 | if ($type eq 'SOA') {
|
---|
4775 | # also !$args{rwsoa}, but if that's set, it should be impossible to get here.
|
---|
4776 | my @tmp1 = split /:/, $host;
|
---|
4777 | my @tmp2 = split /:/, $val;
|
---|
4778 | $logentry .= "Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
4779 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl";
|
---|
4780 | } elsif ($logfrag) {
|
---|
4781 | # special case for log entries we need to meddle with a little.
|
---|
4782 | $logentry .= $logfrag;
|
---|
4783 | } else {
|
---|
4784 | $logentry .= "Added record '$host $type";
|
---|
4785 | $logentry .= " [distance $distance]" if $type eq 'MX';
|
---|
4786 | $logentry .= " [priority $distance] [weight $weight] [port $port]" if $type eq 'SRV';
|
---|
4787 | $logentry .= " $val', TTL $ttl";
|
---|
4788 | }
|
---|
4789 | $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $rdns_id, entry => $logentry);
|
---|
4790 |
|
---|
4791 | } # while axfr_next
|
---|
4792 |
|
---|
4793 | # Detect and handle delegated subzones
|
---|
4794 | # Placeholder for when we decide what to actually do with this, see previous comments in NS and CNAME handling.
|
---|
4795 | #foreach (keys %suboct) {
|
---|
4796 | # print "found ".($suboct{$_}{ns} ? @{$suboct{$_}{ns}} : '0')." NS records and ".
|
---|
4797 | # ($suboct{$_}{cname} ? @{$suboct{$_}{cname}} : '0')." CNAMEs for $_\n";
|
---|
4798 | #}
|
---|
4799 |
|
---|
4800 | # Overwrite SOA record
|
---|
4801 | if ($args{rwsoa}) {
|
---|
4802 | $soaflag = 1;
|
---|
4803 | my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
|
---|
4804 | my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
4805 | $sthgetsoa->execute($group,$reverse_typemap{SOA});
|
---|
4806 | while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
|
---|
4807 | $host =~ s/DOMAIN/$zone/g;
|
---|
4808 | $val =~ s/DOMAIN/$zone/g;
|
---|
4809 | $sthputsoa->execute($zone_id,$host,$reverse_typemap{SOA},$val,$ttl);
|
---|
4810 | }
|
---|
4811 | }
|
---|
4812 |
|
---|
4813 | # Overwrite NS records
|
---|
4814 | if ($args{rwns}) {
|
---|
4815 | $nsflag = 1;
|
---|
4816 | my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
|
---|
4817 | my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
4818 | $sthgetns->execute($group,$reverse_typemap{NS});
|
---|
4819 | while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
|
---|
4820 | $host =~ s/DOMAIN/$zone/g;
|
---|
4821 | $val =~ s/DOMAIN/$zone/g;
|
---|
4822 | $sthputns->execute($zone_id,$host,$reverse_typemap{NS},$val,$ttl);
|
---|
4823 | }
|
---|
4824 | }
|
---|
4825 |
|
---|
4826 | die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
|
---|
4827 | die "Bad zone: No SOA record!\n" if !$soaflag;
|
---|
4828 | die "Bad zone: No NS records!\n" if !$nsflag;
|
---|
4829 |
|
---|
4830 | $dbh->commit;
|
---|
4831 |
|
---|
4832 | };
|
---|
4833 |
|
---|
4834 | if ($@) {
|
---|
4835 | my $msg = $@;
|
---|
4836 | eval { $dbh->rollback; };
|
---|
4837 | return ('FAIL',$msg." $warnmsg");
|
---|
4838 | } else {
|
---|
4839 | return ('WARN', $warnmsg) if $warnmsg;
|
---|
4840 | return ('OK',"Imported OK");
|
---|
4841 | }
|
---|
4842 |
|
---|
4843 | # it should be impossible to get here.
|
---|
4844 | return ('WARN',"OOOK!");
|
---|
4845 | } # end importAXFR()
|
---|
4846 |
|
---|
4847 |
|
---|
4848 | ## DNSDB::importBIND()
|
---|
4849 | sub importBIND {
|
---|
4850 | } # end importBIND()
|
---|
4851 |
|
---|
4852 |
|
---|
4853 | ## DNSDB::import_tinydns()
|
---|
4854 | sub import_tinydns {
|
---|
4855 | } # end import_tinydns()
|
---|
4856 |
|
---|
4857 |
|
---|
4858 | ## DNSDB::export()
|
---|
4859 | # Export the DNS database, or a part of it
|
---|
4860 | # Takes a string indicating the export type, plus optional arguments depending on type
|
---|
4861 | # Writes zone data to targets as appropriate for type
|
---|
4862 | sub export {
|
---|
4863 | my $self = shift;
|
---|
4864 | my $target = shift;
|
---|
4865 |
|
---|
4866 | if ($target eq 'tiny') {
|
---|
4867 | $self->__export_tiny(@_);
|
---|
4868 | }
|
---|
4869 | # elsif ($target eq 'foo') {
|
---|
4870 | # __export_foo(@_);
|
---|
4871 | #}
|
---|
4872 | # etc
|
---|
4873 |
|
---|
4874 | } # end export()
|
---|
4875 |
|
---|
4876 |
|
---|
4877 | ## DNSDB::__export_tiny
|
---|
4878 | # Internal sub to implement tinyDNS (compatible) export
|
---|
4879 | # Takes filehandle to write export to, optional argument(s)
|
---|
4880 | # to determine which data gets exported
|
---|
4881 | sub __export_tiny {
|
---|
4882 | my $self = shift;
|
---|
4883 | my $dbh = $self->{dbh};
|
---|
4884 | my $datafile = shift;
|
---|
4885 |
|
---|
4886 | ##fixme: slurp up further options to specify particular zone(s) to export
|
---|
4887 |
|
---|
4888 | ##fixme: fail if $datafile isn't an open, writable file
|
---|
4889 |
|
---|
4890 | # easy case - export all evarything
|
---|
4891 | # not-so-easy case - export item(s) specified
|
---|
4892 | # todo: figure out what kind of list we use to export items
|
---|
4893 |
|
---|
4894 | # raw packet in unknown format: first byte indicates length
|
---|
4895 | # of remaining data, allows up to 255 raw bytes
|
---|
4896 |
|
---|
4897 | # Locations/views - worth including in the caching setup?
|
---|
4898 | my $lochash = $dbh->selectall_hashref("SELECT location,iplist FROM locations", 'location');
|
---|
4899 | foreach my $location (keys %$lochash) {
|
---|
4900 | foreach my $ipprefix (split /[,\s]+/, $lochash->{$location}{iplist}) {
|
---|
4901 | $ipprefix =~ s/\s+//g;
|
---|
4902 | $ipprefix = new NetAddr::IP $ipprefix;
|
---|
4903 | ##fixme: how to handle IPv6?
|
---|
4904 | next if $ipprefix->{isv6};
|
---|
4905 | # have to account for /nn CIDR entries. tinydns only speaks octet-sliced prefix.
|
---|
4906 | if ($ipprefix->masklen <= 8) {
|
---|
4907 | foreach ($ipprefix->split(8)) {
|
---|
4908 | my $tmp = $_->addr;
|
---|
4909 | $tmp =~ s/\.\d+\.\d+\.\d+$//;
|
---|
4910 | print $datafile "%$location:$tmp\n";
|
---|
4911 | }
|
---|
4912 | } elsif ($ipprefix->masklen <= 16) {
|
---|
4913 | foreach ($ipprefix->split(16)) {
|
---|
4914 | my $tmp = $_->addr;
|
---|
4915 | $tmp =~ s/\.\d+\.\d+$//;
|
---|
4916 | print $datafile "%$location:$tmp\n";
|
---|
4917 | }
|
---|
4918 | } elsif ($ipprefix->masklen <= 24) {
|
---|
4919 | foreach ($ipprefix->split(24)) {
|
---|
4920 | my $tmp = $_->addr;
|
---|
4921 | $tmp =~ s/\.\d+$//;
|
---|
4922 | print $datafile "%$location:$tmp\n";
|
---|
4923 | }
|
---|
4924 | } else {
|
---|
4925 | foreach ($ipprefix->split(32)) {
|
---|
4926 | print $datafile "%$location:".$_->addr."\n";
|
---|
4927 | }
|
---|
4928 | }
|
---|
4929 | }
|
---|
4930 | print $datafile "%$location\n" if !$lochash->{$location}{iplist};
|
---|
4931 | }
|
---|
4932 |
|
---|
4933 | # tracking hash so we don't double-export A+PTR or AAAA+PTR records.
|
---|
4934 | my %recflags;
|
---|
4935 |
|
---|
4936 | my $domsth = $dbh->prepare("SELECT domain_id,domain,status,changed FROM domains WHERE status=1");
|
---|
4937 | my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
4938 | "FROM records WHERE domain_id=? AND type < 65280"); # Just exclude all types relating to rDNS
|
---|
4939 | my $zonesth = $dbh->prepare("UPDATE domains SET changed='n' WHERE domain_id=?");
|
---|
4940 | $domsth->execute();
|
---|
4941 | while (my ($domid,$dom,$domstat,$changed) = $domsth->fetchrow_array) {
|
---|
4942 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
4943 | # O_NOFOLLOW
|
---|
4944 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
4945 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
4946 | # still be followed.
|
---|
4947 | # but that doesn't help other platforms. :/
|
---|
4948 | sysopen(ZONECACHE, "$config{exportcache}/$dom", O_RDWR|O_CREAT);
|
---|
4949 | flock(ZONECACHE, LOCK_EX);
|
---|
4950 | if ($changed || -s "$config{exportcache}/$dom" == 0) {
|
---|
4951 | $recsth->execute($domid);
|
---|
4952 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc) = $recsth->fetchrow_array) {
|
---|
4953 | next if $recflags{$recid};
|
---|
4954 |
|
---|
4955 | $loc = '' if !$loc; # de-nullify - just in case
|
---|
4956 | ##fixme: handle case of record-with-location-that-doesn't-exist better.
|
---|
4957 | # note this currently fails safe (tested) - records with a location that
|
---|
4958 | # doesn't exist will not be sent to any client
|
---|
4959 | # $loc = '' if !$lochash->{$loc};
|
---|
4960 |
|
---|
4961 | ##fixme: record validity timestamp. tinydns supports fiddling with timestamps.
|
---|
4962 | # note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
|
---|
4963 | # timestamps are TAI64
|
---|
4964 | # ~~ 2^62 + time()
|
---|
4965 | my $stamp = '';
|
---|
4966 |
|
---|
4967 | # support tinydns' auto-TTL
|
---|
4968 | $ttl = '' if $ttl == '0';
|
---|
4969 |
|
---|
4970 | # Spaces are evil.
|
---|
4971 | $host =~ s/^\s+//;
|
---|
4972 | $host =~ s/\s+$//;
|
---|
4973 | if ($typemap{$type} ne 'TXT') {
|
---|
4974 | # Leading or trailng spaces could be legit in TXT records.
|
---|
4975 | $val =~ s/^\s+//;
|
---|
4976 | $val =~ s/\s+$//;
|
---|
4977 | }
|
---|
4978 |
|
---|
4979 | _printrec_tiny(*ZONECACHE, 'n', \%recflags,
|
---|
4980 | $dom, $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp)
|
---|
4981 | if *ZONECACHE;
|
---|
4982 |
|
---|
4983 | # in case the zone shrunk, get rid of garbage at the end of the file.
|
---|
4984 | truncate(ZONECACHE, tell(ZONECACHE));
|
---|
4985 |
|
---|
4986 | $recflags{$recid} = 1;
|
---|
4987 | } # while ($recsth)
|
---|
4988 | }
|
---|
4989 | # stream from cache, whether freshly created or existing
|
---|
4990 | print $datafile $_ while <ZONECACHE>;
|
---|
4991 | close ZONECACHE;
|
---|
4992 | # mark domain as unmodified
|
---|
4993 | $zonesth->execute($domid);
|
---|
4994 | } # while ($domsth)
|
---|
4995 |
|
---|
4996 | my $revsth = $dbh->prepare("SELECT rdns_id,revnet,status,changed FROM revzones WHERE status=1 ".
|
---|
4997 | "ORDER BY masklen(revnet) DESC");
|
---|
4998 |
|
---|
4999 | # For reasons unknown, we can't sanely UNION these statements. Feh.
|
---|
5000 | # Supposedly it should work though (note last 3 lines):
|
---|
5001 | ## PG manual
|
---|
5002 | #UNION Clause
|
---|
5003 | #
|
---|
5004 | #The UNION clause has this general form:
|
---|
5005 | #
|
---|
5006 | # select_statement UNION [ ALL ] select_statement
|
---|
5007 | #
|
---|
5008 | #select_statement is any SELECT statement without an ORDER BY, LIMIT, FOR UPDATE, or FOR SHARE clause. (ORDER BY
|
---|
5009 | #and LIMIT can be attached to a subexpression if it is enclosed in parentheses. Without parentheses, these
|
---|
5010 | #clauses will be taken to apply to the result of the UNION, not to its right-hand input expression.)
|
---|
5011 | my $soasth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
5012 | "FROM records WHERE rdns_id=? AND type=6");
|
---|
5013 | $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
5014 | "FROM records WHERE rdns_id=? AND not type=6 ".
|
---|
5015 | "ORDER BY masklen(CAST(val AS inet)) DESC, CAST(val AS inet)");
|
---|
5016 | $zonesth = $dbh->prepare("UPDATE revzones SET changed='n' WHERE rdns_id=?");
|
---|
5017 | $revsth->execute();
|
---|
5018 | while (my ($revid,$revzone,$revstat,$changed) = $revsth->fetchrow_array) {
|
---|
5019 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
5020 | # O_NOFOLLOW
|
---|
5021 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
5022 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
5023 | # still be followed.
|
---|
5024 | # but that doesn't help other platforms. :/
|
---|
5025 | my $tmpzone = NetAddr::IP->new($revzone);
|
---|
5026 | sysopen(ZONECACHE, "$config{exportcache}/".$tmpzone->network->addr, O_RDWR|O_CREAT);
|
---|
5027 | flock(ZONECACHE, LOCK_EX);
|
---|
5028 | if ($changed || -s "$config{exportcache}/".$tmpzone->network->addr == 0) {
|
---|
5029 | # need to fetch this separately since the rest of the records all (should) have real IPs in val
|
---|
5030 | $soasth->execute($revid);
|
---|
5031 | my (@zsoa) = $soasth->fetchrow_array();
|
---|
5032 | _printrec_tiny(*ZONECACHE,'y',\%recflags,$revzone,
|
---|
5033 | $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],'');
|
---|
5034 |
|
---|
5035 | $recsth->execute($revid);
|
---|
5036 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc) = $recsth->fetchrow_array) {
|
---|
5037 | next if $recflags{$recid};
|
---|
5038 |
|
---|
5039 | $loc = '' if !$loc; # de-nullify - just in case
|
---|
5040 | ##fixme: handle case of record-with-location-that-doesn't-exist better.
|
---|
5041 | # note this currently fails safe (tested) - records with a location that
|
---|
5042 | # doesn't exist will not be sent to any client
|
---|
5043 | # $loc = '' if !$lochash->{$loc};
|
---|
5044 |
|
---|
5045 | ##fixme: record validity timestamp. tinydns supports fiddling with timestamps.
|
---|
5046 | # note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
|
---|
5047 | # timestamps are TAI64
|
---|
5048 | # ~~ 2^62 + time()
|
---|
5049 | my $stamp = '';
|
---|
5050 |
|
---|
5051 | # support tinydns' auto-TTL
|
---|
5052 | $ttl = '' if $ttl == '0';
|
---|
5053 |
|
---|
5054 | _printrec_tiny(*ZONECACHE, 'y', \%recflags, $revzone,
|
---|
5055 | $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp)
|
---|
5056 | if *ZONECACHE;
|
---|
5057 |
|
---|
5058 | # in case the zone shrunk, get rid of garbage at the end of the file.
|
---|
5059 | truncate(ZONECACHE, tell(ZONECACHE));
|
---|
5060 |
|
---|
5061 | $recflags{$recid} = 1;
|
---|
5062 | } # while ($recsth)
|
---|
5063 | }
|
---|
5064 | # stream from cache, whether freshly created or existing
|
---|
5065 | print $datafile $_ while <ZONECACHE>;
|
---|
5066 | close ZONECACHE;
|
---|
5067 | # mark zone as unmodified
|
---|
5068 | $zonesth->execute($revid);
|
---|
5069 | } # while ($domsth)
|
---|
5070 |
|
---|
5071 | } # end __export_tiny()
|
---|
5072 |
|
---|
5073 |
|
---|
5074 | # Utility sub for __export_tiny above
|
---|
5075 | sub _printrec_tiny {
|
---|
5076 | my ($datafile,$revrec,$recflags,$zone,$host,$type,$val,$dist,$weight,$port,$ttl,$loc,$stamp) = @_;
|
---|
5077 |
|
---|
5078 | ## Convert a bare number into an octal-coded pair of octets.
|
---|
5079 | # Take optional arg to indicate a decimal or hex input. Defaults to hex.
|
---|
5080 | sub octalize {
|
---|
5081 | my $tmp = shift;
|
---|
5082 | my $srctype = shift || 'h'; # default assumes hex string
|
---|
5083 | $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
|
---|
5084 | $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
|
---|
5085 | my @o = ($tmp =~ /^(..)(..)$/); # split into octets
|
---|
5086 | return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);;
|
---|
5087 | }
|
---|
5088 |
|
---|
5089 | ## WARNING: This works to export even the whole Internet's worth of IP space...
|
---|
5090 | ## if you have the disk/RAM to handle the dataset, and you call this sub based on /16-sized chunks
|
---|
5091 | ## A /16 took ~3 seconds with a handful of separate records; adding a /8 pushed export time out to ~13m:40s
|
---|
5092 | ## 0/0 is estimated to take ~54 hours and ~256G of disk
|
---|
5093 | ## RAM usage depends on how many non-template entries you have in the set.
|
---|
5094 | ## This should probably be done on record addition rather than export; large blocks may need to be done in a
|
---|
5095 | ## forked process
|
---|
5096 | sub __publish_subnet {
|
---|
5097 | my $sub = shift;
|
---|
5098 | my $recflags = shift;
|
---|
5099 | my $hpat = shift;
|
---|
5100 | my $fh = shift;
|
---|
5101 | my $ttl = shift;
|
---|
5102 | my $stamp = shift;
|
---|
5103 | my $loc = shift;
|
---|
5104 | my $ptronly = shift || 0;
|
---|
5105 |
|
---|
5106 | my $iplist = $sub->splitref(32);
|
---|
5107 | foreach (@$iplist) {
|
---|
5108 | my $ip = $_->addr;
|
---|
5109 | # make as if we split the non-octet-aligned block into octet-aligned blocks as with SOA
|
---|
5110 | next if $ip =~ /\.(0|255)$/;
|
---|
5111 | next if $$recflags{$ip};
|
---|
5112 | $$recflags{$ip}++;
|
---|
5113 | next if $hpat eq '%blank%'; # Allows blanking a subnet so no records are published.
|
---|
5114 | my $rec = $hpat; # start fresh with the template for each IP
|
---|
5115 | _template4_expand(\$rec, $ip);
|
---|
5116 | print $fh ($ptronly ? "^"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$rec" : "=$rec:$ip").
|
---|
5117 | ":$ttl:$stamp:$loc\n";
|
---|
5118 | }
|
---|
5119 | }
|
---|
5120 |
|
---|
5121 | ##fixme? append . to all host/val hostnames
|
---|
5122 | if ($typemap{$type} eq 'SOA') {
|
---|
5123 |
|
---|
5124 | # host contains pri-ns:responsible
|
---|
5125 | # val is abused to contain refresh:retry:expire:minttl
|
---|
5126 | ##fixme: "manual" serial vs tinydns-autoserial
|
---|
5127 | # let's be explicit about abusing $host and $val
|
---|
5128 | my ($email, $primary) = (split /:/, $host)[0,1];
|
---|
5129 | my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
|
---|
5130 | if ($revrec eq 'y') {
|
---|
5131 | ##fixme: have to publish SOA records for each v4 /24 in sub-/16, and each /16 in sub-/8
|
---|
5132 | # what about v6?
|
---|
5133 | # -> only need SOA for local chunks offset from reverse delegation boundaries, so v6 is fine
|
---|
5134 | $zone = NetAddr::IP->new($zone);
|
---|
5135 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
5136 | if (!$zone->{isv6} && ($zone->masklen < 24) && ($zone->masklen % 8 != 0)) {
|
---|
5137 | foreach my $szone ($zone->split($zone->masklen + (8 - $zone->masklen % 8))) {
|
---|
5138 | $szone = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
5139 | print $datafile "Z$szone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
|
---|
5140 | }
|
---|
5141 | return; # skips "default" bits just below
|
---|
5142 | }
|
---|
5143 | $zone = _ZONE($zone, 'ZONE', 'r', '.').($zone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
5144 | }
|
---|
5145 | print $datafile "Z$zone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
|
---|
5146 |
|
---|
5147 | } elsif ($typemap{$type} eq 'A') {
|
---|
5148 |
|
---|
5149 | print $datafile "+$host:$val:$ttl:$stamp:$loc\n";
|
---|
5150 |
|
---|
5151 | } elsif ($typemap{$type} eq 'NS') {
|
---|
5152 |
|
---|
5153 | if ($revrec eq 'y') {
|
---|
5154 | $val = NetAddr::IP->new($val);
|
---|
5155 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
5156 | if (!$val->{isv6} && ($val->masklen < 24) && ($val->masklen % 8 != 0)) {
|
---|
5157 | foreach my $szone ($val->split($val->masklen + (8 - $val->masklen % 8))) {
|
---|
5158 | my $szone2 = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
5159 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
5160 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n";
|
---|
5161 | $$recflags{$szone2} = $val->masklen;
|
---|
5162 | }
|
---|
5163 | } elsif ($val->{isv6} && ($val->masklen < 64) && ($val->masklen % 4 !=0)) {
|
---|
5164 | foreach my $szone ($val->split($val->masklen + (4 - $val->masklen % 4))) {
|
---|
5165 | my $szone2 = _ZONE($szone, 'ZONE.ip6.arpa', 'r', '.');
|
---|
5166 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
5167 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n";
|
---|
5168 | $$recflags{$szone2} = $val->masklen;
|
---|
5169 | }
|
---|
5170 | } else {
|
---|
5171 | my $val2 = _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
5172 | print $datafile "\&$val2"."::$host:$ttl:$stamp:$loc\n";
|
---|
5173 | $$recflags{$val2} = $val->masklen;
|
---|
5174 | }
|
---|
5175 | } else {
|
---|
5176 | print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n";
|
---|
5177 | }
|
---|
5178 |
|
---|
5179 | } elsif ($typemap{$type} eq 'AAAA') {
|
---|
5180 |
|
---|
5181 | print $datafile ":$host:28:";
|
---|
5182 | my $altgrp = 0;
|
---|
5183 | my @altconv;
|
---|
5184 | # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
|
---|
5185 | foreach (split /:/, $val) {
|
---|
5186 | if (/^$/) {
|
---|
5187 | # flag blank entry; this is a series of 0's of (currently) unknown length
|
---|
5188 | $altconv[$altgrp++] = 's';
|
---|
5189 | } else {
|
---|
5190 | # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
|
---|
5191 | $altconv[$altgrp++] = octalize($_)
|
---|
5192 | }
|
---|
5193 | }
|
---|
5194 | foreach my $octet (@altconv) {
|
---|
5195 | # if not 's', output
|
---|
5196 | print $datafile $octet unless $octet =~ /^s$/;
|
---|
5197 | # if 's', output (9-array length)x literal '\000\000'
|
---|
5198 | print $datafile '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
|
---|
5199 | }
|
---|
5200 | print $datafile ":$ttl:$stamp:$loc\n";
|
---|
5201 |
|
---|
5202 | } elsif ($typemap{$type} eq 'MX') {
|
---|
5203 |
|
---|
5204 | print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n";
|
---|
5205 |
|
---|
5206 | } elsif ($typemap{$type} eq 'TXT') {
|
---|
5207 |
|
---|
5208 | ##fixme: split v-e-r-y long TXT strings? will need to do so for BIND export, at least
|
---|
5209 | if ($revrec eq 'n') {
|
---|
5210 | $val =~ s/:/\\072/g; # may need to replace other symbols
|
---|
5211 | print $datafile "'$host:$val:$ttl:$stamp:$loc\n";
|
---|
5212 | } else {
|
---|
5213 | $host =~ s/:/\\072/g; # may need to replace other symbols
|
---|
5214 | my $val2 = NetAddr::IP->new($val);
|
---|
5215 | print $datafile "'"._ZONE($val2, 'ZONE', 'r', '.').($val2->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
5216 | ":$host:$ttl:$stamp:$loc\n";
|
---|
5217 | }
|
---|
5218 |
|
---|
5219 | # by-hand TXT
|
---|
5220 | #:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
|
---|
5221 | #@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
|
---|
5222 | #'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
|
---|
5223 |
|
---|
5224 | #txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
|
---|
5225 | #: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
|
---|
5226 |
|
---|
5227 | # very long TXT record as brought in by axfr-get
|
---|
5228 | # note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
|
---|
5229 | # also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
|
---|
5230 | #:longtxt.deepnet.cx:16:
|
---|
5231 | #\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
|
---|
5232 | #\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.
|
---|
5233 | #\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.
|
---|
5234 | #:3600
|
---|
5235 |
|
---|
5236 | } elsif ($typemap{$type} eq 'CNAME') {
|
---|
5237 |
|
---|
5238 | if ($revrec eq 'n') {
|
---|
5239 | print $datafile "C$host:$val:$ttl:$stamp:$loc\n";
|
---|
5240 | } else {
|
---|
5241 | my $val2 = NetAddr::IP->new($val);
|
---|
5242 | print $datafile "C"._ZONE($val2, 'ZONE', 'r', '.').($val2->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
5243 | ":$host:$ttl:$stamp:$loc\n";
|
---|
5244 | }
|
---|
5245 |
|
---|
5246 | } elsif ($typemap{$type} eq 'SRV') {
|
---|
5247 |
|
---|
5248 | # data is two-byte values for priority, weight, port, in that order,
|
---|
5249 | # followed by length/string data
|
---|
5250 |
|
---|
5251 | print $datafile ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
|
---|
5252 |
|
---|
5253 | $val .= '.' if $val !~ /\.$/;
|
---|
5254 | foreach (split /\./, $val) {
|
---|
5255 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
5256 | }
|
---|
5257 | print $datafile "\\000:$ttl:$stamp:$loc\n";
|
---|
5258 |
|
---|
5259 | } elsif ($typemap{$type} eq 'RP') {
|
---|
5260 |
|
---|
5261 | # RP consists of two mostly free-form strings.
|
---|
5262 | # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
|
---|
5263 | # The second is the "hostname" of a TXT record with more info.
|
---|
5264 | print $datafile ":$host:17:";
|
---|
5265 | my ($who,$what) = split /\s/, $val;
|
---|
5266 | foreach (split /\./, $who) {
|
---|
5267 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
5268 | }
|
---|
5269 | print $datafile '\000';
|
---|
5270 | foreach (split /\./, $what) {
|
---|
5271 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
5272 | }
|
---|
5273 | print $datafile "\\000:$ttl:$stamp:$loc\n";
|
---|
5274 |
|
---|
5275 | } elsif ($typemap{$type} eq 'PTR') {
|
---|
5276 |
|
---|
5277 | $zone = NetAddr::IP->new($zone);
|
---|
5278 | $$recflags{$val}++;
|
---|
5279 | if (!$zone->{isv6} && $zone->masklen > 24) {
|
---|
5280 | ($val) = ($val =~ /\.(\d+)$/);
|
---|
5281 | print $datafile "^$val."._ZONE($zone, 'ZONE', 'r', '.').'.in-addr.arpa'.
|
---|
5282 | ":$host:ttl:$stamp:$loc\n";
|
---|
5283 | } else {
|
---|
5284 | $val = NetAddr::IP->new($val);
|
---|
5285 | print $datafile "^".
|
---|
5286 | _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
5287 | ":$host:$ttl:$stamp:$loc\n";
|
---|
5288 | }
|
---|
5289 |
|
---|
5290 | } elsif ($type == 65280) { # A+PTR
|
---|
5291 |
|
---|
5292 | $$recflags{$val}++;
|
---|
5293 | print $datafile "=$host:$val:$ttl:$stamp:$loc\n";
|
---|
5294 |
|
---|
5295 | } elsif ($type == 65281) { # AAAA+PTR
|
---|
5296 |
|
---|
5297 | #$$recflags{$val}++;
|
---|
5298 | # treat these as two separate records. since tinydns doesn't have
|
---|
5299 | # a native combined type, we have to create them separately anyway.
|
---|
5300 | if ($revrec eq 'n') {
|
---|
5301 | $type = 28;
|
---|
5302 | } else {
|
---|
5303 | $type = 12;
|
---|
5304 | }
|
---|
5305 | _printrec_tiny($datafile,$revrec,$recflags,$zone,$host,$type,$val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
5306 | ##fixme: add a config flag to indicate use of the patch from http://www.fefe.de/dns/
|
---|
5307 | # type 6 is for AAAA+PTR, type 3 is for AAAA
|
---|
5308 |
|
---|
5309 | } elsif ($type == 65282) { # PTR template
|
---|
5310 |
|
---|
5311 | # only useful for v4 with standard DNS software, since this expands all
|
---|
5312 | # IPs in $zone (or possibly $val?) with autogenerated records
|
---|
5313 | $val = NetAddr::IP->new($val);
|
---|
5314 | return if $val->{isv6};
|
---|
5315 |
|
---|
5316 | if ($val->masklen <= 16) {
|
---|
5317 | foreach my $sub ($val->split(16)) {
|
---|
5318 | __publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, 1);
|
---|
5319 | }
|
---|
5320 | } else {
|
---|
5321 | __publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, 1);
|
---|
5322 | }
|
---|
5323 |
|
---|
5324 | } elsif ($type == 65283) { # A+PTR template
|
---|
5325 |
|
---|
5326 | $val = NetAddr::IP->new($val);
|
---|
5327 | # Just In Case. An A+PTR should be impossible to add to a v6 revzone via API.
|
---|
5328 | return if $val->{isv6};
|
---|
5329 |
|
---|
5330 | if ($val->masklen <= 16) {
|
---|
5331 | foreach my $sub ($val->split(16)) {
|
---|
5332 | __publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, 0);
|
---|
5333 | }
|
---|
5334 | } else {
|
---|
5335 | __publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, 0);
|
---|
5336 | }
|
---|
5337 |
|
---|
5338 | } elsif ($type == 65284) { # AAAA+PTR template
|
---|
5339 | # Stub for completeness. Could be exported to DNS software that supports
|
---|
5340 | # some degree of internal automagic in generic-record-creation
|
---|
5341 | # (eg http://search.cpan.org/dist/AllKnowingDNS/ )
|
---|
5342 |
|
---|
5343 | } elsif ($type == 65285) { # Delegation
|
---|
5344 | # This is intended for reverse zones, but may prove useful in forward zones.
|
---|
5345 |
|
---|
5346 | # All delegations need to create one or more NS records. The NS record handler knows what to do.
|
---|
5347 | _printrec_tiny($datafile,$revrec,$recflags,$zone,$host,$reverse_typemap{'NS'},
|
---|
5348 | $val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
5349 | if ($revrec eq 'y') {
|
---|
5350 | # In the case of a sub-/24 v4 reverse delegation, we need to generate CNAMEs
|
---|
5351 | # to redirect all of the individual IP lookups as well.
|
---|
5352 | # Not sure how this would actually resolve if a /24 or larger was delegated
|
---|
5353 | # one way, and a sub-/24 in that >=/24 was delegated elsewhere...
|
---|
5354 | my $dblock = NetAddr::IP->new($val);
|
---|
5355 | if (!$dblock->{isv6} && $dblock->masklen > 24) {
|
---|
5356 | my @subs = $dblock->split;
|
---|
5357 | foreach (@subs) {
|
---|
5358 | next if $$recflags{"$_"};
|
---|
5359 | my ($oct) = ($_->addr =~ /(\d+)$/);
|
---|
5360 | print $datafile "C"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$oct.".
|
---|
5361 | _ZONE($dblock, 'ZONE.in-addr.arpa', 'r', '.').":$ttl:$stamp:$loc\n";
|
---|
5362 | $$recflags{"$_"}++;
|
---|
5363 | }
|
---|
5364 | }
|
---|
5365 | }
|
---|
5366 |
|
---|
5367 | ##
|
---|
5368 | ## Uncommon types. These will need better UI support Any Day Sometime Maybe(TM).
|
---|
5369 | ##
|
---|
5370 |
|
---|
5371 | } elsif ($type == 44) { # SSHFP
|
---|
5372 | my ($algo,$fpt,$fp) = split /\s+/, $val;
|
---|
5373 |
|
---|
5374 | my $rec = sprintf ":$host:44:\\%0.3o\\%0.3o", $algo, $fpt;
|
---|
5375 | while (my ($byte) = ($fp =~ /^(..)/) ) {
|
---|
5376 | $rec .= sprintf "\\%0.3o", hex($byte);
|
---|
5377 | $fp =~ s/^..//;
|
---|
5378 | }
|
---|
5379 | print $datafile "$rec:$ttl:$stamp:$loc\n";
|
---|
5380 |
|
---|
5381 | } else {
|
---|
5382 | # raw record. we don't know what's in here, so we ASS-U-ME the user has
|
---|
5383 | # put it in correctly, since either the user is messing directly with the
|
---|
5384 | # database, or the record was imported via AXFR
|
---|
5385 | # <split by char>
|
---|
5386 | # convert anything not a-zA-Z0-9.- to octal coding
|
---|
5387 |
|
---|
5388 | ##fixme: add flag to export "unknown" record types - note we'll probably end up
|
---|
5389 | # mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
|
---|
5390 | #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
|
---|
5391 |
|
---|
5392 | } # record type if-else
|
---|
5393 |
|
---|
5394 | } # end _printrec_tiny()
|
---|
5395 |
|
---|
5396 |
|
---|
5397 | ## DNSDB::mailNotify()
|
---|
5398 | # Sends notification mail to recipients regarding a DNSDB operation
|
---|
5399 | sub mailNotify {
|
---|
5400 | my $self = shift;
|
---|
5401 | my $dbh = $self->{dbh};
|
---|
5402 | my ($subj,$message) = @_;
|
---|
5403 |
|
---|
5404 | return if $config{mailhost} eq 'smtp.example.com'; # do nothing if still using default SMTP host.
|
---|
5405 |
|
---|
5406 | my $mailer = Net::SMTP->new($config{mailhost}, Hello => "dnsadmin.$config{domain}");
|
---|
5407 |
|
---|
5408 | my $mailsender = ($config{mailsender} ? $config{mailsender} : $config{mailnotify});
|
---|
5409 |
|
---|
5410 | $mailer->mail($mailsender);
|
---|
5411 | $mailer->to($config{mailnotify});
|
---|
5412 | $mailer->data("From: \"$config{mailname}\" <$mailsender>\n",
|
---|
5413 | "To: <$config{mailnotify}>\n",
|
---|
5414 | "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
|
---|
5415 | "Subject: $subj\n",
|
---|
5416 | "X-Mailer: DNSAdmin Notify v".sprintf("%.1d",$DNSDB::VERSION)."\n",
|
---|
5417 | "Organization: $config{orgname}\n",
|
---|
5418 | "\n$message\n");
|
---|
5419 | $mailer->quit;
|
---|
5420 | }
|
---|
5421 |
|
---|
5422 | # shut Perl up
|
---|
5423 | 1;
|
---|