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