[2] | 1 | # dns/trunk/DNSDB.pm
|
---|
| 2 | # Abstraction functions for DNS administration
|
---|
[262] | 3 | ##
|
---|
| 4 | # $Id: DNSDB.pm 661 2014-09-30 21:28:03Z 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;
|
---|
[559] | 29 | use Digest::MD5 qw(md5_hex);
|
---|
[198] | 30 | use Net::SMTP;
|
---|
[539] | 31 | use NetAddr::IP 4.027 qw(:lower);
|
---|
[198] | 32 | use POSIX;
|
---|
[368] | 33 | use Fcntl qw(:flock);
|
---|
[543] | 34 | use Time::TAI64 qw(:tai64);
|
---|
[368] | 35 |
|
---|
[2] | 36 | use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
|
---|
| 37 |
|
---|
[561] | 38 | $VERSION = 1.3; ##VERSION##
|
---|
[2] | 39 | @ISA = qw(Exporter);
|
---|
| 40 | @EXPORT_OK = qw(
|
---|
[279] | 41 | &initGlobals &login &initActionLog
|
---|
[489] | 42 | &getPermissions &changePermissions &comparePermissions
|
---|
[112] | 43 | &changeGroup
|
---|
[517] | 44 | &connectDB &finish
|
---|
[276] | 45 | &addDomain &delZone &domainName &revName &domainID &revID &addRDNS
|
---|
[383] | 46 | &getZoneCount &getZoneList &getZoneLocation
|
---|
[22] | 47 | &addGroup &delGroup &getChildren &groupName
|
---|
[314] | 48 | &getGroupCount &getGroupList
|
---|
[83] | 49 | &addUser &updateUser &delUser &userFullName &userStatus &getUserData
|
---|
[326] | 50 | &getUserCount &getUserList &getUserDropdown
|
---|
[375] | 51 | &addLoc &updateLoc &delLoc &getLoc
|
---|
[370] | 52 | &getLocCount &getLocList &getLocDropdown
|
---|
[495] | 53 | &getSOA &updateSOA &getRecLine &getRecList &getRecCount
|
---|
[22] | 54 | &addRec &updateRec &delRec
|
---|
[323] | 55 | &getLogCount &getLogEntries
|
---|
[452] | 56 | &getRevPattern
|
---|
[225] | 57 | &getTypelist
|
---|
[254] | 58 | &parentID
|
---|
[117] | 59 | &isParent
|
---|
[452] | 60 | &zoneStatus &getZonesByCIDR &importAXFR
|
---|
[103] | 61 | &export
|
---|
[197] | 62 | &mailNotify
|
---|
[517] | 63 | %typemap %reverse_typemap
|
---|
[489] | 64 | @permtypes $permlist %permchains
|
---|
[2] | 65 | );
|
---|
| 66 |
|
---|
[489] | 67 | @EXPORT = qw(%typemap %reverse_typemap @permtypes $permlist %permchains);
|
---|
[2] | 68 | %EXPORT_TAGS = ( ALL => [qw(
|
---|
[279] | 69 | &initGlobals &login &initActionLog
|
---|
[489] | 70 | &getPermissions &changePermissions &comparePermissions
|
---|
[112] | 71 | &changeGroup
|
---|
[517] | 72 | &connectDB &finish
|
---|
[276] | 73 | &addDomain &delZone &domainName &revName &domainID &revID &addRDNS
|
---|
[383] | 74 | &getZoneCount &getZoneList &getZoneLocation
|
---|
[22] | 75 | &addGroup &delGroup &getChildren &groupName
|
---|
[314] | 76 | &getGroupCount &getGroupList
|
---|
[83] | 77 | &addUser &updateUser &delUser &userFullName &userStatus &getUserData
|
---|
[326] | 78 | &getUserCount &getUserList &getUserDropdown
|
---|
[375] | 79 | &addLoc &updateLoc &delLoc &getLoc
|
---|
[370] | 80 | &getLocCount &getLocList &getLocDropdown
|
---|
[495] | 81 | &getSOA &updateSOA &getRecLine &getRecList &getRecCount
|
---|
[22] | 82 | &addRec &updateRec &delRec
|
---|
[323] | 83 | &getLogCount &getLogEntries
|
---|
[452] | 84 | &getRevPattern
|
---|
[225] | 85 | &getTypelist
|
---|
[254] | 86 | &parentID
|
---|
[117] | 87 | &isParent
|
---|
[452] | 88 | &zoneStatus &getZonesByCIDR &importAXFR
|
---|
[103] | 89 | &export
|
---|
[197] | 90 | &mailNotify
|
---|
[517] | 91 | %typemap %reverse_typemap
|
---|
[489] | 92 | @permtypes $permlist %permchains
|
---|
[2] | 93 | )]
|
---|
| 94 | );
|
---|
| 95 |
|
---|
| 96 | our $errstr = '';
|
---|
[283] | 97 | our $resultstr = '';
|
---|
[2] | 98 |
|
---|
[66] | 99 | # Arguably defined wholly in the db, but little reason to change without supporting code changes
|
---|
[370] | 100 | # group_view, user_view permissions? separate rDNS permission(s)?
|
---|
[66] | 101 | our @permtypes = qw (
|
---|
| 102 | group_edit group_create group_delete
|
---|
| 103 | user_edit user_create user_delete
|
---|
| 104 | domain_edit domain_create domain_delete
|
---|
[387] | 105 | record_edit record_create record_delete record_locchg
|
---|
[370] | 106 | location_edit location_create location_delete location_view
|
---|
[66] | 107 | self_edit admin
|
---|
| 108 | );
|
---|
| 109 | our $permlist = join(',',@permtypes);
|
---|
| 110 |
|
---|
[390] | 111 | # Some permissions more or less require certain others.
|
---|
| 112 | our %permchains = (
|
---|
| 113 | user_edit => 'self_edit',
|
---|
| 114 | location_edit => 'location_view',
|
---|
| 115 | location_create => 'location_view',
|
---|
| 116 | location_delete => 'location_view',
|
---|
| 117 | record_locchg => 'location_view',
|
---|
| 118 | );
|
---|
| 119 |
|
---|
[2] | 120 | # DNS record type map and reverse map.
|
---|
| 121 | # loaded from the database, from http://www.iana.org/assignments/dns-parameters
|
---|
| 122 | our %typemap;
|
---|
| 123 | our %reverse_typemap;
|
---|
| 124 |
|
---|
[228] | 125 | ## (Semi)private variables
|
---|
[278] | 126 |
|
---|
[228] | 127 | # Hash of functions for validating record types. Filled in initGlobals() since
|
---|
| 128 | # it relies on visibility flags from the rectypes table in the DB
|
---|
| 129 | my %validators;
|
---|
[128] | 130 |
|
---|
[295] | 131 | # Entity-relationship reference hashes.
|
---|
| 132 | my %par_tbl = (
|
---|
| 133 | group => 'groups',
|
---|
| 134 | user => 'users',
|
---|
| 135 | defrec => 'default_records',
|
---|
| 136 | defrevrec => 'default_rev_records',
|
---|
| 137 | domain => 'domains',
|
---|
| 138 | revzone => 'revzones',
|
---|
| 139 | record => 'records'
|
---|
| 140 | );
|
---|
| 141 | my %id_col = (
|
---|
| 142 | group => 'group_id',
|
---|
| 143 | user => 'user_id',
|
---|
| 144 | defrec => 'record_id',
|
---|
| 145 | defrevrec => 'record_id',
|
---|
| 146 | domain => 'domain_id',
|
---|
| 147 | revzone => 'rdns_id',
|
---|
| 148 | record => 'record_id'
|
---|
| 149 | );
|
---|
| 150 | my %par_col = (
|
---|
| 151 | group => 'parent_group_id',
|
---|
| 152 | user => 'group_id',
|
---|
| 153 | defrec => 'group_id',
|
---|
| 154 | defrevrec => 'group_id',
|
---|
| 155 | domain => 'group_id',
|
---|
| 156 | revzone => 'group_id',
|
---|
| 157 | record => 'domain_id'
|
---|
| 158 | );
|
---|
| 159 | my %par_type = (
|
---|
| 160 | group => 'group',
|
---|
| 161 | user => 'group',
|
---|
| 162 | defrec => 'group',
|
---|
| 163 | defrevrec => 'group',
|
---|
| 164 | domain => 'group',
|
---|
| 165 | revzone => 'group',
|
---|
| 166 | record => 'domain'
|
---|
| 167 | );
|
---|
[278] | 168 |
|
---|
[2] | 169 | ##
|
---|
[465] | 170 | ## Constructor and destructor
|
---|
| 171 | ##
|
---|
| 172 |
|
---|
| 173 | sub new {
|
---|
| 174 | my $this = shift;
|
---|
| 175 | my $class = ref($this) || $this;
|
---|
| 176 | my %args = @_;
|
---|
[517] | 177 |
|
---|
| 178 | # Prepopulate a basic config. Note some of these *will* cause errors if left unset.
|
---|
| 179 | # note: add appropriate stanzas in __cfgload() to parse these
|
---|
| 180 | my %defconfig = (
|
---|
[529] | 181 | # The only configuration options not loadable from a config file.
|
---|
| 182 | configfile => "/etc/dnsdb/dnsdb.conf", ##CFG_LEAF##
|
---|
[517] | 183 |
|
---|
| 184 | # Database connection info
|
---|
| 185 | dbname => 'dnsdb',
|
---|
| 186 | dbuser => 'dnsdb',
|
---|
| 187 | dbpass => 'secret',
|
---|
| 188 | dbhost => '',
|
---|
| 189 |
|
---|
| 190 | # Email notice settings
|
---|
| 191 | mailhost => 'smtp.example.com',
|
---|
| 192 | mailnotify => 'dnsdb@example.com', # to
|
---|
| 193 | mailsender => 'dnsdb@example.com', # from
|
---|
| 194 | mailname => 'DNS Administration',
|
---|
| 195 | orgname => 'Example Corp',
|
---|
| 196 | domain => 'example.com',
|
---|
| 197 |
|
---|
| 198 | # Template directory
|
---|
| 199 | templatedir => 'templates/',
|
---|
| 200 | # fmeh. this is a real web path, not a logical internal one. hm..
|
---|
| 201 | # cssdir => 'templates/',
|
---|
| 202 | sessiondir => 'session/',
|
---|
| 203 | exportcache => 'cache/',
|
---|
[559] | 204 | usecache => 1, # do we bother using the cache above?
|
---|
[517] | 205 |
|
---|
| 206 | # Session params
|
---|
| 207 | timeout => '1h', # passed as-is to CGI::Session
|
---|
| 208 |
|
---|
| 209 | # Other miscellanea
|
---|
| 210 | log_failures => 1, # log all evarthing by default
|
---|
| 211 | perpage => 15,
|
---|
[559] | 212 | maxfcgi => 10, # reasonable default?
|
---|
[524] | 213 | force_refresh => 1,
|
---|
[542] | 214 | lowercase => 0, # mangle as little as possible by default
|
---|
[583] | 215 | # show IPs and CIDR blocks as-is for reverse zones. valid values are
|
---|
| 216 | # 'none' (default, show natural IP or CIDR)
|
---|
| 217 | # 'zone' (zone name, wherever used)
|
---|
| 218 | # 'record' (IP or CIDR values in reverse record lists)
|
---|
| 219 | # 'all' (all IP values in any reverse zone view)
|
---|
| 220 | showrev_arpa => 'none',
|
---|
[644] | 221 | # Two options for template record expansion:
|
---|
| 222 | template_skip_0 => 0, # publish .0 by default
|
---|
| 223 | template_skip_255 => 0, # publish .255 by default
|
---|
[517] | 224 | );
|
---|
| 225 |
|
---|
| 226 | # Config file parse calls.
|
---|
| 227 | # If we are passed a blank argument for $args{configfile},
|
---|
| 228 | # we should NOT parse the default config file - we will
|
---|
| 229 | # rely on hardcoded defaults OR caller-specified values.
|
---|
| 230 | # If we are passed a non-blank argument, parse that file.
|
---|
| 231 | # If no config file is specified, parse the default one.
|
---|
| 232 | my %siteconfig;
|
---|
| 233 | if (defined($args{configfile})) {
|
---|
| 234 | if ($args{configfile}) {
|
---|
| 235 | return if !__cfgload($args{configfile}, \%siteconfig);
|
---|
| 236 | }
|
---|
| 237 | } else {
|
---|
| 238 | return if !__cfgload($defconfig{configfile}, \%siteconfig);
|
---|
[465] | 239 | }
|
---|
[517] | 240 |
|
---|
| 241 | # Assemble the object. Apply configuration hashes in order of precedence.
|
---|
| 242 | my $self = {
|
---|
| 243 | # Hardcoded defaults
|
---|
| 244 | %defconfig,
|
---|
| 245 | # Default config file OR caller-specified one, loaded above
|
---|
| 246 | %siteconfig,
|
---|
| 247 | # Caller-specified arguments
|
---|
| 248 | %args
|
---|
| 249 | };
|
---|
[465] | 250 | bless $self, $class;
|
---|
[517] | 251 |
|
---|
[524] | 252 | # Several settings are booleans. Handle multiple possible ways of setting them.
|
---|
[644] | 253 | for my $boolopt ('log_failures', 'force_refresh', 'lowercase', 'usecache',
|
---|
| 254 | 'template_skip_0', 'template_skip_255') {
|
---|
[524] | 255 | if ($self->{$boolopt} ne '1' && $self->{$boolopt} ne '0') {
|
---|
| 256 | # true/false, on/off, yes/no all valid.
|
---|
| 257 | if ($self->{$boolopt} =~ /^(?:true|false|t|f|on|off|yes|no)$/) {
|
---|
| 258 | if ($self->{$boolopt} =~ /(?:true|t|on|yes)/) {
|
---|
| 259 | $self->{$boolopt} = 1;
|
---|
| 260 | } else {
|
---|
| 261 | $self->{$boolopt} = 0;
|
---|
| 262 | }
|
---|
| 263 | } else {
|
---|
[583] | 264 | warn "Bad $boolopt setting $self->{$boolopt}, using default\n";
|
---|
| 265 | $self->{$boolopt} = $defconfig{$boolopt};
|
---|
[524] | 266 | }
|
---|
| 267 | }
|
---|
| 268 | }
|
---|
| 269 |
|
---|
[583] | 270 | # Enum-ish option(s)
|
---|
| 271 | if (!grep /$self->{showrev_arpa}/, ('none','zone','record','all')) {
|
---|
| 272 | warn "Bad showrev_arpa setting $self->{showrev_arpa}, using default\n";
|
---|
| 273 | $self->{showrev_arpa} = 'none';
|
---|
| 274 | }
|
---|
| 275 |
|
---|
[517] | 276 | # Try to connect to the DB, and initialize a number of handy globals.
|
---|
[465] | 277 | $self->{dbh} = connectDB($self->{dbname}, $self->{dbuser}, $self->{dbpass}, $self->{dbhost}) or return;
|
---|
| 278 | $self->initGlobals();
|
---|
| 279 |
|
---|
| 280 | return $self;
|
---|
| 281 | }
|
---|
| 282 |
|
---|
| 283 | sub DESTROY {
|
---|
| 284 | my $self = shift;
|
---|
[517] | 285 | $self->{dbh}->disconnect if $self->{dbh};
|
---|
[465] | 286 | }
|
---|
| 287 |
|
---|
[495] | 288 | sub errstr { $DNSDB::errstr; }
|
---|
| 289 |
|
---|
[465] | 290 | ##
|
---|
[225] | 291 | ## utility functions
|
---|
[281] | 292 | ##
|
---|
| 293 |
|
---|
| 294 | ## DNSDB::_rectable()
|
---|
[224] | 295 | # Takes default+rdns flags, returns appropriate table name
|
---|
| 296 | sub _rectable {
|
---|
| 297 | my $def = shift;
|
---|
| 298 | my $rev = shift;
|
---|
| 299 |
|
---|
| 300 | return 'records' if $def ne 'y';
|
---|
| 301 | return 'default_records' if $rev ne 'y';
|
---|
| 302 | return 'default_rev_records';
|
---|
| 303 | } # end _rectable()
|
---|
| 304 |
|
---|
[281] | 305 | ## DNSDB::_recparent()
|
---|
[224] | 306 | # Takes default+rdns flags, returns appropriate parent-id column name
|
---|
| 307 | sub _recparent {
|
---|
| 308 | my $def = shift;
|
---|
| 309 | my $rev = shift;
|
---|
| 310 |
|
---|
| 311 | return 'group_id' if $def eq 'y';
|
---|
| 312 | return 'rdns_id' if $rev eq 'y';
|
---|
| 313 | return 'domain_id';
|
---|
| 314 | } # end _recparent()
|
---|
| 315 |
|
---|
[281] | 316 | ## DNSDB::_ipparent()
|
---|
[226] | 317 | # Check an IP to be added in a reverse zone to see if it's really in the requested parent.
|
---|
[466] | 318 | # Takes default and reverse flags, IP (fragment) to check, parent zone ID,
|
---|
[226] | 319 | # and a reference to a NetAddr::IP object (also used to pass back a fully-reconstructed IP for
|
---|
| 320 | # database insertion)
|
---|
| 321 | sub _ipparent {
|
---|
[466] | 322 | my $self = shift;
|
---|
| 323 | my $dbh = $self->{dbh};
|
---|
[226] | 324 | my $defrec = shift;
|
---|
| 325 | my $revrec = shift;
|
---|
| 326 | my $val = shift;
|
---|
| 327 | my $id = shift;
|
---|
| 328 | my $addr = shift;
|
---|
[224] | 329 |
|
---|
[232] | 330 | return if $revrec ne 'y'; # this sub not useful in forward zones
|
---|
| 331 |
|
---|
| 332 | $$addr = NetAddr::IP->new($$val); #necessary?
|
---|
| 333 |
|
---|
[226] | 334 | # subsub to split, reverse, and overlay an IP fragment on a netblock
|
---|
| 335 | sub __rev_overlay {
|
---|
| 336 | my $splitme = shift; # ':' or '.', m'lud?
|
---|
| 337 | my $parnet = shift;
|
---|
| 338 | my $val = shift;
|
---|
| 339 | my $addr = shift;
|
---|
| 340 |
|
---|
| 341 | my $joinme = $splitme;
|
---|
| 342 | $splitme = '\.' if $splitme eq '.';
|
---|
[232] | 343 | my @working = reverse(split($splitme, $parnet->addr));
|
---|
| 344 | my @parts = reverse(split($splitme, $$val));
|
---|
[226] | 345 | for (my $i = 0; $i <= $#parts; $i++) {
|
---|
| 346 | $working[$i] = $parts[$i];
|
---|
| 347 | }
|
---|
[232] | 348 | my $checkme = NetAddr::IP->new(join($joinme, reverse(@working))) or return 0;
|
---|
| 349 | return 0 unless $checkme->within($parnet);
|
---|
[226] | 350 | $$addr = $checkme; # force "correct" IP to be recorded.
|
---|
| 351 | return 1;
|
---|
| 352 | }
|
---|
| 353 |
|
---|
| 354 | my ($parstr) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id = ?", undef, ($id));
|
---|
| 355 | my $parnet = NetAddr::IP->new($parstr);
|
---|
| 356 |
|
---|
| 357 | # Fail early on v6-in-v4 or v4-in-v6. We're not accepting these ATM.
|
---|
[232] | 358 | return 0 if $parnet->addr =~ /\./ && $$val =~ /:/;
|
---|
| 359 | return 0 if $parnet->addr =~ /:/ && $$val =~ /\./;
|
---|
[226] | 360 |
|
---|
[340] | 361 | if ($$addr && ($$val =~ /^[\da-fA-F][\da-fA-F:]+[\da-fA-F]$/ || $$val =~ m|/\d+$|)) {
|
---|
| 362 | # the only case where NetAddr::IP's acceptance of legitimate IPs is "correct" is for a proper IPv6 address,
|
---|
| 363 | # or a netblock (only expected on templates)
|
---|
[232] | 364 | # the rest we have to restructure before fiddling. *sigh*
|
---|
| 365 | return 1 if $$addr->within($parnet);
|
---|
| 366 | } else {
|
---|
[340] | 367 | # We don't have a complete IP in $$val (yet)... unless we have a netblock
|
---|
[232] | 368 | if ($parnet->addr =~ /:/) {
|
---|
| 369 | $$val =~ s/^:+//; # gotta strip'em all...
|
---|
[226] | 370 | return __rev_overlay(':', $parnet, $val, $addr);
|
---|
| 371 | }
|
---|
[232] | 372 | if ($parnet->addr =~ /\./) {
|
---|
| 373 | $$val =~ s/^\.+//;
|
---|
| 374 | return __rev_overlay('.', $parnet, $val, $addr);
|
---|
| 375 | }
|
---|
[226] | 376 | # should be impossible to get here...
|
---|
| 377 | }
|
---|
| 378 | # ... and here.
|
---|
| 379 | # can't do nuttin' in forward zones
|
---|
| 380 | } # end _ipparent()
|
---|
| 381 |
|
---|
[609] | 382 | ## DNSDB::_maybeip()
|
---|
| 383 | # Wrapper for quick "does this look like an IP address?" regex, so we don't make dumb copy-paste mistakes
|
---|
| 384 | sub _maybeip {
|
---|
| 385 | my $izzit = shift; # reference
|
---|
| 386 | return 1 if $$izzit =~ m,^(?:[\d\./]+|[0-9a-fA-F:/]+)$,;
|
---|
| 387 | }
|
---|
| 388 |
|
---|
[610] | 389 | ## DNSDB::_inrev()
|
---|
| 390 | # Check if a given "hostname" is within a given reverse zone
|
---|
| 391 | # Takes a reference to the "hostname" and the reverse zone CIDR as a NetAddr::IP
|
---|
| 392 | # Returns true/false. Sets $errstr on errors.
|
---|
| 393 | sub _inrev {
|
---|
| 394 | my $self = shift;
|
---|
| 395 | my $dbh = $self->{dbh};
|
---|
| 396 | # References, since we might munge them
|
---|
| 397 | my $fq = shift;
|
---|
| 398 | my $zone = shift;
|
---|
| 399 |
|
---|
| 400 | # set default error
|
---|
| 401 | $errstr = "$$fq not within $zone";
|
---|
| 402 |
|
---|
| 403 | # Unlike forward zones, we will not coerce the data into the reverse zone - an A record
|
---|
| 404 | # in a reverse zone is already silly enough without appending a mess of 1.2.3.in-addr.arpa
|
---|
| 405 | # (or worse, 1.2.3.4.5.6.7.8.ip6.arpa) on the end of the nominal "hostname".
|
---|
| 406 | # We're also going to allow the "hostname" to be stored as .arpa or IP, because of
|
---|
| 407 | # non-IP FQDNs in .arpa
|
---|
| 408 | if ($$fq =~ /\.arpa$/) {
|
---|
| 409 | # "FQDN" could be any syntactically legitimate string, but it must be within the formal
|
---|
| 410 | # .arpa zone. Note we're not validating these for correct reverse-IP values.
|
---|
| 411 | # yes, we really need the v6 branch on the end here.
|
---|
| 412 | $zone = _ZONE($zone, 'ZONE', 'r', '.').($zone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 413 | return unless $$fq =~ /$zone$/;
|
---|
| 414 | } else {
|
---|
| 415 | # in most cases we should be getting a real IP as the "FQDN" to test
|
---|
| 416 | my $addr = new NetAddr::IP $$fq if _maybeip($fq);
|
---|
| 417 |
|
---|
| 418 | # "FQDN" should be a valid IP address. Normalize formatting if so.
|
---|
| 419 | if (!$addr) {
|
---|
| 420 | $errstr = "$$fq is not a valid IP address";
|
---|
| 421 | return;
|
---|
| 422 | }
|
---|
| 423 | return if !$zone->contains($addr);
|
---|
| 424 | ($$fq = $addr) =~ s{/(?:32|128)$}{};
|
---|
| 425 | }
|
---|
| 426 | return 1;
|
---|
| 427 | } # end _inrev()
|
---|
| 428 |
|
---|
[281] | 429 | ## DNSDB::_hostparent()
|
---|
[232] | 430 | # A little different than _ipparent above; this tries to *find* the parent zone of a hostname
|
---|
[466] | 431 | # Takes a hostname.
|
---|
[281] | 432 | # Returns the domain ID of the parent domain if one was found.
|
---|
[232] | 433 | sub _hostparent {
|
---|
[466] | 434 | my $self = shift;
|
---|
| 435 | my $dbh = $self->{dbh};
|
---|
[232] | 436 | my $hname = shift;
|
---|
[347] | 437 |
|
---|
| 438 | $hname =~ s/^\*\.//; # this should be impossible to find in the domains table.
|
---|
[232] | 439 | my @hostbits = split /\./, $hname;
|
---|
[349] | 440 | my $sth = $dbh->prepare("SELECT count(*),domain_id FROM domains WHERE lower(domain) = lower(?) GROUP BY domain_id");
|
---|
[232] | 441 | foreach (@hostbits) {
|
---|
| 442 | $sth->execute($hname);
|
---|
| 443 | my ($found, $parid) = $sth->fetchrow_array;
|
---|
| 444 | if ($found) {
|
---|
| 445 | return $parid;
|
---|
| 446 | }
|
---|
| 447 | $hname =~ s/^$_\.//;
|
---|
| 448 | }
|
---|
| 449 | } # end _hostparent()
|
---|
[228] | 450 |
|
---|
[281] | 451 | ## DNSDB::_log()
|
---|
| 452 | # Log an action
|
---|
[466] | 453 | # Takes a log entry hash containing at least:
|
---|
[282] | 454 | # group_id, log entry
|
---|
[281] | 455 | # and optionally one or more of:
|
---|
| 456 | # domain_id, rdns_id
|
---|
[282] | 457 | # The %userdata hash provides the user ID, username, and fullname
|
---|
[281] | 458 | sub _log {
|
---|
[466] | 459 | my $self = shift;
|
---|
| 460 | my $dbh = $self->{dbh};
|
---|
[281] | 461 |
|
---|
| 462 | my %args = @_;
|
---|
| 463 |
|
---|
| 464 | $args{rdns_id} = 0 if !$args{rdns_id};
|
---|
| 465 | $args{domain_id} = 0 if !$args{domain_id};
|
---|
| 466 |
|
---|
| 467 | ##fixme: farm out the actual logging to different subs for file, syslog, internal, etc based on config
|
---|
[517] | 468 | # if ($self->{log_channel} eq 'sql') {
|
---|
[281] | 469 | $dbh->do("INSERT INTO log (domain_id,rdns_id,group_id,entry,user_id,email,name) VALUES (?,?,?,?,?,?,?)",
|
---|
| 470 | undef,
|
---|
| 471 | ($args{domain_id}, $args{rdns_id}, $args{group_id}, $args{entry},
|
---|
[488] | 472 | $self->{loguserid}, $self->{logusername}, $self->{logfullname}) );
|
---|
[517] | 473 | # } elsif ($self->{log_channel} eq 'file') {
|
---|
| 474 | # } elsif ($self->{log_channel} eq 'syslog') {
|
---|
[281] | 475 | # }
|
---|
| 476 | } # end _log
|
---|
| 477 |
|
---|
| 478 |
|
---|
[224] | 479 | ##
|
---|
[228] | 480 | ## Record validation subs.
|
---|
| 481 | ##
|
---|
| 482 |
|
---|
[281] | 483 | ## All of these subs take substantially the same arguments:
|
---|
| 484 | # a hash containing at least the following keys:
|
---|
| 485 | # - defrec (default/live flag)
|
---|
| 486 | # - revrec (forward/reverse flag)
|
---|
| 487 | # - id (parent entity ID)
|
---|
| 488 | # - host (hostname)
|
---|
| 489 | # - rectype
|
---|
| 490 | # - val (IP, hostname [CNAME/MX/SRV] or text)
|
---|
| 491 | # - addr (NetAddr::IP object from val. May be undef.)
|
---|
| 492 | # MX and SRV record validation also expect distance, and SRV records expect weight and port as well.
|
---|
| 493 | # host, rectype, and addr should be references as these may be modified in validation
|
---|
| 494 |
|
---|
[228] | 495 | # A record
|
---|
| 496 | sub _validate_1 {
|
---|
[467] | 497 | my $self = shift;
|
---|
| 498 | my $dbh = $self->{dbh};
|
---|
[229] | 499 |
|
---|
[230] | 500 | my %args = @_;
|
---|
[229] | 501 |
|
---|
[606] | 502 | # only for strict type restrictions
|
---|
| 503 | # return ('FAIL', 'Reverse zones cannot contain A records') if $args{revrec} eq 'y';
|
---|
[229] | 504 |
|
---|
[606] | 505 | if ($args{revrec} eq 'y') {
|
---|
| 506 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 507 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
[229] | 508 |
|
---|
[610] | 509 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
[606] | 510 |
|
---|
[611] | 511 | # ${$args{val}} is either a valid IP or a string ending with the .arpa zone name;
|
---|
| 512 | # now check if it's a well-formed FQDN
|
---|
[613] | 513 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
[612] | 514 | ${$args{val}} =~ /\.arpa$/;
|
---|
[611] | 515 |
|
---|
[606] | 516 | # Check IP is well-formed, and that it's a v4 address
|
---|
| 517 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
|
---|
| 518 | return ('FAIL',"A record must be a valid IPv4 address")
|
---|
[660] | 519 | unless ${$args{host}} =~ m{^\d+\.\d+\.\d+\.\d+(/\d+)?$};
|
---|
[606] | 520 | $args{addr} = new NetAddr::IP ${$args{host}};
|
---|
| 521 | return ('FAIL',"A record must be a valid IPv4 address")
|
---|
| 522 | unless $args{addr} && !$args{addr}->{isv6};
|
---|
| 523 | # coerce IP/value to normalized form for storage
|
---|
| 524 | ${$args{host}} = $args{addr}->addr;
|
---|
| 525 |
|
---|
| 526 | # I'm just going to ignore the utterly barmy idea of an A record in the *default*
|
---|
| 527 | # records for a reverse zone; it's bad enough to find one in funky legacy data.
|
---|
| 528 |
|
---|
| 529 | } else {
|
---|
| 530 | # revrec ne 'y'
|
---|
| 531 |
|
---|
| 532 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 533 | # or the intended parent domain for live records.
|
---|
| 534 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[657] | 535 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i);
|
---|
[606] | 536 |
|
---|
[620] | 537 | # Check if it's a proper formal .arpa name for an IP, and renormalize it to the IP
|
---|
| 538 | # value if so. Done mainly for symmetry with PTR/A+PTR, and saves a conversion on export.
|
---|
| 539 | if (${$args{val}} =~ /\.arpa$/) {
|
---|
| 540 | my ($code,$tmp) = _zone2cidr(${$args{val}});
|
---|
| 541 | if ($code ne 'FAIL') {
|
---|
| 542 | ${$args{val}} = $tmp->addr;
|
---|
| 543 | $args{addr} = $tmp;
|
---|
| 544 | }
|
---|
| 545 | }
|
---|
[606] | 546 | # Check IP is well-formed, and that it's a v4 address
|
---|
| 547 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
|
---|
| 548 | return ('FAIL',"A record must be a valid IPv4 address")
|
---|
[234] | 549 | unless ${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/;
|
---|
[629] | 550 | $args{addr} = new NetAddr::IP ${$args{val}};
|
---|
[606] | 551 | return ('FAIL',"A record must be a valid IPv4 address")
|
---|
[230] | 552 | unless $args{addr} && !$args{addr}->{isv6};
|
---|
[606] | 553 | # coerce IP/value to normalized form for storage
|
---|
| 554 | ${$args{val}} = $args{addr}->addr;
|
---|
| 555 | }
|
---|
[229] | 556 |
|
---|
[228] | 557 | return ('OK','OK');
|
---|
| 558 | } # done A record
|
---|
| 559 |
|
---|
| 560 | # NS record
|
---|
| 561 | sub _validate_2 {
|
---|
[467] | 562 | my $self = shift;
|
---|
| 563 | my $dbh = $self->{dbh};
|
---|
[230] | 564 |
|
---|
| 565 | my %args = @_;
|
---|
| 566 |
|
---|
[616] | 567 | # NS target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 568 | if ($args{revrec} eq 'y') {
|
---|
| 569 | return ('FAIL', "NS records cannot point directly to an IP address")
|
---|
| 570 | if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
| 571 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
| 572 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 573 | } else {
|
---|
| 574 | return ('FAIL', "NS records cannot point directly to an IP address")
|
---|
| 575 | if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
| 576 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
| 577 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 578 | }
|
---|
| 579 |
|
---|
[328] | 580 | # Check that the target of the record is within the parent.
|
---|
| 581 | if ($args{defrec} eq 'n') {
|
---|
| 582 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
| 583 | if ($args{revrec} eq 'y') {
|
---|
[616] | 584 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 585 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
| 586 |
|
---|
| 587 | # Note the NS record may or may not be for the zone itself, it may be a pointer for a subzone
|
---|
| 588 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
| 589 |
|
---|
| 590 | # ${$args{val}} is either a valid IP or a string ending with the .arpa zone name;
|
---|
| 591 | # now check if it's a well-formed FQDN
|
---|
| 592 | ##enhance or ##fixme
|
---|
| 593 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design
|
---|
| 594 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
| 595 | ${$args{val}} =~ /\.arpa$/;
|
---|
[328] | 596 | } else {
|
---|
[616] | 597 | # Forcibly append the domain name if the hostname being added does not end with the current domain name
|
---|
[467] | 598 | my $pname = $self->domainName($args{id});
|
---|
[657] | 599 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i);
|
---|
[328] | 600 | }
|
---|
[230] | 601 | } else {
|
---|
[616] | 602 | # Default reverse NS records should always refer to the implied parent.
|
---|
| 603 | if ($args{revrec} eq 'y') {
|
---|
| 604 | ${$args{val}} = 'ZONE';
|
---|
| 605 | } else {
|
---|
| 606 | ${$args{host}} = 'DOMAIN';
|
---|
| 607 | }
|
---|
[230] | 608 | }
|
---|
| 609 |
|
---|
[228] | 610 | return ('OK','OK');
|
---|
| 611 | } # done NS record
|
---|
| 612 |
|
---|
| 613 | # CNAME record
|
---|
| 614 | sub _validate_5 {
|
---|
[467] | 615 | my $self = shift;
|
---|
| 616 | my $dbh = $self->{dbh};
|
---|
[230] | 617 |
|
---|
| 618 | my %args = @_;
|
---|
| 619 |
|
---|
[618] | 620 | # CNAMEs in reverse zones shouldn't be handled manually, they should be generated on
|
---|
| 621 | # export by use of the "delegation" type. For the masochistic, and those importing
|
---|
| 622 | # legacy data from $deity-knows-where, we'll support them.
|
---|
[230] | 623 |
|
---|
[618] | 624 | if ($args{revrec} eq 'y') {
|
---|
| 625 | # CNAME target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 626 | return ('FAIL', "CNAME records cannot point directly to an IP address")
|
---|
| 627 | if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
[230] | 628 |
|
---|
[618] | 629 | if ($args{defrec} eq 'n') {
|
---|
| 630 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 631 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
| 632 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
[632] | 633 | # CNAMEs can not be used for parent nodes; just leaf nodes with no other record types
|
---|
| 634 | # note that this WILL probably miss some edge cases.
|
---|
| 635 | if (${$args{val}} =~ /^[\d.\/]+$/) {
|
---|
| 636 | # convert IP "hostname" to .arpa
|
---|
| 637 | my $tmphn = _ZONE(NetAddr::IP->new(${$args{val}}), 'ZONE', 'r', '.');
|
---|
| 638 | my $tmpz = _ZONE($revzone, 'ZONE', 'r', '.');
|
---|
| 639 | return ('FAIL', "The bare zone may not be a CNAME") if $tmphn eq $tmpz;
|
---|
[656] | 640 | ##enhance: look up the target name and publish that instead on export
|
---|
[632] | 641 | }
|
---|
[618] | 642 | }
|
---|
| 643 |
|
---|
| 644 | ##enhance or ##fixme
|
---|
| 645 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design
|
---|
| 646 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
| 647 | ${$args{val}} =~ /\.arpa$/;
|
---|
| 648 |
|
---|
| 649 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
| 650 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 651 | } else {
|
---|
| 652 | # CNAME target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 653 | return ('FAIL', "CNAME records cannot point directly to an IP address")
|
---|
| 654 | if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
| 655 |
|
---|
| 656 | # Forcibly append the domain name if the hostname being added does not end with the current domain name
|
---|
| 657 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[657] | 658 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/i;
|
---|
[618] | 659 |
|
---|
[632] | 660 | # CNAMEs can not be used for parent nodes; just leaf nodes with no other record types
|
---|
| 661 | # Enforce this for the zone name
|
---|
[653] | 662 | return ('FAIL', "The bare zone name may not be a CNAME") if ${$args{host}} eq $pname || ${$args{host}} =~ /^\@/;
|
---|
[632] | 663 |
|
---|
[618] | 664 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
| 665 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 666 | }
|
---|
| 667 |
|
---|
[228] | 668 | return ('OK','OK');
|
---|
| 669 | } # done CNAME record
|
---|
| 670 |
|
---|
| 671 | # SOA record
|
---|
| 672 | sub _validate_6 {
|
---|
[230] | 673 | # Smart monkeys won't stick their fingers in here; we have
|
---|
| 674 | # separate dedicated routines to deal with SOA records.
|
---|
[228] | 675 | return ('OK','OK');
|
---|
| 676 | } # done SOA record
|
---|
| 677 |
|
---|
| 678 | # PTR record
|
---|
| 679 | sub _validate_12 {
|
---|
[467] | 680 | my $self = shift;
|
---|
| 681 | my $dbh = $self->{dbh};
|
---|
[232] | 682 |
|
---|
| 683 | my %args = @_;
|
---|
[620] | 684 | my $warnflag = '';
|
---|
[232] | 685 |
|
---|
[620] | 686 | if ($args{defrec} eq 'y') {
|
---|
| 687 | if ($args{revrec} eq 'y') {
|
---|
| 688 | if (${$args{val}} =~ /^[\d.]+$/) {
|
---|
| 689 | # v4 or bare number
|
---|
| 690 | if (${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/) {
|
---|
| 691 | # probable full IP. pointless but harmless. validate/normalize.
|
---|
| 692 | my $tmp = NetAddr::IP->new(${$args{val}})->addr
|
---|
| 693 | or return ('FAIL', "${$args{val}} is not a valid IP address");
|
---|
| 694 | ${$args{val}} = $tmp;
|
---|
| 695 | $warnflag = "${$args{val}} will only be added to a small number of zones\n";
|
---|
| 696 | } elsif (${$args{val}} =~ /^\d+$/) {
|
---|
| 697 | # bare number. This can be expanded to either a v4 or v6 zone
|
---|
| 698 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
| 699 | } else {
|
---|
| 700 | # $deity-only-knows what kind of gibberish we've been given. Only usable as a formal .arpa name.
|
---|
| 701 | # Append ARPAZONE to be replaced with the formal .arpa zone name when converted to a live record.
|
---|
| 702 | ${$args{val}} =~ s/\.*$/.ARPAZONE/ unless ${$args{val}} =~ /ARPAZONE$/;
|
---|
| 703 | }
|
---|
| 704 | } elsif (${$args{val}} =~ /^[a-fA-F0-9:]+$/) {
|
---|
| 705 | # v6 or fragment; pray it's not complete gibberish
|
---|
| 706 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
[234] | 707 | } else {
|
---|
[620] | 708 | # $deity-only-knows what kind of gibberish we've been given. Only usable as a formal .arpa name.
|
---|
| 709 | # Append ARPAZONE to be replaced with the formal .arpa zone name when converted to a live record.
|
---|
| 710 | ${$args{val}} .= ".ARPAZONE" unless ${$args{val}} =~ /ARPAZONE$/;
|
---|
[234] | 711 | }
|
---|
[620] | 712 | } else {
|
---|
| 713 | return ('FAIL', "PTR records are not supported in default record sets for forward zones (domains)");
|
---|
[232] | 714 | }
|
---|
[620] | 715 | } else {
|
---|
| 716 | if ($args{revrec} eq 'y') {
|
---|
| 717 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 718 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
[232] | 719 |
|
---|
[620] | 720 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
[249] | 721 |
|
---|
[620] | 722 | if (${$args{val}} =~ /\.arpa$/) {
|
---|
| 723 | # Check that it's well-formed
|
---|
| 724 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 725 |
|
---|
| 726 | # Check if it's a proper formal .arpa name for an IP, and renormalize it to the IP
|
---|
| 727 | # value if so. I can't see why someone would voluntarily work with those instead of
|
---|
| 728 | # the natural IP values but what the hey.
|
---|
| 729 | my ($code,$tmp) = _zone2cidr(${$args{val}});
|
---|
| 730 | ${$args{val}} = $tmp->addr if $code ne 'FAIL';
|
---|
[272] | 731 | } else {
|
---|
[620] | 732 | # not a formal .arpa name, so it should be an IP value. Validate...
|
---|
| 733 | return ('FAIL', "${$args{val}} is not a valid IP value")
|
---|
| 734 | unless ${$args{val}} =~ /^(?:\d+\.\d+\.\d+\.\d+|[a-fA-F0-9:]+)$/;
|
---|
| 735 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
| 736 | or return ('FAIL', "IP/value looks like an IP address but isn't valid");
|
---|
| 737 | # ... and normalize.
|
---|
| 738 | ${$args{val}} = $args{addr}->addr;
|
---|
[272] | 739 | }
|
---|
[620] | 740 | # Validate PTR target for form.
|
---|
| 741 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 742 | } else { # revrec ne 'y'
|
---|
| 743 | # Fetch the domain and append if the passed hostname isn't within it.
|
---|
| 744 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[657] | 745 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i);
|
---|
[620] | 746 | # Validate hostname and target for form
|
---|
| 747 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 748 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
[249] | 749 | }
|
---|
[620] | 750 | }
|
---|
[272] | 751 |
|
---|
[620] | 752 | # Multiple PTR records do NOT generally do what most people believe they do,
|
---|
| 753 | # and tend to fail in the most awkward way possible. Check and warn.
|
---|
| 754 |
|
---|
| 755 | my $chkbase = ${$args{val}};;
|
---|
| 756 | my $hostcol = 'val'; # Reverse zone hostnames are stored "backwards"
|
---|
| 757 | if ($args{revrec} eq 'n') { # PTRs in forward zones should be rare.
|
---|
| 758 | $chkbase = ${$args{host}};
|
---|
| 759 | $hostcol = 'host';
|
---|
[232] | 760 | }
|
---|
[620] | 761 | my @checkvals = ($chkbase);
|
---|
| 762 | if ($chkbase =~ /,/) {
|
---|
| 763 | # push . and :: variants into checkvals if $chkbase has ,
|
---|
| 764 | my $tmp;
|
---|
| 765 | ($tmp = $chkbase) =~ s/,/./;
|
---|
| 766 | push @checkvals, $tmp;
|
---|
| 767 | ($tmp = $chkbase) =~ s/,/::/;
|
---|
| 768 | push @checkvals, $tmp;
|
---|
| 769 | }
|
---|
[232] | 770 |
|
---|
[620] | 771 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE $hostcol = ?");
|
---|
| 772 | foreach my $checkme (@checkvals) {
|
---|
| 773 | if ($args{update}) {
|
---|
| 774 | # $args{update} contains the ID of the record being updated. If the list of records that matches
|
---|
| 775 | # the new hostname specification doesn't include this, the change effectively adds a new PTR that's
|
---|
| 776 | # the same as one or more existing ones.
|
---|
| 777 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 778 | " WHERE val = ?", undef, ($checkme)) };
|
---|
| 779 | $warnflag .= "PTR record for $checkme already exists; adding another will probably not do what you want"
|
---|
| 780 | if @ptrs && (!grep /^$args{update}$/, @ptrs);
|
---|
| 781 | } else {
|
---|
| 782 | # New record. Always warn if a PTR exists
|
---|
[661] | 783 | # Don't warn when a matching A record exists tho
|
---|
[620] | 784 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
[661] | 785 | " WHERE $hostcol = ? AND (type=12 OR type=65280 OR type=65281)", undef, ($checkme));
|
---|
[620] | 786 | $warnflag .= "PTR record for $checkme already exists; adding another will probably not do what you want"
|
---|
| 787 | if $ptrcount;
|
---|
| 788 | }
|
---|
| 789 | }
|
---|
| 790 |
|
---|
| 791 | return ('WARN',$warnflag) if $warnflag;
|
---|
| 792 |
|
---|
[228] | 793 | return ('OK','OK');
|
---|
| 794 | } # done PTR record
|
---|
| 795 |
|
---|
| 796 | # MX record
|
---|
| 797 | sub _validate_15 {
|
---|
[467] | 798 | my $self = shift;
|
---|
| 799 | my $dbh = $self->{dbh};
|
---|
[230] | 800 |
|
---|
| 801 | my %args = @_;
|
---|
| 802 |
|
---|
[622] | 803 | # only for strict type restrictions
|
---|
| 804 | # return ('FAIL', 'Reverse zones cannot contain MX records') if $args{revrec} eq 'y';
|
---|
[230] | 805 |
|
---|
| 806 | return ('FAIL', "Distance is required for MX records") unless defined(${$args{dist}});
|
---|
| 807 | ${$args{dist}} =~ s/\s*//g;
|
---|
| 808 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
|
---|
| 809 |
|
---|
| 810 | ${$args{fields}} = "distance,";
|
---|
| 811 | push @{$args{vallist}}, ${$args{dist}};
|
---|
| 812 |
|
---|
[622] | 813 | if ($args{revrec} eq 'n') {
|
---|
| 814 | # MX target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 815 | return ('FAIL', "MX records cannot point directly to an IP address")
|
---|
| 816 | if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
[230] | 817 |
|
---|
[622] | 818 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 819 | # or the intended parent domain for live records.
|
---|
| 820 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[657] | 821 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i);
|
---|
[653] | 822 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
[622] | 823 | } else {
|
---|
| 824 | # MX target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 825 | return ('FAIL', "MX records cannot point directly to an IP address")
|
---|
[627] | 826 | if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
[273] | 827 |
|
---|
[622] | 828 | # MX records in reverse zones get stricter treatment. The UI bars adding them in
|
---|
| 829 | # reverse record sets, but we "need" to allow editing existing ones. And we'll allow
|
---|
| 830 | # editing them if some loon manually munges one into a default reverse record set.
|
---|
| 831 | if ($args{defrec} eq 'n') {
|
---|
| 832 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 833 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
| 834 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
| 835 | }
|
---|
| 836 |
|
---|
| 837 | ##enhance or ##fixme
|
---|
| 838 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design
|
---|
| 839 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
| 840 | ${$args{val}} =~ /\.arpa$/;
|
---|
| 841 |
|
---|
| 842 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
| 843 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 844 |
|
---|
| 845 | }
|
---|
| 846 |
|
---|
[228] | 847 | return ('OK','OK');
|
---|
| 848 | } # done MX record
|
---|
| 849 |
|
---|
| 850 | # TXT record
|
---|
| 851 | sub _validate_16 {
|
---|
[586] | 852 | my $self = shift;
|
---|
| 853 |
|
---|
| 854 | my %args = @_;
|
---|
| 855 |
|
---|
[623] | 856 | if ($args{revrec} eq 'n') {
|
---|
[586] | 857 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 858 | # or the intended parent domain for live records.
|
---|
| 859 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[657] | 860 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i);
|
---|
[623] | 861 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 862 | } else {
|
---|
| 863 | # We don't coerce reverse "hostnames" into the zone, mainly because we store most sane
|
---|
| 864 | # records as IP values, not .arpa names.
|
---|
| 865 | if ($args{defrec} eq 'n') {
|
---|
| 866 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 867 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
| 868 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
| 869 | }
|
---|
| 870 |
|
---|
| 871 | ##enhance or ##fixme
|
---|
| 872 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design
|
---|
| 873 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
| 874 | ${$args{val}} =~ /\.arpa$/;
|
---|
[586] | 875 | }
|
---|
| 876 |
|
---|
[231] | 877 | # Could arguably put a WARN return here on very long (>512) records
|
---|
[228] | 878 | return ('OK','OK');
|
---|
| 879 | } # done TXT record
|
---|
| 880 |
|
---|
| 881 | # RP record
|
---|
| 882 | sub _validate_17 {
|
---|
[623] | 883 | # Probably have to validate these separately some day. Call _validate_16() above since
|
---|
| 884 | # they're otherwise very similar
|
---|
| 885 | return _validate_16(@_);
|
---|
[228] | 886 | } # done RP record
|
---|
| 887 |
|
---|
| 888 | # AAAA record
|
---|
[626] | 889 | # Almost but not quite an exact duplicate of A record
|
---|
[228] | 890 | sub _validate_28 {
|
---|
[467] | 891 | my $self = shift;
|
---|
| 892 | my $dbh = $self->{dbh};
|
---|
[229] | 893 |
|
---|
[230] | 894 | my %args = @_;
|
---|
[229] | 895 |
|
---|
[626] | 896 | # only for strict type restrictions
|
---|
| 897 | # return ('FAIL', 'Reverse zones cannot contain AAAA records') if $args{revrec} eq 'y';
|
---|
[229] | 898 |
|
---|
[626] | 899 | if ($args{revrec} eq 'y') {
|
---|
| 900 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 901 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
[229] | 902 |
|
---|
[626] | 903 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
| 904 |
|
---|
| 905 | # ${$args{val}} is either a valid IP or a string ending with the .arpa zone name;
|
---|
| 906 | # now check if it's a well-formed FQDN
|
---|
| 907 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
| 908 | ${$args{val}} =~ /\.arpa$/;
|
---|
| 909 |
|
---|
| 910 | # Check IP is well-formed, and that it's a v4 address
|
---|
| 911 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
|
---|
| 912 | return ('FAIL',"AAAA record must be a valid IPv6 address")
|
---|
| 913 | unless ${$args{host}} =~ /^[a-fA-F0-9:]+$/;
|
---|
| 914 | $args{addr} = new NetAddr::IP ${$args{host}};
|
---|
| 915 | return ('FAIL',"AAAA record must be a valid IPv6 address")
|
---|
[230] | 916 | unless $args{addr} && $args{addr}->{isv6};
|
---|
[626] | 917 | # coerce IP/value to normalized form for storage
|
---|
| 918 | ${$args{host}} = $args{addr}->addr;
|
---|
[229] | 919 |
|
---|
[626] | 920 | # I'm just going to ignore the utterly barmy idea of an AAAA record in the *default*
|
---|
| 921 | # records for a reverse zone; it's bad enough to find one in funky legacy data.
|
---|
| 922 |
|
---|
| 923 | } else {
|
---|
| 924 | # revrec ne 'y'
|
---|
| 925 |
|
---|
| 926 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 927 | # or the intended parent domain for live records.
|
---|
| 928 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[657] | 929 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i);
|
---|
[626] | 930 |
|
---|
| 931 | # Check if it's a proper formal .arpa name for an IP, and renormalize it to the IP
|
---|
| 932 | # value if so. Done mainly for symmetry with PTR/AAAA+PTR, and saves a conversion on export.
|
---|
| 933 | if (${$args{val}} =~ /\.arpa$/) {
|
---|
| 934 | my ($code,$tmp) = _zone2cidr(${$args{val}});
|
---|
| 935 | if ($code ne 'FAIL') {
|
---|
| 936 | ${$args{val}} = $tmp->addr;
|
---|
| 937 | $args{addr} = $tmp;
|
---|
| 938 | }
|
---|
| 939 | }
|
---|
| 940 | # Check IP is well-formed, and that it's a v6 address
|
---|
| 941 | return ('FAIL',"AAAA record must be a valid IPv6 address")
|
---|
| 942 | unless ${$args{val}} =~ /^[a-fA-F0-9:]+$/;
|
---|
| 943 | $args{addr} = new NetAddr::IP ${$args{val}};
|
---|
| 944 | return ('FAIL',"AAAA record must be a valid IPv6 address")
|
---|
| 945 | unless $args{addr} && $args{addr}->{isv6};
|
---|
| 946 | # coerce IP/value to normalized form for storage
|
---|
| 947 | ${$args{val}} = $args{addr}->addr;
|
---|
| 948 | }
|
---|
| 949 |
|
---|
[228] | 950 | return ('OK','OK');
|
---|
| 951 | } # done AAAA record
|
---|
| 952 |
|
---|
| 953 | # SRV record
|
---|
| 954 | sub _validate_33 {
|
---|
[467] | 955 | my $self = shift;
|
---|
| 956 | my $dbh = $self->{dbh};
|
---|
[231] | 957 |
|
---|
| 958 | my %args = @_;
|
---|
| 959 |
|
---|
| 960 | # Not absolutely true but WTF use is an SRV record for a reverse zone?
|
---|
[656] | 961 | # return ('FAIL', 'Reverse zones cannot contain SRV records') if $args{revrec} eq 'y';
|
---|
[231] | 962 |
|
---|
[627] | 963 | # Key additional record parts. Always required.
|
---|
| 964 | return ('FAIL',"Distance, port and weight are required for SRV records")
|
---|
| 965 | unless defined(${$args{weight}}) && defined(${$args{port}}) && defined(${$args{dist}});
|
---|
[231] | 966 | ${$args{dist}} =~ s/\s*//g;
|
---|
| 967 | ${$args{weight}} =~ s/\s*//g;
|
---|
| 968 | ${$args{port}} =~ s/\s*//g;
|
---|
[627] | 969 | return ('FAIL',"Distance, port and weight are required, and must be numeric")
|
---|
[231] | 970 | unless ${$args{weight}} =~ /^\d+$/ && ${$args{port}} =~ /^\d+$/;
|
---|
| 971 |
|
---|
| 972 | ${$args{fields}} = "distance,weight,port,";
|
---|
| 973 | push @{$args{vallist}}, (${$args{dist}}, ${$args{weight}}, ${$args{port}});
|
---|
| 974 |
|
---|
[627] | 975 | if ($args{revrec} eq 'n') {
|
---|
| 976 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 977 | # or the intended parent domain for live records.
|
---|
| 978 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[657] | 979 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/i;
|
---|
[627] | 980 |
|
---|
[631] | 981 | ##enhance: Rejig so that we can pass back a WARN red flag, instead of
|
---|
| 982 | # hard-failing, since it seems that purely from the DNS record perspective,
|
---|
| 983 | # SRV records without underscores are syntactically valid
|
---|
[627] | 984 | # Not strictly true, but SRV records not following this convention won't be found.
|
---|
| 985 | return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]")
|
---|
| 986 | unless ${$args{host}} =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/;
|
---|
| 987 |
|
---|
| 988 | # SRV target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 989 | return ('FAIL', "SRV records cannot point directly to an IP address")
|
---|
| 990 | if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
| 991 | } else {
|
---|
| 992 | # hm. we can't do anything sane with IP values here; part of the record data is in
|
---|
| 993 | # fact encoded in the "hostname". enforce .arpa names? OTOH, SRV records in a reverse
|
---|
| 994 | # zone are pretty silly.
|
---|
| 995 |
|
---|
[631] | 996 | ##enhance: Rejig so that we can pass back a WARN red flag, instead of
|
---|
| 997 | # hard-failing, since it seems that purely from the DNS record perspective,
|
---|
| 998 | # SRV records without underscores are syntactically valid
|
---|
[627] | 999 | # Not strictly true, but SRV records not following this convention won't be found.
|
---|
| 1000 | return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]")
|
---|
| 1001 | unless ${$args{val}} =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/;
|
---|
| 1002 |
|
---|
| 1003 | # SRV target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 1004 | return ('FAIL', "SRV records cannot point directly to an IP address")
|
---|
| 1005 | if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
| 1006 |
|
---|
| 1007 | # SRV records in reverse zones get stricter treatment. The UI bars adding them in
|
---|
| 1008 | # reverse record sets, but we "need" to allow editing existing ones. And we'll allow
|
---|
| 1009 | # editing them if some loon manually munges one into a default reverse record set.
|
---|
| 1010 | if ($args{defrec} eq 'n') {
|
---|
| 1011 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 1012 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
| 1013 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
| 1014 | }
|
---|
| 1015 |
|
---|
| 1016 | ##enhance or ##fixme
|
---|
| 1017 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design
|
---|
| 1018 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
| 1019 | ${$args{val}} =~ /\.arpa$/;
|
---|
| 1020 |
|
---|
| 1021 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
| 1022 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 1023 |
|
---|
| 1024 | }
|
---|
| 1025 |
|
---|
[228] | 1026 | return ('OK','OK');
|
---|
| 1027 | } # done SRV record
|
---|
| 1028 |
|
---|
| 1029 | # Now the custom types
|
---|
| 1030 |
|
---|
[232] | 1031 | # A+PTR record. With a very little bit of magic we can also use this sub to validate AAAA+PTR. Whee!
|
---|
[228] | 1032 | sub _validate_65280 {
|
---|
[467] | 1033 | my $self = shift;
|
---|
| 1034 | my $dbh = $self->{dbh};
|
---|
[232] | 1035 |
|
---|
| 1036 | my %args = @_;
|
---|
| 1037 |
|
---|
| 1038 | my $code = 'OK';
|
---|
| 1039 | my $msg = 'OK';
|
---|
| 1040 |
|
---|
| 1041 | if ($args{defrec} eq 'n') {
|
---|
| 1042 | # live record; revrec determines whether we validate the PTR or A component first.
|
---|
[233] | 1043 |
|
---|
[630] | 1044 | # Fail early on non-IP gibberish in ${$args{val}}. Arguably .arpa names might be acceptable
|
---|
| 1045 | # but that gets stupid in forward zones, since these records are shared.
|
---|
| 1046 | return ('FAIL', "$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
[660] | 1047 | if ${$args{rectype}} == 65280 && ${$args{val}} !~ m{^\d+\.\d+\.\d+\.\d+(?:/\d+)?$};
|
---|
[630] | 1048 | return ('FAIL', "$typemap{${$args{rectype}}} record must be a valid IPv6 address")
|
---|
[660] | 1049 | if ${$args{rectype}} == 65281 && ${$args{val}} !~ m{^[a-fA-F0-9:]+(?:/\d+)?$};
|
---|
[630] | 1050 | # If things are not OK, this should prevent Stupid in the error log.
|
---|
| 1051 | $args{addr} = new NetAddr::IP ${$args{val}}
|
---|
| 1052 | or return ('FAIL', "$typemap{${$args{rectype}}} record must be a valid IPv".
|
---|
| 1053 | (${$args{rectype}} == 65280 ? '4' : '6')." address");
|
---|
| 1054 | ${$args{val}} = $args{addr}->addr;
|
---|
| 1055 |
|
---|
[232] | 1056 | if ($args{revrec} eq 'y') {
|
---|
[467] | 1057 | ($code,$msg) = $self->_validate_12(%args);
|
---|
[232] | 1058 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 1059 |
|
---|
[467] | 1060 | # check A+PTR is really v4
|
---|
| 1061 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
| 1062 | if ${$args{rectype}} == 65280 && $args{addr}->{isv6};
|
---|
| 1063 | # check AAAA+PTR is really v6
|
---|
| 1064 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
|
---|
| 1065 | if ${$args{rectype}} == 65281 && !$args{addr}->{isv6};
|
---|
| 1066 |
|
---|
[232] | 1067 | # Check if the reqested domain exists. If not, coerce the type down to PTR and warn.
|
---|
[467] | 1068 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) {
|
---|
[272] | 1069 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
| 1070 | " as PTR instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
[232] | 1071 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
| 1072 | $msg = $addmsg if $code eq 'OK';
|
---|
| 1073 | ${$args{rectype}} = $reverse_typemap{PTR};
|
---|
| 1074 | return ('WARN', $msg);
|
---|
| 1075 | }
|
---|
| 1076 |
|
---|
[242] | 1077 | # Add domain ID to field list and values
|
---|
| 1078 | ${$args{fields}} .= "domain_id,";
|
---|
| 1079 | push @{$args{vallist}}, ${$args{domid}};
|
---|
| 1080 |
|
---|
[232] | 1081 | } else {
|
---|
[467] | 1082 | ($code,$msg) = $self->_validate_1(%args) if ${$args{rectype}} == 65280;
|
---|
| 1083 | ($code,$msg) = $self->_validate_28(%args) if ${$args{rectype}} == 65281;
|
---|
[232] | 1084 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 1085 |
|
---|
| 1086 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
| 1087 | # work here since we don't *know* which parent to put it in.
|
---|
[233] | 1088 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
[232] | 1089 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
| 1090 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
| 1091 | if (!$revid) {
|
---|
[272] | 1092 | $msg = "Record ".($args{update} ? 'updated' : 'added')." as ".(${$args{rectype}} == 65280 ? 'A' : 'AAAA').
|
---|
[232] | 1093 | " instead of $typemap{${$args{rectype}}}; reverse zone not found for ${$args{val}}";
|
---|
| 1094 | ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
| 1095 | return ('WARN', $msg);
|
---|
| 1096 | }
|
---|
| 1097 |
|
---|
| 1098 | # Check for duplicate PTRs. Note we don't have to play games with $code and $msg, because
|
---|
| 1099 | # by definition there can't be duplicate PTRs if the reverse zone isn't managed here.
|
---|
[272] | 1100 | if ($args{update}) {
|
---|
| 1101 | # Record update. There should usually be an existing PTR (the record being updated)
|
---|
| 1102 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 1103 | " WHERE val = ?", undef, (${$args{val}})) };
|
---|
[273] | 1104 | if (@ptrs && (!grep /^$args{update}$/, @ptrs)) {
|
---|
[272] | 1105 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
|
---|
| 1106 | $code = 'WARN';
|
---|
| 1107 | }
|
---|
| 1108 | } else {
|
---|
| 1109 | # New record. Always warn if a PTR exists
|
---|
| 1110 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 1111 | " WHERE val = ?", undef, (${$args{val}}));
|
---|
| 1112 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want"
|
---|
| 1113 | if $ptrcount;
|
---|
| 1114 | $code = 'WARN' if $ptrcount;
|
---|
[232] | 1115 | }
|
---|
| 1116 |
|
---|
[630] | 1117 | # Add the reverse zone ID to the fieldlist
|
---|
[232] | 1118 | ${$args{fields}} .= "rdns_id,";
|
---|
| 1119 | push @{$args{vallist}}, $revid;
|
---|
| 1120 |
|
---|
[653] | 1121 | # Coerce the hostname back to the domain; this is so it displays and manipulates
|
---|
| 1122 | # sanely in the reverse zone.
|
---|
| 1123 | if (${$args{host}} eq '@') {
|
---|
| 1124 | ${$args{host}} = $self->domainName($args{id}); # errors? What errors?
|
---|
| 1125 | }
|
---|
| 1126 | } # revrec ne 'y'
|
---|
| 1127 |
|
---|
[233] | 1128 | } else { # defrec eq 'y'
|
---|
[630] | 1129 |
|
---|
[233] | 1130 | if ($args{revrec} eq 'y') {
|
---|
[467] | 1131 | ($code,$msg) = $self->_validate_12(%args);
|
---|
[233] | 1132 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 1133 | if (${$args{rectype}} == 65280) {
|
---|
| 1134 | return ('FAIL',"A+PTR record must be a valid IPv4 address or fragment")
|
---|
| 1135 | if ${$args{val}} =~ /:/;
|
---|
[234] | 1136 | ${$args{val}} =~ s/^ZONE,/ZONE./; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
[233] | 1137 | } elsif (${$args{rectype}} == 65281) {
|
---|
| 1138 | return ('FAIL',"AAAA+PTR record must be a valid IPv6 address or fragment")
|
---|
| 1139 | if ${$args{val}} =~ /\./;
|
---|
[234] | 1140 | ${$args{val}} =~ s/^ZONE,/ZONE::/; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
[233] | 1141 | }
|
---|
| 1142 | } else {
|
---|
| 1143 | # This is easy. I also can't see a real use-case for A/AAAA+PTR in *all* forward
|
---|
| 1144 | # domains, since you wouldn't be able to substitute both domain and reverse zone
|
---|
| 1145 | # sanely, and you'd end up with guaranteed over-replicated PTR records that would
|
---|
| 1146 | # confuse the hell out of pretty much anything that uses them.
|
---|
[234] | 1147 | ##fixme: make this a config flag?
|
---|
[233] | 1148 | return ('FAIL', "$typemap{${$args{rectype}}} records not allowed in default domains");
|
---|
| 1149 | }
|
---|
[232] | 1150 | }
|
---|
| 1151 |
|
---|
| 1152 | return ($code, $msg);
|
---|
[228] | 1153 | } # done A+PTR record
|
---|
| 1154 |
|
---|
| 1155 | # AAAA+PTR record
|
---|
[232] | 1156 | # A+PTR above has been magicked to handle AAAA+PTR as well.
|
---|
[228] | 1157 | sub _validate_65281 {
|
---|
[232] | 1158 | return _validate_65280(@_);
|
---|
[228] | 1159 | } # done AAAA+PTR record
|
---|
| 1160 |
|
---|
| 1161 | # PTR template record
|
---|
| 1162 | sub _validate_65282 {
|
---|
[467] | 1163 | my $self = shift;
|
---|
| 1164 | my $dbh = $self->{dbh};
|
---|
[340] | 1165 |
|
---|
| 1166 | my %args = @_;
|
---|
| 1167 |
|
---|
| 1168 | # we're *this* >.< close to being able to just call _validate_12... unfortunately we can't, quite.
|
---|
| 1169 | if ($args{revrec} eq 'y') {
|
---|
| 1170 | if ($args{defrec} eq 'n') {
|
---|
[467] | 1171 | return ('FAIL', "Template block ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
| 1172 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
[340] | 1173 | ##fixme: warn if $args{val} is not /31 or larger block?
|
---|
| 1174 | ${$args{val}} = "$args{addr}";
|
---|
| 1175 | } else {
|
---|
| 1176 | if (${$args{val}} =~ /\./) {
|
---|
| 1177 | # looks like a v4 or fragment
|
---|
| 1178 | if (${$args{val}} =~ m|^\d+\.\d+\.\d+\.\d+(?:/\d+)?$|) {
|
---|
| 1179 | # woo! a complete IP! validate it and normalize, or fail.
|
---|
| 1180 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
| 1181 | or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
|
---|
| 1182 | ${$args{val}} = "$args{addr}";
|
---|
| 1183 | } else {
|
---|
| 1184 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
| 1185 | }
|
---|
| 1186 | } elsif (${$args{val}} =~ /[a-f:]/) {
|
---|
| 1187 | # looks like a v6 or fragment
|
---|
| 1188 | ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
|
---|
| 1189 | if ($args{addr}) {
|
---|
| 1190 | if ($args{addr}->addr =~ /^0/) {
|
---|
| 1191 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
| 1192 | } else {
|
---|
| 1193 | ${$args{val}} = "$args{addr}";
|
---|
| 1194 | }
|
---|
| 1195 | }
|
---|
| 1196 | } else {
|
---|
| 1197 | # bare number (probably). These could be v4 or v6, so we'll
|
---|
| 1198 | # expand on these on creation of a reverse zone.
|
---|
| 1199 | ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
|
---|
| 1200 | }
|
---|
| 1201 | }
|
---|
| 1202 | ##fixme: validate %-patterns?
|
---|
| 1203 |
|
---|
| 1204 | # Unlike single PTR records, there is absolutely no way to sanely support multiple
|
---|
| 1205 | # PTR templates for the same block, since they expect to expand to all the individual
|
---|
| 1206 | # IPs on export. Nested templates should be supported though.
|
---|
| 1207 |
|
---|
| 1208 | my @checkvals = (${$args{val}});
|
---|
| 1209 | if (${$args{val}} =~ /,/) {
|
---|
| 1210 | # push . and :: variants into checkvals if val has ,
|
---|
| 1211 | my $tmp;
|
---|
| 1212 | ($tmp = ${$args{val}}) =~ s/,/./;
|
---|
| 1213 | push @checkvals, $tmp;
|
---|
| 1214 | ($tmp = ${$args{val}}) =~ s/,/::/;
|
---|
| 1215 | push @checkvals, $tmp;
|
---|
| 1216 | }
|
---|
| 1217 | ##fixme: this feels wrong still - need to restrict template pseudorecords to One Of Each
|
---|
| 1218 | # Per Netblock such that they don't conflict on export
|
---|
| 1219 | my $typeck;
|
---|
| 1220 | # type 65282 -> ptr template -> look for any of 65282, 65283, 65284
|
---|
| 1221 | $typeck = 'type=65283 OR type=65284' if ${$args{rectype}} == 65282;
|
---|
| 1222 | # type 65283 -> a+ptr template -> v4 -> look for 65282 or 65283
|
---|
| 1223 | $typeck = 'type=65283' if ${$args{rectype}} == 65282;
|
---|
| 1224 | # type 65284 -> aaaa+ptr template -> v6 -> look for 65282 or 65284
|
---|
| 1225 | $typeck = 'type=65284' if ${$args{rectype}} == 65282;
|
---|
| 1226 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ? ".
|
---|
| 1227 | "AND (type=65282 OR $typeck)");
|
---|
| 1228 | foreach my $checkme (@checkvals) {
|
---|
| 1229 | $pcsth->execute($checkme);
|
---|
| 1230 | my ($rc) = $pcsth->fetchrow_array;
|
---|
[442] | 1231 | return ('FAIL', "Only one template pseudorecord may exist for a given IP block") if $rc > 1;
|
---|
[340] | 1232 | }
|
---|
| 1233 |
|
---|
| 1234 | } else {
|
---|
| 1235 | return ('FAIL', "Forward zones cannot contain PTR records");
|
---|
| 1236 | }
|
---|
| 1237 |
|
---|
[228] | 1238 | return ('OK','OK');
|
---|
| 1239 | } # done PTR template record
|
---|
| 1240 |
|
---|
| 1241 | # A+PTR template record
|
---|
| 1242 | sub _validate_65283 {
|
---|
[467] | 1243 | my $self = shift;
|
---|
| 1244 | my $dbh = $self->{dbh};
|
---|
[340] | 1245 |
|
---|
| 1246 | my %args = @_;
|
---|
| 1247 |
|
---|
| 1248 | my ($code,$msg) = ('OK','OK');
|
---|
| 1249 |
|
---|
| 1250 | ##fixme: need to fiddle things since A+PTR templates are acceptable in live
|
---|
| 1251 | # forward zones but not default records
|
---|
| 1252 | if ($args{defrec} eq 'n') {
|
---|
| 1253 | if ($args{revrec} eq 'n') {
|
---|
| 1254 |
|
---|
[653] | 1255 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 1256 | # or the intended parent domain for live records.
|
---|
| 1257 | my $pname = $self->domainName($args{id});
|
---|
[657] | 1258 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/i;
|
---|
[653] | 1259 |
|
---|
| 1260 | # check for form; note this checks both normal and "other" hostnames.
|
---|
| 1261 | return ('FAIL', $errstr)
|
---|
| 1262 | if !_check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 1263 |
|
---|
[340] | 1264 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
| 1265 | # work here since we don't *know* which parent to put it in.
|
---|
| 1266 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
| 1267 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
| 1268 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
| 1269 | # Fail if no match; we can't coerce a PTR-template type down to not include the PTR bit currently.
|
---|
| 1270 | if (!$revid) {
|
---|
| 1271 | $msg = "Can't ".($args{update} ? 'update' : 'add')." ${$args{host}}/${$args{val}} as ".
|
---|
| 1272 | "$typemap{${$args{rectype}}}: reverse zone not found for ${$args{val}}";
|
---|
| 1273 | ##fixme: add A template, AAAA template types?
|
---|
| 1274 | # ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
| 1275 | return ('FAIL', $msg);
|
---|
| 1276 | }
|
---|
| 1277 |
|
---|
| 1278 | # Add reverse zone ID to field list and values
|
---|
| 1279 | ${$args{fields}} .= "rdns_id,";
|
---|
| 1280 | push @{$args{vallist}}, $revid;
|
---|
| 1281 |
|
---|
| 1282 | } else {
|
---|
[467] | 1283 | return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
| 1284 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
[340] | 1285 | ${$args{val}} = "$args{addr}";
|
---|
| 1286 |
|
---|
[467] | 1287 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) {
|
---|
[340] | 1288 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
| 1289 | " as PTR template instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
| 1290 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
| 1291 | $msg = $addmsg if $code eq 'OK';
|
---|
| 1292 | ${$args{rectype}} = 65282;
|
---|
| 1293 | return ('WARN', $msg);
|
---|
| 1294 | }
|
---|
| 1295 |
|
---|
| 1296 | # Add domain ID to field list and values
|
---|
| 1297 | ${$args{fields}} .= "domain_id,";
|
---|
| 1298 | push @{$args{vallist}}, ${$args{domid}};
|
---|
| 1299 | }
|
---|
| 1300 |
|
---|
| 1301 | } else {
|
---|
[467] | 1302 | my ($code,$msg) = $self->_validate_65282(%args);
|
---|
[340] | 1303 | return ($code, $msg) if $code eq 'FAIL';
|
---|
| 1304 | # get domain, check against ${$args{name}}
|
---|
| 1305 | }
|
---|
| 1306 |
|
---|
[228] | 1307 | return ('OK','OK');
|
---|
[624] | 1308 | } # done A+PTR template record
|
---|
[228] | 1309 |
|
---|
| 1310 | # AAAA+PTR template record
|
---|
[624] | 1311 | # Not sure this can be handled sanely due to the size of IPv6 address space
|
---|
[228] | 1312 | sub _validate_65284 {
|
---|
| 1313 | return ('OK','OK');
|
---|
| 1314 | } # done AAAA+PTR template record
|
---|
| 1315 |
|
---|
[342] | 1316 | # Delegation record
|
---|
[345] | 1317 | # This is essentially a specialized clone of the NS record, primarily useful
|
---|
| 1318 | # for delegating IPv4 sub-/24 reverse blocks
|
---|
[342] | 1319 | sub _validate_65285 {
|
---|
[467] | 1320 | my $self = shift;
|
---|
| 1321 | my $dbh = $self->{dbh};
|
---|
[345] | 1322 |
|
---|
| 1323 | my %args = @_;
|
---|
| 1324 |
|
---|
| 1325 | # Almost, but not quite, identical to NS record validation.
|
---|
| 1326 |
|
---|
| 1327 | # Check that the target of the record is within the parent.
|
---|
| 1328 | # Yes, host<->val are mixed up here; can't see a way to avoid it. :(
|
---|
| 1329 | if ($args{defrec} eq 'n') {
|
---|
| 1330 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
| 1331 | if ($args{revrec} eq 'y') {
|
---|
| 1332 | my $tmpip = NetAddr::IP->new(${$args{val}});
|
---|
[467] | 1333 | my $pname = $self->revName($args{id});
|
---|
[345] | 1334 | return ('FAIL',"${$args{val}} not within $pname")
|
---|
[467] | 1335 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$tmpip);
|
---|
[345] | 1336 | # Normalize
|
---|
| 1337 | ${$args{val}} = "$tmpip";
|
---|
| 1338 | } else {
|
---|
[467] | 1339 | my $pname = $self->domainName($args{id});
|
---|
[657] | 1340 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/i;
|
---|
[345] | 1341 | }
|
---|
| 1342 | } else {
|
---|
| 1343 | return ('FAIL',"Delegation records are not permitted in default record sets");
|
---|
| 1344 | }
|
---|
[342] | 1345 | return ('OK','OK');
|
---|
| 1346 | }
|
---|
[228] | 1347 |
|
---|
[617] | 1348 | # Subs not specific to a particular record type
|
---|
[342] | 1349 |
|
---|
[617] | 1350 | # Convert $$host and/or $$val to lowercase as appropriate.
|
---|
| 1351 | # Should only be called if $self->{lowercase} is true.
|
---|
| 1352 | # $rectype is also a reference for caller convenience
|
---|
| 1353 | sub _caseclean {
|
---|
| 1354 | my ($rectype, $host, $val, $defrec, $revrec) = @_;
|
---|
| 1355 |
|
---|
| 1356 | # Can't case-squash default records, due to DOMAIN, ZONE, and ADMINDOMAIN templating
|
---|
| 1357 | return if $defrec eq 'y';
|
---|
| 1358 |
|
---|
| 1359 | if ($typemap{$$rectype} eq 'TXT' || $typemap{$$rectype} eq 'SPF') {
|
---|
| 1360 | # TXT records should preserve user entry in the string.
|
---|
| 1361 | # SPF records are a duplicate of TXT with a new record type value (99)
|
---|
| 1362 | $$host = lc($$host) if $revrec eq 'n'; # only lowercase $$host on live forward TXT; preserve TXT content
|
---|
| 1363 | $$val = lc($$val) if $revrec eq 'y'; # only lowercase $$val on live reverse TXT; preserve TXT content
|
---|
| 1364 | } else {
|
---|
| 1365 | # Non-TXT, live records, are fully case-insensitive
|
---|
| 1366 | $$host = lc($$host);
|
---|
| 1367 | $$val = lc($$val);
|
---|
| 1368 | } # $typemap{$$rectype} else
|
---|
| 1369 |
|
---|
| 1370 | } # _caseclean()
|
---|
| 1371 |
|
---|
| 1372 |
|
---|
[265] | 1373 | ##
|
---|
| 1374 | ## Record data substitution subs
|
---|
| 1375 | ##
|
---|
[228] | 1376 |
|
---|
[298] | 1377 | # Replace ZONE in hostname, or create (most of) the actual proper zone name
|
---|
[265] | 1378 | sub _ZONE {
|
---|
| 1379 | my $zone = shift;
|
---|
| 1380 | my $string = shift;
|
---|
| 1381 | my $fr = shift || 'f'; # flag for forward/reverse order? nb: ignored for IP
|
---|
[298] | 1382 | my $sep = shift || '-'; # Separator character - unlikely we'll ever need more than . or -
|
---|
[265] | 1383 |
|
---|
[298] | 1384 | my $prefix;
|
---|
[265] | 1385 |
|
---|
| 1386 | $string =~ s/,/./ if !$zone->{isv6};
|
---|
| 1387 | $string =~ s/,/::/ if $zone->{isv6};
|
---|
| 1388 |
|
---|
[298] | 1389 | # Subbing ZONE in the host. We need to properly ID the netblock range
|
---|
| 1390 | # The subbed text should have "network IP with trailing zeros stripped" for
|
---|
| 1391 | # blocks lined up on octet (for v4) or hex-quad (for v6) boundaries
|
---|
| 1392 | # For blocks that do NOT line up on these boundaries, we take the most
|
---|
| 1393 | # significant octet or 16-bit chunk of the "broadcast" IP and append it
|
---|
| 1394 | # after a double-dash
|
---|
| 1395 | # ie:
|
---|
| 1396 | # 8.0.0.0/6 -> 8.0.0.0 -> 11.255.255.255; sub should be 8--11
|
---|
| 1397 | # 10.0.0.0/12 -> 10.0.0.0 -> 10.0.0.0 -> 10.15.255.255; sub should be 10-0--15
|
---|
| 1398 | # 192.168.4.0/22 -> 192.168.4.0 -> 192.168.7.255; sub should be 192-168-4--7
|
---|
| 1399 | # 192.168.0.8/29 -> 192.168.0.8 -> 192.168.0.15; sub should be 192-168-0-8--15
|
---|
| 1400 | # Similar for v6
|
---|
[265] | 1401 |
|
---|
[298] | 1402 | if (!$zone->{isv6}) { # IPv4
|
---|
| 1403 |
|
---|
| 1404 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
| 1405 | # a funky subnet that had host bits set.
|
---|
| 1406 | my $bc = $zone->broadcast->addr;
|
---|
| 1407 |
|
---|
| 1408 | if ($zone->masklen > 24) {
|
---|
| 1409 | $bc =~ s/^\d+\.\d+\.\d+\.//;
|
---|
| 1410 | } elsif ($zone->masklen > 16) {
|
---|
| 1411 | $prefix =~ s/\.0$//;
|
---|
| 1412 | $bc =~ s/^\d+\.\d+\.//;
|
---|
| 1413 | } elsif ($zone->masklen > 8) {
|
---|
| 1414 | $bc =~ s/^\d+\.//;
|
---|
| 1415 | $prefix =~ s/\.0\.0$//;
|
---|
| 1416 | } else {
|
---|
| 1417 | $prefix =~ s/\.0\.0\.0$//;
|
---|
| 1418 | }
|
---|
| 1419 | if ($zone->masklen % 8) {
|
---|
| 1420 | $bc =~ s/(\.255)+$//;
|
---|
| 1421 | $prefix .= "--$bc"; #"--".zone->masklen; # use range or mask length?
|
---|
| 1422 | }
|
---|
| 1423 | if ($fr eq 'f') {
|
---|
| 1424 | $prefix =~ s/\.+/$sep/g;
|
---|
| 1425 | } else {
|
---|
| 1426 | $prefix = join($sep, reverse(split(/\./, $prefix)));
|
---|
| 1427 | }
|
---|
| 1428 |
|
---|
| 1429 | } else { # IPv6
|
---|
| 1430 |
|
---|
| 1431 | if ($fr eq 'f') {
|
---|
| 1432 |
|
---|
| 1433 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
| 1434 | # a funky subnet that had host bits set.
|
---|
[265] | 1435 | my $bc = $zone->broadcast->addr;
|
---|
| 1436 | if (($zone->masklen % 16) != 0) {
|
---|
[298] | 1437 | # Strip trailing :0 off $prefix, and :ffff off the broadcast IP
|
---|
| 1438 | for (my $i=0; $i<(7-int($zone->masklen / 16)); $i++) {
|
---|
| 1439 | $prefix =~ s/:0$//;
|
---|
| 1440 | $bc =~ s/:ffff$//;
|
---|
| 1441 | }
|
---|
| 1442 | # Strip the leading 16-bit chunks off the front of the broadcast IP
|
---|
| 1443 | $bc =~ s/^([a-f0-9]+:)+//;
|
---|
| 1444 | # Append the remaining 16-bit chunk to the prefix after "--"
|
---|
| 1445 | $prefix .= "--$bc";
|
---|
[265] | 1446 | } else {
|
---|
[298] | 1447 | # Strip off :0 from the end until we reach the netblock length.
|
---|
| 1448 | for (my $i=0; $i<(8-$zone->masklen / 16); $i++) {
|
---|
[265] | 1449 | $prefix =~ s/:0$//;
|
---|
[298] | 1450 | }
|
---|
[265] | 1451 | }
|
---|
[298] | 1452 | # Actually deal with the separator
|
---|
| 1453 | $prefix =~ s/:/$sep/g;
|
---|
| 1454 |
|
---|
| 1455 | } else { # $fr eq 'f'
|
---|
| 1456 |
|
---|
| 1457 | $prefix = $zone->network->full; # Just In Case someone managed to slip in
|
---|
| 1458 | # a funky subnet that had host bits set.
|
---|
| 1459 | my $bc = $zone->broadcast->full;
|
---|
| 1460 | $prefix =~ s/://g; # clean these out since they're not spaced right for this case
|
---|
| 1461 | $bc =~ s/://g;
|
---|
| 1462 | # Strip trailing 0 off $prefix, and f off the broadcast IP, to match the mask length
|
---|
| 1463 | for (my $i=0; $i<(31-int($zone->masklen / 4)); $i++) {
|
---|
| 1464 | $prefix =~ s/0$//;
|
---|
| 1465 | $bc =~ s/f$//;
|
---|
| 1466 | }
|
---|
| 1467 | # Split and reverse the order of the nibbles in the network/broadcast IPs
|
---|
[332] | 1468 | # trim another 0 for nibble-aligned blocks first, but only if we really have a block, not an IP
|
---|
| 1469 | $prefix =~ s/0$// if $zone->masklen % 4 == 0 && $zone->masklen != 128;
|
---|
[298] | 1470 | my @nbits = reverse split //, $prefix;
|
---|
| 1471 | my @bbits = reverse split //, $bc;
|
---|
| 1472 | # Handle the sub-nibble case. Eww. I feel dirty supporting this...
|
---|
| 1473 | $nbits[0] = "$nbits[0]-$bbits[0]" if ($zone->masklen % 4) != 0;
|
---|
| 1474 | # Glue it back together
|
---|
| 1475 | $prefix = join($sep, @nbits);
|
---|
| 1476 |
|
---|
| 1477 | } # $fr ne 'f'
|
---|
| 1478 |
|
---|
| 1479 | } # $zone->{isv6}
|
---|
| 1480 |
|
---|
| 1481 | # Do the substitution, finally
|
---|
| 1482 | $string =~ s/ZONE/$prefix/;
|
---|
| 1483 | $string =~ s/--/-/ if $sep ne '-'; # - as separator needs extra help for sub-octet v4 netblocks
|
---|
| 1484 | return $string;
|
---|
| 1485 | } # done _ZONE()
|
---|
| 1486 |
|
---|
| 1487 | # Not quite a substitution sub, but placed here as it's basically the inverse of above;
|
---|
| 1488 | # given the .arpa zone name, return the CIDR netblock the zone is for.
|
---|
[304] | 1489 | # Supports v4 non-octet/non-classful netblocks as per the method outlined in the Grasshopper Book (2nd Ed p217-218)
|
---|
[298] | 1490 | # Does NOT support non-quad v6 netblocks via the same scheme; it shouldn't ever be necessary.
|
---|
| 1491 | # Takes a nominal .arpa zone name, returns a success code and NetAddr::IP, or a fail code and message
|
---|
| 1492 | sub _zone2cidr {
|
---|
| 1493 | my $zone = shift;
|
---|
| 1494 |
|
---|
| 1495 | my $cidr;
|
---|
[301] | 1496 | my $tmpcidr;
|
---|
| 1497 | my $warnmsg = '';
|
---|
[298] | 1498 |
|
---|
| 1499 | if ($zone =~ /\.in-addr\.arpa\.?$/) {
|
---|
| 1500 | # v4 revzone, formal zone name type
|
---|
| 1501 | my $tmpzone = $zone;
|
---|
[583] | 1502 | return ('FAIL', "Non-numerics in apparent IPv4 reverse zone name [$tmpzone]")
|
---|
| 1503 | if $tmpzone !~ m{^(?:\d+[/-])?[\d\.]+\.in-addr\.arpa\.?$};
|
---|
[298] | 1504 | $tmpzone =~ s/\.in-addr\.arpa\.?//;
|
---|
| 1505 |
|
---|
| 1506 | # Snag the octet pieces
|
---|
| 1507 | my @octs = split /\./, $tmpzone;
|
---|
| 1508 |
|
---|
| 1509 | # Map result of a range manipulation to a mask length change. Cheaper than finding the 2-root of $octets[0]+1.
|
---|
[304] | 1510 | # Note we will not support /31 blocks, mostly due to issues telling "24-31" -> .24/29 apart from
|
---|
| 1511 | # "24-31" -> .24/31", with a litte bit of "/31 is icky".
|
---|
| 1512 | my %maskmap = ( 3 => 2, 7 => 3, 15 => 4, 31 => 5, 63 => 6, 127 => 7,
|
---|
| 1513 | 30 => 2, 29 => 3, 28 => 4, 27 => 5, 26 => 6, 25 => 7
|
---|
| 1514 | );
|
---|
[298] | 1515 |
|
---|
| 1516 | # Handle "range" blocks, eg, 80-83.168.192.in-addr.arpa (192.168.80.0/22)
|
---|
| 1517 | # Need to take the size of the range to offset the basic octet-based mask length,
|
---|
| 1518 | # and make sure the first number in the range gets used as the network address for the block
|
---|
[304] | 1519 | # Alternate form: The second number is actually the real netmask, not the end of the range.
|
---|
[298] | 1520 | my $masklen = 0;
|
---|
[571] | 1521 | if ($octs[0] =~ m{^((\d+)[/-](\d+))$}) { # take the range...
|
---|
[307] | 1522 | if (24 < $3 && $3 < 31) {
|
---|
[304] | 1523 | # we have a real netmask
|
---|
[307] | 1524 | $masklen = -$maskmap{$3};
|
---|
[304] | 1525 | } else {
|
---|
| 1526 | # we have a range. NB: only real CIDR ranges are supported
|
---|
[307] | 1527 | $masklen -= $maskmap{-(eval $1)}; # find the mask base...
|
---|
[304] | 1528 | }
|
---|
[307] | 1529 | $octs[0] = $2; # set the base octet of the range...
|
---|
[265] | 1530 | }
|
---|
[298] | 1531 | @octs = reverse @octs; # We can reverse the octet pieces now that we've extracted and munged any ranges
|
---|
[265] | 1532 |
|
---|
[304] | 1533 | # arguably we should only allow sub-octet range/mask in-addr.arpa
|
---|
| 1534 | # specifications in the least significant octet, but the code is
|
---|
| 1535 | # simpler if we deal with sub-octet delegations at any level.
|
---|
| 1536 |
|
---|
[298] | 1537 | # Now we find the "true" mask with the aid of the "base" calculated above
|
---|
| 1538 | if ($#octs == 0) {
|
---|
| 1539 | $masklen += 8;
|
---|
| 1540 | $tmpcidr = "$octs[0].0.0.0/$masklen"; # really hope we don't see one of these very often.
|
---|
| 1541 | } elsif ($#octs == 1) {
|
---|
| 1542 | $masklen += 16;
|
---|
| 1543 | $tmpcidr = "$octs[0].$octs[1].0.0/$masklen";
|
---|
| 1544 | } elsif ($#octs == 2) {
|
---|
| 1545 | $masklen += 24;
|
---|
| 1546 | $tmpcidr = "$octs[0].$octs[1].$octs[2].0/$masklen";
|
---|
[265] | 1547 | } else {
|
---|
[298] | 1548 | $masklen += 32;
|
---|
| 1549 | $tmpcidr = "$octs[0].$octs[1].$octs[2].$octs[3]/$masklen";
|
---|
[265] | 1550 | }
|
---|
| 1551 |
|
---|
[583] | 1552 | } elsif ($zone =~ /\.ip6\.arpa\.?$/) {
|
---|
[298] | 1553 | # v6 revzone, formal zone name type
|
---|
| 1554 | my $tmpzone = $zone;
|
---|
[583] | 1555 | ##fixme: if-n-when we decide we can support sub-nibble v6 zone names, we'll need to change this segment
|
---|
| 1556 | return ('FAIL', "Non-hexadecimals in apparent IPv6 reverse zone name [$tmpzone]")
|
---|
| 1557 | if $tmpzone !~ /^[a-fA-F\d\.]+\.ip6\.arpa\.?$/;
|
---|
[298] | 1558 | $tmpzone =~ s/\.ip6\.arpa\.?//;
|
---|
| 1559 | my @quads = reverse(split(/\./, $tmpzone));
|
---|
| 1560 | $warnmsg .= "Apparent sub-/64 IPv6 reverse zone\n" if $#quads > 15;
|
---|
| 1561 | my $nc;
|
---|
| 1562 | foreach (@quads) {
|
---|
[301] | 1563 | $tmpcidr .= $_;
|
---|
[583] | 1564 | $tmpcidr .= ":" if ++$nc % 4 == 0 && $nc < $#quads;
|
---|
[298] | 1565 | }
|
---|
| 1566 | my $nq = 1 if $nc % 4 != 0;
|
---|
| 1567 | my $mask = $nc * 4; # need to do this here because we probably increment it below
|
---|
| 1568 | while ($nc++ % 4 != 0) {
|
---|
[301] | 1569 | $tmpcidr .= "0";
|
---|
[298] | 1570 | }
|
---|
[583] | 1571 | # polish it off with trailing ::/mask if this is a CIDR block instead of an IP
|
---|
| 1572 | $tmpcidr .= "::/$mask" if $mask != 128;
|
---|
[298] | 1573 | }
|
---|
[301] | 1574 |
|
---|
| 1575 | # Just to be sure, use NetAddr::IP to validate. Saves a lot of nasty regex watching for valid octet values.
|
---|
| 1576 | return ('FAIL', "Invalid zone $zone (apparent netblock $tmpcidr)")
|
---|
| 1577 | unless $cidr = NetAddr::IP->new($tmpcidr);
|
---|
| 1578 |
|
---|
| 1579 | if ($warnmsg) {
|
---|
| 1580 | $errstr = $warnmsg;
|
---|
| 1581 | return ('WARN', $cidr);
|
---|
| 1582 | }
|
---|
| 1583 | return ('OK', $cidr);
|
---|
[583] | 1584 | ##fixme: use wantarray() to decide what to return?
|
---|
[298] | 1585 | } # done _zone2cidr()
|
---|
[265] | 1586 |
|
---|
[337] | 1587 | # Record template %-parameter expansion, IPv4. Note that IPv6 doesn't
|
---|
| 1588 | # really have a sane way to handle this type of expansion at the moment
|
---|
| 1589 | # due to the size of the address space.
|
---|
| 1590 | # Takes a reference to a template string to be expanded, and an IP to use in the replacement.
|
---|
| 1591 | sub _template4_expand {
|
---|
| 1592 | my $tmpl = shift;
|
---|
| 1593 | my $ip = shift;
|
---|
[298] | 1594 |
|
---|
[337] | 1595 | my @ipparts = split /\./, $ip;
|
---|
| 1596 | my @iphex;
|
---|
| 1597 | my @ippad;
|
---|
| 1598 | for (@ipparts) {
|
---|
| 1599 | push @iphex, sprintf("%x", $_);
|
---|
[443] | 1600 | push @ippad, sprintf("%0.3u", $_);
|
---|
[337] | 1601 | }
|
---|
| 1602 |
|
---|
| 1603 | # IP substitutions in template records:
|
---|
| 1604 | #major patterns:
|
---|
| 1605 | #dashed IP, forward and reverse
|
---|
[532] | 1606 | #underscoreed IP, forward and reverse
|
---|
[337] | 1607 | #dotted IP, forward and reverse (even if forward is... dumb)
|
---|
[532] | 1608 | # -> %r for reverse, %i for forward, leading -, _, or . to indicate separator, defaults to -
|
---|
[337] | 1609 | # %r or %-r => %4d-%3d-%2d-%1d
|
---|
[532] | 1610 | # %_r => %4d_%3d_%2d_%1d
|
---|
[337] | 1611 | # %.r => %4d.%3d.%2d.%1d
|
---|
| 1612 | # %i or %-i => %1d-%2d-%3d-%4d
|
---|
[532] | 1613 | # %_i => %1d_%2d_%3d_%4d
|
---|
[337] | 1614 | # %.i => %1d.%2d.%3d.%4d
|
---|
| 1615 | $$tmpl =~ s/\%r/\%4d-\%3d-\%2d-\%1d/g;
|
---|
[532] | 1616 | $$tmpl =~ s/\%([-._])r/\%4d$1\%3d$1\%2d$1\%1d/g;
|
---|
[337] | 1617 | $$tmpl =~ s/\%i/\%1d-\%2d-\%3d-\%4d/g;
|
---|
[532] | 1618 | $$tmpl =~ s/\%([-._])i/\%1d$1\%2d$1\%3d$1\%4d/g;
|
---|
[337] | 1619 |
|
---|
| 1620 | #hex-coded IP
|
---|
| 1621 | # %h
|
---|
| 1622 | $$tmpl =~ s/\%h/$iphex[0]$iphex[1]$iphex[2]$iphex[3]/g;
|
---|
| 1623 |
|
---|
| 1624 | #IP as decimal-coded 32-bit value
|
---|
| 1625 | # %d
|
---|
| 1626 | my $iptmp = $ipparts[0]*256*256*256 + $ipparts[1]*256*256 + $ipparts[2]*256 + $ipparts[3];
|
---|
| 1627 | $$tmpl =~ s/\%d/$iptmp/g;
|
---|
| 1628 |
|
---|
| 1629 | #minor patterns (per-octet)
|
---|
| 1630 | # %[1234][dh0]
|
---|
| 1631 | #octet
|
---|
| 1632 | #hex-coded octet
|
---|
| 1633 | #0-padded octet
|
---|
| 1634 | $$tmpl =~ s/\%([1234])d/$ipparts[$1-1]/g;
|
---|
| 1635 | $$tmpl =~ s/\%([1234])h/$iphex[$1-1]/g;
|
---|
[443] | 1636 | $$tmpl =~ s/\%([1234])0/$ippad[$1-1]/g;
|
---|
[337] | 1637 | } # _template4_expand()
|
---|
| 1638 |
|
---|
[532] | 1639 | # Broad syntactic check on the hostname. Checks for valid characters, correctly-expandable template patterns.
|
---|
| 1640 | # Takes the hostname, type, and live/default and forward/reverse flags
|
---|
| 1641 | # Returns true/false, sets errstr on failures
|
---|
| 1642 | sub _check_hostname_form {
|
---|
| 1643 | my ($hname,$rectype,$defrec,$revrec) = @_;
|
---|
[337] | 1644 |
|
---|
[532] | 1645 | if ($hname =~ /\%/ && ($rectype == 65282 || $rectype == 65283) ) {
|
---|
| 1646 | my $tmphost = $hname;
|
---|
| 1647 | # we don't actually need to test with the real IP passed; that saves a bit of fiddling.
|
---|
| 1648 | _template4_expand(\$tmphost, '10.10.10.10');
|
---|
[653] | 1649 | if ($tmphost =~ /\%/ || lc($tmphost) !~ /^(?:\*\.)?(?:[0-9a-z_.-]+)$/) {
|
---|
[532] | 1650 | $errstr = "Invalid template $hname";
|
---|
| 1651 | return;
|
---|
| 1652 | }
|
---|
[625] | 1653 | } elsif ($rectype == $reverse_typemap{CNAME}) {
|
---|
| 1654 | # Allow / in reverse CNAME hostnames for sub-/24 delegation
|
---|
| 1655 | if (lc($hname) !~ m|^[0-9a-z_./-]+$|) {
|
---|
| 1656 | # error message is deliberately restrictive; special cases are SPECIAL and not for general use
|
---|
| 1657 | $errstr = "Hostnames may not contain anything other than (0-9 a-z . _)";
|
---|
| 1658 | return;
|
---|
| 1659 | }
|
---|
[532] | 1660 | } elsif ($revrec eq 'y') {
|
---|
| 1661 | # Reverse zones don't support @ in hostnames
|
---|
[625] | 1662 | if (lc($hname) !~ /^(?:\*\.)?[0-9a-z_.-]+$/) {
|
---|
| 1663 | # error message is deliberately restrictive; special cases are SPECIAL and not for general use
|
---|
[532] | 1664 | $errstr = "Hostnames may not contain anything other than (0-9 a-z . _)";
|
---|
| 1665 | return;
|
---|
| 1666 | }
|
---|
| 1667 | } else {
|
---|
[600] | 1668 | if (lc($hname) !~ /^(?:\*\.)?(?:[0-9a-z_.-]+|@)$/) {
|
---|
[532] | 1669 | # Don't mention @, because it would be far too wordy to explain the nuance of @
|
---|
| 1670 | $errstr = "Hostnames may not contain anything other than (0-9 a-z . _)";
|
---|
| 1671 | return;
|
---|
| 1672 | }
|
---|
| 1673 | }
|
---|
| 1674 | return 1;
|
---|
| 1675 | } # _check_hostname_form()
|
---|
| 1676 |
|
---|
| 1677 |
|
---|
[228] | 1678 | ##
|
---|
[2] | 1679 | ## Initialization and cleanup subs
|
---|
| 1680 | ##
|
---|
| 1681 |
|
---|
[128] | 1682 | ## DNSDB::__cfgload()
|
---|
| 1683 | # Private sub to parse a config file and load it into %config
|
---|
[517] | 1684 | # Takes a filename and a hashref to put the parsed entries in
|
---|
[128] | 1685 | sub __cfgload {
|
---|
| 1686 | $errstr = '';
|
---|
| 1687 | my $cfgfile = shift;
|
---|
[517] | 1688 | my $cfg = shift;
|
---|
[131] | 1689 |
|
---|
[128] | 1690 | if (open CFG, "<$cfgfile") {
|
---|
| 1691 | while (<CFG>) {
|
---|
| 1692 | chomp;
|
---|
| 1693 | s/^\s*//;
|
---|
| 1694 | next if /^#/;
|
---|
| 1695 | next if /^$/;
|
---|
| 1696 | # hmm. more complex bits in this file might require [heading] headers, maybe?
|
---|
| 1697 | # $mode = $1 if /^\[(a-z)+]/;
|
---|
| 1698 | # DB connect info
|
---|
[517] | 1699 | $cfg->{dbname} = $1 if /^dbname\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1700 | $cfg->{dbuser} = $1 if /^dbuser\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1701 | $cfg->{dbpass} = $1 if /^dbpass\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1702 | $cfg->{dbhost} = $1 if /^dbhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
[128] | 1703 | # Mail settings
|
---|
[517] | 1704 | $cfg->{mailhost} = $1 if /^mailhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1705 | $cfg->{mailnotify} = $1 if /^mailnotify\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
| 1706 | $cfg->{mailsender} = $1 if /^mailsender\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
| 1707 | $cfg->{mailname} = $1 if /^mailname\s*=\s*([a-z0-9\s_.-]+)/i;
|
---|
| 1708 | $cfg->{orgname} = $1 if /^orgname\s*=\s*([a-z0-9\s_.,'-]+)/i;
|
---|
| 1709 | $cfg->{domain} = $1 if /^domain\s*=\s*([a-z0-9_.-]+)/i;
|
---|
[163] | 1710 | # session - note this is fed directly to CGI::Session
|
---|
[517] | 1711 | $cfg->{timeout} = $1 if /^[tT][iI][mM][eE][oO][uU][tT]\s*=\s*(\d+[smhdwMy]?)/;
|
---|
| 1712 | $cfg->{sessiondir} = $1 if m{^sessiondir\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
[201] | 1713 | # misc
|
---|
[517] | 1714 | $cfg->{log_failures} = $1 if /^log_failures\s*=\s*([a-z01]+)/i;
|
---|
| 1715 | $cfg->{perpage} = $1 if /^perpage\s*=\s*(\d+)/i;
|
---|
| 1716 | $cfg->{exportcache} = $1 if m{^exportcache\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
[559] | 1717 | $cfg->{usecache} = $1 if m{^usecache\s*=\s*([a-z01]+)}i;
|
---|
| 1718 | $cfg->{force_refresh} = $1 if /^force_refresh\s*=\s*([a-z01]+)/i;
|
---|
[542] | 1719 | $cfg->{lowercase} = $1 if /^lowercase\s*=\s*([a-z01]+)/i;
|
---|
[583] | 1720 | $cfg->{showrev_arpa} = $1 if /^showrev_arpa\s*=\s*([a-z]+)/i;
|
---|
[644] | 1721 | $cfg->{template_skip_0} = $1 if /^template_skip_0\s*=\s*([a-z01]+)/i;
|
---|
| 1722 | $cfg->{template_skip_255} = $1 if /^template_skip_255\s*=\s*([a-z01]+)/i;
|
---|
[517] | 1723 | # not supported in dns.cgi yet
|
---|
| 1724 | # $cfg->{templatedir} = $1 if m{^templatedir\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
| 1725 | # $cfg->{templateoverride} = $1 if m{^templateoverride\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
[400] | 1726 | # RPC options
|
---|
[517] | 1727 | $cfg->{rpcmode} = $1 if /^rpc_mode\s*=\s*(socket|HTTP|XMLRPC)\s*$/i;
|
---|
| 1728 | $cfg->{maxfcgi} = $1 if /^max_fcgi_requests\s*=\s*(\d+)\s*$/i;
|
---|
[465] | 1729 | if (my ($tmp) = /^rpc_iplist\s*=\s*(.+)/i) {
|
---|
| 1730 | my @ips = split /[,\s]+/, $tmp;
|
---|
| 1731 | my $rpcsys = shift @ips;
|
---|
[517] | 1732 | push @{$cfg->{rpcacl}{$rpcsys}}, @ips;
|
---|
[400] | 1733 | }
|
---|
[128] | 1734 | }
|
---|
| 1735 | close CFG;
|
---|
| 1736 | } else {
|
---|
[517] | 1737 | $errstr = "Couldn't load configuration file $cfgfile: $!";
|
---|
[128] | 1738 | return;
|
---|
| 1739 | }
|
---|
| 1740 | return 1;
|
---|
| 1741 | } # end __cfgload()
|
---|
| 1742 |
|
---|
| 1743 |
|
---|
[2] | 1744 | ## DNSDB::connectDB()
|
---|
| 1745 | # Creates connection to DNS database.
|
---|
| 1746 | # Requires the database name, username, and password.
|
---|
[465] | 1747 | # Returns a handle to the db or undef on failure.
|
---|
[2] | 1748 | # Set up for a PostgreSQL db; could be any transactional DBMS with the
|
---|
| 1749 | # right changes.
|
---|
[465] | 1750 | # Called by new(); not intended to be called publicly.
|
---|
[2] | 1751 | sub connectDB {
|
---|
| 1752 | $errstr = '';
|
---|
[15] | 1753 | my $dbname = shift;
|
---|
| 1754 | my $user = shift;
|
---|
| 1755 | my $pass = shift;
|
---|
[2] | 1756 | my $dbh;
|
---|
| 1757 | my $DSN = "DBI:Pg:dbname=$dbname";
|
---|
| 1758 |
|
---|
| 1759 | my $host = shift;
|
---|
| 1760 | $DSN .= ";host=$host" if $host;
|
---|
| 1761 |
|
---|
| 1762 | # Note that we want to autocommit by default, and we will turn it off locally as necessary.
|
---|
| 1763 | # We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
|
---|
| 1764 | $dbh = DBI->connect($DSN, $user, $pass, {
|
---|
| 1765 | AutoCommit => 1,
|
---|
| 1766 | PrintError => 0
|
---|
[465] | 1767 | });
|
---|
| 1768 | if (!$dbh) {
|
---|
| 1769 | $errstr = $DBI::errstr;
|
---|
| 1770 | return;
|
---|
| 1771 | }
|
---|
| 1772 | #) if(!$dbh);
|
---|
[2] | 1773 |
|
---|
[465] | 1774 | local $dbh->{RaiseError} = 1;
|
---|
| 1775 |
|
---|
| 1776 | eval {
|
---|
[212] | 1777 | ##fixme: initialize the DB if we can't find the table (since, by definition, there's
|
---|
| 1778 | # nothing there if we can't select from it...)
|
---|
[465] | 1779 | my $tblsth = $dbh->prepare("SELECT count(*) FROM pg_catalog.pg_class WHERE relkind='r' AND relname=?");
|
---|
| 1780 | my ($tblcount) = $dbh->selectrow_array($tblsth, undef, ('misc'));
|
---|
| 1781 | # return (undef,$DBI::errstr) if $dbh->err;
|
---|
[212] | 1782 |
|
---|
| 1783 | #if ($tblcount == 0) {
|
---|
| 1784 | # # create tables one at a time, checking for each.
|
---|
| 1785 | # return (undef, "check table misc missing");
|
---|
| 1786 | #}
|
---|
| 1787 |
|
---|
| 1788 | # Return here if we can't select.
|
---|
| 1789 | # This should retrieve the dbversion key.
|
---|
[465] | 1790 | my $sth = $dbh->prepare("SELECT key,value FROM misc WHERE misc_id=1");
|
---|
| 1791 | $sth->execute();
|
---|
| 1792 | # return (undef,$DBI::errstr) if ($sth->err);
|
---|
[2] | 1793 |
|
---|
[212] | 1794 | ##fixme: do stuff to the DB on version mismatch
|
---|
| 1795 | # x.y series should upgrade on $DNSDB::VERSION > misc(key=>version)
|
---|
| 1796 | # DB should be downward-compatible; column defaults should give sane (if possibly
|
---|
| 1797 | # useless-and-needs-help) values in columns an older software stack doesn't know about.
|
---|
| 1798 |
|
---|
[2] | 1799 | # See if the select returned anything (or null data). This should
|
---|
| 1800 | # succeed if the select executed, but...
|
---|
[465] | 1801 | $sth->fetchrow();
|
---|
| 1802 | # return (undef,$DBI::errstr) if ($sth->err);
|
---|
[2] | 1803 |
|
---|
[465] | 1804 | $sth->finish;
|
---|
[2] | 1805 |
|
---|
[465] | 1806 | }; # wrapped DB checks
|
---|
| 1807 | if ($@) {
|
---|
| 1808 | $errstr = $@;
|
---|
| 1809 | return;
|
---|
| 1810 | }
|
---|
| 1811 |
|
---|
[2] | 1812 | # If we get here, we should be OK.
|
---|
[465] | 1813 | return $dbh;
|
---|
[2] | 1814 | } # end connectDB
|
---|
| 1815 |
|
---|
| 1816 |
|
---|
| 1817 | ## DNSDB::finish()
|
---|
| 1818 | # Cleans up after database handles and so on.
|
---|
| 1819 | # Requires a database handle
|
---|
| 1820 | sub finish {
|
---|
[465] | 1821 | my $self = shift;
|
---|
| 1822 | $self->{dbh}->disconnect;
|
---|
[2] | 1823 | } # end finish
|
---|
| 1824 |
|
---|
| 1825 |
|
---|
| 1826 | ## DNSDB::initGlobals()
|
---|
| 1827 | # Initialize global variables
|
---|
| 1828 | # NB: this does NOT include web-specific session variables!
|
---|
| 1829 | sub initGlobals {
|
---|
[465] | 1830 | my $self = shift;
|
---|
| 1831 | my $dbh = $self->{dbh};
|
---|
[2] | 1832 |
|
---|
[208] | 1833 | # load record types from database
|
---|
[228] | 1834 | my $sth = $dbh->prepare("SELECT val,name,stdflag FROM rectypes");
|
---|
[2] | 1835 | $sth->execute;
|
---|
[228] | 1836 | while (my ($recval,$recname,$stdflag) = $sth->fetchrow_array()) {
|
---|
[2] | 1837 | $typemap{$recval} = $recname;
|
---|
| 1838 | $reverse_typemap{$recname} = $recval;
|
---|
[228] | 1839 | # now we fill the record validation function hash
|
---|
| 1840 | if ($stdflag < 5) {
|
---|
| 1841 | my $fn = "_validate_$recval";
|
---|
| 1842 | $validators{$recval} = \&$fn;
|
---|
| 1843 | } else {
|
---|
| 1844 | my $fn = "sub { return ('FAIL','Type $recval ($recname) not supported'); }";
|
---|
| 1845 | $validators{$recval} = eval $fn;
|
---|
| 1846 | }
|
---|
[2] | 1847 | }
|
---|
| 1848 | } # end initGlobals
|
---|
| 1849 |
|
---|
| 1850 |
|
---|
[401] | 1851 | ## DNSDB::initRPC()
|
---|
[469] | 1852 | # Takes a remote username and remote fullname.
|
---|
[401] | 1853 | # Sets up the RPC logging-pseudouser if needed.
|
---|
| 1854 | # Sets the %userdata hash for logging.
|
---|
| 1855 | # Returns undef on failure
|
---|
| 1856 | sub initRPC {
|
---|
[469] | 1857 | my $self = shift;
|
---|
| 1858 | my $dbh = $self->{dbh};
|
---|
[401] | 1859 | my %args = @_;
|
---|
| 1860 |
|
---|
| 1861 | return if !$args{username};
|
---|
| 1862 | return if !$args{fullname};
|
---|
| 1863 |
|
---|
[406] | 1864 | $args{username} = "$args{username}/$args{rpcsys}";
|
---|
| 1865 |
|
---|
| 1866 | my $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
|
---|
[404] | 1867 | " FROM users WHERE username=?", undef, ($args{username}) );
|
---|
[406] | 1868 | if (!$tmpuser) {
|
---|
[401] | 1869 | $dbh->do("INSERT INTO users (username,password,firstname,type) VALUES (?,'RPC',?,'R')", undef,
|
---|
| 1870 | ($args{username}, $args{fullname}) );
|
---|
[406] | 1871 | $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
|
---|
[404] | 1872 | " FROM users WHERE username=?", undef, ($args{username}) );
|
---|
[401] | 1873 | }
|
---|
[488] | 1874 | $tmpuser->{lastname} = '' if !$tmpuser->{lastname};
|
---|
| 1875 | $self->{loguserid} = $tmpuser->{userid};
|
---|
| 1876 | $self->{logusername} = $tmpuser->{username};
|
---|
| 1877 | $self->{logfullname} = "$tmpuser->{firstname} $tmpuser->{lastname} ($args{rpcsys})";
|
---|
[406] | 1878 | return 1 if $tmpuser;
|
---|
[401] | 1879 | } # end initRPC()
|
---|
| 1880 |
|
---|
| 1881 |
|
---|
[278] | 1882 | ## DNSDB::login()
|
---|
| 1883 | # Takes a database handle, username and password
|
---|
[316] | 1884 | # Returns a userdata hash (UID, GID, username, fullname parts) if username exists,
|
---|
| 1885 | # password matches the one on file, and account is not disabled
|
---|
[278] | 1886 | # Returns undef otherwise
|
---|
| 1887 | sub login {
|
---|
[469] | 1888 | my $self = shift;
|
---|
| 1889 | my $dbh = $self->{dbh};
|
---|
[278] | 1890 | my $user = shift;
|
---|
| 1891 | my $pass = shift;
|
---|
| 1892 |
|
---|
[316] | 1893 | my $userinfo = $dbh->selectrow_hashref("SELECT user_id,group_id,password,firstname,lastname,status".
|
---|
| 1894 | " FROM users WHERE username=?",
|
---|
[279] | 1895 | undef, ($user) );
|
---|
| 1896 | return if !$userinfo;
|
---|
[316] | 1897 | return if !$userinfo->{status};
|
---|
[278] | 1898 |
|
---|
[279] | 1899 | if ($userinfo->{password} =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
|
---|
[278] | 1900 | # native passwords (crypt-md5)
|
---|
[279] | 1901 | return if $userinfo->{password} ne unix_md5_crypt($pass,$1);
|
---|
| 1902 | } elsif ($userinfo->{password} =~ /^[0-9a-f]{32}$/) {
|
---|
[278] | 1903 | # VegaDNS import (hex-coded MD5)
|
---|
[279] | 1904 | return if $userinfo->{password} ne md5_hex($pass);
|
---|
[278] | 1905 | } else {
|
---|
| 1906 | # plaintext (convenient now and then)
|
---|
[279] | 1907 | return if $userinfo->{password} ne $pass;
|
---|
[278] | 1908 | }
|
---|
| 1909 |
|
---|
[279] | 1910 | return $userinfo;
|
---|
[278] | 1911 | } # end login()
|
---|
| 1912 |
|
---|
| 1913 |
|
---|
[279] | 1914 | ## DNSDB::initActionLog()
|
---|
| 1915 | # Set up action logging. Takes a database handle and user ID
|
---|
| 1916 | # Sets some internal globals and Does The Right Thing to set up a logging channel.
|
---|
| 1917 | # This sets up _log() to spew out log entries to the defined channel without worrying
|
---|
| 1918 | # about having to open a file or a syslog channel
|
---|
| 1919 | ##fixme Need to call _initActionLog_blah() for various logging channels, configured
|
---|
[517] | 1920 | # via dnsdb.conf, in $self->{log_channel} or something
|
---|
[279] | 1921 | # See https://secure.deepnet.cx/trac/dnsadmin/ticket/21
|
---|
| 1922 | sub initActionLog {
|
---|
[469] | 1923 | my $self = shift;
|
---|
| 1924 | my $dbh = $self->{dbh};
|
---|
[279] | 1925 | my $uid = shift;
|
---|
| 1926 |
|
---|
| 1927 | return if !$uid;
|
---|
| 1928 |
|
---|
| 1929 | # snag user info for logging. there's got to be a way to not have to pass this back
|
---|
| 1930 | # and forth from a caller, but web usage means no persistence we can rely on from
|
---|
| 1931 | # the server side.
|
---|
| 1932 | my ($username,$fullname) = $dbh->selectrow_array("SELECT username, firstname || ' ' || lastname".
|
---|
| 1933 | " FROM users WHERE user_id=?", undef, ($uid));
|
---|
| 1934 | ##fixme: errors are unpossible!
|
---|
| 1935 |
|
---|
[488] | 1936 | $self->{logusername} = $username;
|
---|
| 1937 | $self->{loguserid} = $uid;
|
---|
| 1938 | $self->{logfullname} = $fullname;
|
---|
[279] | 1939 |
|
---|
| 1940 | # convert to real check once we have other logging channels
|
---|
[517] | 1941 | # if ($self->{log_channel} eq 'sql') {
|
---|
[279] | 1942 | # Open Log, Sez Me!
|
---|
| 1943 | # }
|
---|
| 1944 |
|
---|
| 1945 | } # end initActionLog
|
---|
| 1946 |
|
---|
| 1947 |
|
---|
[65] | 1948 | ## DNSDB::getPermissions()
|
---|
| 1949 | # Get permissions from DB
|
---|
| 1950 | # Requires DB handle, group or user flag, ID, and hashref.
|
---|
| 1951 | sub getPermissions {
|
---|
[469] | 1952 | my $self = shift;
|
---|
| 1953 | my $dbh = $self->{dbh};
|
---|
| 1954 |
|
---|
[65] | 1955 | my $type = shift;
|
---|
| 1956 | my $id = shift;
|
---|
| 1957 | my $hash = shift;
|
---|
| 1958 |
|
---|
| 1959 | my $sql = qq(
|
---|
| 1960 | SELECT
|
---|
| 1961 | p.admin,p.self_edit,
|
---|
| 1962 | p.group_create,p.group_edit,p.group_delete,
|
---|
| 1963 | p.user_create,p.user_edit,p.user_delete,
|
---|
| 1964 | p.domain_create,p.domain_edit,p.domain_delete,
|
---|
[387] | 1965 | p.record_create,p.record_edit,p.record_delete,p.record_locchg,
|
---|
[382] | 1966 | p.location_create,p.location_edit,p.location_delete,p.location_view
|
---|
[65] | 1967 | FROM permissions p
|
---|
| 1968 | );
|
---|
| 1969 | if ($type eq 'group') {
|
---|
| 1970 | $sql .= qq(
|
---|
| 1971 | JOIN groups g ON g.permission_id=p.permission_id
|
---|
| 1972 | WHERE g.group_id=?
|
---|
| 1973 | );
|
---|
| 1974 | } else {
|
---|
| 1975 | $sql .= qq(
|
---|
| 1976 | JOIN users u ON u.permission_id=p.permission_id
|
---|
| 1977 | WHERE u.user_id=?
|
---|
| 1978 | );
|
---|
| 1979 | }
|
---|
| 1980 |
|
---|
| 1981 | my $sth = $dbh->prepare($sql);
|
---|
| 1982 |
|
---|
[514] | 1983 | ##fixme? we don't trap other plain SELECT errors
|
---|
| 1984 | $sth->execute($id);
|
---|
[65] | 1985 |
|
---|
| 1986 | # my $permref = $sth->fetchrow_hashref;
|
---|
| 1987 | # return $permref;
|
---|
| 1988 | # $hash = $permref;
|
---|
| 1989 | # Eww. Need to learn how to forcibly drop a hashref onto an existing hash.
|
---|
| 1990 | ($hash->{admin},$hash->{self_edit},
|
---|
| 1991 | $hash->{group_create},$hash->{group_edit},$hash->{group_delete},
|
---|
| 1992 | $hash->{user_create},$hash->{user_edit},$hash->{user_delete},
|
---|
| 1993 | $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete},
|
---|
[387] | 1994 | $hash->{record_create},$hash->{record_edit},$hash->{record_delete},$hash->{record_locchg},
|
---|
[382] | 1995 | $hash->{location_create},$hash->{location_edit},$hash->{location_delete},$hash->{location_view}
|
---|
| 1996 | ) = $sth->fetchrow_array;
|
---|
[65] | 1997 |
|
---|
| 1998 | } # end getPermissions()
|
---|
| 1999 |
|
---|
| 2000 |
|
---|
| 2001 | ## DNSDB::changePermissions()
|
---|
| 2002 | # Update an ACL entry
|
---|
| 2003 | # Takes a db handle, type, owner-id, and hashref for the changed permissions.
|
---|
| 2004 | sub changePermissions {
|
---|
[474] | 2005 | my $self = shift;
|
---|
| 2006 | my $dbh = $self->{dbh};
|
---|
[65] | 2007 | my $type = shift;
|
---|
| 2008 | my $id = shift;
|
---|
| 2009 | my $newperms = shift;
|
---|
[87] | 2010 | my $inherit = shift || 0;
|
---|
[65] | 2011 |
|
---|
[294] | 2012 | my $resultmsg = '';
|
---|
[66] | 2013 |
|
---|
[87] | 2014 | # see if we're switching from inherited to custom. for bonus points,
|
---|
| 2015 | # snag the permid and parent permid anyway, since we'll need the permid
|
---|
| 2016 | # to set/alter custom perms, and both if we're switching from custom to
|
---|
| 2017 | # inherited.
|
---|
[294] | 2018 | my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id,".
|
---|
| 2019 | ($type eq 'user' ? 'u.group_id,u.username' : 'u.parent_group_id,u.group_name').
|
---|
[65] | 2020 | " FROM ".($type eq 'user' ? 'users' : 'groups')." u ".
|
---|
[66] | 2021 | " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ".
|
---|
[65] | 2022 | " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?");
|
---|
| 2023 | $sth->execute($id);
|
---|
| 2024 |
|
---|
[294] | 2025 | my ($wasinherited,$permid,$parpermid,$parid,$name) = $sth->fetchrow_array;
|
---|
[66] | 2026 |
|
---|
[78] | 2027 | # hack phtoui
|
---|
| 2028 | # group id 1 is "special" in that it's it's own parent (err... possibly.)
|
---|
| 2029 | # may make its parent id 0 which doesn't exist, and as a bonus is Perl-false.
|
---|
| 2030 | $wasinherited = 0 if ($type eq 'group' && $id == 1);
|
---|
| 2031 |
|
---|
[66] | 2032 | local $dbh->{AutoCommit} = 0;
|
---|
| 2033 | local $dbh->{RaiseError} = 1;
|
---|
| 2034 |
|
---|
| 2035 | # Wrap all the SQL in a transaction
|
---|
| 2036 | eval {
|
---|
[87] | 2037 | if ($inherit) {
|
---|
| 2038 |
|
---|
| 2039 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ".
|
---|
| 2040 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) );
|
---|
| 2041 | $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) );
|
---|
| 2042 |
|
---|
| 2043 | } else {
|
---|
| 2044 |
|
---|
| 2045 | if ($wasinherited) { # munge new permission entry in if we're switching from inherited perms
|
---|
[66] | 2046 | ##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users
|
---|
[87] | 2047 | # ... if'n'when we have groups with fully inherited permissions.
|
---|
| 2048 | # SQL is coo
|
---|
| 2049 | $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ".
|
---|
| 2050 | "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) );
|
---|
| 2051 | ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ".
|
---|
| 2052 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) );
|
---|
| 2053 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ".
|
---|
| 2054 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) );
|
---|
[66] | 2055 | }
|
---|
[78] | 2056 |
|
---|
[87] | 2057 | # and now set the permissions we were passed
|
---|
| 2058 | foreach (@permtypes) {
|
---|
| 2059 | if (defined ($newperms->{$_})) {
|
---|
| 2060 | $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) );
|
---|
| 2061 | }
|
---|
| 2062 | }
|
---|
| 2063 |
|
---|
| 2064 | } # (inherited->)? custom
|
---|
| 2065 |
|
---|
[294] | 2066 | if ($type eq 'user') {
|
---|
| 2067 | $resultmsg = "Updated permissions for user $name";
|
---|
| 2068 | } else {
|
---|
| 2069 | $resultmsg = "Updated default permissions for group $name";
|
---|
| 2070 | }
|
---|
[487] | 2071 | $self->_log(group_id => ($type eq 'user' ? $parid : $id), entry => $resultmsg);
|
---|
[66] | 2072 | $dbh->commit;
|
---|
| 2073 | }; # end eval
|
---|
| 2074 | if ($@) {
|
---|
| 2075 | my $msg = $@;
|
---|
| 2076 | eval { $dbh->rollback; };
|
---|
[294] | 2077 | return ('FAIL',"Error changing permissions: $msg");
|
---|
[66] | 2078 | }
|
---|
| 2079 |
|
---|
[294] | 2080 | return ('OK',$resultmsg);
|
---|
[65] | 2081 | } # end changePermissions()
|
---|
| 2082 |
|
---|
| 2083 |
|
---|
[67] | 2084 | ## DNSDB::comparePermissions()
|
---|
| 2085 | # Compare two permission hashes
|
---|
| 2086 | # Returns '>', '<', '=', '!'
|
---|
| 2087 | sub comparePermissions {
|
---|
[592] | 2088 | my $self = shift;
|
---|
[67] | 2089 | my $p1 = shift;
|
---|
| 2090 | my $p2 = shift;
|
---|
| 2091 |
|
---|
| 2092 | my $retval = '='; # assume equality until proven otherwise
|
---|
| 2093 |
|
---|
| 2094 | no warnings "uninitialized";
|
---|
| 2095 |
|
---|
| 2096 | foreach (@permtypes) {
|
---|
| 2097 | next if $p1->{$_} == $p2->{$_}; # equal is good
|
---|
| 2098 | if ($p1->{$_} && !$p2->{$_}) {
|
---|
| 2099 | if ($retval eq '<') { # if we've already found an unequal pair where
|
---|
| 2100 | $retval = '!'; # $p2 has more access, and we now find a pair
|
---|
| 2101 | last; # where $p1 has more access, the overall access
|
---|
| 2102 | } # is neither greater or lesser, it's unequal.
|
---|
| 2103 | $retval = '>';
|
---|
| 2104 | }
|
---|
| 2105 | if (!$p1->{$_} && $p2->{$_}) {
|
---|
| 2106 | if ($retval eq '>') { # if we've already found an unequal pair where
|
---|
| 2107 | $retval = '!'; # $p1 has more access, and we now find a pair
|
---|
| 2108 | last; # where $p2 has more access, the overall access
|
---|
| 2109 | } # is neither greater or lesser, it's unequal.
|
---|
| 2110 | $retval = '<';
|
---|
| 2111 | }
|
---|
| 2112 | }
|
---|
| 2113 | return $retval;
|
---|
| 2114 | } # end comparePermissions()
|
---|
| 2115 |
|
---|
| 2116 |
|
---|
[112] | 2117 | ## DNSDB::changeGroup()
|
---|
| 2118 | # Change group ID of an entity
|
---|
| 2119 | # Takes a database handle, entity type, entity ID, and new group ID
|
---|
| 2120 | sub changeGroup {
|
---|
[476] | 2121 | my $self = shift;
|
---|
| 2122 | my $dbh = $self->{dbh};
|
---|
[112] | 2123 | my $type = shift;
|
---|
| 2124 | my $id = shift;
|
---|
| 2125 | my $newgrp = shift;
|
---|
| 2126 |
|
---|
| 2127 | ##fixme: fail on not enough args
|
---|
| 2128 | #return ('FAIL', "Missing
|
---|
| 2129 |
|
---|
[295] | 2130 | return ('FAIL', "Can't change the group of a $type")
|
---|
| 2131 | unless grep /^$type$/, ('domain','revzone','user','group'); # could be extended for defrecs?
|
---|
| 2132 |
|
---|
| 2133 | # Collect some names for logging and messages
|
---|
| 2134 | my $entname;
|
---|
[112] | 2135 | if ($type eq 'domain') {
|
---|
[473] | 2136 | $entname = $self->domainName($id);
|
---|
[295] | 2137 | } elsif ($type eq 'revzone') {
|
---|
[473] | 2138 | $entname = $self->revName($id);
|
---|
[112] | 2139 | } elsif ($type eq 'user') {
|
---|
[473] | 2140 | $entname = $self->userFullName($id, '%u');
|
---|
[112] | 2141 | } elsif ($type eq 'group') {
|
---|
[473] | 2142 | $entname = $self->groupName($id);
|
---|
[112] | 2143 | }
|
---|
[295] | 2144 |
|
---|
| 2145 | my ($oldgid) = $dbh->selectrow_array("SELECT group_id FROM $par_tbl{$type} WHERE $id_col{$type}=?",
|
---|
| 2146 | undef, ($id));
|
---|
[473] | 2147 | my $oldgname = $self->groupName($oldgid);
|
---|
| 2148 | my $newgname = $self->groupName($newgrp);
|
---|
[295] | 2149 |
|
---|
| 2150 | return ('FAIL', "Can't move things into a group that doesn't exist") if !$newgname;
|
---|
| 2151 |
|
---|
| 2152 | return ('WARN', "Nothing to do, new group is the same as the old group") if $oldgid == $newgrp;
|
---|
| 2153 |
|
---|
| 2154 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2155 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2156 | local $dbh->{AutoCommit} = 0;
|
---|
| 2157 | local $dbh->{RaiseError} = 1;
|
---|
| 2158 |
|
---|
| 2159 | eval {
|
---|
| 2160 | $dbh->do("UPDATE $par_tbl{$type} SET group_id=? WHERE $id_col{$type}=?", undef, ($newgrp, $id));
|
---|
| 2161 | # Log the change in both the old and new groups
|
---|
[487] | 2162 | $self->_log(group_id => $oldgid, entry => "Moved $type $entname from $oldgname to $newgname");
|
---|
| 2163 | $self->_log(group_id => $newgrp, entry => "Moved $type $entname from $oldgname to $newgname");
|
---|
[295] | 2164 | $dbh->commit;
|
---|
| 2165 | };
|
---|
| 2166 | if ($@) {
|
---|
| 2167 | my $msg = $@;
|
---|
| 2168 | eval { $dbh->rollback; };
|
---|
[517] | 2169 | if ($self->{log_failures}) {
|
---|
[487] | 2170 | $self->_log(group_id => $oldgid, entry => "Error moving $type $entname to $newgname: $msg");
|
---|
[295] | 2171 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2172 | }
|
---|
| 2173 | return ('FAIL',"Error moving $type $entname to $newgname: $msg");
|
---|
| 2174 | }
|
---|
| 2175 |
|
---|
| 2176 | return ('OK',"Moved $type $entname from $oldgname to $newgname");
|
---|
[112] | 2177 | } # end changeGroup()
|
---|
| 2178 |
|
---|
| 2179 |
|
---|
[2] | 2180 | ##
|
---|
| 2181 | ## Processing subs
|
---|
| 2182 | ##
|
---|
| 2183 |
|
---|
| 2184 | ## DNSDB::addDomain()
|
---|
| 2185 | # Add a domain
|
---|
[190] | 2186 | # Takes a database handle, domain name, numeric group, boolean(ish) state (active/inactive),
|
---|
| 2187 | # and user info hash (for logging).
|
---|
[2] | 2188 | # Returns a status code and message
|
---|
| 2189 | sub addDomain {
|
---|
| 2190 | $errstr = '';
|
---|
[477] | 2191 | my $self = shift;
|
---|
| 2192 | my $dbh = $self->{dbh};
|
---|
[2] | 2193 | my $domain = shift;
|
---|
[497] | 2194 | return ('FAIL',"Domain must not be blank\n") if !$domain;
|
---|
[2] | 2195 | my $group = shift;
|
---|
[497] | 2196 | return ('FAIL',"Group must be specified\n") if !defined($group);
|
---|
[2] | 2197 | my $state = shift;
|
---|
[497] | 2198 | return ('FAIL',"Domain status must be specified\n") if !defined($state);
|
---|
[516] | 2199 | my $defloc = shift || '';
|
---|
[2] | 2200 |
|
---|
[116] | 2201 | $state = 1 if $state =~ /^active$/;
|
---|
| 2202 | $state = 1 if $state =~ /^on$/;
|
---|
| 2203 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 2204 | $state = 0 if $state =~ /^off$/;
|
---|
| 2205 |
|
---|
| 2206 | return ('FAIL',"Invalid domain status") if $state !~ /^\d+$/;
|
---|
| 2207 |
|
---|
[542] | 2208 | $domain = lc($domain) if $self->{lowercase};
|
---|
| 2209 |
|
---|
[190] | 2210 | return ('FAIL', "Invalid characters in domain") if $domain !~ /^[a-zA-Z0-9_.-]+$/;
|
---|
| 2211 |
|
---|
[349] | 2212 | my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)");
|
---|
[3] | 2213 | my $dom_id;
|
---|
| 2214 |
|
---|
[38] | 2215 | # quick check to start to see if we've already got one
|
---|
| 2216 | $sth->execute($domain);
|
---|
| 2217 | ($dom_id) = $sth->fetchrow_array;
|
---|
| 2218 |
|
---|
| 2219 | return ('FAIL', "Domain already exists") if $dom_id;
|
---|
| 2220 |
|
---|
[2] | 2221 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2222 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2223 | local $dbh->{AutoCommit} = 0;
|
---|
| 2224 | local $dbh->{RaiseError} = 1;
|
---|
| 2225 |
|
---|
| 2226 | # Wrap all the SQL in a transaction
|
---|
| 2227 | eval {
|
---|
| 2228 | # insert the domain...
|
---|
[516] | 2229 | $dbh->do("INSERT INTO domains (domain,group_id,status,default_location) VALUES (?,?,?,?)", undef,
|
---|
| 2230 | ($domain, $group, $state, $defloc));
|
---|
[2] | 2231 |
|
---|
| 2232 | # get the ID...
|
---|
[349] | 2233 | ($dom_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
| 2234 | undef, ($domain));
|
---|
[2] | 2235 |
|
---|
[487] | 2236 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
| 2237 | entry => "Added ".($state ? 'active' : 'inactive')." domain $domain");
|
---|
[190] | 2238 |
|
---|
[2] | 2239 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
[190] | 2240 | my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
[516] | 2241 | my $sth_in = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,distance,weight,port,ttl,location)".
|
---|
| 2242 | " VALUES ($dom_id,?,?,?,?,?,?,?,?)");
|
---|
[190] | 2243 | $sth->execute($group);
|
---|
[516] | 2244 | while (my ($host, $type, $val, $dist, $weight, $port, $ttl) = $sth->fetchrow_array()) {
|
---|
[2] | 2245 | $host =~ s/DOMAIN/$domain/g;
|
---|
[37] | 2246 | $val =~ s/DOMAIN/$domain/g;
|
---|
[617] | 2247 | _caseclean(\$type, \$host, \$val, 'n', 'n') if $self->{lowercase};
|
---|
[516] | 2248 | $sth_in->execute($host, $type, $val, $dist, $weight, $port, $ttl, $defloc);
|
---|
[190] | 2249 | if ($typemap{$type} eq 'SOA') {
|
---|
| 2250 | my @tmp1 = split /:/, $host;
|
---|
| 2251 | my @tmp2 = split /:/, $val;
|
---|
[487] | 2252 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
[284] | 2253 | entry => "[new $domain] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
[487] | 2254 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl");
|
---|
[190] | 2255 | } else {
|
---|
| 2256 | my $logentry = "[new $domain] Added record '$host $typemap{$type}";
|
---|
| 2257 | $logentry .= " [distance $dist]" if $typemap{$type} eq 'MX';
|
---|
| 2258 | $logentry .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$type} eq 'SRV';
|
---|
[487] | 2259 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
| 2260 | entry => $logentry." $val', TTL $ttl");
|
---|
[190] | 2261 | }
|
---|
[2] | 2262 | }
|
---|
| 2263 |
|
---|
| 2264 | # once we get here, we should have suceeded.
|
---|
| 2265 | $dbh->commit;
|
---|
| 2266 | }; # end eval
|
---|
| 2267 |
|
---|
| 2268 | if ($@) {
|
---|
| 2269 | my $msg = $@;
|
---|
| 2270 | eval { $dbh->rollback; };
|
---|
[487] | 2271 | $self->_log(group_id => $group, entry => "Failed adding domain $domain ($msg)")
|
---|
[517] | 2272 | if $self->{log_failures};
|
---|
[284] | 2273 | $dbh->commit; # since we enabled transactions earlier
|
---|
[193] | 2274 | return ('FAIL',$msg);
|
---|
[2] | 2275 | } else {
|
---|
[3] | 2276 | return ('OK',$dom_id);
|
---|
[2] | 2277 | }
|
---|
| 2278 | } # end addDomain
|
---|
| 2279 |
|
---|
| 2280 |
|
---|
[274] | 2281 | ## DNSDB::delZone()
|
---|
| 2282 | # Delete a forward or reverse zone.
|
---|
| 2283 | # Takes a database handle, zone ID, and forward/reverse flag.
|
---|
[3] | 2284 | # for now, just delete the records, then the domain.
|
---|
| 2285 | # later we may want to archive it in some way instead (status code 2, for example?)
|
---|
[274] | 2286 | sub delZone {
|
---|
[477] | 2287 | my $self = shift;
|
---|
| 2288 | my $dbh = $self->{dbh};
|
---|
[274] | 2289 | my $zoneid = shift;
|
---|
| 2290 | my $revrec = shift;
|
---|
[3] | 2291 |
|
---|
| 2292 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2293 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2294 | local $dbh->{AutoCommit} = 0;
|
---|
| 2295 | local $dbh->{RaiseError} = 1;
|
---|
| 2296 |
|
---|
[285] | 2297 | my $msg = '';
|
---|
[23] | 2298 | my $failmsg = '';
|
---|
[473] | 2299 | my $zone = ($revrec eq 'n' ? $self->domainName($zoneid) : $self->revName($zoneid));
|
---|
[23] | 2300 |
|
---|
[343] | 2301 | return ('FAIL', ($revrec eq 'n' ? 'Domain' : 'Reverse zone')." ID $zoneid doesn't exist") if !$zone;
|
---|
| 2302 |
|
---|
[517] | 2303 | # Set this up here since we may use if if $self->{log_failures} is enabled
|
---|
[285] | 2304 | my %loghash;
|
---|
| 2305 | $loghash{domain_id} = $zoneid if $revrec eq 'n';
|
---|
| 2306 | $loghash{rdns_id} = $zoneid if $revrec eq 'y';
|
---|
[473] | 2307 | $loghash{group_id} = $self->parentID(
|
---|
| 2308 | id => $zoneid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec);
|
---|
[285] | 2309 |
|
---|
[3] | 2310 | # Wrap all the SQL in a transaction
|
---|
| 2311 | eval {
|
---|
[274] | 2312 | # Disentangle custom record types before removing the
|
---|
| 2313 | # ones that are only in the zone to be deleted
|
---|
| 2314 | if ($revrec eq 'n') {
|
---|
| 2315 | my $sth = $dbh->prepare("UPDATE records SET type=?,domain_id=0 WHERE domain_id=? AND type=?");
|
---|
| 2316 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
| 2317 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65280);
|
---|
| 2318 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65281);
|
---|
| 2319 | $sth->execute(65282, $zoneid, 65283);
|
---|
| 2320 | $sth->execute(65282, $zoneid, 65284);
|
---|
| 2321 | $failmsg = "Failure removing domain records";
|
---|
| 2322 | $dbh->do("DELETE FROM records WHERE domain_id=?", undef, ($zoneid));
|
---|
| 2323 | $failmsg = "Failure removing domain";
|
---|
| 2324 | $dbh->do("DELETE FROM domains WHERE domain_id=?", undef, ($zoneid));
|
---|
| 2325 | } else {
|
---|
| 2326 | my $sth = $dbh->prepare("UPDATE records SET type=?,rdns_id=0 WHERE rdns_id=? AND type=?");
|
---|
| 2327 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
| 2328 | $sth->execute($reverse_typemap{A}, $zoneid, 65280);
|
---|
| 2329 | $sth->execute($reverse_typemap{AAAA}, $zoneid, 65281);
|
---|
| 2330 | # We don't have an "A template" or "AAAA template" type, although it might be useful for symmetry.
|
---|
[345] | 2331 | # $sth->execute(65286?, $zoneid, 65283);
|
---|
| 2332 | # $sth->execute(65286?, $zoneid, 65284);
|
---|
[274] | 2333 | $failmsg = "Failure removing reverse records";
|
---|
| 2334 | $dbh->do("DELETE FROM records WHERE rdns_id=?", undef, ($zoneid));
|
---|
| 2335 | $failmsg = "Failure removing reverse zone";
|
---|
| 2336 | $dbh->do("DELETE FROM revzones WHERE rdns_id=?", undef, ($zoneid));
|
---|
| 2337 | }
|
---|
[3] | 2338 |
|
---|
[285] | 2339 | $msg = "Deleted ".($revrec eq 'n' ? 'domain' : 'reverse zone')." $zone";
|
---|
| 2340 | $loghash{entry} = $msg;
|
---|
[487] | 2341 | $self->_log(%loghash);
|
---|
[285] | 2342 |
|
---|
[3] | 2343 | # once we get here, we should have suceeded.
|
---|
[23] | 2344 | $dbh->commit;
|
---|
[3] | 2345 | }; # end eval
|
---|
| 2346 |
|
---|
| 2347 | if ($@) {
|
---|
[285] | 2348 | $msg = $@;
|
---|
[3] | 2349 | eval { $dbh->rollback; };
|
---|
[295] | 2350 | $loghash{entry} = "Error deleting $zone: $msg ($failmsg)";
|
---|
[517] | 2351 | if ($self->{log_failures}) {
|
---|
[487] | 2352 | $self->_log(%loghash);
|
---|
[295] | 2353 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2354 | }
|
---|
| 2355 | return ('FAIL', $loghash{entry});
|
---|
[3] | 2356 | } else {
|
---|
[295] | 2357 | return ('OK', $msg);
|
---|
[3] | 2358 | }
|
---|
| 2359 |
|
---|
[274] | 2360 | } # end delZone()
|
---|
[3] | 2361 |
|
---|
| 2362 |
|
---|
[2] | 2363 | ## DNSDB::domainName()
|
---|
| 2364 | # Return the domain name based on a domain ID
|
---|
| 2365 | # Takes a database handle and the domain ID
|
---|
| 2366 | # Returns the domain name or undef on failure
|
---|
| 2367 | sub domainName {
|
---|
| 2368 | $errstr = '';
|
---|
[473] | 2369 | my $self = shift;
|
---|
| 2370 | my $dbh = $self->{dbh};
|
---|
[2] | 2371 | my $domid = shift;
|
---|
[91] | 2372 | my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
|
---|
[2] | 2373 | $errstr = $DBI::errstr if !$domname;
|
---|
| 2374 | return $domname if $domname;
|
---|
[91] | 2375 | } # end domainName()
|
---|
[2] | 2376 |
|
---|
| 2377 |
|
---|
[224] | 2378 | ## DNSDB::revName()
|
---|
| 2379 | # Return the reverse zone name based on an rDNS ID
|
---|
[583] | 2380 | # Takes a database handle and the rDNS ID, and an optional flag to force return of the CIDR zone
|
---|
| 2381 | # instead of the formal .arpa zone name
|
---|
[224] | 2382 | # Returns the reverse zone name or undef on failure
|
---|
| 2383 | sub revName {
|
---|
| 2384 | $errstr = '';
|
---|
[473] | 2385 | my $self = shift;
|
---|
| 2386 | my $dbh = $self->{dbh};
|
---|
[224] | 2387 | my $revid = shift;
|
---|
[583] | 2388 | my $cidrflag = shift || 'n';
|
---|
[224] | 2389 | my ($revname) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id=?", undef, ($revid) );
|
---|
| 2390 | $errstr = $DBI::errstr if !$revname;
|
---|
[583] | 2391 | my $tmp = new NetAddr::IP $revname;
|
---|
| 2392 | $revname = _ZONE($tmp, 'ZONE', 'r', '.').($tmp->{isv6} ? '.ip6.arpa' : '.in-addr.arpa')
|
---|
| 2393 | if ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all') && $cidrflag eq 'n';
|
---|
[224] | 2394 | return $revname if $revname;
|
---|
| 2395 | } # end revName()
|
---|
| 2396 |
|
---|
| 2397 |
|
---|
[91] | 2398 | ## DNSDB::domainID()
|
---|
| 2399 | # Takes a database handle and domain name
|
---|
| 2400 | # Returns the domain ID number
|
---|
| 2401 | sub domainID {
|
---|
| 2402 | $errstr = '';
|
---|
[473] | 2403 | my $self = shift;
|
---|
| 2404 | my $dbh = $self->{dbh};
|
---|
[91] | 2405 | my $domain = shift;
|
---|
[349] | 2406 | my ($domid) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
| 2407 | undef, ($domain) );
|
---|
[501] | 2408 | if (!$domid) {
|
---|
| 2409 | if ($dbh->err) {
|
---|
| 2410 | $errstr = $DBI::errstr;
|
---|
| 2411 | } else {
|
---|
| 2412 | $errstr = "Domain $domain not present";
|
---|
| 2413 | }
|
---|
| 2414 | }
|
---|
[91] | 2415 | return $domid if $domid;
|
---|
| 2416 | } # end domainID()
|
---|
| 2417 |
|
---|
| 2418 |
|
---|
[276] | 2419 | ## DNSDB::revID()
|
---|
| 2420 | # Takes a database handle and reverse zone name
|
---|
| 2421 | # Returns the rDNS ID number
|
---|
| 2422 | sub revID {
|
---|
| 2423 | $errstr = '';
|
---|
[473] | 2424 | my $self = shift;
|
---|
| 2425 | my $dbh = $self->{dbh};
|
---|
[276] | 2426 | my $revzone = shift;
|
---|
| 2427 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ($revzone) );
|
---|
[501] | 2428 | if (!$revid) {
|
---|
| 2429 | if ($dbh->err) {
|
---|
| 2430 | $errstr = $DBI::errstr;
|
---|
| 2431 | } else {
|
---|
| 2432 | $errstr = "Reverse zone $revzone not present";
|
---|
| 2433 | }
|
---|
| 2434 | }
|
---|
[276] | 2435 | return $revid if $revid;
|
---|
| 2436 | } # end revID()
|
---|
| 2437 |
|
---|
| 2438 |
|
---|
[260] | 2439 | ## DNSDB::addRDNS
|
---|
| 2440 | # Adds a reverse DNS zone
|
---|
[286] | 2441 | # Takes a database handle, CIDR block, reverse DNS pattern, numeric group,
|
---|
| 2442 | # and boolean(ish) state (active/inactive)
|
---|
[260] | 2443 | # Returns a status code and message
|
---|
| 2444 | sub addRDNS {
|
---|
[477] | 2445 | my $self = shift;
|
---|
| 2446 | my $dbh = $self->{dbh};
|
---|
[583] | 2447 | my $zone = shift;
|
---|
[446] | 2448 |
|
---|
[583] | 2449 | # Autodetect formal .arpa zones
|
---|
| 2450 | if ($zone =~ /\.arpa\.?$/) {
|
---|
| 2451 | my $code;
|
---|
| 2452 | ($code,$zone) = _zone2cidr($zone);
|
---|
| 2453 | return ('FAIL', $zone) if $code eq 'FAIL';
|
---|
| 2454 | }
|
---|
| 2455 | $zone = NetAddr::IP->new($zone);
|
---|
| 2456 |
|
---|
[260] | 2457 | return ('FAIL',"Zone name must be a valid CIDR netblock") unless ($zone && $zone->addr !~ /^0/);
|
---|
[270] | 2458 | my $revpatt = shift; # construct a custom (A/AAAA+)? PTR template record
|
---|
[260] | 2459 | my $group = shift;
|
---|
| 2460 | my $state = shift;
|
---|
[446] | 2461 | my $defloc = shift || '';
|
---|
[260] | 2462 |
|
---|
| 2463 | $state = 1 if $state =~ /^active$/;
|
---|
| 2464 | $state = 1 if $state =~ /^on$/;
|
---|
| 2465 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 2466 | $state = 0 if $state =~ /^off$/;
|
---|
| 2467 |
|
---|
| 2468 | return ('FAIL',"Invalid zone status") if $state !~ /^\d+$/;
|
---|
| 2469 |
|
---|
| 2470 | # quick check to start to see if we've already got one
|
---|
[299] | 2471 | my ($rdns_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ("$zone"));
|
---|
[260] | 2472 |
|
---|
| 2473 | return ('FAIL', "Zone already exists") if $rdns_id;
|
---|
| 2474 |
|
---|
| 2475 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2476 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2477 | local $dbh->{AutoCommit} = 0;
|
---|
| 2478 | local $dbh->{RaiseError} = 1;
|
---|
| 2479 |
|
---|
[264] | 2480 | my $warnstr = '';
|
---|
[270] | 2481 | my $defttl = 3600; # 1 hour should be reasonable. And unless things have gone horribly
|
---|
| 2482 | # wrong, we should have a value to override this anyway.
|
---|
[264] | 2483 |
|
---|
[260] | 2484 | # Wrap all the SQL in a transaction
|
---|
| 2485 | eval {
|
---|
[446] | 2486 | # insert the zone...
|
---|
| 2487 | $dbh->do("INSERT INTO revzones (revnet,group_id,status,default_location) VALUES (?,?,?,?)", undef,
|
---|
| 2488 | ($zone, $group, $state, $defloc) );
|
---|
[260] | 2489 |
|
---|
| 2490 | # get the ID...
|
---|
| 2491 | ($rdns_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
| 2492 |
|
---|
[487] | 2493 | $self->_log(rdns_id => $rdns_id, group_id => $group,
|
---|
| 2494 | entry => "Added ".($state ? 'active' : 'inactive')." reverse zone $zone");
|
---|
[260] | 2495 |
|
---|
| 2496 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
| 2497 | my $sth = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
[446] | 2498 | my $sth_in = $dbh->prepare("INSERT INTO records (rdns_id,domain_id,host,type,val,ttl,location)".
|
---|
| 2499 | " VALUES ($rdns_id,?,?,?,?,?,?)");
|
---|
[260] | 2500 | $sth->execute($group);
|
---|
| 2501 | while (my ($host,$type,$val,$ttl) = $sth->fetchrow_array()) {
|
---|
[264] | 2502 | # Silently skip v4/v6 mismatches. This is not an error, this is expected.
|
---|
| 2503 | if ($zone->{isv6}) {
|
---|
| 2504 | next if ($type == 65280 || $type == 65283);
|
---|
| 2505 | } else {
|
---|
| 2506 | next if ($type == 65281 || $type == 65284);
|
---|
| 2507 | }
|
---|
[269] | 2508 |
|
---|
[517] | 2509 | $host =~ s/ADMINDOMAIN/$self->{domain}/g;
|
---|
[264] | 2510 |
|
---|
[265] | 2511 | # Check to make sure the IP stubs will fit in the zone. Under most usage failures here should be rare.
|
---|
| 2512 | # On failure, tack a note on to a warning string and continue without adding this record.
|
---|
| 2513 | # While we're at it, we substitute $zone for ZONE in the value.
|
---|
| 2514 | if ($val eq 'ZONE') {
|
---|
[444] | 2515 | # If we've got a pattern, we skip the default record version on (A+)PTR-template types
|
---|
| 2516 | next if $revpatt && ($type == 65282 || $type == 65283);
|
---|
[269] | 2517 | ##fixme? do we care if we have multiple whole-zone templates?
|
---|
[265] | 2518 | $val = $zone->network;
|
---|
| 2519 | } elsif ($val =~ /ZONE/) {
|
---|
| 2520 | my $tmpval = $val;
|
---|
| 2521 | $tmpval =~ s/ZONE//;
|
---|
[269] | 2522 | # Bend the rules and allow single-trailing-number PTR or PTR template records to be inserted
|
---|
| 2523 | # as either v4 or v6. May make this an off-by-default config flag
|
---|
| 2524 | # Note that the origin records that may trigger this **SHOULD** already have ZONE,\d
|
---|
| 2525 | if ($type == 12 || $type == 65282) {
|
---|
| 2526 | $tmpval =~ s/[,.]/::/ if ($tmpval =~ /^[,.]\d+$/ && $zone->{isv6});
|
---|
| 2527 | $tmpval =~ s/[,:]+/./ if ($tmpval =~ /^(?:,|::)\d+$/ && !$zone->{isv6});
|
---|
| 2528 | }
|
---|
[265] | 2529 | my $addr;
|
---|
[471] | 2530 | if ($self->_ipparent('n', 'y', \$tmpval, $rdns_id, \$addr)) {
|
---|
[265] | 2531 | $val = $addr->addr;
|
---|
| 2532 | } else {
|
---|
[269] | 2533 | $warnstr .= "\nDefault record '$val $typemap{$type} $host' doesn't fit in $zone, skipping";
|
---|
[264] | 2534 | next;
|
---|
| 2535 | }
|
---|
| 2536 | }
|
---|
| 2537 |
|
---|
[328] | 2538 | # Substitute $zone for ZONE in the hostname, but only for non-NS records.
|
---|
| 2539 | # NS records get this substitution on the value instead.
|
---|
| 2540 | $host = _ZONE($zone, $host) if $type != 2;
|
---|
[265] | 2541 |
|
---|
[269] | 2542 | # Fill in the forward domain ID if we can find it, otherwise:
|
---|
| 2543 | # Coerce type down to PTR or PTR template if we can't
|
---|
| 2544 | my $domid = 0;
|
---|
| 2545 | if ($type >= 65280) {
|
---|
[471] | 2546 | if (!($domid = $self->_hostparent($host))) {
|
---|
[269] | 2547 | $warnstr .= "\nRecord added as PTR instead of $typemap{$type}; domain not found for $host";
|
---|
| 2548 | $type = $reverse_typemap{PTR};
|
---|
| 2549 | $domid = 0; # just to be explicit.
|
---|
| 2550 | }
|
---|
| 2551 | }
|
---|
| 2552 |
|
---|
[617] | 2553 | _caseclean(\$type, \$host, \$val, 'n', 'y') if $self->{lowercase};
|
---|
| 2554 |
|
---|
[446] | 2555 | $sth_in->execute($domid,$host,$type,$val,$ttl,$defloc);
|
---|
[269] | 2556 |
|
---|
[260] | 2557 | if ($typemap{$type} eq 'SOA') {
|
---|
| 2558 | my @tmp1 = split /:/, $host;
|
---|
| 2559 | my @tmp2 = split /:/, $val;
|
---|
[487] | 2560 | $self->_log(rdns_id => $rdns_id, group_id => $group,
|
---|
[286] | 2561 | entry => "[new $zone] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
[487] | 2562 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl");
|
---|
[270] | 2563 | $defttl = $tmp2[3];
|
---|
[260] | 2564 | } else {
|
---|
[446] | 2565 | my $logentry = "[new $zone] Added record '$host $typemap{$type} $val', TTL $ttl";
|
---|
[480] | 2566 | $logentry .= ", default location ".$self->getLoc($defloc)->{description} if $defloc;
|
---|
[487] | 2567 | $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group, entry => $logentry);
|
---|
[260] | 2568 | }
|
---|
| 2569 | }
|
---|
| 2570 |
|
---|
[270] | 2571 | # Generate record based on provided pattern.
|
---|
| 2572 | if ($revpatt) {
|
---|
| 2573 | my $host;
|
---|
| 2574 | my $type = ($zone->{isv6} ? 65284 : 65283);
|
---|
| 2575 | my $val = $zone->network;
|
---|
[269] | 2576 |
|
---|
[270] | 2577 | # Substitute $zone for ZONE in the hostname.
|
---|
| 2578 | $host = _ZONE($zone, $revpatt);
|
---|
| 2579 |
|
---|
| 2580 | my $domid = 0;
|
---|
[471] | 2581 | if (!($domid = $self->_hostparent($host))) {
|
---|
[270] | 2582 | $warnstr .= "\nDefault pattern added as PTR template instead of $typemap{$type}; domain not found for $host";
|
---|
| 2583 | $type = 65282;
|
---|
| 2584 | $domid = 0; # just to be explicit.
|
---|
| 2585 | }
|
---|
| 2586 |
|
---|
[446] | 2587 | $sth_in->execute($domid,$host,$type,$val,$defttl,$defloc);
|
---|
[286] | 2588 | my $logentry = "[new $zone] Added record '$host $typemap{$type}";
|
---|
[487] | 2589 | $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group,
|
---|
| 2590 | entry => $logentry." $val', TTL $defttl from pattern");
|
---|
[270] | 2591 | }
|
---|
| 2592 |
|
---|
[264] | 2593 | # If there are warnings (presumably about default records skipped for cause) log them
|
---|
[487] | 2594 | $self->_log(rdns_id => $rdns_id, group_id => $group, entry => "Warning(s) adding $zone:$warnstr")
|
---|
[264] | 2595 | if $warnstr;
|
---|
[269] | 2596 |
|
---|
[260] | 2597 | # once we get here, we should have suceeded.
|
---|
| 2598 | $dbh->commit;
|
---|
| 2599 | }; # end eval
|
---|
| 2600 |
|
---|
| 2601 | if ($@) {
|
---|
| 2602 | my $msg = $@;
|
---|
| 2603 | eval { $dbh->rollback; };
|
---|
[487] | 2604 | $self->_log(group_id => $group, entry => "Failed adding reverse zone $zone ($msg)")
|
---|
[517] | 2605 | if $self->{log_failures};
|
---|
[286] | 2606 | $dbh->commit; # since we enabled transactions earlier
|
---|
[260] | 2607 | return ('FAIL',$msg);
|
---|
| 2608 | } else {
|
---|
[286] | 2609 | my $retcode = 'OK';
|
---|
| 2610 | if ($warnstr) {
|
---|
| 2611 | $resultstr = $warnstr;
|
---|
| 2612 | $retcode = 'WARN';
|
---|
| 2613 | }
|
---|
| 2614 | return ($retcode, $rdns_id);
|
---|
[260] | 2615 | }
|
---|
| 2616 |
|
---|
| 2617 | } # end addRDNS()
|
---|
| 2618 |
|
---|
| 2619 |
|
---|
[237] | 2620 | ## DNSDB::getZoneCount
|
---|
| 2621 | # Get count of zones in group or groups
|
---|
| 2622 | # Takes a database handle and hash containing:
|
---|
| 2623 | # - the "current" group
|
---|
| 2624 | # - an array of "acceptable" groups
|
---|
| 2625 | # - a flag for forward/reverse zones
|
---|
| 2626 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
| 2627 | # Returns an integer count of the resulting zone list.
|
---|
| 2628 | sub getZoneCount {
|
---|
[477] | 2629 | my $self = shift;
|
---|
| 2630 | my $dbh = $self->{dbh};
|
---|
[237] | 2631 |
|
---|
| 2632 | my %args = @_;
|
---|
| 2633 |
|
---|
[509] | 2634 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 2635 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 2636 | $errstr = "Bad or missing curgroup argument";
|
---|
| 2637 | return;
|
---|
| 2638 | }
|
---|
| 2639 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 2640 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 2641 | $errstr = "Bad childlist argument";
|
---|
| 2642 | return;
|
---|
| 2643 | }
|
---|
| 2644 |
|
---|
[237] | 2645 | my @filterargs;
|
---|
[239] | 2646 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2647 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2648 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
[237] | 2649 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2650 |
|
---|
| 2651 | my $sql;
|
---|
| 2652 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
| 2653 | if ($args{revrec} eq 'n') {
|
---|
| 2654 | $sql = "SELECT count(*) FROM domains".
|
---|
| 2655 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2656 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
| 2657 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
| 2658 | } else {
|
---|
| 2659 | $sql = "SELECT count(*) FROM revzones".
|
---|
| 2660 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
[583] | 2661 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2662 | # if ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all') {
|
---|
| 2663 | # Just In Case the UI is using formal .arpa notation, and someone enters something reversed,
|
---|
| 2664 | # we want to match both the formal and natural zone name
|
---|
| 2665 | $sql .= ($args{filter} ? " AND (CAST(revnet AS VARCHAR) ~* ? OR CAST(revnet AS VARCHAR) ~* ?)" : '');
|
---|
| 2666 | push @filterargs, join('[.]',reverse(split(/\[\.\]/,$args{filter}))) if $args{filter};
|
---|
| 2667 | # } else {
|
---|
| 2668 | # $sql .= ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2669 | # }
|
---|
[237] | 2670 | }
|
---|
| 2671 | my ($count) = $dbh->selectrow_array($sql, undef, @filterargs);
|
---|
| 2672 | return $count;
|
---|
| 2673 | } # end getZoneCount()
|
---|
| 2674 |
|
---|
| 2675 |
|
---|
| 2676 | ## DNSDB::getZoneList()
|
---|
| 2677 | # Get a list of zones in the specified group(s)
|
---|
| 2678 | # Takes the same arguments as getZoneCount() above
|
---|
| 2679 | # Returns a reference to an array of hashrefs suitable for feeding to HTML::Template
|
---|
| 2680 | sub getZoneList {
|
---|
[477] | 2681 | my $self = shift;
|
---|
| 2682 | my $dbh = $self->{dbh};
|
---|
[237] | 2683 |
|
---|
| 2684 | my %args = @_;
|
---|
| 2685 |
|
---|
| 2686 | my @zonelist;
|
---|
| 2687 |
|
---|
[475] | 2688 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
[239] | 2689 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[237] | 2690 |
|
---|
[509] | 2691 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 2692 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 2693 | $errstr = "Bad or missing curgroup argument";
|
---|
| 2694 | return;
|
---|
| 2695 | }
|
---|
| 2696 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 2697 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 2698 | $errstr = "Bad childlist argument";
|
---|
| 2699 | return;
|
---|
| 2700 | }
|
---|
| 2701 |
|
---|
[237] | 2702 | my @filterargs;
|
---|
[239] | 2703 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2704 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2705 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
[237] | 2706 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2707 |
|
---|
| 2708 | my $sql;
|
---|
| 2709 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
| 2710 | if ($args{revrec} eq 'n') {
|
---|
[475] | 2711 | $args{sortby} = 'domain' if !$args{sortby} || !grep /^$args{sortby}$/, ('domain','group','status');
|
---|
[572] | 2712 | $sql = "SELECT domain_id AS zoneid,domain AS zone,status,groups.group_name AS group FROM domains".
|
---|
[237] | 2713 | " INNER JOIN groups ON domains.group_id=groups.group_id".
|
---|
| 2714 | " WHERE domains.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2715 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
| 2716 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
| 2717 | } else {
|
---|
[239] | 2718 | ##fixme: arguably startwith here is irrelevant. depends on the UI though.
|
---|
[475] | 2719 | $args{sortby} = 'revnet' if !$args{sortby} || !grep /^$args{sortby}$/, ('revnet','group','status');
|
---|
[572] | 2720 | $sql = "SELECT rdns_id AS zoneid,revnet AS zone,status,groups.group_name AS group FROM revzones".
|
---|
[237] | 2721 | " INNER JOIN groups ON revzones.group_id=groups.group_id".
|
---|
| 2722 | " WHERE revzones.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
[583] | 2723 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2724 | # if ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all') {
|
---|
| 2725 | # Just In Case the UI is using formal .arpa notation, and someone enters something reversed,
|
---|
| 2726 | # we want to match both the formal and natural zone name
|
---|
| 2727 | $sql .= ($args{filter} ? " AND (CAST(revnet AS VARCHAR) ~* ? OR CAST(revnet AS VARCHAR) ~* ?)" : '');
|
---|
| 2728 | push @filterargs, join('[.]',reverse(split(/\[\.\]/,$args{filter}))) if $args{filter};
|
---|
| 2729 | # } else {
|
---|
| 2730 | # $sql .= ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2731 | # }
|
---|
[237] | 2732 | }
|
---|
| 2733 | # A common tail.
|
---|
[239] | 2734 | $sql .= " ORDER BY ".($args{sortby} eq 'group' ? 'groups.group_name' : $args{sortby})." $args{sortorder} ".
|
---|
[517] | 2735 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage}".
|
---|
| 2736 | " OFFSET ".$args{offset}*$self->{perpage});
|
---|
[237] | 2737 |
|
---|
[583] | 2738 | my @working;
|
---|
| 2739 | my $zsth = $dbh->prepare($sql);
|
---|
| 2740 | $zsth->execute(@filterargs);
|
---|
| 2741 | while (my $zone = $zsth->fetchrow_hashref) {
|
---|
| 2742 | if ($args{revrec} eq 'y' && ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all')) {
|
---|
| 2743 | my $tmp = new NetAddr::IP $zone->{zone};
|
---|
| 2744 | $zone->{zone} = DNSDB::_ZONE($tmp, 'ZONE', 'r', '.').($tmp->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 2745 | }
|
---|
| 2746 | push @working, $zone;
|
---|
| 2747 | }
|
---|
| 2748 | return \@working;
|
---|
[237] | 2749 | } # end getZoneList()
|
---|
| 2750 |
|
---|
| 2751 |
|
---|
[383] | 2752 | ## DNSDB::getZoneLocation()
|
---|
[387] | 2753 | # Retrieve the default location for a zone.
|
---|
[383] | 2754 | # Takes a database handle, forward/reverse flag, and zone ID
|
---|
| 2755 | sub getZoneLocation {
|
---|
[477] | 2756 | my $self = shift;
|
---|
| 2757 | my $dbh = $self->{dbh};
|
---|
[383] | 2758 | my $revrec = shift;
|
---|
| 2759 | my $zoneid = shift;
|
---|
| 2760 |
|
---|
| 2761 | my ($loc) = $dbh->selectrow_array("SELECT default_location FROM ".
|
---|
| 2762 | ($revrec eq 'n' ? 'domains WHERE domain_id = ?' : 'revzones WHERE rdns_id = ?'),
|
---|
| 2763 | undef, ($zoneid));
|
---|
| 2764 | return $loc;
|
---|
| 2765 | } # end getZoneLocation()
|
---|
| 2766 |
|
---|
| 2767 |
|
---|
[18] | 2768 | ## DNSDB::addGroup()
|
---|
| 2769 | # Add a group
|
---|
[66] | 2770 | # Takes a database handle, group name, parent group, hashref for permissions,
|
---|
[292] | 2771 | # and optional template-vs-cloneme flag for the default records
|
---|
[18] | 2772 | # Returns a status code and message
|
---|
| 2773 | sub addGroup {
|
---|
| 2774 | $errstr = '';
|
---|
[476] | 2775 | my $self = shift;
|
---|
| 2776 | my $dbh = $self->{dbh};
|
---|
[20] | 2777 | my $groupname = shift;
|
---|
| 2778 | my $pargroup = shift;
|
---|
[66] | 2779 | my $permissions = shift;
|
---|
[18] | 2780 |
|
---|
[66] | 2781 | # 0 indicates "custom", hardcoded.
|
---|
[18] | 2782 | # Any other value clones that group's default records, if it exists.
|
---|
[66] | 2783 | my $inherit = shift || 0;
|
---|
| 2784 | ##fixme: need a flag to indicate clone records or <?> ?
|
---|
[18] | 2785 |
|
---|
| 2786 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2787 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2788 | local $dbh->{AutoCommit} = 0;
|
---|
| 2789 | local $dbh->{RaiseError} = 1;
|
---|
| 2790 |
|
---|
[292] | 2791 | my ($group_id) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($groupname));
|
---|
[38] | 2792 |
|
---|
| 2793 | return ('FAIL', "Group already exists") if $group_id;
|
---|
| 2794 |
|
---|
[18] | 2795 | # Wrap all the SQL in a transaction
|
---|
| 2796 | eval {
|
---|
[292] | 2797 | $dbh->do("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)", undef, ($pargroup, $groupname) );
|
---|
[18] | 2798 |
|
---|
[292] | 2799 | my ($groupid) = $dbh->selectrow_array("SELECT currval('groups_group_id_seq')");
|
---|
[18] | 2800 |
|
---|
[292] | 2801 | # We work through the whole set of permissions instead of specifying them so
|
---|
| 2802 | # that when we add a new permission, we don't have to change the code anywhere
|
---|
| 2803 | # that doesn't explicitly deal with that specific permission.
|
---|
| 2804 | my @permvals;
|
---|
| 2805 | foreach (@permtypes) {
|
---|
| 2806 | if (!defined ($permissions->{$_})) {
|
---|
| 2807 | push @permvals, 0;
|
---|
| 2808 | } else {
|
---|
| 2809 | push @permvals, $permissions->{$_};
|
---|
[66] | 2810 | }
|
---|
[292] | 2811 | }
|
---|
| 2812 | $dbh->do("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")",
|
---|
| 2813 | undef, ($groupid, @permvals) );
|
---|
| 2814 | my ($permid) = $dbh->selectrow_array("SELECT currval('permissions_permission_id_seq')");
|
---|
| 2815 | $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
|
---|
[66] | 2816 |
|
---|
[292] | 2817 | # Default records
|
---|
[255] | 2818 | my $sthf = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
|
---|
[20] | 2819 | "VALUES ($groupid,?,?,?,?,?,?,?)");
|
---|
[255] | 2820 | my $sthr = $dbh->prepare("INSERT INTO default_rev_records (group_id,host,type,val,ttl) ".
|
---|
| 2821 | "VALUES ($groupid,?,?,?,?)");
|
---|
[66] | 2822 | if ($inherit) {
|
---|
[87] | 2823 | # Duplicate records from parent. Actually relying on inherited records feels
|
---|
| 2824 | # very fragile, and it would be problematic to roll over at a later time.
|
---|
[18] | 2825 | my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
[87] | 2826 | $sth2->execute($pargroup);
|
---|
[18] | 2827 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
[255] | 2828 | $sthf->execute(@clonedata);
|
---|
[18] | 2829 | }
|
---|
[255] | 2830 | # And now the reverse records
|
---|
[292] | 2831 | $sth2 = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
[255] | 2832 | $sth2->execute($pargroup);
|
---|
| 2833 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
| 2834 | $sthr->execute(@clonedata);
|
---|
| 2835 | }
|
---|
[18] | 2836 | } else {
|
---|
[66] | 2837 | ##fixme: Hardcoding is Bad, mmmmkaaaay?
|
---|
[18] | 2838 | # reasonable basic defaults for SOA, MX, NS, and minimal hosting
|
---|
| 2839 | # could load from a config file, but somewhere along the line we need hardcoded bits.
|
---|
[255] | 2840 | $sthf->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
|
---|
| 2841 | $sthf->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
|
---|
| 2842 | $sthf->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
|
---|
| 2843 | $sthf->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
|
---|
| 2844 | $sthf->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
|
---|
| 2845 | $sthf->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
|
---|
| 2846 | # reasonable basic defaults for generic reverse zone. Same as initial SQL tabledef.
|
---|
| 2847 | $sthr->execute('hostmaster.ADMINDOMAIN:ns1.ADMINDOMAIN', 6, '10800:3600:604800:10800', 86400);
|
---|
| 2848 | $sthr->execute('unused-%r.ADMINDOMAIN', 65283, 'ZONE', 3600);
|
---|
[18] | 2849 | }
|
---|
| 2850 |
|
---|
[487] | 2851 | $self->_log(group_id => $pargroup, entry => "Added group $groupname");
|
---|
[292] | 2852 |
|
---|
[18] | 2853 | # once we get here, we should have suceeded.
|
---|
| 2854 | $dbh->commit;
|
---|
| 2855 | }; # end eval
|
---|
| 2856 |
|
---|
| 2857 | if ($@) {
|
---|
| 2858 | my $msg = $@;
|
---|
| 2859 | eval { $dbh->rollback; };
|
---|
[517] | 2860 | if ($self->{log_failures}) {
|
---|
[487] | 2861 | $self->_log(group_id => $pargroup, entry => "Failed to add group $groupname: $msg");
|
---|
[292] | 2862 | $dbh->commit;
|
---|
| 2863 | }
|
---|
[18] | 2864 | return ('FAIL',$msg);
|
---|
| 2865 | }
|
---|
| 2866 |
|
---|
[292] | 2867 | return ('OK','OK');
|
---|
[18] | 2868 | } # end addGroup()
|
---|
| 2869 |
|
---|
| 2870 |
|
---|
[22] | 2871 | ## DNSDB::delGroup()
|
---|
| 2872 | # Delete a group.
|
---|
| 2873 | # Takes a group ID
|
---|
| 2874 | # Returns a status code and message
|
---|
| 2875 | sub delGroup {
|
---|
[476] | 2876 | my $self = shift;
|
---|
| 2877 | my $dbh = $self->{dbh};
|
---|
[22] | 2878 | my $groupid = shift;
|
---|
| 2879 |
|
---|
| 2880 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2881 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2882 | local $dbh->{AutoCommit} = 0;
|
---|
| 2883 | local $dbh->{RaiseError} = 1;
|
---|
| 2884 |
|
---|
| 2885 | ##fixme: locate "knowable" error conditions and deal with them before the eval
|
---|
[23] | 2886 | # ... or inside, whatever.
|
---|
[22] | 2887 | # -> domains still exist in group
|
---|
| 2888 | # -> ...
|
---|
[23] | 2889 | my $failmsg = '';
|
---|
[293] | 2890 | my $resultmsg = '';
|
---|
[22] | 2891 |
|
---|
[293] | 2892 | # collect some pieces for logging and error messages
|
---|
[473] | 2893 | my $groupname = $self->groupName($groupid);
|
---|
| 2894 | my $parid = $self->parentID(id => $groupid, type => 'group');
|
---|
[293] | 2895 |
|
---|
[22] | 2896 | # Wrap all the SQL in a transaction
|
---|
| 2897 | eval {
|
---|
[293] | 2898 | # Check for Things in the group
|
---|
| 2899 | $failmsg = "Can't remove group $groupname";
|
---|
| 2900 | my ($grpcnt) = $dbh->selectrow_array("SELECT count(*) FROM groups WHERE parent_group_id=?", undef, ($groupid));
|
---|
| 2901 | die "$grpcnt groups still in group\n" if $grpcnt;
|
---|
| 2902 | my ($domcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($groupid));
|
---|
[23] | 2903 | die "$domcnt domains still in group\n" if $domcnt;
|
---|
[512] | 2904 | my ($revcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($groupid));
|
---|
| 2905 | die "$revcnt reverse zones still in group\n" if $revcnt;
|
---|
[293] | 2906 | my ($usercnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($groupid));
|
---|
| 2907 | die "$usercnt users still in group\n" if $usercnt;
|
---|
[23] | 2908 |
|
---|
[293] | 2909 | $failmsg = "Failed to delete default records for $groupname";
|
---|
| 2910 | $dbh->do("DELETE from default_records WHERE group_id=?", undef, ($groupid));
|
---|
| 2911 | $failmsg = "Failed to delete default reverse records for $groupname";
|
---|
| 2912 | $dbh->do("DELETE from default_rev_records WHERE group_id=?", undef, ($groupid));
|
---|
| 2913 | $failmsg = "Failed to remove group $groupname";
|
---|
| 2914 | $dbh->do("DELETE from groups WHERE group_id=?", undef, ($groupid));
|
---|
[22] | 2915 |
|
---|
[487] | 2916 | $self->_log(group_id => $parid, entry => "Deleted group $groupname");
|
---|
[293] | 2917 | $resultmsg = "Deleted group $groupname";
|
---|
| 2918 |
|
---|
[22] | 2919 | # once we get here, we should have suceeded.
|
---|
| 2920 | $dbh->commit;
|
---|
| 2921 | }; # end eval
|
---|
| 2922 |
|
---|
| 2923 | if ($@) {
|
---|
| 2924 | my $msg = $@;
|
---|
| 2925 | eval { $dbh->rollback; };
|
---|
[517] | 2926 | if ($self->{log_failures}) {
|
---|
[487] | 2927 | $self->_log(group_id => $parid, entry => "$failmsg: $msg");
|
---|
[293] | 2928 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2929 | }
|
---|
[23] | 2930 | return ('FAIL',"$failmsg: $msg");
|
---|
[22] | 2931 | }
|
---|
[293] | 2932 |
|
---|
| 2933 | return ('OK',$resultmsg);
|
---|
[22] | 2934 | } # end delGroup()
|
---|
| 2935 |
|
---|
| 2936 |
|
---|
[19] | 2937 | ## DNSDB::getChildren()
|
---|
| 2938 | # Get a list of all groups whose parent^n is group <n>
|
---|
[24] | 2939 | # Takes a database handle, group ID, reference to an array to put the group IDs in,
|
---|
| 2940 | # and an optional flag to return only immediate children or all children-of-children
|
---|
| 2941 | # default to returning all children
|
---|
[19] | 2942 | # Calls itself
|
---|
| 2943 | sub getChildren {
|
---|
| 2944 | $errstr = '';
|
---|
[476] | 2945 | my $self = shift;
|
---|
| 2946 | my $dbh = $self->{dbh};
|
---|
[20] | 2947 | my $rootgroup = shift;
|
---|
| 2948 | my $groupdest = shift;
|
---|
[24] | 2949 | my $immed = shift || 'all';
|
---|
[19] | 2950 |
|
---|
| 2951 | # special break for default group; otherwise we get stuck.
|
---|
[20] | 2952 | if ($rootgroup == 1) {
|
---|
[19] | 2953 | # by definition, group 1 is the Root Of All Groups
|
---|
[24] | 2954 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
|
---|
[331] | 2955 | ($immed ne 'all' ? " AND parent_group_id=1" : '')." ORDER BY group_name");
|
---|
[19] | 2956 | $sth->execute;
|
---|
| 2957 | while (my @this = $sth->fetchrow_array) {
|
---|
[20] | 2958 | push @$groupdest, @this;
|
---|
[19] | 2959 | }
|
---|
| 2960 | } else {
|
---|
[331] | 2961 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=? ORDER BY group_name");
|
---|
[20] | 2962 | $sth->execute($rootgroup);
|
---|
[19] | 2963 | return if $sth->rows == 0;
|
---|
[20] | 2964 | my @grouplist;
|
---|
| 2965 | while (my ($group) = $sth->fetchrow_array) {
|
---|
| 2966 | push @$groupdest, $group;
|
---|
[476] | 2967 | $self->getChildren($group, $groupdest) if $immed eq 'all';
|
---|
[19] | 2968 | }
|
---|
| 2969 | }
|
---|
| 2970 | } # end getChildren()
|
---|
| 2971 |
|
---|
| 2972 |
|
---|
[20] | 2973 | ## DNSDB::groupName()
|
---|
[17] | 2974 | # Return the group name based on a group ID
|
---|
| 2975 | # Takes a database handle and the group ID
|
---|
| 2976 | # Returns the group name or undef on failure
|
---|
[20] | 2977 | sub groupName {
|
---|
[13] | 2978 | $errstr = '';
|
---|
[473] | 2979 | my $self = shift;
|
---|
| 2980 | my $dbh = $self->{dbh};
|
---|
[20] | 2981 | my $groupid = shift;
|
---|
| 2982 | my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
|
---|
| 2983 | $sth->execute($groupid);
|
---|
| 2984 | my ($groupname) = $sth->fetchrow_array();
|
---|
| 2985 | $errstr = $DBI::errstr if !$groupname;
|
---|
| 2986 | return $groupname if $groupname;
|
---|
| 2987 | } # end groupName
|
---|
[13] | 2988 |
|
---|
| 2989 |
|
---|
[314] | 2990 | ## DNSDB::getGroupCount()
|
---|
| 2991 | # Get count of subgroups in group or groups
|
---|
| 2992 | # Takes a database handle and hash containing:
|
---|
| 2993 | # - the "current" group
|
---|
| 2994 | # - an array of "acceptable" groups
|
---|
| 2995 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
| 2996 | # Returns an integer count of the resulting group list.
|
---|
| 2997 | sub getGroupCount {
|
---|
[476] | 2998 | my $self = shift;
|
---|
| 2999 | my $dbh = $self->{dbh};
|
---|
[314] | 3000 |
|
---|
| 3001 | my %args = @_;
|
---|
| 3002 |
|
---|
[509] | 3003 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 3004 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 3005 | $errstr = "Bad or missing curgroup argument";
|
---|
| 3006 | return;
|
---|
| 3007 | }
|
---|
| 3008 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 3009 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 3010 | $errstr = "Bad childlist argument";
|
---|
| 3011 | return;
|
---|
| 3012 | }
|
---|
| 3013 |
|
---|
[314] | 3014 | my @filterargs;
|
---|
| 3015 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3016 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3017 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3018 |
|
---|
| 3019 | my $sql = "SELECT count(*) FROM groups ".
|
---|
| 3020 | "WHERE parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3021 | ($args{startwith} ? " AND group_name ~* ?" : '').
|
---|
| 3022 | ($args{filter} ? " AND group_name ~* ?" : '');
|
---|
| 3023 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 3024 | $errstr = $dbh->errstr if !$count;
|
---|
| 3025 | return $count;
|
---|
| 3026 | } # end getGroupCount
|
---|
| 3027 |
|
---|
| 3028 |
|
---|
| 3029 | ## DNSDB::getGroupList()
|
---|
| 3030 | # Get a list of sub^n-groups in the specified group(s)
|
---|
| 3031 | # Takes the same arguments as getGroupCount() above
|
---|
| 3032 | # Returns an arrayref containing hashrefs suitable for feeding straight to HTML::Template
|
---|
| 3033 | sub getGroupList {
|
---|
[476] | 3034 | my $self = shift;
|
---|
| 3035 | my $dbh = $self->{dbh};
|
---|
[314] | 3036 |
|
---|
| 3037 | my %args = @_;
|
---|
| 3038 |
|
---|
[509] | 3039 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 3040 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 3041 | $errstr = "Bad or missing curgroup argument";
|
---|
| 3042 | return;
|
---|
| 3043 | }
|
---|
| 3044 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 3045 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 3046 | $errstr = "Bad childlist argument";
|
---|
| 3047 | return;
|
---|
| 3048 | }
|
---|
| 3049 |
|
---|
[314] | 3050 | my @filterargs;
|
---|
| 3051 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3052 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3053 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3054 |
|
---|
| 3055 | # protection against bad or missing arguments
|
---|
[508] | 3056 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
| 3057 | $args{sortby} = 'group' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
[397] | 3058 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[314] | 3059 |
|
---|
| 3060 | # munge sortby for columns in database
|
---|
| 3061 | $args{sortby} = 'g.group_name' if $args{sortby} eq 'group';
|
---|
| 3062 | $args{sortby} = 'g2.group_name' if $args{sortby} eq 'parent';
|
---|
| 3063 |
|
---|
[385] | 3064 | my $sql = q(SELECT g.group_id AS groupid, g.group_name AS groupname, g2.group_name AS pgroup
|
---|
[314] | 3065 | FROM groups g
|
---|
| 3066 | INNER JOIN groups g2 ON g2.group_id=g.parent_group_id
|
---|
| 3067 | ).
|
---|
[385] | 3068 | " WHERE g.parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
[314] | 3069 | ($args{startwith} ? " AND g.group_name ~* ?" : '').
|
---|
| 3070 | ($args{filter} ? " AND g.group_name ~* ?" : '').
|
---|
| 3071 | " GROUP BY g.group_id, g.group_name, g2.group_name ".
|
---|
| 3072 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
[517] | 3073 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
[314] | 3074 | my $glist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 3075 | $errstr = $dbh->errstr if !$glist;
|
---|
[385] | 3076 |
|
---|
| 3077 | # LEFT JOINs make the result set balloon beyond sanity just to include counts;
|
---|
| 3078 | # this means there's lots of crunching needed to trim the result set back down.
|
---|
| 3079 | # So instead we track the order of the groups, and push the counts into the
|
---|
| 3080 | # arrayref result separately.
|
---|
| 3081 | ##fixme: put this whole sub in a transaction? might be
|
---|
| 3082 | # needed for accurate results on very busy systems.
|
---|
[386] | 3083 | ##fixme: large group lists need prepared statements?
|
---|
| 3084 | #my $ucsth = $dbh->prepare("SELECT count(*) FROM users WHERE group_id=?");
|
---|
| 3085 | #my $dcsth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
|
---|
| 3086 | #my $rcsth = $dbh->prepare("SELECT count(*) FROM revzones WHERE group_id=?");
|
---|
[385] | 3087 | foreach (@{$glist}) {
|
---|
[386] | 3088 | my ($ucnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 3089 | $$_{nusers} = $ucnt;
|
---|
| 3090 | my ($dcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 3091 | $$_{ndomains} = $dcnt;
|
---|
| 3092 | my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 3093 | $$_{nrevzones} = $rcnt;
|
---|
[385] | 3094 | }
|
---|
| 3095 |
|
---|
[314] | 3096 | return $glist;
|
---|
| 3097 | } # end getGroupList
|
---|
| 3098 |
|
---|
| 3099 |
|
---|
[118] | 3100 | ## DNSDB::groupID()
|
---|
| 3101 | # Return the group ID based on the group name
|
---|
| 3102 | # Takes a database handle and the group name
|
---|
| 3103 | # Returns the group ID or undef on failure
|
---|
| 3104 | sub groupID {
|
---|
| 3105 | $errstr = '';
|
---|
[473] | 3106 | my $self = shift;
|
---|
| 3107 | my $dbh = $self->{dbh};
|
---|
[118] | 3108 | my $group = shift;
|
---|
[406] | 3109 | my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($group) );
|
---|
[118] | 3110 | $errstr = $DBI::errstr if !$grpid;
|
---|
| 3111 | return $grpid if $grpid;
|
---|
| 3112 | } # end groupID()
|
---|
| 3113 |
|
---|
| 3114 |
|
---|
[24] | 3115 | ## DNSDB::addUser()
|
---|
[87] | 3116 | # Add a user.
|
---|
| 3117 | # Takes a DB handle, username, group ID, password, state (active/inactive).
|
---|
| 3118 | # Optionally accepts:
|
---|
| 3119 | # user type (user/admin) - defaults to user
|
---|
| 3120 | # permissions string - defaults to inherit from group
|
---|
| 3121 | # three valid forms:
|
---|
| 3122 | # i - Inherit permissions
|
---|
| 3123 | # c:<user_id> - Clone permissions from <user_id>
|
---|
| 3124 | # C:<permission list> - Set these specific permissions
|
---|
| 3125 | # first name - defaults to username
|
---|
| 3126 | # last name - defaults to blank
|
---|
| 3127 | # phone - defaults to blank (could put other data within column def)
|
---|
[90] | 3128 | # Returns (OK,<uid>) on success, (FAIL,<message>) on failure
|
---|
[24] | 3129 | sub addUser {
|
---|
| 3130 | $errstr = '';
|
---|
[479] | 3131 | my $self = shift;
|
---|
| 3132 | my $dbh = $self->{dbh};
|
---|
[24] | 3133 | my $username = shift;
|
---|
| 3134 | my $group = shift;
|
---|
| 3135 | my $pass = shift;
|
---|
| 3136 | my $state = shift;
|
---|
[25] | 3137 |
|
---|
[90] | 3138 | return ('FAIL', "Missing one or more required entries") if !defined($state);
|
---|
| 3139 | return ('FAIL', "Username must not be blank") if !$username;
|
---|
[87] | 3140 |
|
---|
[408] | 3141 | # Munge in some alternate state values
|
---|
| 3142 | $state = 1 if $state =~ /^active$/;
|
---|
| 3143 | $state = 1 if $state =~ /^on$/;
|
---|
| 3144 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 3145 | $state = 0 if $state =~ /^off$/;
|
---|
| 3146 |
|
---|
[25] | 3147 | my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
|
---|
| 3148 |
|
---|
[67] | 3149 | my $permstring = shift || 'i'; # default is to inhert permissions from group
|
---|
| 3150 |
|
---|
[25] | 3151 | my $fname = shift || $username;
|
---|
[24] | 3152 | my $lname = shift || '';
|
---|
[25] | 3153 | my $phone = shift || ''; # not going format-check
|
---|
[24] | 3154 |
|
---|
[38] | 3155 | my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
|
---|
[24] | 3156 | my $user_id;
|
---|
| 3157 |
|
---|
[38] | 3158 | # quick check to start to see if we've already got one
|
---|
| 3159 | $sth->execute($username);
|
---|
| 3160 | ($user_id) = $sth->fetchrow_array;
|
---|
| 3161 |
|
---|
| 3162 | return ('FAIL', "User already exists") if $user_id;
|
---|
| 3163 |
|
---|
[24] | 3164 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3165 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3166 | local $dbh->{AutoCommit} = 0;
|
---|
| 3167 | local $dbh->{RaiseError} = 1;
|
---|
| 3168 |
|
---|
| 3169 | # Wrap all the SQL in a transaction
|
---|
| 3170 | eval {
|
---|
[87] | 3171 | # insert the user... note we set inherited perms by default since
|
---|
| 3172 | # it's simple and cleans up some other bits of state
|
---|
[592] | 3173 | ##fixme: need better handling of case of inherited or missing (!!) permissions entries
|
---|
[87] | 3174 | my $sth = $dbh->prepare("INSERT INTO users ".
|
---|
| 3175 | "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
|
---|
| 3176 | "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
|
---|
| 3177 | $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);
|
---|
[24] | 3178 |
|
---|
| 3179 | # get the ID...
|
---|
[94] | 3180 | ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");
|
---|
[24] | 3181 |
|
---|
[87] | 3182 | # Permissions! Gotta set'em all!
|
---|
[401] | 3183 | die "Invalid permission string $permstring\n"
|
---|
[87] | 3184 | if $permstring !~ /^(?:
|
---|
| 3185 | i # inherit
|
---|
| 3186 | |c:\d+ # clone
|
---|
| 3187 | # custom. no, the leading , is not a typo
|
---|
[391] | 3188 | |C:(?:,(?:group|user|domain|record|location|self)_(?:edit|create|delete|locchg|view))*
|
---|
[87] | 3189 | )$/x;
|
---|
| 3190 | # bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
|
---|
| 3191 | if ($permstring ne 'i') {
|
---|
| 3192 | # for cloned or custom permissions, we have to create a new permissions entry.
|
---|
| 3193 | my $clonesrc = $group;
|
---|
| 3194 | if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
|
---|
| 3195 | $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
|
---|
| 3196 | "SELECT $permlist,? FROM permissions WHERE permission_id=".
|
---|
| 3197 | "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
|
---|
| 3198 | undef, ($user_id,$clonesrc) );
|
---|
| 3199 | $dbh->do("UPDATE users SET permission_id=".
|
---|
| 3200 | "(SELECT permission_id FROM permissions WHERE user_id=?) ".
|
---|
| 3201 | "WHERE user_id=?", undef, ($user_id, $user_id) );
|
---|
| 3202 | }
|
---|
| 3203 | if ($permstring =~ /^C:/) {
|
---|
| 3204 | # finally for custom permissions, we set the passed-in permissions (and unset
|
---|
| 3205 | # any that might have been brought in by the clone operation above)
|
---|
| 3206 | my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
|
---|
| 3207 | undef, ($user_id) );
|
---|
| 3208 | foreach (@permtypes) {
|
---|
| 3209 | if ($permstring =~ /,$_/) {
|
---|
| 3210 | $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
|
---|
| 3211 | } else {
|
---|
| 3212 | $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
|
---|
| 3213 | }
|
---|
| 3214 | }
|
---|
| 3215 | }
|
---|
| 3216 |
|
---|
| 3217 | $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
|
---|
| 3218 |
|
---|
[25] | 3219 | ##fixme: add another table to hold name/email for log table?
|
---|
| 3220 |
|
---|
[487] | 3221 | $self->_log(group_id => $group, entry => "Added user $username ($fname $lname)");
|
---|
[24] | 3222 | # once we get here, we should have suceeded.
|
---|
| 3223 | $dbh->commit;
|
---|
| 3224 | }; # end eval
|
---|
| 3225 |
|
---|
| 3226 | if ($@) {
|
---|
| 3227 | my $msg = $@;
|
---|
| 3228 | eval { $dbh->rollback; };
|
---|
[517] | 3229 | if ($self->{log_failures}) {
|
---|
[487] | 3230 | $self->_log(group_id => $group, entry => "Error adding user $username: $msg");
|
---|
[294] | 3231 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 3232 | }
|
---|
| 3233 | return ('FAIL',"Error adding user $username: $msg");
|
---|
[24] | 3234 | }
|
---|
[294] | 3235 |
|
---|
| 3236 | return ('OK',"User $username ($fname $lname) added");
|
---|
[24] | 3237 | } # end addUser
|
---|
| 3238 |
|
---|
| 3239 |
|
---|
[325] | 3240 | ## DNSDB::getUserCount()
|
---|
| 3241 | # Get count of users in group
|
---|
| 3242 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
| 3243 | # - a reference list of secondary groups
|
---|
| 3244 | # - a filter string
|
---|
| 3245 | # - a "Starts with" string
|
---|
| 3246 | sub getUserCount {
|
---|
[479] | 3247 | my $self = shift;
|
---|
| 3248 | my $dbh = $self->{dbh};
|
---|
[325] | 3249 |
|
---|
| 3250 | my %args = @_;
|
---|
| 3251 |
|
---|
[509] | 3252 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 3253 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 3254 | $errstr = "Bad or missing curgroup argument";
|
---|
| 3255 | return;
|
---|
| 3256 | }
|
---|
| 3257 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 3258 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 3259 | $errstr = "Bad childlist argument";
|
---|
| 3260 | return;
|
---|
| 3261 | }
|
---|
| 3262 |
|
---|
[325] | 3263 | my @filterargs;
|
---|
| 3264 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3265 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3266 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3267 |
|
---|
| 3268 | my $sql = "SELECT count(*) FROM users ".
|
---|
| 3269 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3270 | ($args{startwith} ? " AND username ~* ?" : '').
|
---|
| 3271 | ($args{filter} ? " AND username ~* ?" : '');
|
---|
| 3272 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 3273 | $errstr = $dbh->errstr if !$count;
|
---|
| 3274 | return $count;
|
---|
| 3275 | } # end getUserCount()
|
---|
| 3276 |
|
---|
| 3277 |
|
---|
| 3278 | ## DNSDB::getUserList()
|
---|
| 3279 | # Get list of users
|
---|
| 3280 | # Takes the same arguments as getUserCount() above, plus optional:
|
---|
| 3281 | # - sort field
|
---|
| 3282 | # - sort order
|
---|
| 3283 | # - offset/return-all-everything flag (defaults to $perpage records)
|
---|
| 3284 | sub getUserList {
|
---|
[479] | 3285 | my $self = shift;
|
---|
| 3286 | my $dbh = $self->{dbh};
|
---|
[325] | 3287 |
|
---|
| 3288 | my %args = @_;
|
---|
| 3289 |
|
---|
[509] | 3290 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 3291 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 3292 | $errstr = "Bad or missing curgroup argument";
|
---|
| 3293 | return;
|
---|
| 3294 | }
|
---|
| 3295 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 3296 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 3297 | $errstr = "Bad childlist argument";
|
---|
| 3298 | return;
|
---|
| 3299 | }
|
---|
| 3300 |
|
---|
[325] | 3301 | my @filterargs;
|
---|
| 3302 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3303 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3304 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3305 |
|
---|
| 3306 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
| 3307 | my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
| 3308 | fname => 'fname');
|
---|
| 3309 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 3310 |
|
---|
| 3311 | # protection against bad or missing arguments
|
---|
[508] | 3312 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
| 3313 | $args{sortby} = 'u.username' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
[397] | 3314 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[325] | 3315 |
|
---|
| 3316 | my $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ".
|
---|
| 3317 | "FROM users u ".
|
---|
| 3318 | "INNER JOIN groups g ON u.group_id=g.group_id ".
|
---|
| 3319 | "WHERE u.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3320 | ($args{startwith} ? " AND u.username ~* ?" : '').
|
---|
| 3321 | ($args{filter} ? " AND u.username ~* ?" : '').
|
---|
[401] | 3322 | " AND NOT u.type = 'R' ".
|
---|
[325] | 3323 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
[517] | 3324 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
[325] | 3325 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 3326 | $errstr = $dbh->errstr if !$ulist;
|
---|
| 3327 | return $ulist;
|
---|
| 3328 | } # end getUserList()
|
---|
| 3329 |
|
---|
| 3330 |
|
---|
[326] | 3331 | ## DNSDB::getUserDropdown()
|
---|
| 3332 | # Get a list of usernames for use in a dropdown menu.
|
---|
| 3333 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
| 3334 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
| 3335 | sub getUserDropdown {
|
---|
[479] | 3336 | my $self = shift;
|
---|
| 3337 | my $dbh = $self->{dbh};
|
---|
[326] | 3338 | my $grp = shift;
|
---|
| 3339 | my $sel = shift || 0;
|
---|
| 3340 |
|
---|
| 3341 | my $sth = $dbh->prepare("SELECT username,user_id FROM users WHERE group_id=?");
|
---|
| 3342 | $sth->execute($grp);
|
---|
| 3343 |
|
---|
| 3344 | my @userlist;
|
---|
| 3345 | while (my ($username,$uid) = $sth->fetchrow_array) {
|
---|
| 3346 | my %row = (
|
---|
| 3347 | username => $username,
|
---|
| 3348 | uid => $uid,
|
---|
| 3349 | selected => ($sel == $uid ? 1 : 0)
|
---|
| 3350 | );
|
---|
| 3351 | push @userlist, \%row;
|
---|
| 3352 | }
|
---|
| 3353 | return \@userlist;
|
---|
| 3354 | } # end getUserDropdown()
|
---|
| 3355 |
|
---|
| 3356 |
|
---|
[83] | 3357 | ## DNSDB:: updateUser()
|
---|
[90] | 3358 | # Update general data about user
|
---|
[83] | 3359 | sub updateUser {
|
---|
[479] | 3360 | my $self = shift;
|
---|
| 3361 | my $dbh = $self->{dbh};
|
---|
[118] | 3362 |
|
---|
| 3363 | ##fixme: tweak calling convention so that we can update any given bit of data
|
---|
[83] | 3364 | my $uid = shift;
|
---|
| 3365 | my $username = shift;
|
---|
| 3366 | my $group = shift;
|
---|
| 3367 | my $pass = shift;
|
---|
| 3368 | my $state = shift;
|
---|
[87] | 3369 | my $type = shift || 'u';
|
---|
[83] | 3370 | my $fname = shift || $username;
|
---|
| 3371 | my $lname = shift || '';
|
---|
| 3372 | my $phone = shift || ''; # not going format-check
|
---|
| 3373 |
|
---|
[294] | 3374 | my $resultmsg = '';
|
---|
[83] | 3375 |
|
---|
[411] | 3376 | # Munge in some alternate state values
|
---|
| 3377 | $state = 1 if $state =~ /^active$/;
|
---|
| 3378 | $state = 1 if $state =~ /^on$/;
|
---|
| 3379 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 3380 | $state = 0 if $state =~ /^off$/;
|
---|
| 3381 |
|
---|
[83] | 3382 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3383 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3384 | local $dbh->{AutoCommit} = 0;
|
---|
| 3385 | local $dbh->{RaiseError} = 1;
|
---|
| 3386 |
|
---|
| 3387 | my $sth;
|
---|
| 3388 |
|
---|
| 3389 | # Password can be left blank; if so we assume there's one on file.
|
---|
| 3390 | # Actual blank passwords are bad, mm'kay?
|
---|
| 3391 | if (!$pass) {
|
---|
[294] | 3392 | ($pass) = $dbh->selectrow_array("SELECT password FROM users WHERE user_id=?", undef, ($uid));
|
---|
[83] | 3393 | } else {
|
---|
| 3394 | $pass = unix_md5_crypt($pass);
|
---|
| 3395 | }
|
---|
| 3396 |
|
---|
| 3397 | eval {
|
---|
[294] | 3398 | $dbh->do("UPDATE users SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?".
|
---|
| 3399 | " WHERE user_id=?", undef, ($username, $pass, $fname, $lname, $phone, $type, $state, $uid));
|
---|
| 3400 | $resultmsg = "Updated user info for $username ($fname $lname)";
|
---|
[487] | 3401 | $self->_log(group_id => $group, entry => $resultmsg);
|
---|
[83] | 3402 | $dbh->commit;
|
---|
| 3403 | };
|
---|
| 3404 | if ($@) {
|
---|
| 3405 | my $msg = $@;
|
---|
| 3406 | eval { $dbh->rollback; };
|
---|
[517] | 3407 | if ($self->{log_failures}) {
|
---|
[487] | 3408 | $self->_log(group_id => $group, entry => "Error updating user $username: $msg");
|
---|
[294] | 3409 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 3410 | }
|
---|
| 3411 | return ('FAIL',"Error updating user $username: $msg");
|
---|
[83] | 3412 | }
|
---|
[294] | 3413 |
|
---|
| 3414 | return ('OK',$resultmsg);
|
---|
[83] | 3415 | } # end updateUser()
|
---|
| 3416 |
|
---|
| 3417 |
|
---|
[24] | 3418 | ## DNSDB::delUser()
|
---|
[297] | 3419 | # Delete a user.
|
---|
| 3420 | # Takes a database handle and user ID
|
---|
| 3421 | # Returns a success/failure code and matching message
|
---|
[24] | 3422 | sub delUser {
|
---|
[479] | 3423 | my $self = shift;
|
---|
| 3424 | my $dbh = $self->{dbh};
|
---|
[25] | 3425 | my $userid = shift;
|
---|
| 3426 |
|
---|
[297] | 3427 | return ('FAIL',"Bad userid") if !defined($userid);
|
---|
[25] | 3428 |
|
---|
[479] | 3429 | my $userdata = $self->getUserData($userid);
|
---|
[25] | 3430 |
|
---|
[297] | 3431 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3432 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3433 | local $dbh->{AutoCommit} = 0;
|
---|
| 3434 | local $dbh->{RaiseError} = 1;
|
---|
[25] | 3435 |
|
---|
[297] | 3436 | eval {
|
---|
| 3437 | $dbh->do("DELETE FROM users WHERE user_id=?", undef, ($userid));
|
---|
[487] | 3438 | $self->_log(group_id => $userdata->{group_id},
|
---|
[297] | 3439 | entry => "Deleted user ID $userid/".$userdata->{username}.
|
---|
[487] | 3440 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")");
|
---|
[297] | 3441 | $dbh->commit;
|
---|
| 3442 | };
|
---|
| 3443 | if ($@) {
|
---|
| 3444 | my $msg = $@;
|
---|
| 3445 | eval { $dbh->rollback; };
|
---|
[517] | 3446 | if ($self->{log_failures}) {
|
---|
[487] | 3447 | $self->_log(group_id => $userdata->{group_id}, entry => "Error deleting user ID ".
|
---|
| 3448 | "$userid/".$userdata->{username}.": $msg");
|
---|
[297] | 3449 | $dbh->commit;
|
---|
| 3450 | }
|
---|
| 3451 | return ('FAIL',"Error deleting user $userid/".$userdata->{username}.": $msg");
|
---|
| 3452 | }
|
---|
| 3453 |
|
---|
| 3454 | return ('OK',"Deleted user ".$userdata->{username}." (".$userdata->{firstname}." ".$userdata->{lastname}.")");
|
---|
[24] | 3455 | } # end delUser
|
---|
| 3456 |
|
---|
| 3457 |
|
---|
[25] | 3458 | ## DNSDB::userFullName()
|
---|
| 3459 | # Return a pretty string!
|
---|
| 3460 | # Takes a user_id and optional printf-ish string to indicate which pieces where:
|
---|
| 3461 | # %u for the username
|
---|
| 3462 | # %f for the first name
|
---|
| 3463 | # %l for the last name
|
---|
| 3464 | # All other text in the passed string will be left as-is.
|
---|
| 3465 | ##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
|
---|
| 3466 | sub userFullName {
|
---|
| 3467 | $errstr = '';
|
---|
[473] | 3468 | my $self = shift;
|
---|
| 3469 | my $dbh = $self->{dbh};
|
---|
[25] | 3470 | my $userid = shift;
|
---|
| 3471 | my $fullformat = shift || '%f %l (%u)';
|
---|
| 3472 | my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
|
---|
| 3473 | $sth->execute($userid);
|
---|
| 3474 | my ($uname,$fname,$lname) = $sth->fetchrow_array();
|
---|
| 3475 | $errstr = $DBI::errstr if !$uname;
|
---|
| 3476 |
|
---|
| 3477 | $fullformat =~ s/\%u/$uname/g;
|
---|
| 3478 | $fullformat =~ s/\%f/$fname/g;
|
---|
| 3479 | $fullformat =~ s/\%l/$lname/g;
|
---|
| 3480 |
|
---|
| 3481 | return $fullformat;
|
---|
| 3482 | } # end userFullName
|
---|
| 3483 |
|
---|
| 3484 |
|
---|
[51] | 3485 | ## DNSDB::userStatus()
|
---|
| 3486 | # Sets and/or returns a user's status
|
---|
| 3487 | # Takes a database handle, user ID and optionally a status argument
|
---|
| 3488 | # Returns undef on errors.
|
---|
| 3489 | sub userStatus {
|
---|
[479] | 3490 | my $self = shift;
|
---|
| 3491 | my $dbh = $self->{dbh};
|
---|
[51] | 3492 | my $id = shift;
|
---|
[296] | 3493 | my $newstatus = shift || 'mu';
|
---|
[51] | 3494 |
|
---|
| 3495 | return undef if $id !~ /^\d+$/;
|
---|
| 3496 |
|
---|
[479] | 3497 | my $userdata = $self->getUserData($id);
|
---|
[51] | 3498 |
|
---|
[296] | 3499 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3500 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3501 | local $dbh->{AutoCommit} = 0;
|
---|
| 3502 | local $dbh->{RaiseError} = 1;
|
---|
| 3503 |
|
---|
| 3504 | if ($newstatus ne 'mu') {
|
---|
| 3505 | # ooo, fun! let's see what we were passed for status
|
---|
| 3506 | eval {
|
---|
| 3507 | $newstatus = 0 if $newstatus eq 'useroff';
|
---|
| 3508 | $newstatus = 1 if $newstatus eq 'useron';
|
---|
| 3509 | $dbh->do("UPDATE users SET status=? WHERE user_id=?", undef, ($newstatus, $id));
|
---|
| 3510 |
|
---|
[297] | 3511 | $resultstr = ($newstatus ? 'Enabled' : 'Disabled')." user ".$userdata->{username}.
|
---|
| 3512 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")";
|
---|
[296] | 3513 |
|
---|
| 3514 | my %loghash;
|
---|
[473] | 3515 | $loghash{group_id} = $self->parentID(id => $id, type => 'user');
|
---|
[296] | 3516 | $loghash{entry} = $resultstr;
|
---|
[487] | 3517 | $self->_log(%loghash);
|
---|
[296] | 3518 |
|
---|
| 3519 | $dbh->commit;
|
---|
| 3520 | };
|
---|
| 3521 | if ($@) {
|
---|
| 3522 | my $msg = $@;
|
---|
| 3523 | eval { $dbh->rollback; };
|
---|
| 3524 | $resultstr = '';
|
---|
| 3525 | $errstr = $msg;
|
---|
| 3526 | ##fixme: failure logging?
|
---|
| 3527 | return;
|
---|
[51] | 3528 | }
|
---|
| 3529 | }
|
---|
| 3530 |
|
---|
[296] | 3531 | my ($status) = $dbh->selectrow_array("SELECT status FROM users WHERE user_id=?", undef, ($id));
|
---|
[51] | 3532 | return $status;
|
---|
| 3533 | } # end userStatus()
|
---|
| 3534 |
|
---|
| 3535 |
|
---|
[83] | 3536 | ## DNSDB::getUserData()
|
---|
| 3537 | # Get misc user data for display
|
---|
| 3538 | sub getUserData {
|
---|
[479] | 3539 | my $self = shift;
|
---|
| 3540 | my $dbh = $self->{dbh};
|
---|
[83] | 3541 | my $uid = shift;
|
---|
| 3542 |
|
---|
| 3543 | my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
|
---|
| 3544 | "FROM users WHERE user_id=?");
|
---|
| 3545 | $sth->execute($uid);
|
---|
| 3546 | return $sth->fetchrow_hashref();
|
---|
| 3547 | } # end getUserData()
|
---|
| 3548 |
|
---|
| 3549 |
|
---|
[370] | 3550 | ## DNSDB::addLoc()
|
---|
[375] | 3551 | # Add a new location.
|
---|
| 3552 | # Takes a database handle, group ID, short and long description, and a comma-separated
|
---|
| 3553 | # list of IP addresses.
|
---|
| 3554 | # Returns ('OK',<location>) on success, ('FAIL',<failmsg>) on failure
|
---|
| 3555 | sub addLoc {
|
---|
[480] | 3556 | my $self = shift;
|
---|
| 3557 | my $dbh = $self->{dbh};
|
---|
[375] | 3558 | my $grp = shift;
|
---|
| 3559 | my $shdesc = shift;
|
---|
| 3560 | my $comments = shift;
|
---|
| 3561 | my $iplist = shift;
|
---|
[370] | 3562 |
|
---|
[375] | 3563 | # $shdesc gets set to the generated location ID if possible, but these can be de-undefined here.
|
---|
| 3564 | $comments = '' if !$comments;
|
---|
| 3565 | $iplist = '' if !$iplist;
|
---|
| 3566 |
|
---|
| 3567 | my $loc;
|
---|
| 3568 |
|
---|
| 3569 | # Generate a location ID. This is, by spec, a two-character widget. We'll use [a-z][a-z]
|
---|
| 3570 | # for now; 676 locations should satisfy all but the largest of the huge networks.
|
---|
| 3571 | # Not sure whether these are case-sensitive, or what other rules might apply - in any case
|
---|
| 3572 | # the absolute maximum is 16K (256*256) since it's parsed by tinydns as a two-character field.
|
---|
| 3573 |
|
---|
| 3574 | # add just after "my $origloc = $loc;":
|
---|
| 3575 | # # These expand the possible space from 26^2 to 52^2 [* note in testing only 2052 were achieved],
|
---|
| 3576 | # # and wrap it around.
|
---|
| 3577 | # # Yes, they skip a couple of possibles. No, I don't care.
|
---|
| 3578 | # $loc = 'aA' if $loc eq 'zz';
|
---|
| 3579 | # $loc = 'Aa' if $loc eq 'zZ';
|
---|
| 3580 | # $loc = 'ZA' if $loc eq 'Zz';
|
---|
| 3581 | # $loc = 'aa' if $loc eq 'ZZ';
|
---|
| 3582 |
|
---|
| 3583 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3584 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3585 | local $dbh->{AutoCommit} = 0;
|
---|
| 3586 | local $dbh->{RaiseError} = 1;
|
---|
| 3587 |
|
---|
| 3588 | ##fixme: There is probably a far better way to do this. Sequential increments
|
---|
| 3589 | # are marginally less stupid that pure random generation though, and the existence
|
---|
| 3590 | # check makes sure we don't stomp on an imported one.
|
---|
| 3591 |
|
---|
| 3592 | eval {
|
---|
| 3593 | # Get the "last" location. Note this is the only use for loc_id, because selecting on location Does Funky Things
|
---|
| 3594 | ($loc) = $dbh->selectrow_array("SELECT location FROM locations ORDER BY loc_id DESC LIMIT 1");
|
---|
[478] | 3595 | ($loc) = ($loc =~ /^(..)/) if $loc;
|
---|
[375] | 3596 | my $origloc = $loc;
|
---|
[446] | 3597 | $loc = 'aa' if !$loc;
|
---|
[375] | 3598 | # Make a change...
|
---|
| 3599 | $loc++;
|
---|
| 3600 | # ... and keep changing if it exists
|
---|
| 3601 | while ($dbh->selectrow_array("SELECT count(*) FROM locations WHERE location LIKE ?", undef, ($loc.'%'))) {
|
---|
| 3602 | $loc++;
|
---|
| 3603 | ($loc) = ($loc =~ /^(..)/);
|
---|
| 3604 | die "too many locations in use, can't add another one\n" if $loc eq $origloc;
|
---|
| 3605 | ##fixme: really need to handle this case faster somehow
|
---|
| 3606 | #if $loc eq $origloc die "<thwap> bad admin: all locations used, your network is too fragmented";
|
---|
| 3607 | }
|
---|
| 3608 | # And now we should have a unique location. tinydns fundamentally limits the
|
---|
| 3609 | # number of these but there's no doc on what characters are valid.
|
---|
| 3610 | $shdesc = $loc if !$shdesc;
|
---|
| 3611 | $dbh->do("INSERT INTO locations (location, group_id, iplist, description, comments) VALUES (?,?,?,?,?)",
|
---|
| 3612 | undef, ($loc, $grp, $iplist, $shdesc, $comments) );
|
---|
[487] | 3613 | $self->_log(entry => "Added location ($shdesc, '$iplist')");
|
---|
[377] | 3614 | $dbh->commit;
|
---|
[375] | 3615 | };
|
---|
| 3616 | if ($@) {
|
---|
| 3617 | my $msg = $@;
|
---|
| 3618 | eval { $dbh->rollback; };
|
---|
[517] | 3619 | if ($self->{log_failures}) {
|
---|
[375] | 3620 | $shdesc = $loc if !$shdesc;
|
---|
[487] | 3621 | $self->_log(entry => "Failed adding location ($shdesc, '$iplist'): $msg");
|
---|
[375] | 3622 | $dbh->commit;
|
---|
| 3623 | }
|
---|
| 3624 | return ('FAIL',$msg);
|
---|
| 3625 | }
|
---|
| 3626 |
|
---|
| 3627 | return ('OK',$loc);
|
---|
[377] | 3628 | } # end addLoc()
|
---|
[375] | 3629 |
|
---|
| 3630 |
|
---|
[370] | 3631 | ## DNSDB::updateLoc()
|
---|
[428] | 3632 | # Update details of a location.
|
---|
| 3633 | # Takes a database handle, location ID, group ID, short description,
|
---|
| 3634 | # long comments/notes, and comma/space-separated IP list
|
---|
| 3635 | # Returns a result code and message
|
---|
[377] | 3636 | sub updateLoc {
|
---|
[480] | 3637 | my $self = shift;
|
---|
| 3638 | my $dbh = $self->{dbh};
|
---|
[377] | 3639 | my $loc = shift;
|
---|
| 3640 | my $grp = shift;
|
---|
| 3641 | my $shdesc = shift;
|
---|
| 3642 | my $comments = shift;
|
---|
| 3643 | my $iplist = shift;
|
---|
[370] | 3644 |
|
---|
[377] | 3645 | $shdesc = '' if !$shdesc;
|
---|
| 3646 | $comments = '' if !$comments;
|
---|
| 3647 | $iplist = '' if !$iplist;
|
---|
| 3648 |
|
---|
| 3649 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3650 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3651 | local $dbh->{AutoCommit} = 0;
|
---|
| 3652 | local $dbh->{RaiseError} = 1;
|
---|
| 3653 |
|
---|
[480] | 3654 | my $oldloc = $self->getLoc($loc);
|
---|
[377] | 3655 | my $okmsg = "Updated location (".$oldloc->{description}.", '".$oldloc->{iplist}."') to ($shdesc, '$iplist')";
|
---|
| 3656 |
|
---|
| 3657 | eval {
|
---|
| 3658 | $dbh->do("UPDATE locations SET group_id=?,iplist=?,description=?,comments=? WHERE location=?",
|
---|
| 3659 | undef, ($grp, $iplist, $shdesc, $comments, $loc) );
|
---|
[487] | 3660 | $self->_log(entry => $okmsg);
|
---|
[377] | 3661 | $dbh->commit;
|
---|
| 3662 | };
|
---|
| 3663 | if ($@) {
|
---|
| 3664 | my $msg = $@;
|
---|
| 3665 | eval { $dbh->rollback; };
|
---|
[517] | 3666 | if ($self->{log_failures}) {
|
---|
[377] | 3667 | $shdesc = $loc if !$shdesc;
|
---|
[487] | 3668 | $self->_log(entry => "Failed updating location ($shdesc, '$iplist'): $msg");
|
---|
[377] | 3669 | $dbh->commit;
|
---|
| 3670 | }
|
---|
| 3671 | return ('FAIL',$msg);
|
---|
| 3672 | }
|
---|
| 3673 |
|
---|
| 3674 | return ('OK',$okmsg);
|
---|
| 3675 | } # end updateLoc()
|
---|
| 3676 |
|
---|
| 3677 |
|
---|
[370] | 3678 | ## DNSDB::delLoc()
|
---|
[428] | 3679 | sub delLoc {
|
---|
[480] | 3680 | my $self = shift;
|
---|
| 3681 | my $dbh = $self->{dbh};
|
---|
[428] | 3682 | my $loc = shift;
|
---|
[370] | 3683 |
|
---|
[428] | 3684 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3685 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3686 | local $dbh->{AutoCommit} = 0;
|
---|
| 3687 | local $dbh->{RaiseError} = 1;
|
---|
[370] | 3688 |
|
---|
[480] | 3689 | my $oldloc = $self->getLoc($loc);
|
---|
[428] | 3690 | my $olddesc = ($oldloc->{description} ? $oldloc->{description} : $loc);
|
---|
| 3691 | my $okmsg = "Deleted location ($olddesc, '".$oldloc->{iplist}."')";
|
---|
| 3692 |
|
---|
| 3693 | eval {
|
---|
| 3694 | # Check for records with this location first. Deleting a location without deleting records
|
---|
| 3695 | # tagged for that location will render them unpublished without other warning.
|
---|
| 3696 | my ($r) = $dbh->selectrow_array("SELECT record_id FROM records WHERE location=? LIMIT 1", undef, ($loc) );
|
---|
| 3697 | die "Records still exist in location $olddesc\n" if $r;
|
---|
| 3698 | $dbh->do("DELETE FROM locations WHERE location=?", undef, ($loc) );
|
---|
[487] | 3699 | $self->_log(entry => $okmsg);
|
---|
[428] | 3700 | $dbh->commit;
|
---|
| 3701 | };
|
---|
| 3702 | if ($@) {
|
---|
| 3703 | my $msg = $@;
|
---|
| 3704 | eval { $dbh->rollback; };
|
---|
[517] | 3705 | if ($self->{log_failures}) {
|
---|
[487] | 3706 | $self->_log(entry => "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
|
---|
[428] | 3707 | $dbh->commit;
|
---|
| 3708 | }
|
---|
| 3709 | return ('FAIL', "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
|
---|
| 3710 | }
|
---|
| 3711 |
|
---|
| 3712 | return ('OK',$okmsg);
|
---|
| 3713 | } # end delLoc()
|
---|
| 3714 |
|
---|
| 3715 |
|
---|
[375] | 3716 | ## DNSDB::getLoc()
|
---|
[428] | 3717 | # Get details about a location/view
|
---|
| 3718 | # Takes a database handle and location ID.
|
---|
| 3719 | # Returns a reference to a hash containing the group ID, IP list, description, and comments/notes
|
---|
[375] | 3720 | sub getLoc {
|
---|
[480] | 3721 | my $self = shift;
|
---|
| 3722 | my $dbh = $self->{dbh};
|
---|
[375] | 3723 | my $loc = shift;
|
---|
| 3724 |
|
---|
| 3725 | my $sth = $dbh->prepare("SELECT group_id,iplist,description,comments FROM locations WHERE location=?");
|
---|
| 3726 | $sth->execute($loc);
|
---|
| 3727 | return $sth->fetchrow_hashref();
|
---|
| 3728 | } # end getLoc()
|
---|
| 3729 |
|
---|
| 3730 |
|
---|
[370] | 3731 | ## DNSDB::getLocCount()
|
---|
| 3732 | # Get count of locations/views
|
---|
| 3733 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
| 3734 | # - a reference list of secondary groups
|
---|
| 3735 | # - a filter string
|
---|
| 3736 | # - a "Starts with" string
|
---|
| 3737 | sub getLocCount {
|
---|
[480] | 3738 | my $self = shift;
|
---|
| 3739 | my $dbh = $self->{dbh};
|
---|
[370] | 3740 |
|
---|
| 3741 | my %args = @_;
|
---|
| 3742 |
|
---|
[509] | 3743 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 3744 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 3745 | $errstr = "Bad or missing curgroup argument";
|
---|
| 3746 | return;
|
---|
| 3747 | }
|
---|
| 3748 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 3749 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 3750 | $errstr = "Bad childlist argument";
|
---|
| 3751 | return;
|
---|
| 3752 | }
|
---|
| 3753 |
|
---|
[370] | 3754 | my @filterargs;
|
---|
| 3755 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3756 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3757 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3758 |
|
---|
| 3759 | my $sql = "SELECT count(*) FROM locations ".
|
---|
| 3760 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3761 | ($args{startwith} ? " AND description ~* ?" : '').
|
---|
| 3762 | ($args{filter} ? " AND description ~* ?" : '');
|
---|
| 3763 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 3764 | $errstr = $dbh->errstr if !$count;
|
---|
| 3765 | return $count;
|
---|
| 3766 | } # end getLocCount()
|
---|
| 3767 |
|
---|
| 3768 |
|
---|
| 3769 | ## DNSDB::getLocList()
|
---|
| 3770 | sub getLocList {
|
---|
[480] | 3771 | my $self = shift;
|
---|
| 3772 | my $dbh = $self->{dbh};
|
---|
[370] | 3773 |
|
---|
| 3774 | my %args = @_;
|
---|
| 3775 |
|
---|
[509] | 3776 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 3777 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 3778 | $errstr = "Bad or missing curgroup argument";
|
---|
| 3779 | return;
|
---|
| 3780 | }
|
---|
| 3781 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 3782 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 3783 | $errstr = "Bad childlist argument";
|
---|
| 3784 | return;
|
---|
| 3785 | }
|
---|
| 3786 |
|
---|
[370] | 3787 | my @filterargs;
|
---|
| 3788 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3789 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3790 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3791 |
|
---|
| 3792 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
| 3793 | # my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
| 3794 | # fname => 'fname');
|
---|
| 3795 | # $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 3796 |
|
---|
| 3797 | # protection against bad or missing arguments
|
---|
[508] | 3798 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
| 3799 | $args{sortby} = 'l.description' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
[397] | 3800 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[370] | 3801 |
|
---|
| 3802 | my $sql = "SELECT l.location, l.description, l.iplist, g.group_name ".
|
---|
| 3803 | "FROM locations l ".
|
---|
| 3804 | "INNER JOIN groups g ON l.group_id=g.group_id ".
|
---|
| 3805 | "WHERE l.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3806 | ($args{startwith} ? " AND l.description ~* ?" : '').
|
---|
| 3807 | ($args{filter} ? " AND l.description ~* ?" : '').
|
---|
| 3808 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
[517] | 3809 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
[370] | 3810 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 3811 | $errstr = $dbh->errstr if !$ulist;
|
---|
| 3812 | return $ulist;
|
---|
| 3813 | } # end getLocList()
|
---|
| 3814 |
|
---|
| 3815 |
|
---|
| 3816 | ## DNSDB::getLocDropdown()
|
---|
[383] | 3817 | # Get a list of location names for use in a dropdown menu.
|
---|
| 3818 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
| 3819 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
| 3820 | sub getLocDropdown {
|
---|
[480] | 3821 | my $self = shift;
|
---|
| 3822 | my $dbh = $self->{dbh};
|
---|
[383] | 3823 | my $grp = shift;
|
---|
| 3824 | my $sel = shift || '';
|
---|
[370] | 3825 |
|
---|
[383] | 3826 | my $sth = $dbh->prepare(qq(
|
---|
| 3827 | SELECT description,location FROM locations
|
---|
| 3828 | WHERE group_id=?
|
---|
| 3829 | ORDER BY description
|
---|
| 3830 | ) );
|
---|
| 3831 | $sth->execute($grp);
|
---|
[370] | 3832 |
|
---|
[383] | 3833 | my @loclist;
|
---|
[446] | 3834 | push @loclist, { locname => "(Default/All)", loc => '', selected => ($sel ? 0 : ($sel eq '' ? 1 : 0)) };
|
---|
[383] | 3835 | while (my ($locname, $loc) = $sth->fetchrow_array) {
|
---|
| 3836 | my %row = (
|
---|
| 3837 | locname => $locname,
|
---|
| 3838 | loc => $loc,
|
---|
| 3839 | selected => ($sel eq $loc ? 1 : 0)
|
---|
| 3840 | );
|
---|
| 3841 | push @loclist, \%row;
|
---|
| 3842 | }
|
---|
| 3843 | return \@loclist;
|
---|
| 3844 | } # end getLocDropdown()
|
---|
| 3845 |
|
---|
| 3846 |
|
---|
[2] | 3847 | ## DNSDB::getSOA()
|
---|
| 3848 | # Return all suitable fields from an SOA record in separate elements of a hash
|
---|
[224] | 3849 | # Takes a database handle, default/live flag, domain/reverse flag, and parent ID
|
---|
[2] | 3850 | sub getSOA {
|
---|
| 3851 | $errstr = '';
|
---|
[481] | 3852 | my $self = shift;
|
---|
| 3853 | my $dbh = $self->{dbh};
|
---|
[2] | 3854 | my $def = shift;
|
---|
[224] | 3855 | my $rev = shift;
|
---|
[2] | 3856 | my $id = shift;
|
---|
| 3857 |
|
---|
[224] | 3858 | # (ab)use distance and weight columns to store SOA data? can't for default_rev_records...
|
---|
| 3859 | # - should really attach serial to the zone parent somewhere
|
---|
[101] | 3860 |
|
---|
[224] | 3861 | my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev).
|
---|
| 3862 | " WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}";
|
---|
[311] | 3863 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
| 3864 | return if !$ret;
|
---|
[246] | 3865 | ##fixme: stick a flag somewhere if the record doesn't exist. by the API, this is an impossible case, but...
|
---|
[2] | 3866 |
|
---|
[311] | 3867 | ($ret->{contact},$ret->{prins}) = split /:/, $ret->{host};
|
---|
| 3868 | delete $ret->{host};
|
---|
| 3869 | ($ret->{refresh},$ret->{retry},$ret->{expire},$ret->{minttl}) = split /:/, $ret->{val};
|
---|
| 3870 | delete $ret->{val};
|
---|
[2] | 3871 |
|
---|
[311] | 3872 | return $ret;
|
---|
[2] | 3873 | } # end getSOA()
|
---|
| 3874 |
|
---|
| 3875 |
|
---|
[246] | 3876 | ## DNSDB::updateSOA()
|
---|
| 3877 | # Update the specified SOA record
|
---|
| 3878 | # Takes a database handle, default/live flag, forward/reverse flag, and SOA data hash
|
---|
[277] | 3879 | # Returns a two-element list with a result code and message
|
---|
[246] | 3880 | sub updateSOA {
|
---|
[473] | 3881 | my $self = shift;
|
---|
| 3882 | my $dbh = $self->{dbh};
|
---|
[246] | 3883 | my $defrec = shift;
|
---|
[248] | 3884 | my $revrec = shift;
|
---|
[246] | 3885 |
|
---|
| 3886 | my %soa = @_;
|
---|
| 3887 |
|
---|
[473] | 3888 | my $oldsoa = $self->getSOA($defrec, $revrec, $soa{id});
|
---|
[277] | 3889 |
|
---|
[311] | 3890 | my $msg;
|
---|
| 3891 | my %logdata;
|
---|
| 3892 | if ($defrec eq 'n') {
|
---|
| 3893 | $logdata{domain_id} = $soa{id} if $revrec eq 'n';
|
---|
| 3894 | $logdata{rdns_id} = $soa{id} if $revrec eq 'y';
|
---|
[473] | 3895 | $logdata{group_id} = $self->parentID(id => $soa{id}, revrec => $revrec,
|
---|
| 3896 | type => ($revrec eq 'n' ? 'domain' : 'revzone') );
|
---|
[311] | 3897 | } else {
|
---|
| 3898 | $logdata{group_id} = $soa{id};
|
---|
| 3899 | }
|
---|
[473] | 3900 | my $parname = ($defrec eq 'y' ? $self->groupName($soa{id}) :
|
---|
| 3901 | ($revrec eq 'n' ? $self->domainName($soa{id}) : $self->revName($soa{id})) );
|
---|
[311] | 3902 |
|
---|
[277] | 3903 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3904 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3905 | local $dbh->{AutoCommit} = 0;
|
---|
| 3906 | local $dbh->{RaiseError} = 1;
|
---|
| 3907 |
|
---|
| 3908 | eval {
|
---|
[565] | 3909 | if (!$oldsoa) {
|
---|
| 3910 | # old SOA record is missing for some reason. create a new one.
|
---|
[583] | 3911 | my $sql = "INSERT INTO "._rectable($defrec, $revrec)." ("._recparent($defrec, $revrec).
|
---|
| 3912 | ", host, type, val, ttl) VALUES (?,?,6,?,?)";
|
---|
[565] | 3913 | $dbh->do($sql, undef, ($soa{id}, "$soa{contact}:$soa{prins}",
|
---|
| 3914 | "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}", $soa{ttl}) );
|
---|
| 3915 | $msg = ($defrec eq 'y' ? ($revrec eq 'y' ? 'Default reverse ' : 'Default ') : '').
|
---|
| 3916 | "SOA missing for $parname; added (ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
|
---|
| 3917 | " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})";
|
---|
| 3918 | } else {
|
---|
| 3919 | my $sql = "UPDATE "._rectable($defrec, $revrec)." SET host=?, val=?, ttl=? WHERE record_id=? AND type=6";
|
---|
| 3920 | $dbh->do($sql, undef, ("$soa{contact}:$soa{prins}", "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}",
|
---|
[311] | 3921 | $soa{ttl}, $oldsoa->{record_id}) );
|
---|
[565] | 3922 | $msg = "Updated ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse ' : 'default ') : '').
|
---|
[311] | 3923 | "SOA for $parname: ".
|
---|
| 3924 | "(ns $oldsoa->{prins}, contact $oldsoa->{contact}, refresh $oldsoa->{refresh},".
|
---|
| 3925 | " retry $oldsoa->{retry}, expire $oldsoa->{expire}, minTTL $oldsoa->{minttl}, TTL $oldsoa->{ttl}) to ".
|
---|
[277] | 3926 | "(ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
|
---|
| 3927 | " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})";
|
---|
[565] | 3928 | }
|
---|
[311] | 3929 | $logdata{entry} = $msg;
|
---|
[487] | 3930 | $self->_log(%logdata);
|
---|
[277] | 3931 |
|
---|
| 3932 | $dbh->commit;
|
---|
| 3933 | };
|
---|
| 3934 | if ($@) {
|
---|
| 3935 | $msg = $@;
|
---|
| 3936 | eval { $dbh->rollback; };
|
---|
[311] | 3937 | $logdata{entry} = "Error updating ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse zone ' : 'default ') : '').
|
---|
| 3938 | "SOA record for $parname: $msg";
|
---|
[517] | 3939 | if ($self->{log_failures}) {
|
---|
[487] | 3940 | $self->_log(%logdata);
|
---|
[311] | 3941 | $dbh->commit;
|
---|
| 3942 | }
|
---|
| 3943 | return ('FAIL', $logdata{entry});
|
---|
[277] | 3944 | } else {
|
---|
| 3945 | return ('OK', $msg);
|
---|
| 3946 | }
|
---|
[246] | 3947 | } # end updateSOA()
|
---|
| 3948 |
|
---|
| 3949 |
|
---|
[2] | 3950 | ## DNSDB::getRecLine()
|
---|
| 3951 | # Return all data fields for a zone record in separate elements of a hash
|
---|
[243] | 3952 | # Takes a database handle, default/live flag, forward/reverse flag, and record ID
|
---|
[2] | 3953 | sub getRecLine {
|
---|
| 3954 | $errstr = '';
|
---|
[481] | 3955 | my $self = shift;
|
---|
| 3956 | my $dbh = $self->{dbh};
|
---|
[243] | 3957 | my $defrec = shift;
|
---|
| 3958 | my $revrec = shift;
|
---|
[2] | 3959 | my $id = shift;
|
---|
| 3960 |
|
---|
[543] | 3961 | ##fixme: do we need a knob to twist to switch between unix epoch and postgres time string?
|
---|
[429] | 3962 | my $sql = "SELECT record_id,host,type,val,ttl".
|
---|
| 3963 | ($defrec eq 'n' ? ',location' : '').
|
---|
| 3964 | ($revrec eq 'n' ? ',distance,weight,port' : '').
|
---|
[543] | 3965 | (($defrec eq 'y') ? ',group_id FROM ' : ',domain_id,rdns_id,stamp,stamp < now() AS ispast,expires,stampactive FROM ').
|
---|
[243] | 3966 | _rectable($defrec,$revrec)." WHERE record_id=?";
|
---|
[123] | 3967 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
[2] | 3968 |
|
---|
[90] | 3969 | if ($dbh->err) {
|
---|
[2] | 3970 | $errstr = $DBI::errstr;
|
---|
| 3971 | return undef;
|
---|
| 3972 | }
|
---|
| 3973 |
|
---|
[123] | 3974 | if (!$ret) {
|
---|
| 3975 | $errstr = "No such record";
|
---|
| 3976 | return undef;
|
---|
| 3977 | }
|
---|
| 3978 |
|
---|
[243] | 3979 | # explicitly set a parent id
|
---|
| 3980 | if ($defrec eq 'y') {
|
---|
| 3981 | $ret->{parid} = $ret->{group_id};
|
---|
| 3982 | } else {
|
---|
| 3983 | $ret->{parid} = (($revrec eq 'n') ? $ret->{domain_id} : $ret->{rdns_id});
|
---|
| 3984 | # and a secondary if we have a custom type that lives in both a forward and reverse zone
|
---|
| 3985 | $ret->{secid} = (($revrec eq 'y') ? $ret->{domain_id} : $ret->{rdns_id}) if $ret->{type} > 65279;
|
---|
| 3986 | }
|
---|
[451] | 3987 | $ret->{address} = $ret->{val}; # because.
|
---|
[90] | 3988 |
|
---|
| 3989 | return $ret;
|
---|
[2] | 3990 | }
|
---|
| 3991 |
|
---|
| 3992 |
|
---|
| 3993 | ##fixme: should use above (getRecLine()) to get lines for below?
|
---|
[495] | 3994 | ## DNSDB::getRecList()
|
---|
| 3995 | # Return records for a group or zone
|
---|
| 3996 | # Takes a default/live flag, group or zone ID, start,
|
---|
[2] | 3997 | # number of records, sort field, and sort order
|
---|
| 3998 | # Returns a reference to an array of hashes
|
---|
[495] | 3999 | sub getRecList {
|
---|
[2] | 4000 | $errstr = '';
|
---|
[481] | 4001 | my $self = shift;
|
---|
| 4002 | my $dbh = $self->{dbh};
|
---|
[2] | 4003 |
|
---|
[397] | 4004 | my %args = @_;
|
---|
[4] | 4005 |
|
---|
[397] | 4006 | # protection against bad or missing arguments
|
---|
[508] | 4007 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
[510] | 4008 | my $defsort;
|
---|
| 4009 | $defsort = 'host' if $args{revrec} eq 'n'; # default sort by host on domain record list
|
---|
| 4010 | $defsort = 'val' if $args{revrec} eq 'y'; # default sort by IP on revzone record list
|
---|
[513] | 4011 | $args{sortby} = '' if !$args{sortby};
|
---|
[508] | 4012 | $args{sortby} = $defsort if !$args{revrec};
|
---|
[512] | 4013 | $args{sortby} = $defsort if $args{sortby} !~ /^[\w_,.]+$/;
|
---|
[397] | 4014 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[517] | 4015 | my $perpage = ($args{nrecs} ? $args{nrecs} : $self->{perpage});
|
---|
[397] | 4016 |
|
---|
[352] | 4017 | # sort reverse zones on IP, correctly
|
---|
[397] | 4018 | # do other fiddling with $args{sortby} while we're at it.
|
---|
[420] | 4019 | # whee! multisort means just passing comma-separated fields in sortby!
|
---|
| 4020 | my $newsort = '';
|
---|
| 4021 | foreach my $sf (split /,/, $args{sortby}) {
|
---|
| 4022 | $sf = "r.$sf";
|
---|
[660] | 4023 | $sf =~ s/r\.val/inetlazy(r.val)/;
|
---|
| 4024 | # hmm. do we really need to limit this?
|
---|
| 4025 | # if $args{revrec} eq 'y' && $args{defrec} eq 'n';
|
---|
[420] | 4026 | $sf =~ s/r\.type/t.alphaorder/;
|
---|
| 4027 | $newsort .= ",$sf";
|
---|
| 4028 | }
|
---|
| 4029 | $newsort =~ s/^,//;
|
---|
[352] | 4030 |
|
---|
[584] | 4031 | my @bindvars = ($args{id});
|
---|
| 4032 | push @bindvars, ($args{filter},$args{filter}) if $args{filter};
|
---|
| 4033 |
|
---|
[543] | 4034 | ##fixme: do we need a knob to twist to switch from unix epoch to postgres time string?
|
---|
[224] | 4035 | my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.ttl";
|
---|
[543] | 4036 | $sql .= ",l.description AS locname,stamp,r.stamp < now() AS ispast,r.expires,r.stampactive"
|
---|
| 4037 | if $args{defrec} eq 'n';
|
---|
[397] | 4038 | $sql .= ",r.distance,r.weight,r.port" if $args{revrec} eq 'n';
|
---|
| 4039 | $sql .= " FROM "._rectable($args{defrec},$args{revrec})." r ";
|
---|
[104] | 4040 | $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
|
---|
[397] | 4041 | $sql .= "LEFT JOIN locations l ON r.location=l.location " if $args{defrec} eq 'n';
|
---|
| 4042 | $sql .= "WHERE "._recparent($args{defrec},$args{revrec})." = ?";
|
---|
[104] | 4043 | $sql .= " AND NOT r.type=$reverse_typemap{SOA}";
|
---|
[614] | 4044 | if ($args{filter}) {
|
---|
| 4045 | $sql .= " AND (r.host ~* ? OR r.val ~* ? OR r.host ~* ? OR r.val ~* ?)";
|
---|
| 4046 | my $tmp = join('.',reverse(split(/\./,$args{filter})));
|
---|
| 4047 | push @bindvars, ($tmp, $tmp);
|
---|
| 4048 | }
|
---|
[420] | 4049 | $sql .= " ORDER BY $newsort $args{sortorder}";
|
---|
[324] | 4050 | # ensure consistent ordering by sorting on record_id too
|
---|
[397] | 4051 | $sql .= ", record_id $args{sortorder}";
|
---|
[501] | 4052 | $sql .= ($args{offset} eq 'all' ? '' : " LIMIT $perpage OFFSET ".$args{offset}*$perpage);
|
---|
[4] | 4053 |
|
---|
[583] | 4054 | my @working;
|
---|
| 4055 | my $recsth = $dbh->prepare($sql);
|
---|
| 4056 | $recsth->execute(@bindvars);
|
---|
| 4057 | while (my $rec = $recsth->fetchrow_hashref) {
|
---|
[594] | 4058 | if ($args{revrec} eq 'y' && $args{defrec} eq 'n' &&
|
---|
[607] | 4059 | ($self->{showrev_arpa} eq 'record' || $self->{showrev_arpa} eq 'all') &&
|
---|
| 4060 | $rec->{val} !~ /\.arpa$/ ) {
|
---|
[608] | 4061 | # skip all reverse zone .arpa "hostnames" since they're already .arpa names.
|
---|
[583] | 4062 | ##enhance: extend {showrev_arpa} eq 'record' to specify record types
|
---|
[633] | 4063 | my $tmpip = new NetAddr::IP $rec->{val} if $rec->{val} =~ /^(?:[\d.\/]+|[a-fA-F0-9:\/]+)$/;
|
---|
[607] | 4064 | $rec->{val} = DNSDB::_ZONE($tmpip, 'ZONE', 'r', '.').($tmpip->{isv6} ? '.ip6.arpa' : '.in-addr.arpa') if $tmpip;
|
---|
[583] | 4065 | }
|
---|
| 4066 | push @working, $rec;
|
---|
| 4067 | }
|
---|
| 4068 | return \@working;
|
---|
[495] | 4069 | } # end getRecList()
|
---|
[2] | 4070 |
|
---|
| 4071 |
|
---|
[91] | 4072 | ## DNSDB::getRecCount()
|
---|
[224] | 4073 | # Return count of non-SOA records in zone (or default records in a group)
|
---|
| 4074 | # Takes a database handle, default/live flag, reverse/forward flag, group/domain ID,
|
---|
| 4075 | # and optional filtering modifier
|
---|
[91] | 4076 | # Returns the count
|
---|
| 4077 | sub getRecCount {
|
---|
[481] | 4078 | my $self = shift;
|
---|
| 4079 | my $dbh = $self->{dbh};
|
---|
[91] | 4080 | my $defrec = shift;
|
---|
[224] | 4081 | my $revrec = shift;
|
---|
[91] | 4082 | my $id = shift;
|
---|
[135] | 4083 | my $filter = shift || '';
|
---|
[91] | 4084 |
|
---|
[135] | 4085 | # keep the nasties down, since we can't ?-sub this bit. :/
|
---|
| 4086 | # note this is chars allowed in DNS hostnames
|
---|
| 4087 | $filter =~ s/[^a-zA-Z0-9_.:-]//g;
|
---|
| 4088 |
|
---|
[222] | 4089 | my @bindvars = ($id);
|
---|
[584] | 4090 | push @bindvars, ($filter,$filter) if $filter;
|
---|
[224] | 4091 | my $sql = "SELECT count(*) FROM ".
|
---|
| 4092 | _rectable($defrec,$revrec).
|
---|
| 4093 | " WHERE "._recparent($defrec,$revrec)."=? ".
|
---|
[584] | 4094 | "AND NOT type=$reverse_typemap{SOA}";
|
---|
[615] | 4095 | if ($filter) {
|
---|
[614] | 4096 | $sql .= " AND (r.host ~* ? OR r.val ~* ? OR r.host ~* ? OR r.val ~* ?)";
|
---|
[615] | 4097 | my $tmp = join('.',reverse(split(/\./,$filter)));
|
---|
[614] | 4098 | push @bindvars, ($tmp, $tmp);
|
---|
| 4099 | }
|
---|
| 4100 | $sql .= " AND (host ~* ? OR val ~* ? OR host ~* ? OR val ~* ?)" if $filter;
|
---|
| 4101 | my $tmp = join('.',reverse(split(/\./,$filter)));
|
---|
| 4102 | push @bindvars, ($tmp, $tmp) if $filter;
|
---|
[584] | 4103 |
|
---|
[224] | 4104 | my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) );
|
---|
[91] | 4105 |
|
---|
| 4106 | return $count;
|
---|
| 4107 |
|
---|
| 4108 | } # end getRecCount()
|
---|
| 4109 |
|
---|
| 4110 |
|
---|
[3] | 4111 | ## DNSDB::addRec()
|
---|
[2] | 4112 | # Add a new record to a domain or a group's default records
|
---|
| 4113 | # Takes a database handle, default/live flag, group/domain ID,
|
---|
| 4114 | # host, type, value, and TTL
|
---|
| 4115 | # Some types require additional detail: "distance" for MX and SRV,
|
---|
| 4116 | # and weight/port for SRV
|
---|
| 4117 | # Returns a status code and detail message in case of error
|
---|
[234] | 4118 | ##fixme: pass a hash with the record data, not a series of separate values
|
---|
[2] | 4119 | sub addRec {
|
---|
| 4120 | $errstr = '';
|
---|
[481] | 4121 | my $self = shift;
|
---|
| 4122 | my $dbh = $self->{dbh};
|
---|
[2] | 4123 | my $defrec = shift;
|
---|
[226] | 4124 | my $revrec = shift;
|
---|
| 4125 | my $id = shift; # parent (group_id for defrecs, rdns_id for reverse records,
|
---|
| 4126 | # domain_id for domain records)
|
---|
[2] | 4127 |
|
---|
| 4128 | my $host = shift;
|
---|
[234] | 4129 | my $rectype = shift; # reference so we can coerce it if "+"-types can't find both zones
|
---|
[2] | 4130 | my $val = shift;
|
---|
| 4131 | my $ttl = shift;
|
---|
[389] | 4132 | my $location = shift;
|
---|
| 4133 | $location = '' if !$location;
|
---|
[2] | 4134 |
|
---|
[658] | 4135 | my $expires = shift || '';
|
---|
[543] | 4136 | $expires = 1 if $expires eq 'until'; # Turn some special values into the appropriate booleans.
|
---|
| 4137 | $expires = 0 if $expires eq 'after';
|
---|
| 4138 | my $stamp = shift;
|
---|
| 4139 | $stamp = '' if !$stamp; # Timestamp should be a string at this point.
|
---|
| 4140 |
|
---|
[417] | 4141 | # Spaces are evil.
|
---|
| 4142 | $$host =~ s/^\s+//;
|
---|
| 4143 | $$host =~ s/\s+$//;
|
---|
[418] | 4144 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
[417] | 4145 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 4146 | $$val =~ s/^\s+//;
|
---|
| 4147 | $$val =~ s/\s+$//;
|
---|
| 4148 | }
|
---|
| 4149 |
|
---|
[617] | 4150 | _caseclean($rectype, $host, $val, $defrec, $revrec) if $self->{lowercase};
|
---|
[542] | 4151 |
|
---|
[226] | 4152 | # prep for validation
|
---|
[609] | 4153 | my $addr = NetAddr::IP->new($$val) if _maybeip($val);
|
---|
[252] | 4154 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
[226] | 4155 |
|
---|
| 4156 | my $domid = 0;
|
---|
| 4157 | my $revid = 0;
|
---|
| 4158 |
|
---|
| 4159 | my $retcode = 'OK'; # assume everything will go OK
|
---|
| 4160 | my $retmsg = '';
|
---|
| 4161 |
|
---|
| 4162 | # do simple validation first
|
---|
[559] | 4163 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^-?\d+$/;
|
---|
[226] | 4164 |
|
---|
[234] | 4165 | # Collect these even if we're only doing a simple A record so we can call *any* validation sub
|
---|
| 4166 | my $dist = shift;
|
---|
[281] | 4167 | my $weight = shift;
|
---|
[234] | 4168 | my $port = shift;
|
---|
[226] | 4169 |
|
---|
[234] | 4170 | my $fields;
|
---|
| 4171 | my @vallist;
|
---|
[226] | 4172 |
|
---|
[234] | 4173 | # Call the validation sub for the type requested.
|
---|
[481] | 4174 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec, id => $id,
|
---|
[249] | 4175 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
[234] | 4176 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
[481] | 4177 | fields => \$fields, vallist => \@vallist);
|
---|
[129] | 4178 |
|
---|
[234] | 4179 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
[209] | 4180 |
|
---|
[234] | 4181 | # Set up database fields and bind parameters
|
---|
[481] | 4182 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
| 4183 | push @vallist, ($$host,$$rectype,$$val,$ttl,$id);
|
---|
| 4184 |
|
---|
| 4185 | if ($defrec eq 'n') {
|
---|
[543] | 4186 | # locations are not for default records, silly coder!
|
---|
[481] | 4187 | $fields .= ",location";
|
---|
| 4188 | push @vallist, $location;
|
---|
[543] | 4189 | # timestamps are rare.
|
---|
| 4190 | if ($stamp) {
|
---|
| 4191 | $fields .= ",stamp,expires,stampactive";
|
---|
| 4192 | push @vallist, $stamp, $expires, 'y';
|
---|
| 4193 | } else {
|
---|
| 4194 | $fields .= ",stampactive";
|
---|
| 4195 | push @vallist, 'n';
|
---|
| 4196 | }
|
---|
[481] | 4197 | }
|
---|
[543] | 4198 |
|
---|
| 4199 | # a little magic to get the right number of ? placeholders based on how many values we're providing
|
---|
[234] | 4200 | my $vallen = '?'.(',?'x$#vallist);
|
---|
[2] | 4201 |
|
---|
[287] | 4202 | # Put together the success log entry. We have to use this horrible kludge
|
---|
| 4203 | # because domain_id and rdns_id may or may not be present, and if they are,
|
---|
| 4204 | # they're not at a guaranteed consistent index in the array. wheee!
|
---|
| 4205 | my %logdata;
|
---|
| 4206 | my @ftmp = split /,/, $fields;
|
---|
| 4207 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
| 4208 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
| 4209 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
| 4210 | }
|
---|
| 4211 | $logdata{group_id} = $id if $defrec eq 'y';
|
---|
[473] | 4212 | $logdata{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec)
|
---|
[287] | 4213 | if $defrec eq 'n';
|
---|
[328] | 4214 | $logdata{entry} = "Added ".($defrec eq 'y' ? 'default record' : 'record');
|
---|
[621] | 4215 | # Log reverse records to match the formal .arpa tree
|
---|
| 4216 | if ($revrec eq 'y') {
|
---|
[328] | 4217 | $logdata{entry} .= " '$$val $typemap{$$rectype} $$host";
|
---|
| 4218 | } else {
|
---|
| 4219 | $logdata{entry} .= " '$$host $typemap{$$rectype} $$val";
|
---|
| 4220 | }
|
---|
| 4221 |
|
---|
[287] | 4222 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
| 4223 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]"
|
---|
| 4224 | if $typemap{$$rectype} eq 'SRV';
|
---|
[425] | 4225 | $logdata{entry} .= "', TTL $ttl";
|
---|
[480] | 4226 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location;
|
---|
[642] | 4227 | $logdata{entry} .= ($expires ? ', expires at ' : ', valid after ').$stamp if $stamp;
|
---|
[287] | 4228 |
|
---|
[90] | 4229 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4230 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4231 | local $dbh->{AutoCommit} = 0;
|
---|
| 4232 | local $dbh->{RaiseError} = 1;
|
---|
[2] | 4233 |
|
---|
[90] | 4234 | eval {
|
---|
[236] | 4235 | $dbh->do("INSERT INTO "._rectable($defrec, $revrec)." ($fields) VALUES ($vallen)",
|
---|
[90] | 4236 | undef, @vallist);
|
---|
[487] | 4237 | $self->_log(%logdata);
|
---|
[90] | 4238 | $dbh->commit;
|
---|
| 4239 | };
|
---|
| 4240 | if ($@) {
|
---|
| 4241 | my $msg = $@;
|
---|
| 4242 | eval { $dbh->rollback; };
|
---|
[517] | 4243 | if ($self->{log_failures}) {
|
---|
[289] | 4244 | $logdata{entry} = "Failed adding ".($defrec eq 'y' ? 'default ' : '').
|
---|
| 4245 | "record '$$host $typemap{$$rectype} $$val', TTL $ttl ($msg)";
|
---|
[487] | 4246 | $self->_log(%logdata);
|
---|
[289] | 4247 | $dbh->commit;
|
---|
| 4248 | }
|
---|
[90] | 4249 | return ('FAIL',$msg);
|
---|
| 4250 | }
|
---|
[2] | 4251 |
|
---|
[287] | 4252 | $resultstr = $logdata{entry};
|
---|
[226] | 4253 | return ($retcode, $retmsg);
|
---|
[90] | 4254 |
|
---|
[2] | 4255 | } # end addRec()
|
---|
| 4256 |
|
---|
| 4257 |
|
---|
[16] | 4258 | ## DNSDB::updateRec()
|
---|
| 4259 | # Update a record
|
---|
[273] | 4260 | # Takes a database handle, default and reverse flags, record ID, immediate parent ID, and new record data.
|
---|
| 4261 | # Returns a status code and message
|
---|
[16] | 4262 | sub updateRec {
|
---|
| 4263 | $errstr = '';
|
---|
[17] | 4264 |
|
---|
[481] | 4265 | my $self = shift;
|
---|
| 4266 | my $dbh = $self->{dbh};
|
---|
[16] | 4267 | my $defrec = shift;
|
---|
[272] | 4268 | my $revrec = shift;
|
---|
[16] | 4269 | my $id = shift;
|
---|
[272] | 4270 | my $parid = shift; # immediate parent entity that we're descending from to update the record
|
---|
[16] | 4271 |
|
---|
[273] | 4272 | # all records have these
|
---|
[16] | 4273 | my $host = shift;
|
---|
[272] | 4274 | my $hostbk = $$host; # Keep a backup copy of the original, so we can WARN if the update mangles the domain
|
---|
| 4275 | my $rectype = shift;
|
---|
[16] | 4276 | my $val = shift;
|
---|
| 4277 | my $ttl = shift;
|
---|
[389] | 4278 | my $location = shift; # may be empty/null/undef depending on caller
|
---|
| 4279 | $location = '' if !$location;
|
---|
[16] | 4280 |
|
---|
[658] | 4281 | my $expires = shift || '';
|
---|
[543] | 4282 | $expires = 1 if $expires eq 'until'; # Turn some special values into the appropriate booleans.
|
---|
| 4283 | $expires = 0 if $expires eq 'after';
|
---|
| 4284 | my $stamp = shift;
|
---|
| 4285 | $stamp = '' if !$stamp; # Timestamp should be a string at this point.
|
---|
| 4286 |
|
---|
[510] | 4287 | # just set it to an empty string; failures will be caught later.
|
---|
| 4288 | $$host = '' if !$$host;
|
---|
| 4289 |
|
---|
[417] | 4290 | # Spaces are evil.
|
---|
| 4291 | $$host =~ s/^\s+//;
|
---|
| 4292 | $$host =~ s/\s+$//;
|
---|
[418] | 4293 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
[417] | 4294 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 4295 | $$val =~ s/^\s+//;
|
---|
| 4296 | $$val =~ s/\s+$//;
|
---|
| 4297 | }
|
---|
| 4298 |
|
---|
[617] | 4299 | _caseclean($rectype, $host, $val, $defrec, $revrec) if $self->{lowercase};
|
---|
[542] | 4300 |
|
---|
[272] | 4301 | # prep for validation
|
---|
[609] | 4302 | my $addr = NetAddr::IP->new($$val) if _maybeip($val);
|
---|
[272] | 4303 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
[16] | 4304 |
|
---|
[272] | 4305 | my $domid = 0;
|
---|
| 4306 | my $revid = 0;
|
---|
| 4307 |
|
---|
| 4308 | my $retcode = 'OK'; # assume everything will go OK
|
---|
| 4309 | my $retmsg = '';
|
---|
| 4310 |
|
---|
[273] | 4311 | # do simple validation first
|
---|
[559] | 4312 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^-?\d+$/;
|
---|
[272] | 4313 |
|
---|
[273] | 4314 | # only MX and SRV will use these
|
---|
[288] | 4315 | my $dist = shift || 0;
|
---|
| 4316 | my $weight = shift || 0;
|
---|
| 4317 | my $port = shift || 0;
|
---|
[16] | 4318 |
|
---|
[272] | 4319 | my $fields;
|
---|
| 4320 | my @vallist;
|
---|
[16] | 4321 |
|
---|
[273] | 4322 | # get old record data so we have the right parent ID
|
---|
| 4323 | # and for logging (eventually)
|
---|
[481] | 4324 | my $oldrec = $self->getRecLine($defrec, $revrec, $id);
|
---|
[223] | 4325 |
|
---|
[272] | 4326 | # Call the validation sub for the type requested.
|
---|
| 4327 | # Note the ID to pass here is the *parent*, not the record
|
---|
[481] | 4328 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec,
|
---|
[272] | 4329 | id => ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})),
|
---|
| 4330 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
| 4331 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
| 4332 | fields => \$fields, vallist => \@vallist,
|
---|
[481] | 4333 | update => $id);
|
---|
[272] | 4334 |
|
---|
| 4335 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
| 4336 |
|
---|
[273] | 4337 | # Set up database fields and bind parameters. Note only the optional fields
|
---|
| 4338 | # (distance, weight, port, secondary parent ID) are added in the validation call above
|
---|
[448] | 4339 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
| 4340 | push @vallist, ($$host,$$rectype,$$val,$ttl,
|
---|
[273] | 4341 | ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})) );
|
---|
[272] | 4342 |
|
---|
[448] | 4343 | if ($defrec eq 'n') {
|
---|
[543] | 4344 | # locations are not for default records, silly coder!
|
---|
[448] | 4345 | $fields .= ",location";
|
---|
| 4346 | push @vallist, $location;
|
---|
[543] | 4347 | # timestamps are rare.
|
---|
| 4348 | if ($stamp) {
|
---|
| 4349 | $fields .= ",stamp,expires,stampactive";
|
---|
| 4350 | push @vallist, $stamp, $expires, 'y';
|
---|
| 4351 | } else {
|
---|
| 4352 | $fields .= ",stampactive";
|
---|
| 4353 | push @vallist, 'n';
|
---|
| 4354 | }
|
---|
[448] | 4355 | }
|
---|
| 4356 |
|
---|
[273] | 4357 | # hack hack PTHUI
|
---|
| 4358 | # need to forcibly make sure we disassociate a record with a parent it's no longer related to.
|
---|
| 4359 | # eg, PTR records may not have a domain parent, or A/AAAA records may not have a revzone parent.
|
---|
[605] | 4360 | # needed for crossover types that got coerced down to "standard" types due to data changes
|
---|
| 4361 | # need to *avoid* funky records being updated like A/AAAA records in revzones, or PTRs in forward zones.
|
---|
| 4362 | if ($defrec eq 'n' && $oldrec->{type} > 65000) {
|
---|
[273] | 4363 | if ($$rectype == $reverse_typemap{PTR}) {
|
---|
| 4364 | $fields .= ",domain_id";
|
---|
| 4365 | push @vallist, 0;
|
---|
| 4366 | }
|
---|
| 4367 | if ($$rectype == $reverse_typemap{A} || $$rectype == $reverse_typemap{AAAA}) {
|
---|
| 4368 | $fields .= ",rdns_id";
|
---|
| 4369 | push @vallist, 0;
|
---|
| 4370 | }
|
---|
| 4371 | }
|
---|
[345] | 4372 | # fix fat-finger-originated record type changes
|
---|
[605] | 4373 | if ($$rectype == 65285) { # delegation
|
---|
[345] | 4374 | $fields .= ",rdns_id" if $revrec eq 'n';
|
---|
| 4375 | $fields .= ",domain_id" if $revrec eq 'y';
|
---|
| 4376 | push @vallist, 0;
|
---|
| 4377 | }
|
---|
[605] | 4378 | # ... and now make sure we *do* associate a record with the "calling" parent
|
---|
[341] | 4379 | if ($defrec eq 'n') {
|
---|
| 4380 | $domid = $parid if $revrec eq 'n';
|
---|
| 4381 | $revid = $parid if $revrec eq 'y';
|
---|
| 4382 | }
|
---|
[272] | 4383 |
|
---|
[288] | 4384 | # Put together the success log entry. Horrible kludge from addRec() copied as-is since
|
---|
| 4385 | # we don't know whether the passed arguments or retrieved values for domain_id and rdns_id
|
---|
| 4386 | # will be maintained (due to "not-in-zone" validation changes)
|
---|
| 4387 | my %logdata;
|
---|
[341] | 4388 | $logdata{domain_id} = $domid;
|
---|
| 4389 | $logdata{rdns_id} = $revid;
|
---|
[288] | 4390 | my @ftmp = split /,/, $fields;
|
---|
| 4391 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
| 4392 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
| 4393 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
| 4394 | }
|
---|
| 4395 | $logdata{group_id} = $parid if $defrec eq 'y';
|
---|
[473] | 4396 | $logdata{group_id} = $self->parentID(id => $parid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec)
|
---|
[288] | 4397 | if $defrec eq 'n';
|
---|
[328] | 4398 | $logdata{entry} = "Updated ".($defrec eq 'y' ? 'default record' : 'record')." from\n";
|
---|
[621] | 4399 | # Log reverse records "naturally", since they're stored, um, unnaturally.
|
---|
| 4400 | if ($revrec eq 'y') {
|
---|
[328] | 4401 | $logdata{entry} .= " '$oldrec->{val} $typemap{$oldrec->{type}} $oldrec->{host}";
|
---|
| 4402 | } else {
|
---|
| 4403 | $logdata{entry} .= " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
| 4404 | }
|
---|
[288] | 4405 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
| 4406 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
| 4407 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
[425] | 4408 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
[480] | 4409 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location};
|
---|
[543] | 4410 | $logdata{entry} .= ($oldrec->{expires} ? ', expires at ' : ', valid after ').$oldrec->{stamp}
|
---|
| 4411 | if $oldrec->{stampactive};
|
---|
[425] | 4412 | $logdata{entry} .= "\nto\n";
|
---|
[621] | 4413 | # Log reverse records "naturally", since they're stored, um, unnaturally.
|
---|
| 4414 | if ($revrec eq 'y') {
|
---|
[328] | 4415 | $logdata{entry} .= "'$$val $typemap{$$rectype} $$host";
|
---|
| 4416 | } else {
|
---|
| 4417 | $logdata{entry} .= "'$$host $typemap{$$rectype} $$val";
|
---|
| 4418 | }
|
---|
[288] | 4419 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
| 4420 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$$rectype} eq 'SRV';
|
---|
[425] | 4421 | $logdata{entry} .= "', TTL $ttl";
|
---|
[480] | 4422 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location;
|
---|
[642] | 4423 | $logdata{entry} .= ($expires ? ', expires at ' : ', valid after ').$stamp if $stamp;
|
---|
[288] | 4424 |
|
---|
[90] | 4425 | local $dbh->{AutoCommit} = 0;
|
---|
| 4426 | local $dbh->{RaiseError} = 1;
|
---|
| 4427 |
|
---|
[341] | 4428 | # Fiddle the field list into something suitable for updates
|
---|
| 4429 | $fields =~ s/,/=?,/g;
|
---|
| 4430 | $fields .= "=?";
|
---|
| 4431 |
|
---|
[90] | 4432 | eval {
|
---|
[273] | 4433 | $dbh->do("UPDATE "._rectable($defrec,$revrec)." SET $fields WHERE record_id=?", undef, (@vallist, $id) );
|
---|
[487] | 4434 | $self->_log(%logdata);
|
---|
[130] | 4435 | $dbh->commit;
|
---|
[90] | 4436 | };
|
---|
| 4437 | if ($@) {
|
---|
| 4438 | my $msg = $@;
|
---|
[288] | 4439 | eval { $dbh->rollback; };
|
---|
[517] | 4440 | if ($self->{log_failures}) {
|
---|
[289] | 4441 | $logdata{entry} = "Failed updating ".($defrec eq 'y' ? 'default ' : '').
|
---|
| 4442 | "record '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
[487] | 4443 | $self->_log(%logdata);
|
---|
[289] | 4444 | $dbh->commit;
|
---|
| 4445 | }
|
---|
[90] | 4446 | return ('FAIL', $msg);
|
---|
| 4447 | }
|
---|
| 4448 |
|
---|
[288] | 4449 | $resultstr = $logdata{entry};
|
---|
[272] | 4450 | return ($retcode, $retmsg);
|
---|
[16] | 4451 | } # end updateRec()
|
---|
| 4452 |
|
---|
| 4453 |
|
---|
[459] | 4454 | ## DNSDB::downconvert()
|
---|
| 4455 | # A mostly internal (not exported) semiutilty sub to downconvert from pseudotype <x>
|
---|
| 4456 | # to a compatible component type. Only a handful of operations are valid, anything
|
---|
| 4457 | # else is a null-op.
|
---|
| 4458 | # Takes the record ID and the new type. Returns boolean.
|
---|
| 4459 | sub downconvert {
|
---|
[481] | 4460 | my $self = shift;
|
---|
| 4461 | my $dbh = $self->{dbh};
|
---|
[459] | 4462 | my $recid = shift;
|
---|
| 4463 | my $newtype = shift;
|
---|
| 4464 |
|
---|
| 4465 | # also, only work on live records; little to no value trying to do this on default records.
|
---|
[481] | 4466 | my $rec = $self->getRecLine('n', 'y', $recid);
|
---|
[459] | 4467 |
|
---|
| 4468 | # hm?
|
---|
| 4469 | #return 1 if !$rec;
|
---|
| 4470 |
|
---|
| 4471 | return 1 if $rec->{type} < 65000; # Only the reverse-record pseudotypes can be downconverted
|
---|
| 4472 | return 1 if $rec->{type} == 65282; # Nowhere to go
|
---|
| 4473 |
|
---|
| 4474 | my $delpar;
|
---|
| 4475 | my @sqlargs;
|
---|
| 4476 | if ($rec->{type} == 65280) {
|
---|
| 4477 | return 1 if $newtype != 1 && $newtype != 12;
|
---|
| 4478 | $delpar = ($newtype == 1 ? 'rdns_id' : 'domain_id');
|
---|
| 4479 | push @sqlargs, 0, $newtype, $recid;
|
---|
| 4480 | } elsif ($rec->{type} == 65281) {
|
---|
| 4481 | return 1 if $newtype != 28 && $newtype != 12;
|
---|
| 4482 | $delpar = ($newtype == 28 ? 'rdns_id' : 'domain_id');
|
---|
| 4483 | push @sqlargs, 0, $newtype, $recid;
|
---|
| 4484 | } elsif ($rec->{type} == 65283) {
|
---|
| 4485 | return 1 if $newtype != 65282;
|
---|
| 4486 | $delpar = 'rdns_id';
|
---|
| 4487 | } elsif ($rec->{type} == 65284) {
|
---|
| 4488 | return 1 if $newtype != 65282;
|
---|
| 4489 | $delpar = 'rdns_id';
|
---|
| 4490 | } else {
|
---|
| 4491 | # Your llama is on fire.
|
---|
| 4492 | }
|
---|
| 4493 |
|
---|
| 4494 | local $dbh->{AutoCommit} = 0;
|
---|
| 4495 | local $dbh->{RaiseError} = 1;
|
---|
| 4496 |
|
---|
| 4497 | eval {
|
---|
| 4498 | $dbh->do("UPDATE records SET $delpar = ?, type = ? WHERE record_id = ?", undef, @sqlargs);
|
---|
| 4499 | $dbh->commit;
|
---|
| 4500 | };
|
---|
| 4501 | if ($@) {
|
---|
| 4502 | $errstr = $@;
|
---|
| 4503 | eval { $dbh->rollback; };
|
---|
| 4504 | return 0;
|
---|
| 4505 | }
|
---|
| 4506 | return 1;
|
---|
| 4507 | } # end downconvert()
|
---|
| 4508 |
|
---|
| 4509 |
|
---|
[3] | 4510 | ## DNSDB::delRec()
|
---|
| 4511 | # Delete a record.
|
---|
| 4512 | sub delRec {
|
---|
| 4513 | $errstr = '';
|
---|
[481] | 4514 | my $self = shift;
|
---|
| 4515 | my $dbh = $self->{dbh};
|
---|
[3] | 4516 | my $defrec = shift;
|
---|
[243] | 4517 | my $revrec = shift;
|
---|
[3] | 4518 | my $id = shift;
|
---|
| 4519 |
|
---|
[481] | 4520 | my $oldrec = $self->getRecLine($defrec, $revrec, $id);
|
---|
[3] | 4521 |
|
---|
[290] | 4522 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4523 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4524 | local $dbh->{AutoCommit} = 0;
|
---|
| 4525 | local $dbh->{RaiseError} = 1;
|
---|
[3] | 4526 |
|
---|
[290] | 4527 | # Put together the log entry
|
---|
| 4528 | my %logdata;
|
---|
| 4529 | $logdata{domain_id} = $oldrec->{domain_id};
|
---|
| 4530 | $logdata{rdns_id} = $oldrec->{rdns_id};
|
---|
| 4531 | $logdata{group_id} = $oldrec->{group_id} if $defrec eq 'y';
|
---|
[473] | 4532 | $logdata{group_id} = $self->parentID(id => $oldrec->{domain_id}, type => ($revrec eq 'n' ? 'domain' : 'revzone'),
|
---|
| 4533 | revrec => $revrec)
|
---|
[290] | 4534 | if $defrec eq 'n';
|
---|
| 4535 | $logdata{entry} = "Deleted ".($defrec eq 'y' ? 'default record ' : 'record ').
|
---|
| 4536 | "'$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
| 4537 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
| 4538 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
| 4539 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
[425] | 4540 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
[480] | 4541 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location};
|
---|
[290] | 4542 |
|
---|
| 4543 | eval {
|
---|
| 4544 | my $sth = $dbh->do("DELETE FROM "._rectable($defrec,$revrec)." WHERE record_id=?", undef, ($id));
|
---|
[487] | 4545 | $self->_log(%logdata);
|
---|
[290] | 4546 | $dbh->commit;
|
---|
| 4547 | };
|
---|
| 4548 | if ($@) {
|
---|
| 4549 | my $msg = $@;
|
---|
| 4550 | eval { $dbh->rollback; };
|
---|
[517] | 4551 | if ($self->{log_failures}) {
|
---|
[290] | 4552 | $logdata{entry} = "Error deleting ".($defrec eq 'y' ? 'default record' : 'record').
|
---|
| 4553 | " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
[487] | 4554 | $self->_log(%logdata);
|
---|
[290] | 4555 | $dbh->commit;
|
---|
| 4556 | }
|
---|
| 4557 | return ('FAIL', $msg);
|
---|
| 4558 | }
|
---|
| 4559 |
|
---|
| 4560 | return ('OK',$logdata{entry});
|
---|
[3] | 4561 | } # end delRec()
|
---|
| 4562 |
|
---|
| 4563 |
|
---|
[323] | 4564 | ## DNSDB::getLogCount()
|
---|
| 4565 | # Get a count of log entries
|
---|
| 4566 | # Takes a database handle and a hash containing at least:
|
---|
| 4567 | # - Entity ID and entity type as the primary log "slice"
|
---|
| 4568 | sub getLogCount {
|
---|
[483] | 4569 | my $self = shift;
|
---|
| 4570 | my $dbh = $self->{dbh};
|
---|
[323] | 4571 |
|
---|
| 4572 | my %args = @_;
|
---|
| 4573 |
|
---|
| 4574 | my @filterargs;
|
---|
| 4575 | ##fixme: which fields do we want to filter on?
|
---|
| 4576 | # push @filterargs,
|
---|
| 4577 |
|
---|
| 4578 | $errstr = 'Missing primary parent ID and/or type';
|
---|
| 4579 | # fail early if we don't have a "prime" ID to look for log entries for
|
---|
| 4580 | return if !$args{id};
|
---|
| 4581 |
|
---|
| 4582 | # or if the prime id type is missing or invalid
|
---|
| 4583 | return if !$args{logtype};
|
---|
| 4584 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
| 4585 | $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
|
---|
| 4586 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
|
---|
| 4587 |
|
---|
| 4588 | my $sql = "SELECT count(*) FROM log ".
|
---|
| 4589 | "WHERE $id_col{$args{logtype}}=?".
|
---|
| 4590 | ($args{filter} ? " AND entry ~* ?" : '');
|
---|
| 4591 | my ($count) = $dbh->selectrow_array($sql, undef, ($args{id}, @filterargs) );
|
---|
| 4592 | $errstr = $dbh->errstr if !$count;
|
---|
| 4593 | return $count;
|
---|
| 4594 | } # end getLogCount()
|
---|
| 4595 |
|
---|
| 4596 |
|
---|
| 4597 | ## DNSDB::getLogEntries()
|
---|
| 4598 | # Get a list of log entries
|
---|
| 4599 | # Takes arguments as with getLogCount() above, plus optional:
|
---|
| 4600 | # - sort field
|
---|
| 4601 | # - sort order
|
---|
| 4602 | # - offset for pagination
|
---|
| 4603 | sub getLogEntries {
|
---|
[483] | 4604 | my $self = shift;
|
---|
| 4605 | my $dbh = $self->{dbh};
|
---|
[323] | 4606 |
|
---|
| 4607 | my %args = @_;
|
---|
| 4608 |
|
---|
| 4609 | my @filterargs;
|
---|
| 4610 |
|
---|
| 4611 | # fail early if we don't have a "prime" ID to look for log entries for
|
---|
| 4612 | return if !$args{id};
|
---|
| 4613 |
|
---|
| 4614 | # or if the prime id type is missing or invalid
|
---|
| 4615 | return if !$args{logtype};
|
---|
| 4616 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
| 4617 | $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
|
---|
| 4618 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
|
---|
| 4619 |
|
---|
| 4620 | # Sorting defaults
|
---|
[508] | 4621 | $args{sortorder} = 'DESC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
| 4622 | $args{sortby} = 'stamp' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
[397] | 4623 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[323] | 4624 |
|
---|
[324] | 4625 | my %sortmap = (fname => 'name', username => 'email', entry => 'entry', stamp => 'stamp');
|
---|
[323] | 4626 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 4627 |
|
---|
| 4628 | my $sql = "SELECT user_id AS userid, email AS useremail, name AS userfname, entry AS logentry, ".
|
---|
| 4629 | "date_trunc('second',stamp) AS logtime ".
|
---|
| 4630 | "FROM log ".
|
---|
| 4631 | "WHERE $id_col{$args{logtype}}=?".
|
---|
| 4632 | ($args{filter} ? " AND entry ~* ?" : '').
|
---|
[324] | 4633 | " ORDER BY $args{sortby} $args{sortorder}, log_id $args{sortorder}".
|
---|
[517] | 4634 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
[323] | 4635 | my $loglist = $dbh->selectall_arrayref($sql, { Slice => {} }, ($args{id}, @filterargs) );
|
---|
| 4636 | $errstr = $dbh->errstr if !$loglist;
|
---|
| 4637 | return $loglist;
|
---|
| 4638 | } # end getLogEntries()
|
---|
| 4639 |
|
---|
| 4640 |
|
---|
[452] | 4641 | ## IPDB::getRevPattern()
|
---|
| 4642 | # Get the narrowest template pattern applicable to a passed CIDR address (may be a netblock or an IP)
|
---|
| 4643 | sub getRevPattern {
|
---|
[483] | 4644 | my $self = shift;
|
---|
| 4645 | my $dbh = $self->{dbh};
|
---|
[452] | 4646 | my $cidr = shift;
|
---|
| 4647 | my $group = shift || 1; # just in case
|
---|
| 4648 |
|
---|
[462] | 4649 | # for speed! Casting and comparing even ~7K records takes ~2.5s, so narrow it down to one revzone first.
|
---|
| 4650 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >>= ? AND group_id = ?",
|
---|
| 4651 | undef, ($cidr, $group) );
|
---|
| 4652 |
|
---|
| 4653 | ##fixme? may need to narrow things down more by octet-chopping and doing text comparisons before casting.
|
---|
| 4654 | my ($revpatt) = $dbh->selectrow_array("SELECT host FROM records ".
|
---|
[599] | 4655 | "WHERE (type in (12,65280,65281,65282,65283,65284)) AND rdns_id = ? AND inetlazy(val) >>= ? ".
|
---|
| 4656 | "ORDER BY inetlazy(val) DESC LIMIT 1", undef, ($revid, $cidr) );
|
---|
[452] | 4657 | return $revpatt;
|
---|
| 4658 | } # end getRevPattern()
|
---|
| 4659 |
|
---|
| 4660 |
|
---|
[225] | 4661 | ## DNSDB::getTypelist()
|
---|
| 4662 | # Get a list of record types for various UI dropdowns
|
---|
| 4663 | # Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A)
|
---|
| 4664 | # Returns an arrayref to list of hashrefs perfect for HTML::Template
|
---|
| 4665 | sub getTypelist {
|
---|
[483] | 4666 | my $self = shift;
|
---|
| 4667 | my $dbh = $self->{dbh};
|
---|
[225] | 4668 | my $recgroup = shift;
|
---|
| 4669 | my $type = shift || $reverse_typemap{A};
|
---|
| 4670 |
|
---|
| 4671 | # also accepting $webvar{revrec}!
|
---|
| 4672 | $recgroup = 'f' if $recgroup eq 'n';
|
---|
| 4673 | $recgroup = 'r' if $recgroup eq 'y';
|
---|
| 4674 |
|
---|
| 4675 | my $sql = "SELECT val,name FROM rectypes WHERE ";
|
---|
| 4676 | if ($recgroup eq 'r') {
|
---|
| 4677 | # reverse zone types
|
---|
| 4678 | $sql .= "stdflag=2 OR stdflag=3";
|
---|
| 4679 | } elsif ($recgroup eq 'l') {
|
---|
| 4680 | # DNS lookup types. Note we avoid our custom types >= 65280, since those are entirely internal.
|
---|
| 4681 | $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280";
|
---|
| 4682 | } else {
|
---|
| 4683 | # default; forward zone types. technically $type eq 'f' but not worth the error message.
|
---|
| 4684 | $sql .= "stdflag=1 OR stdflag=2";
|
---|
[506] | 4685 | $sql .= " AND val < 65280" if $recgroup eq 'fo'; # An extra flag to trim off the pseudotypes as well.
|
---|
[225] | 4686 | }
|
---|
| 4687 | $sql .= " ORDER BY listorder";
|
---|
| 4688 |
|
---|
| 4689 | my $sth = $dbh->prepare($sql);
|
---|
| 4690 | $sth->execute;
|
---|
| 4691 | my @typelist;
|
---|
[603] | 4692 | # track whether the passed type is in the list at all. allows you to edit a record
|
---|
| 4693 | # that wouldn't otherwise be generally available in that zone (typically, reverse zones)
|
---|
| 4694 | # without changing its type (accidentally or otherwise)
|
---|
| 4695 | my $selflag = 0;
|
---|
[225] | 4696 | while (my ($rval,$rname) = $sth->fetchrow_array()) {
|
---|
| 4697 | my %row = ( recval => $rval, recname => $rname );
|
---|
[603] | 4698 | if ($rval == $type) {
|
---|
| 4699 | $row{tselect} = 1;
|
---|
| 4700 | $selflag = 1;
|
---|
| 4701 | }
|
---|
[225] | 4702 | push @typelist, \%row;
|
---|
| 4703 | }
|
---|
| 4704 |
|
---|
[603] | 4705 | # add the passed type if it wasn't in the list
|
---|
| 4706 | if (!$selflag) {
|
---|
| 4707 | my %row = ( recval => $type, recname => $typemap{$type}, tselect => 1 );
|
---|
| 4708 | push @typelist, \%row;
|
---|
| 4709 | }
|
---|
| 4710 |
|
---|
[225] | 4711 | # Add SOA on lookups since it's not listed in other dropdowns.
|
---|
| 4712 | if ($recgroup eq 'l') {
|
---|
| 4713 | my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
|
---|
| 4714 | $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
|
---|
| 4715 | push @typelist, \%row;
|
---|
| 4716 | }
|
---|
| 4717 |
|
---|
| 4718 | return \@typelist;
|
---|
| 4719 | } # end getTypelist()
|
---|
| 4720 |
|
---|
| 4721 |
|
---|
[254] | 4722 | ## DNSDB::parentID()
|
---|
| 4723 | # Get ID of entity that is nearest parent to requested id
|
---|
| 4724 | # Takes a database handle and a hash of entity ID, entity type, optional parent type flag
|
---|
| 4725 | # (domain/reverse zone or group), and optional default/live and forward/reverse flags
|
---|
| 4726 | # Returns the ID or undef on failure
|
---|
| 4727 | sub parentID {
|
---|
[473] | 4728 | my $self = shift;
|
---|
| 4729 | my $dbh = $self->{dbh};
|
---|
[116] | 4730 |
|
---|
[254] | 4731 | my %args = @_;
|
---|
[116] | 4732 |
|
---|
[254] | 4733 | # clean up the parent-type. Set it to group if not set; coerce revzone to domain for simpler logic
|
---|
| 4734 | $args{partype} = 'group' if !$args{partype};
|
---|
| 4735 | $args{partype} = 'domain' if $args{partype} eq 'revzone';
|
---|
[116] | 4736 |
|
---|
[254] | 4737 | # clean up defrec and revrec. default to live record, forward zone
|
---|
| 4738 | $args{defrec} = 'n' if !$args{defrec};
|
---|
| 4739 | $args{revrec} = 'n' if !$args{revrec};
|
---|
[116] | 4740 |
|
---|
[254] | 4741 | if ($par_type{$args{partype}} eq 'domain') {
|
---|
| 4742 | # only live records can have a domain/zone parent
|
---|
| 4743 | return unless ($args{type} eq 'record' && $args{defrec} eq 'n');
|
---|
| 4744 | my $result = $dbh->selectrow_hashref("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
| 4745 | " FROM records WHERE record_id = ?",
|
---|
| 4746 | undef, ($args{id}) ) or return;
|
---|
| 4747 | return $result;
|
---|
| 4748 | } else {
|
---|
| 4749 | # snag some arguments that will either fall through or be overwritten to save some code duplication
|
---|
| 4750 | my $tmpid = $args{id};
|
---|
| 4751 | my $type = $args{type};
|
---|
| 4752 | if ($type eq 'record' && $args{defrec} eq 'n') {
|
---|
| 4753 | # Live records go through the records table first.
|
---|
| 4754 | ($tmpid) = $dbh->selectrow_array("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
| 4755 | " FROM records WHERE record_id = ?",
|
---|
| 4756 | undef, ($args{id}) ) or return;
|
---|
| 4757 | $type = ($args{revrec} eq 'n' ? 'domain' : 'revzone');
|
---|
| 4758 | }
|
---|
| 4759 | my ($result) = $dbh->selectrow_array("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
|
---|
| 4760 | undef, ($tmpid) );
|
---|
| 4761 | return $result;
|
---|
| 4762 | }
|
---|
| 4763 | # should be impossible to get here with even remotely sane arguments
|
---|
| 4764 | return;
|
---|
| 4765 | } # end parentID()
|
---|
[116] | 4766 |
|
---|
| 4767 |
|
---|
[117] | 4768 | ## DNSDB::isParent()
|
---|
| 4769 | # Returns true if $id1 is a parent of $id2, false otherwise
|
---|
| 4770 | sub isParent {
|
---|
[470] | 4771 | my $self = shift;
|
---|
| 4772 | my $dbh = $self->{dbh};
|
---|
[117] | 4773 | my $id1 = shift;
|
---|
| 4774 | my $type1 = shift;
|
---|
| 4775 | my $id2 = shift;
|
---|
| 4776 | my $type2 = shift;
|
---|
| 4777 | ##todo: immediate, secondary, full (default)
|
---|
| 4778 |
|
---|
[157] | 4779 | # Return false on invalid types
|
---|
[244] | 4780 | return 0 if !grep /^$type1$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
| 4781 | return 0 if !grep /^$type2$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
[157] | 4782 |
|
---|
[117] | 4783 | # Return false on impossible relations
|
---|
| 4784 | return 0 if $type1 eq 'record'; # nothing may be a child of a record
|
---|
| 4785 | return 0 if $type1 eq 'defrec'; # nothing may be a child of a record
|
---|
[244] | 4786 | return 0 if $type1 eq 'defrevrec'; # nothing may be a child of a record
|
---|
[117] | 4787 | return 0 if $type1 eq 'user'; # nothing may be child of a user
|
---|
| 4788 | return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record
|
---|
[244] | 4789 | return 0 if $type1 eq 'revzone' && $type2 ne 'record';# reverse zone may not be a parent of anything other than a record
|
---|
[117] | 4790 |
|
---|
[186] | 4791 | # ennnhhhh.... if we're passed an id of 0, it will never be found. usual
|
---|
| 4792 | # case would be the UI creating a new <thing>, and so we don't have an ID for
|
---|
| 4793 | # <thing> to look up yet. in that case the UI should check the parent as well.
|
---|
| 4794 | return 0 if $id1 == 0; # nothing can have a parent id of 0
|
---|
| 4795 | return 1 if $id2 == 0; # anything could have a child id of 0 (or "unknown")
|
---|
| 4796 |
|
---|
[117] | 4797 | # group 1 is the ultimate root parent
|
---|
| 4798 | return 1 if $type1 eq 'group' && $id1 == 1;
|
---|
| 4799 |
|
---|
[155] | 4800 | # groups are always (a) parent of themselves
|
---|
| 4801 | return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2;
|
---|
| 4802 |
|
---|
[117] | 4803 | my $id = $id2;
|
---|
| 4804 | my $type = $type2;
|
---|
| 4805 | my $foundparent = 0;
|
---|
[155] | 4806 |
|
---|
[244] | 4807 | # Records are the only entity with two possible parents. We need to split the parent checks on
|
---|
| 4808 | # domain/rdns.
|
---|
| 4809 | if ($type eq 'record') {
|
---|
| 4810 | my ($dom,$rdns) = $dbh->selectrow_array("SELECT domain_id,rdns_id FROM records WHERE record_id=?",
|
---|
| 4811 | undef, ($id));
|
---|
| 4812 | # check immediate parent against request
|
---|
| 4813 | return 1 if $type1 eq 'domain' && $id1 == $dom;
|
---|
| 4814 | return 1 if $type1 eq 'revzone' && $id1 == $rdns;
|
---|
| 4815 | # if request is group, check *both* parents. Only check if the parent is nonzero though.
|
---|
[470] | 4816 | return 1 if $dom && $self->isParent($id1, $type1, $dom, 'domain');
|
---|
| 4817 | return 1 if $rdns && $self->isParent($id1, $type1, $rdns, 'revzone');
|
---|
[244] | 4818 | # exit here since we've executed the loop below by proxy in the above recursive calls.
|
---|
| 4819 | return 0;
|
---|
| 4820 | }
|
---|
| 4821 |
|
---|
| 4822 | # almost the same loop as getParents() above
|
---|
[186] | 4823 | my $limiter = 0;
|
---|
[117] | 4824 | while (1) {
|
---|
[155] | 4825 | my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
|
---|
[117] | 4826 | my $result = $dbh->selectrow_hashref($sql,
|
---|
[157] | 4827 | undef, ($id) );
|
---|
[186] | 4828 | if (!$result) {
|
---|
| 4829 | $limiter++;
|
---|
[244] | 4830 | ##fixme: how often will this happen on a live site? fail at max limiter <n>?
|
---|
[541] | 4831 | # 2013/10/22 only seems to happen when you request an entity that doesn't exist.
|
---|
[186] | 4832 | warn "no results looking for $sql with id $id (depth $limiter)\n";
|
---|
| 4833 | last;
|
---|
| 4834 | }
|
---|
[157] | 4835 | if ($result && $result->{$par_col{$type}} == $id1) {
|
---|
[117] | 4836 | $foundparent = 1;
|
---|
| 4837 | last;
|
---|
[157] | 4838 | } else {
|
---|
| 4839 | ##fixme: do we care about trying to return a "no such record/domain/user/group" error?
|
---|
[244] | 4840 | # should be impossible to create an inconsistent DB just with API calls.
|
---|
[157] | 4841 | warn $dbh->errstr." $sql, $id" if $dbh->errstr;
|
---|
[117] | 4842 | }
|
---|
| 4843 | # group 1 is its own parent. need this here more to break strange loops than for detecting a parent
|
---|
| 4844 | last if $result->{$par_col{$type}} == 1;
|
---|
[152] | 4845 | $id = $result->{$par_col{$type}};
|
---|
[117] | 4846 | $type = $par_type{$type};
|
---|
| 4847 | }
|
---|
| 4848 |
|
---|
| 4849 | return $foundparent;
|
---|
| 4850 | } # end isParent()
|
---|
| 4851 |
|
---|
| 4852 |
|
---|
[275] | 4853 | ## DNSDB::zoneStatus()
|
---|
| 4854 | # Returns and optionally sets a zone's status
|
---|
| 4855 | # Takes a database handle, domain/revzone ID, forward/reverse flag, and optionally a status argument
|
---|
| 4856 | # Returns status, or undef on errors.
|
---|
| 4857 | sub zoneStatus {
|
---|
[477] | 4858 | my $self = shift;
|
---|
| 4859 | my $dbh = $self->{dbh};
|
---|
[3] | 4860 | my $id = shift;
|
---|
[275] | 4861 | my $revrec = shift;
|
---|
| 4862 | my $newstatus = shift || 'mu';
|
---|
[3] | 4863 |
|
---|
| 4864 | return undef if $id !~ /^\d+$/;
|
---|
| 4865 |
|
---|
[283] | 4866 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4867 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4868 | local $dbh->{AutoCommit} = 0;
|
---|
| 4869 | local $dbh->{RaiseError} = 1;
|
---|
| 4870 |
|
---|
[275] | 4871 | if ($newstatus ne 'mu') {
|
---|
[283] | 4872 | # ooo, fun! let's see what we were passed for status
|
---|
| 4873 | eval {
|
---|
| 4874 | $newstatus = 0 if $newstatus eq 'domoff';
|
---|
| 4875 | $newstatus = 1 if $newstatus eq 'domon';
|
---|
| 4876 | $dbh->do("UPDATE ".($revrec eq 'n' ? 'domains' : 'revzones')." SET status=? WHERE ".
|
---|
[275] | 4877 | ($revrec eq 'n' ? 'domain_id' : 'rdns_id')."=?", undef, ($newstatus,$id) );
|
---|
[283] | 4878 |
|
---|
| 4879 | ##fixme switch to more consise "Enabled <domain"/"Disabled <domain>" as with users?
|
---|
[473] | 4880 | $resultstr = "Changed ".($revrec eq 'n' ? $self->domainName($id) : $self->revName($id)).
|
---|
[283] | 4881 | " state to ".($newstatus ? 'active' : 'inactive');
|
---|
| 4882 |
|
---|
| 4883 | my %loghash;
|
---|
| 4884 | $loghash{domain_id} = $id if $revrec eq 'n';
|
---|
| 4885 | $loghash{rdns_id} = $id if $revrec eq 'y';
|
---|
[473] | 4886 | $loghash{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec);
|
---|
[283] | 4887 | $loghash{entry} = $resultstr;
|
---|
[487] | 4888 | $self->_log(%loghash);
|
---|
[283] | 4889 |
|
---|
| 4890 | $dbh->commit;
|
---|
| 4891 | };
|
---|
| 4892 | if ($@) {
|
---|
| 4893 | my $msg = $@;
|
---|
| 4894 | eval { $dbh->rollback; };
|
---|
| 4895 | $resultstr = '';
|
---|
| 4896 | $errstr = $msg;
|
---|
| 4897 | return;
|
---|
| 4898 | }
|
---|
[3] | 4899 | }
|
---|
| 4900 |
|
---|
[275] | 4901 | my ($status) = $dbh->selectrow_array("SELECT status FROM ".
|
---|
| 4902 | ($revrec eq 'n' ? "domains WHERE domain_id=?" : "revzones WHERE rdns_id=?"),
|
---|
| 4903 | undef, ($id) );
|
---|
[3] | 4904 | return $status;
|
---|
[275] | 4905 | } # end zoneStatus()
|
---|
[3] | 4906 |
|
---|
| 4907 |
|
---|
[452] | 4908 | ## DNSDB::getZonesByCIDR()
|
---|
| 4909 | # Get a list of zone names and IDs that records for a passed CIDR block are within.
|
---|
| 4910 | sub getZonesByCIDR {
|
---|
[477] | 4911 | my $self = shift;
|
---|
| 4912 | my $dbh = $self->{dbh};
|
---|
[452] | 4913 | my %args = @_;
|
---|
| 4914 |
|
---|
| 4915 | my $result = $dbh->selectall_arrayref("SELECT rdns_id,revnet FROM revzones WHERE revnet >>= ? OR revnet <<= ?",
|
---|
| 4916 | { Slice => {} }, ($args{cidr}, $args{cidr}) );
|
---|
| 4917 | return $result;
|
---|
| 4918 | } # end getZonesByCIDR()
|
---|
| 4919 |
|
---|
| 4920 |
|
---|
[33] | 4921 | ## DNSDB::importAXFR
|
---|
| 4922 | # Import a domain via AXFR
|
---|
[37] | 4923 | # Takes AXFR host, domain to transfer, group to put the domain in,
|
---|
[484] | 4924 | # and an optional hash containing:
|
---|
| 4925 | # status - active/inactive state flag (defaults to active)
|
---|
| 4926 | # rwsoa - overwrite-SOA flag (defaults to off)
|
---|
| 4927 | # rwns - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
|
---|
| 4928 | # merge - flag to automerge A or AAAA records with matching PTR records
|
---|
[37] | 4929 | # Returns a status code (OK, WARN, or FAIL) and message - message should be blank
|
---|
| 4930 | # if status is OK, but WARN includes conditions that are not fatal but should
|
---|
| 4931 | # really be reported.
|
---|
[33] | 4932 | sub importAXFR {
|
---|
[484] | 4933 | my $self = shift;
|
---|
| 4934 | my $dbh = $self->{dbh};
|
---|
[35] | 4935 | my $ifrom_in = shift;
|
---|
[301] | 4936 | my $zone = shift;
|
---|
[33] | 4937 | my $group = shift;
|
---|
[484] | 4938 |
|
---|
| 4939 | my %args = @_;
|
---|
| 4940 |
|
---|
[33] | 4941 | ##fixme: add mode to delete&replace, merge+overwrite, merge new?
|
---|
| 4942 |
|
---|
[484] | 4943 | $args{status} = (defined($args{status}) ? $args{status} : 0);
|
---|
| 4944 | $args{status} = 1 if $args{status} eq 'on';
|
---|
| 4945 |
|
---|
[37] | 4946 | my $nrecs = 0;
|
---|
| 4947 | my $soaflag = 0;
|
---|
| 4948 | my $nsflag = 0;
|
---|
| 4949 | my $warnmsg = '';
|
---|
| 4950 | my $ifrom;
|
---|
[33] | 4951 |
|
---|
[301] | 4952 | my $rev = 'n';
|
---|
[302] | 4953 | my $code = 'OK';
|
---|
| 4954 | my $msg = 'foobar?';
|
---|
[301] | 4955 |
|
---|
[35] | 4956 | # choke on possible bad setting in ifrom
|
---|
[37] | 4957 | # IPv4 and v6, and valid hostnames!
|
---|
[35] | 4958 | ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
| 4959 | return ('FAIL', "Bad AXFR source host $ifrom")
|
---|
| 4960 | unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
| 4961 |
|
---|
[301] | 4962 | my $errmsg;
|
---|
| 4963 |
|
---|
| 4964 | my $zone_id;
|
---|
| 4965 | my $domain_id = 0;
|
---|
| 4966 | my $rdns_id = 0;
|
---|
| 4967 | my $cidr;
|
---|
| 4968 |
|
---|
| 4969 | # magic happens! detect if we're importing a domain or a reverse zone
|
---|
| 4970 | # while we're at it, figure out what the CIDR netblock is (if we got a .arpa)
|
---|
| 4971 | # or what the formal .arpa zone is (if we got a CIDR netblock)
|
---|
| 4972 | # Handles sub-octet v4 zones in the format specified in the Cricket Book, 2nd Ed, p217-218
|
---|
| 4973 |
|
---|
[601] | 4974 | if ($zone =~ m{(?:\.arpa\.?|/\d+|^[\d.]+|^[a-fA-F0-9:]+)$}) {
|
---|
[301] | 4975 | # we seem to have a reverse zone
|
---|
| 4976 | $rev = 'y';
|
---|
| 4977 |
|
---|
| 4978 | if ($zone =~ /\.arpa\.?$/) {
|
---|
| 4979 | # we have a formal reverse zone. call _zone2cidr and get the CIDR block.
|
---|
| 4980 | ($code,$msg) = _zone2cidr($zone);
|
---|
| 4981 | return ($code, $msg) if $code eq 'FAIL';
|
---|
| 4982 | $cidr = $msg;
|
---|
| 4983 | } elsif ($zone =~ m|^[\d.]+/\d+$|) {
|
---|
| 4984 | # v4 revzone, CIDR netblock
|
---|
| 4985 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 4986 | $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
[601] | 4987 | } elsif ($zone =~ /^[\d.]+$/) {
|
---|
| 4988 | # v4 revzone, leading-octet format
|
---|
| 4989 | my $mask = 32;
|
---|
| 4990 | while ($zone !~ /^\d+\.\d+\.\d+\.\d+$/) {
|
---|
| 4991 | $zone .= '.0';
|
---|
| 4992 | $mask -= 8;
|
---|
| 4993 | }
|
---|
| 4994 | $zone .= "/$mask";
|
---|
| 4995 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 4996 | $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
[301] | 4997 | } elsif ($zone =~ m|^[a-fA-F\d:]+/\d+$|) {
|
---|
| 4998 | # v6 revzone, CIDR netblock
|
---|
| 4999 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 5000 | return ('FAIL', "$zone is not a nibble-aligned block") if $cidr->masklen % 4 != 0;
|
---|
| 5001 | $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.');
|
---|
[601] | 5002 | } elsif ($zone =~ /^[a-fA-F\d:]+$/) {
|
---|
| 5003 | # v6 revzone, leading-group format
|
---|
| 5004 | $zone =~ s/::$//;
|
---|
| 5005 | my $mask = 128;
|
---|
| 5006 | while ($zone !~ /^(?:[a-fA-F\d]{1,4}:){7}[a-fA-F\d]$/) {
|
---|
| 5007 | $zone .= ":0";
|
---|
| 5008 | $mask -= 16;
|
---|
| 5009 | }
|
---|
| 5010 | $zone .= "/$mask";
|
---|
| 5011 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 5012 | $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.');
|
---|
[301] | 5013 | } else {
|
---|
| 5014 | # there is. no. else!
|
---|
[601] | 5015 | return ('FAIL', "Unknown zone name format '$zone'");
|
---|
[301] | 5016 | }
|
---|
| 5017 |
|
---|
[601] | 5018 | # several places this can be triggered from; better to do it once.
|
---|
| 5019 | $warnmsg .= "Apparent sub-/64 IPv6 reverse zone\n" if $cidr->masklen > 64;
|
---|
| 5020 |
|
---|
[301] | 5021 | # quick check to start to see if we've already got one
|
---|
| 5022 |
|
---|
| 5023 | ($zone_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?",
|
---|
| 5024 | undef, ("$cidr"));
|
---|
| 5025 | $rdns_id = $zone_id;
|
---|
| 5026 | } else {
|
---|
| 5027 | # default to domain
|
---|
[349] | 5028 | ($zone_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
[301] | 5029 | undef, ($zone));
|
---|
| 5030 | $domain_id = $zone_id;
|
---|
| 5031 | }
|
---|
| 5032 |
|
---|
| 5033 | return ('FAIL', ($rev eq 'n' ? 'Domain' : 'Reverse zone')." already exists") if $zone_id;
|
---|
| 5034 |
|
---|
[303] | 5035 | # little local utility sub to swap $val and $host for revzone records.
|
---|
| 5036 | sub _revswap {
|
---|
| 5037 | my $rechost = shift;
|
---|
| 5038 | my $recdata = shift;
|
---|
| 5039 |
|
---|
| 5040 | if ($rechost =~ /\.in-addr\.arpa\.?$/) {
|
---|
| 5041 | $rechost =~ s/\.in-addr\.arpa\.?$//;
|
---|
| 5042 | $rechost = join '.', reverse split /\./, $rechost;
|
---|
| 5043 | } else {
|
---|
| 5044 | $rechost =~ s/\.ip6\.arpa\.?$//;
|
---|
| 5045 | my @nibs = reverse split /\./, $rechost;
|
---|
| 5046 | $rechost = '';
|
---|
| 5047 | my $nc;
|
---|
| 5048 | foreach (@nibs) {
|
---|
[634] | 5049 | # # fail on multicharacter nibbles; it's syntactically valid but no standard lookup
|
---|
| 5050 | # # will ever reach it, because it doesn't directly represent a real IP address.
|
---|
| 5051 | # return ('FAIL', "Invalid reverse v6 entry") if $_ !~ /^.$/;
|
---|
[303] | 5052 | $rechost.= $_;
|
---|
| 5053 | $rechost .= ":" if ++$nc % 4 == 0 && $nc < 32;
|
---|
| 5054 | }
|
---|
[307] | 5055 | $rechost .= ":" if $nc < 32 && $rechost !~ /\*$/; # close netblock records?
|
---|
| 5056 | ##fixme: there's a case that ends up with a partial entry here:
|
---|
| 5057 | # ip:add:re:ss::
|
---|
| 5058 | # can't reproduce after letting it sit overnight after discovery. :(
|
---|
| 5059 | #print "$rechost\n";
|
---|
[303] | 5060 | # canonicalize with NetAddr::IP
|
---|
| 5061 | $rechost = NetAddr::IP->new($rechost)->addr unless $rechost =~ /\*$/;
|
---|
| 5062 | }
|
---|
| 5063 | return ($recdata,$rechost)
|
---|
| 5064 | }
|
---|
| 5065 |
|
---|
| 5066 |
|
---|
[33] | 5067 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 5068 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 5069 | local $dbh->{AutoCommit} = 0;
|
---|
| 5070 | local $dbh->{RaiseError} = 1;
|
---|
| 5071 |
|
---|
[301] | 5072 | my $sth;
|
---|
| 5073 | eval {
|
---|
[34] | 5074 |
|
---|
[301] | 5075 | if ($rev eq 'n') {
|
---|
[33] | 5076 | ##fixme: serial
|
---|
[484] | 5077 | $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef,
|
---|
| 5078 | ($zone, $group, $args{status}) );
|
---|
[301] | 5079 | # get domain id so we can do the records
|
---|
| 5080 | ($zone_id) = $dbh->selectrow_array("SELECT currval('domains_domain_id_seq')");
|
---|
| 5081 | $domain_id = $zone_id;
|
---|
[487] | 5082 | $self->_log(group_id => $group, domain_id => $domain_id,
|
---|
| 5083 | entry => "[Added ".($args{status} ? 'active' : 'inactive')." domain $zone via AXFR]");
|
---|
[301] | 5084 | } else {
|
---|
| 5085 | ##fixme: serial
|
---|
[484] | 5086 | $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef,
|
---|
| 5087 | ($cidr,$group,$args{status}) );
|
---|
[301] | 5088 | # get revzone id so we can do the records
|
---|
| 5089 | ($zone_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
| 5090 | $rdns_id = $zone_id;
|
---|
[487] | 5091 | $self->_log(group_id => $group, rdns_id => $rdns_id,
|
---|
| 5092 | entry => "[Added ".($args{status} ? 'active' : 'inactive')." reverse zone $cidr via AXFR]");
|
---|
[301] | 5093 | }
|
---|
[33] | 5094 |
|
---|
[35] | 5095 | ## bizarre DBI<->Net::DNS interaction bug:
|
---|
| 5096 | ## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
|
---|
[37] | 5097 | ## fixed, apparently I was doing *something* odd, but not certain what it was that
|
---|
| 5098 | ## caused a commit instead of barfing
|
---|
[35] | 5099 |
|
---|
[34] | 5100 | my $res = Net::DNS::Resolver->new;
|
---|
[35] | 5101 | $res->nameservers($ifrom);
|
---|
[301] | 5102 | $res->axfr_start($zone)
|
---|
[35] | 5103 | or die "Couldn't begin AXFR\n";
|
---|
[34] | 5104 |
|
---|
[301] | 5105 | $sth = $dbh->prepare("INSERT INTO records (domain_id,rdns_id,host,type,val,distance,weight,port,ttl)".
|
---|
| 5106 | " VALUES (?,?,?,?,?,?,?,?,?)");
|
---|
| 5107 |
|
---|
[307] | 5108 | # Stash info about sub-octet v4 revzones here so we don't have
|
---|
| 5109 | # to store the CNAMEs used to delegate a suboctet zone
|
---|
| 5110 | # $suboct{zone}{ns}[] -> array of nameservers
|
---|
| 5111 | # $suboct{zone}{cname}[] -> array of extant CNAMEs (Just In Case someone did something bizarre)
|
---|
| 5112 | ## commented pending actual use of this data. for now, we'll just
|
---|
| 5113 | ## auto-(re)create the CNAMEs in revzones on export
|
---|
| 5114 | # my %suboct;
|
---|
| 5115 |
|
---|
[35] | 5116 | while (my $rr = $res->axfr_next()) {
|
---|
[301] | 5117 |
|
---|
[596] | 5118 | # Discard out-of-zone records. After trying for a while to replicate this with
|
---|
| 5119 | # *nix-based DNS servers, it appears that only MS DNS is prone to including these
|
---|
| 5120 | # in the AXFR data in the first place, and possibly only older versions at that...
|
---|
| 5121 | # so it can't be reasonably tested. Yay Microsoft.
|
---|
| 5122 | if ($rr->name !~ /$zone$/i) {
|
---|
| 5123 | $warnmsg .= "Discarding out-of-zone record ".$rr->string."\n";
|
---|
| 5124 | }
|
---|
| 5125 |
|
---|
[301] | 5126 | my $val;
|
---|
| 5127 | my $distance = 0;
|
---|
| 5128 | my $weight = 0;
|
---|
| 5129 | my $port = 0;
|
---|
[303] | 5130 | my $logfrag = '';
|
---|
[301] | 5131 |
|
---|
[602] | 5132 | # Collect some record parts
|
---|
[33] | 5133 | my $type = $rr->type;
|
---|
[301] | 5134 | my $host = $rr->name;
|
---|
[484] | 5135 | my $ttl = ($args{newttl} ? $args{newttl} : $rr->ttl); # allow force-override TTLs
|
---|
[35] | 5136 |
|
---|
[602] | 5137 | # Info flags for SOA and NS records
|
---|
[37] | 5138 | $soaflag = 1 if $type eq 'SOA';
|
---|
| 5139 | $nsflag = 1 if $type eq 'NS';
|
---|
[35] | 5140 |
|
---|
[34] | 5141 | # "Primary" types:
|
---|
| 5142 | # A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
|
---|
| 5143 | # maybe KEY
|
---|
| 5144 |
|
---|
[302] | 5145 | # BIND supports:
|
---|
| 5146 | # [standard]
|
---|
| 5147 | # A AAAA CNAME MX NS PTR SOA TXT
|
---|
| 5148 | # [variously experimental, obsolete, or obscure]
|
---|
| 5149 | # 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
|
---|
| 5150 | # ... if one can ever find the right magic to format them correctly
|
---|
| 5151 |
|
---|
| 5152 | # Net::DNS supports:
|
---|
| 5153 | # RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
|
---|
| 5154 | # EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
|
---|
| 5155 | # DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
|
---|
| 5156 |
|
---|
[35] | 5157 | # nasty big ugly case-like thing here, since we have to do *some* different
|
---|
| 5158 | # processing depending on the record. le sigh.
|
---|
| 5159 |
|
---|
[602] | 5160 | # do the initial processing as if the record was in a forward zone. If we're
|
---|
| 5161 | # doing a revzone, we can flip $host and $val as needed, once, after this
|
---|
| 5162 | # monster if-elsif-...-elsif-else. This actually simplifies things a lot.
|
---|
| 5163 |
|
---|
[105] | 5164 | ##fixme: what record types other than TXT can/will have >255-byte payloads?
|
---|
| 5165 |
|
---|
[34] | 5166 | if ($type eq 'A') {
|
---|
[301] | 5167 | $val = $rr->address;
|
---|
[34] | 5168 | } elsif ($type eq 'NS') {
|
---|
[635] | 5169 | # hmm. should we warn here if subdomain NS'es are left alone? OTOH, those should rarely be rewritten anyway.
|
---|
[602] | 5170 | next if ($args{rwns} && ($host eq $zone));
|
---|
| 5171 | $val = $rr->nsdname;
|
---|
[639] | 5172 | $warnmsg .= "Suspect record '".$rr->string."' may not be imported correctly: NS records may not be bare IP addresses\n"
|
---|
| 5173 | if $val =~ /^(?:(?:\d+\.){3}\d+|[a-fA-F0-9:]+)$/;
|
---|
[35] | 5174 | $nsflag = 1;
|
---|
[34] | 5175 | } elsif ($type eq 'CNAME') {
|
---|
[602] | 5176 | $val = $rr->cname;
|
---|
[639] | 5177 | $warnmsg .= "Suspect record '".$rr->string."' may not be imported correctly: CNAME records may not be bare IP addresses\n"
|
---|
| 5178 | if $val =~ /^(?:(?:\d+\.){3}\d+|[a-fA-F0-9:]+)$/;
|
---|
[34] | 5179 | } elsif ($type eq 'SOA') {
|
---|
[484] | 5180 | next if $args{rwsoa};
|
---|
[307] | 5181 | $host = $rr->rname.":".$rr->mname;
|
---|
[301] | 5182 | $val = $rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum;
|
---|
[35] | 5183 | $soaflag = 1;
|
---|
[34] | 5184 | } elsif ($type eq 'PTR') {
|
---|
[602] | 5185 | $val = $rr->ptrdname;
|
---|
[34] | 5186 | } elsif ($type eq 'MX') {
|
---|
[301] | 5187 | $val = $rr->exchange;
|
---|
| 5188 | $distance = $rr->preference;
|
---|
[34] | 5189 | } elsif ($type eq 'TXT') {
|
---|
| 5190 | ##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
|
---|
| 5191 | ## but don't really seem enthusiastic about it.
|
---|
[303] | 5192 | #print "should use rdatastr:\n\t".$rr->rdatastr."\n or char_str_list:\n\t".join(' ',$rr->char_str_list())."\n";
|
---|
| 5193 | # rdatastr returns a BIND-targetted logical string, including opening and closing quotes
|
---|
| 5194 | # char_str_list returns a list of the individual string fragments in the record
|
---|
[307] | 5195 | # txtdata returns the more useful all-in-one form (since we want to push such protocol
|
---|
| 5196 | # details as far down the stack as we can)
|
---|
[303] | 5197 | # NB: this may turn out to be more troublesome if we ever have need of >512-byte TXT records.
|
---|
[602] | 5198 | $val = $rr->txtdata;
|
---|
[34] | 5199 | } elsif ($type eq 'SPF') {
|
---|
| 5200 | ##fixme: and the same caveat here, since it is apparently a clone of ::TXT
|
---|
[301] | 5201 | $val = $rr->txtdata;
|
---|
[34] | 5202 | } elsif ($type eq 'AAAA') {
|
---|
[301] | 5203 | $val = $rr->address;
|
---|
[34] | 5204 | } elsif ($type eq 'SRV') {
|
---|
[301] | 5205 | $val = $rr->target;
|
---|
| 5206 | $distance = $rr->priority;
|
---|
| 5207 | $weight = $rr->weight;
|
---|
| 5208 | $port = $rr->port;
|
---|
[639] | 5209 | $warnmsg .= "Suspect record '".$rr->string."' may not be imported correctly: SRV records may not be bare IP addresses\n"
|
---|
| 5210 | if $val =~ /^(?:(?:\d+\.){3}\d+|[a-fA-F0-9:]+)$/;
|
---|
[34] | 5211 | } elsif ($type eq 'KEY') {
|
---|
[35] | 5212 | # we don't actually know what to do with these...
|
---|
[301] | 5213 | $val = $rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname;
|
---|
[35] | 5214 | } else {
|
---|
[301] | 5215 | $val = $rr->rdatastr;
|
---|
[35] | 5216 | # Finding a different record type is not fatal.... just problematic.
|
---|
[37] | 5217 | # We may not be able to export it correctly.
|
---|
[35] | 5218 | $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
|
---|
[33] | 5219 | }
|
---|
| 5220 |
|
---|
[602] | 5221 | if ($rev eq 'y' && $type ne 'SOA') {
|
---|
| 5222 | # up to this point we haven't meddled with the record's hostname part or rdata part.
|
---|
| 5223 | # for reverse records, (except SOA) we must swap the two.
|
---|
| 5224 | $host = $val;
|
---|
| 5225 | $val = $rr->name;
|
---|
| 5226 | my ($tmpcode,$tmpmsg) = _zone2cidr($val);
|
---|
| 5227 | if ($tmpcode eq 'FAIL') {
|
---|
| 5228 | # $val did not have a valid IP value. It's syntactically valid but WTF?
|
---|
| 5229 | $warnmsg .= "Suspect record '".$rr->string."' may not be imported correctly: $tmpmsg\n";
|
---|
| 5230 | } else {
|
---|
| 5231 | # $val has a valid IP value. See if we can store it as that IP value.
|
---|
| 5232 | # Note we're enumerating do-nothing cases for clarity.
|
---|
| 5233 | ##enhance: this is where we will implement the more subtle variations on #53
|
---|
| 5234 | if ($type ne 'PTR' && $type ne 'NS' && $type ne 'CNAME' && $type ne 'TXT') {
|
---|
| 5235 | # case: the record is "weird" - ie, not a PTR, NS, CNAME, or TXT
|
---|
| 5236 | # $warnmsg .= "Discarding suspect record '".$rr->string."'\n" if $self->{strict} eq 'full';
|
---|
| 5237 | } elsif ($type eq 'PTR' && $tmpmsg->masklen != 32 && $tmpmsg->masklen != 128) {
|
---|
| 5238 | # case: PTR with netblock value, not IP value
|
---|
| 5239 | # eg, "@ PTR foo" in zone f.e.e.b.d.a.e.d.ip6.arpa should not be
|
---|
| 5240 | # stored/displayed as dead:beef::/32 PTR foo
|
---|
| 5241 |
|
---|
| 5242 | ## hrm. WTF is this case for, anyway? Needs testing to check the logic.
|
---|
| 5243 | # } elsif ( ($type eq 'PTR' || $type eq 'NS' || $type eq 'CNAME' || $type eq 'TXT') &&
|
---|
| 5244 | # ($tmpmsg->masklen != $cidr->masklen)
|
---|
| 5245 | # ) {
|
---|
| 5246 | # # leave $val as-is if the record is "normal" (a PTR, NS, CNAME, or TXT),
|
---|
| 5247 | # # and the mask does not match the zone
|
---|
| 5248 | #$warnmsg .= "WTF case: $host $type $val\n";
|
---|
| 5249 | # # $warnmsg .= "Discarding suspect record '".$rr->string."'\n" if $self->{strict} eq 'full';
|
---|
| 5250 |
|
---|
| 5251 | } else {
|
---|
| 5252 | $val = $tmpmsg;
|
---|
| 5253 | $val =~ s/\/(?:32|128)$//; # automagically converts $val back to a string before s///
|
---|
| 5254 | #$val =~ s/:0$//g;
|
---|
| 5255 | }
|
---|
| 5256 | }
|
---|
| 5257 | # magic? convert * records to PTR template (not sure this actually makes sense)
|
---|
| 5258 | #if ($val =~ /^\*/) {
|
---|
| 5259 | # $val =~ s/\*\.//;
|
---|
| 5260 | # ($tmpcode,$tmpmsg) = _zone2cidr($val);
|
---|
| 5261 | # if ($tmpcode eq 'FAIL') {
|
---|
| 5262 | # $val = "*.$val";
|
---|
| 5263 | # $warnmsg .= "Suspect record '".$rr->string."' may not be converted to PTR template correctly: $tmpmsg\n";
|
---|
| 5264 | # } else {
|
---|
| 5265 | # $type = 'PTR template';
|
---|
| 5266 | # $val = $tmpmsg; if $tmp
|
---|
| 5267 | # $val =~ s/\/(?:32|128)$//; # automagically converts $val back to a string before s///
|
---|
| 5268 | # }
|
---|
| 5269 | #}
|
---|
| 5270 | } # non-SOA revrec $host/$val inversion and munging
|
---|
| 5271 |
|
---|
[303] | 5272 | my $logentry = "[AXFR ".($rev eq 'n' ? $zone : $cidr)."] ";
|
---|
[34] | 5273 |
|
---|
[484] | 5274 | if ($args{merge}) {
|
---|
[307] | 5275 | if ($rev eq 'n') {
|
---|
| 5276 | # importing a domain; we have A and AAAA records that could be merged with matching PTR records
|
---|
| 5277 | my $etype;
|
---|
| 5278 | my ($erdns,$erid,$ettl) = $dbh->selectrow_array("SELECT rdns_id,record_id,ttl FROM records ".
|
---|
| 5279 | "WHERE host=? AND val=? AND type=12",
|
---|
| 5280 | undef, ($host, $val) );
|
---|
| 5281 | if ($erid) {
|
---|
| 5282 | if ($type eq 'A') { # PTR -> A+PTR
|
---|
| 5283 | $etype = 65280;
|
---|
| 5284 | $logentry .= "Merged A record with existing PTR record '$host A+PTR $val', TTL $ettl";
|
---|
| 5285 | }
|
---|
| 5286 | if ($type eq 'AAAA') { # PTR -> AAAA+PTR
|
---|
| 5287 | $etype = 65281;
|
---|
| 5288 | $logentry .= "Merged AAAA record with existing PTR record '$host AAAA+PTR $val', TTL $ettl";
|
---|
| 5289 | }
|
---|
| 5290 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
| 5291 | $dbh->do("UPDATE records SET domain_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
| 5292 | ($domain_id, $ettl, $etype, $erid));
|
---|
| 5293 | $nrecs++;
|
---|
[487] | 5294 | $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $erdns, entry => $logentry);
|
---|
[307] | 5295 | next; # while axfr_next
|
---|
| 5296 | }
|
---|
| 5297 | } # $rev eq 'n'
|
---|
| 5298 | else {
|
---|
| 5299 | # importing a revzone, we have PTR records that could be merged with matching A/AAAA records
|
---|
| 5300 | my ($domid,$erid,$ettl,$etype) = $dbh->selectrow_array("SELECT domain_id,record_id,ttl,type FROM records ".
|
---|
| 5301 | "WHERE host=? AND val=? AND (type=1 OR type=28)",
|
---|
| 5302 | undef, ($host, $val) );
|
---|
| 5303 | if ($erid) {
|
---|
| 5304 | if ($etype == 1) { # A -> A+PTR
|
---|
| 5305 | $etype = 65280;
|
---|
| 5306 | $logentry .= "Merged PTR record with existing matching A record '$host A+PTR $val', TTL $ettl";
|
---|
| 5307 | }
|
---|
| 5308 | if ($etype == 28) { # AAAA -> AAAA+PTR
|
---|
| 5309 | $etype = 65281;
|
---|
| 5310 | $logentry .= "Merged PTR record with existing matching AAAA record '$host AAAA+PTR $val', TTL $ettl";
|
---|
| 5311 | }
|
---|
| 5312 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
| 5313 | $dbh->do("UPDATE records SET rdns_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
| 5314 | ($rdns_id, $ettl, $etype, $erid));
|
---|
| 5315 | $nrecs++;
|
---|
[487] | 5316 | $self->_log(group_id => $group, domain_id => $domid, rdns_id => $rdns_id, entry => $logentry);
|
---|
[307] | 5317 | next; # while axfr_next
|
---|
| 5318 | }
|
---|
| 5319 | } # $rev eq 'y'
|
---|
[484] | 5320 | } # if $args{merge}
|
---|
[34] | 5321 |
|
---|
[302] | 5322 | # Insert the new record
|
---|
[301] | 5323 | $sth->execute($domain_id, $rdns_id, $host, $reverse_typemap{$type}, $val,
|
---|
| 5324 | $distance, $weight, $port, $ttl);
|
---|
| 5325 |
|
---|
[37] | 5326 | $nrecs++;
|
---|
[34] | 5327 |
|
---|
[301] | 5328 | if ($type eq 'SOA') {
|
---|
[484] | 5329 | # also !$args{rwsoa}, but if that's set, it should be impossible to get here.
|
---|
[301] | 5330 | my @tmp1 = split /:/, $host;
|
---|
| 5331 | my @tmp2 = split /:/, $val;
|
---|
| 5332 | $logentry .= "Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
| 5333 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl";
|
---|
[303] | 5334 | } elsif ($logfrag) {
|
---|
| 5335 | # special case for log entries we need to meddle with a little.
|
---|
| 5336 | $logentry .= $logfrag;
|
---|
[301] | 5337 | } else {
|
---|
[602] | 5338 | $logentry .= "Added record '".($rev eq 'y' ? $val : $host)." $type";
|
---|
[301] | 5339 | $logentry .= " [distance $distance]" if $type eq 'MX';
|
---|
| 5340 | $logentry .= " [priority $distance] [weight $weight] [port $port]" if $type eq 'SRV';
|
---|
[602] | 5341 | $logentry .= " ".($rev eq 'y' ? $host : $val)."', TTL $ttl";
|
---|
[301] | 5342 | }
|
---|
[487] | 5343 | $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $rdns_id, entry => $logentry);
|
---|
[301] | 5344 |
|
---|
[37] | 5345 | } # while axfr_next
|
---|
| 5346 |
|
---|
[307] | 5347 | # Detect and handle delegated subzones
|
---|
| 5348 | # Placeholder for when we decide what to actually do with this, see previous comments in NS and CNAME handling.
|
---|
| 5349 | #foreach (keys %suboct) {
|
---|
| 5350 | # print "found ".($suboct{$_}{ns} ? @{$suboct{$_}{ns}} : '0')." NS records and ".
|
---|
| 5351 | # ($suboct{$_}{cname} ? @{$suboct{$_}{cname}} : '0')." CNAMEs for $_\n";
|
---|
| 5352 | #}
|
---|
| 5353 |
|
---|
[37] | 5354 | # Overwrite SOA record
|
---|
[484] | 5355 | if ($args{rwsoa}) {
|
---|
[37] | 5356 | $soaflag = 1;
|
---|
[573] | 5357 | my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM "._rectable('y', $rev)." WHERE group_id=? AND type=?");
|
---|
| 5358 | my $sthputsoa = $dbh->prepare("INSERT INTO records (".
|
---|
| 5359 | ($rev eq 'n' ? 'domain_id' : 'rdns_id').",host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
[37] | 5360 | $sthgetsoa->execute($group,$reverse_typemap{SOA});
|
---|
| 5361 | while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
|
---|
[573] | 5362 | if ($rev eq 'n') {
|
---|
| 5363 | $host =~ s/DOMAIN/$zone/g;
|
---|
| 5364 | $val =~ s/DOMAIN/$zone/g; # arguably useless
|
---|
| 5365 | } else {
|
---|
| 5366 | $host =~ s/ADMINDOMAIN/$self->{domain}/g;
|
---|
| 5367 | }
|
---|
[301] | 5368 | $sthputsoa->execute($zone_id,$host,$reverse_typemap{SOA},$val,$ttl);
|
---|
[34] | 5369 | }
|
---|
[37] | 5370 | }
|
---|
[34] | 5371 |
|
---|
[573] | 5372 | # Add standard NS records. The old one(s) should have been skipped by this point.
|
---|
[484] | 5373 | if ($args{rwns}) {
|
---|
[37] | 5374 | $nsflag = 1;
|
---|
[573] | 5375 | my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM "._rectable('y',$rev)." WHERE group_id=? AND type=?");
|
---|
| 5376 | my $sthputns = $dbh->prepare("INSERT INTO records (".
|
---|
| 5377 | ($rev eq 'n' ? 'domain_id' : 'rdns_id').",host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
[37] | 5378 | $sthgetns->execute($group,$reverse_typemap{NS});
|
---|
| 5379 | while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
|
---|
[573] | 5380 | if ($rev eq 'n') {
|
---|
| 5381 | $host =~ s/DOMAIN/$zone/g;
|
---|
| 5382 | $val =~ s/DOMAIN/$zone/g; #hmm.
|
---|
| 5383 | } else {
|
---|
| 5384 | $host =~ s/ADMINDOMAIN/$self->{domain}/g; #hmm.
|
---|
| 5385 | $val =~ s/ZONE/$cidr/g;
|
---|
| 5386 | }
|
---|
[301] | 5387 | $sthputns->execute($zone_id,$host,$reverse_typemap{NS},$val,$ttl);
|
---|
[37] | 5388 | }
|
---|
| 5389 | }
|
---|
[34] | 5390 |
|
---|
[35] | 5391 | die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
|
---|
| 5392 | die "Bad zone: No SOA record!\n" if !$soaflag;
|
---|
| 5393 | die "Bad zone: No NS records!\n" if !$nsflag;
|
---|
| 5394 |
|
---|
[37] | 5395 | $dbh->commit;
|
---|
[35] | 5396 |
|
---|
[33] | 5397 | };
|
---|
| 5398 |
|
---|
| 5399 | if ($@) {
|
---|
| 5400 | my $msg = $@;
|
---|
| 5401 | eval { $dbh->rollback; };
|
---|
[34] | 5402 | return ('FAIL',$msg." $warnmsg");
|
---|
[33] | 5403 | } else {
|
---|
[35] | 5404 | return ('WARN', $warnmsg) if $warnmsg;
|
---|
[91] | 5405 | return ('OK',"Imported OK");
|
---|
[33] | 5406 | }
|
---|
| 5407 |
|
---|
[37] | 5408 | # it should be impossible to get here.
|
---|
[34] | 5409 | return ('WARN',"OOOK!");
|
---|
[33] | 5410 | } # end importAXFR()
|
---|
| 5411 |
|
---|
| 5412 |
|
---|
[302] | 5413 | ## DNSDB::importBIND()
|
---|
| 5414 | sub importBIND {
|
---|
| 5415 | } # end importBIND()
|
---|
| 5416 |
|
---|
| 5417 |
|
---|
| 5418 | ## DNSDB::import_tinydns()
|
---|
| 5419 | sub import_tinydns {
|
---|
| 5420 | } # end import_tinydns()
|
---|
| 5421 |
|
---|
| 5422 |
|
---|
[103] | 5423 | ## DNSDB::export()
|
---|
| 5424 | # Export the DNS database, or a part of it
|
---|
[485] | 5425 | # Takes a string indicating the export type, plus optional arguments depending on type
|
---|
[103] | 5426 | # Writes zone data to targets as appropriate for type
|
---|
| 5427 | sub export {
|
---|
[485] | 5428 | my $self = shift;
|
---|
[103] | 5429 | my $target = shift;
|
---|
| 5430 |
|
---|
| 5431 | if ($target eq 'tiny') {
|
---|
[567] | 5432 | eval {
|
---|
| 5433 | $self->__export_tiny(@_);
|
---|
| 5434 | };
|
---|
| 5435 | if ($@) {
|
---|
| 5436 | $errstr = $@;
|
---|
| 5437 | return undef;
|
---|
| 5438 | }
|
---|
[103] | 5439 | }
|
---|
| 5440 | # elsif ($target eq 'foo') {
|
---|
[485] | 5441 | # __export_foo(@_);
|
---|
[103] | 5442 | #}
|
---|
| 5443 | # etc
|
---|
| 5444 |
|
---|
[567] | 5445 | return 1;
|
---|
[103] | 5446 | } # end export()
|
---|
| 5447 |
|
---|
| 5448 |
|
---|
| 5449 | ## DNSDB::__export_tiny
|
---|
| 5450 | # Internal sub to implement tinyDNS (compatible) export
|
---|
[485] | 5451 | # Takes filehandle to write export to, optional argument(s)
|
---|
[103] | 5452 | # to determine which data gets exported
|
---|
| 5453 | sub __export_tiny {
|
---|
[485] | 5454 | my $self = shift;
|
---|
| 5455 | my $dbh = $self->{dbh};
|
---|
[103] | 5456 | my $datafile = shift;
|
---|
[559] | 5457 | my $zonefilehandle = $datafile; # makes cache/no-cache a little simpler
|
---|
[103] | 5458 |
|
---|
| 5459 | ##fixme: slurp up further options to specify particular zone(s) to export
|
---|
| 5460 |
|
---|
| 5461 | ##fixme: fail if $datafile isn't an open, writable file
|
---|
| 5462 |
|
---|
[566] | 5463 | # Error check - does the cache dir exist, if we're using one?
|
---|
| 5464 | if ($self->{usecache}) {
|
---|
| 5465 | die "Cache directory does not exist\n" if !-e $self->{exportcache};
|
---|
| 5466 | die "$self->{exportcache} is not a directory\n" if !-d $self->{exportcache};
|
---|
| 5467 | die "$self->{exportcache} must be both readable and writable\n"
|
---|
| 5468 | if !-r $self->{exportcache} || !-w $self->{exportcache};
|
---|
| 5469 | }
|
---|
| 5470 |
|
---|
[103] | 5471 | # easy case - export all evarything
|
---|
| 5472 | # not-so-easy case - export item(s) specified
|
---|
| 5473 | # todo: figure out what kind of list we use to export items
|
---|
| 5474 |
|
---|
[329] | 5475 | # raw packet in unknown format: first byte indicates length
|
---|
| 5476 | # of remaining data, allows up to 255 raw bytes
|
---|
| 5477 |
|
---|
[566] | 5478 | # note: the only I/O failures we seem to be able to actually catch
|
---|
| 5479 | # here are "closed filehandle" errors. we're probably not writing
|
---|
| 5480 | # enough data at this point to properly trigger an "out of space"
|
---|
| 5481 | # error. :/
|
---|
| 5482 | eval {
|
---|
| 5483 | use warnings FATAL => ('io');
|
---|
| 5484 | # Locations/views - worth including in the caching setup?
|
---|
| 5485 | my $lochash = $dbh->selectall_hashref("SELECT location,iplist FROM locations", 'location');
|
---|
| 5486 | foreach my $location (keys %$lochash) {
|
---|
| 5487 | foreach my $ipprefix (split /[,\s]+/, $lochash->{$location}{iplist}) {
|
---|
| 5488 | $ipprefix =~ s/\s+//g;
|
---|
| 5489 | $ipprefix = new NetAddr::IP $ipprefix;
|
---|
[449] | 5490 | ##fixme: how to handle IPv6?
|
---|
| 5491 | next if $ipprefix->{isv6};
|
---|
[566] | 5492 | # have to account for /nn CIDR entries. tinydns only speaks octet-sliced prefix.
|
---|
| 5493 | if ($ipprefix->masklen <= 8) {
|
---|
| 5494 | foreach ($ipprefix->split(8)) {
|
---|
| 5495 | my $tmp = $_->addr;
|
---|
| 5496 | $tmp =~ s/\.\d+\.\d+\.\d+$//;
|
---|
| 5497 | print $datafile "%$location:$tmp\n";
|
---|
| 5498 | }
|
---|
| 5499 | } elsif ($ipprefix->masklen <= 16) {
|
---|
| 5500 | foreach ($ipprefix->split(16)) {
|
---|
| 5501 | my $tmp = $_->addr;
|
---|
| 5502 | $tmp =~ s/\.\d+\.\d+$//;
|
---|
| 5503 | print $datafile "%$location:$tmp\n";
|
---|
| 5504 | }
|
---|
| 5505 | } elsif ($ipprefix->masklen <= 24) {
|
---|
| 5506 | foreach ($ipprefix->split(24)) {
|
---|
| 5507 | my $tmp = $_->addr;
|
---|
| 5508 | $tmp =~ s/\.\d+$//;
|
---|
| 5509 | print $datafile "%$location:$tmp\n";
|
---|
| 5510 | }
|
---|
| 5511 | } else {
|
---|
| 5512 | foreach ($ipprefix->split(32)) {
|
---|
| 5513 | print $datafile "%$location:".$_->addr."\n";
|
---|
| 5514 | }
|
---|
[449] | 5515 | }
|
---|
| 5516 | }
|
---|
[566] | 5517 | print $datafile "%$location\n" if !$lochash->{$location}{iplist};
|
---|
[372] | 5518 | }
|
---|
[566] | 5519 | };
|
---|
| 5520 | if ($@) {
|
---|
| 5521 | die "Error writing locations to master file: $@, $!\n";
|
---|
[372] | 5522 | }
|
---|
| 5523 |
|
---|
[329] | 5524 | # tracking hash so we don't double-export A+PTR or AAAA+PTR records.
|
---|
| 5525 | my %recflags;
|
---|
| 5526 |
|
---|
[523] | 5527 | # For reasons unknown, we can't sanely UNION these statements. Feh.
|
---|
| 5528 | # Supposedly it should work though (note last 3 lines):
|
---|
| 5529 | ## PG manual
|
---|
| 5530 | #UNION Clause
|
---|
| 5531 | #
|
---|
| 5532 | #The UNION clause has this general form:
|
---|
| 5533 | #
|
---|
| 5534 | # select_statement UNION [ ALL ] select_statement
|
---|
| 5535 | #
|
---|
| 5536 | #select_statement is any SELECT statement without an ORDER BY, LIMIT, FOR UPDATE, or FOR SHARE clause. (ORDER BY
|
---|
| 5537 | #and LIMIT can be attached to a subexpression if it is enclosed in parentheses. Without parentheses, these
|
---|
| 5538 | #clauses will be taken to apply to the result of the UNION, not to its right-hand input expression.)
|
---|
| 5539 | my $soasth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
| 5540 | "FROM records WHERE rdns_id=? AND type=6");
|
---|
[543] | 5541 | my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location,extract(epoch from stamp),expires,stampactive ".
|
---|
[576] | 5542 | "FROM records WHERE rdns_id=? AND NOT type=6 ".
|
---|
[599] | 5543 | "ORDER BY masklen(inetlazy(val)) DESC, inetlazy(val)");
|
---|
[523] | 5544 | my $revsth = $dbh->prepare("SELECT rdns_id,revnet,status,changed FROM revzones WHERE status=1 ".
|
---|
[566] | 5545 | "ORDER BY masklen(revnet) DESC, rdns_id");
|
---|
[523] | 5546 | my $zonesth = $dbh->prepare("UPDATE revzones SET changed='n' WHERE rdns_id=?");
|
---|
| 5547 | $revsth->execute();
|
---|
| 5548 | while (my ($revid,$revzone,$revstat,$changed) = $revsth->fetchrow_array) {
|
---|
[368] | 5549 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
| 5550 | # O_NOFOLLOW
|
---|
| 5551 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
| 5552 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
| 5553 | # still be followed.
|
---|
| 5554 | # but that doesn't help other platforms. :/
|
---|
[523] | 5555 | my $tmpzone = NetAddr::IP->new($revzone);
|
---|
| 5556 | ##fixme: locations/views? subnet mask? need to avoid possible collisions with zone/superzone
|
---|
| 5557 | ## (eg /20 vs /24, starting on .0.0)
|
---|
| 5558 | my $cz = $tmpzone->network->addr."-".$tmpzone->masklen;
|
---|
| 5559 | my $cachefile = "$self->{exportcache}/$cz";
|
---|
| 5560 | my $tmpcache = "$self->{exportcache}/tmp.$cz.$$";
|
---|
[521] | 5561 | eval {
|
---|
[108] | 5562 |
|
---|
[559] | 5563 | # write fresh records if:
|
---|
| 5564 | # - we are not using the cache
|
---|
| 5565 | # - force_refresh is set
|
---|
| 5566 | # - the zone has changed
|
---|
| 5567 | # - the cache file does not exist
|
---|
| 5568 | # - the cache file is empty
|
---|
| 5569 | if (!$self->{usecache} || $self->{force_refresh} || $changed || !-e $cachefile || -z $cachefile) {
|
---|
| 5570 | if ($self->{usecache}) {
|
---|
| 5571 | open ZONECACHE, ">$tmpcache" or die "Error creating temporary file $tmpcache: $!\n";
|
---|
| 5572 | $zonefilehandle = *ZONECACHE;
|
---|
| 5573 | }
|
---|
[521] | 5574 |
|
---|
[523] | 5575 | # need to fetch this separately since the rest of the records all (should) have real IPs in val
|
---|
| 5576 | $soasth->execute($revid);
|
---|
| 5577 | my (@zsoa) = $soasth->fetchrow_array();
|
---|
[644] | 5578 | $self->_printrec_tiny($zonefilehandle, $zsoa[7], 'y',\%recflags,$revzone,
|
---|
[523] | 5579 | $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],'');
|
---|
| 5580 |
|
---|
| 5581 | $recsth->execute($revid);
|
---|
[596] | 5582 | my $fullzone = _ZONE($tmpzone, 'ZONE', 'r', '.').($tmpzone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 5583 |
|
---|
[573] | 5584 | while (my ($host, $type, $val, $dist, $weight, $port, $ttl, $recid, $loc, $stamp, $expires, $stampactive)
|
---|
| 5585 | = $recsth->fetchrow_array) {
|
---|
[523] | 5586 | next if $recflags{$recid};
|
---|
[521] | 5587 |
|
---|
[596] | 5588 | # Check for out-of-zone data
|
---|
| 5589 | if ($val =~ /\.arpa$/) {
|
---|
| 5590 | # val is non-IP
|
---|
| 5591 | if ($val !~ /$fullzone$/) {
|
---|
| 5592 | warn "Not exporting out-of-zone record $val $typemap{$type} $host, $ttl (zone $tmpzone)\n";
|
---|
| 5593 | next;
|
---|
| 5594 | }
|
---|
| 5595 | } else {
|
---|
| 5596 | my $ipval = new NetAddr::IP $val;
|
---|
| 5597 | if (!$tmpzone->contains($ipval)) {
|
---|
| 5598 | warn "Not exporting out-of-zone record $val $typemap{$type} $host, $ttl (zone $tmpzone)\n";
|
---|
| 5599 | next;
|
---|
| 5600 | }
|
---|
| 5601 | } # is $val a raw .arpa name?
|
---|
| 5602 |
|
---|
[597] | 5603 | # Spaces are evil.
|
---|
| 5604 | $val =~ s/^\s+//;
|
---|
| 5605 | $val =~ s/\s+$//;
|
---|
| 5606 | if ($typemap{$type} ne 'TXT') {
|
---|
| 5607 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 5608 | $host =~ s/^\s+//;
|
---|
| 5609 | $host =~ s/\s+$//;
|
---|
| 5610 | }
|
---|
[372] | 5611 |
|
---|
[644] | 5612 | $self->_printrec_tiny($zonefilehandle, $recid, 'y', \%recflags, $revzone,
|
---|
[559] | 5613 | $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp, $expires, $stampactive);
|
---|
[450] | 5614 |
|
---|
[523] | 5615 | $recflags{$recid} = 1;
|
---|
[368] | 5616 |
|
---|
[521] | 5617 | } # while ($recsth)
|
---|
| 5618 |
|
---|
[559] | 5619 | if ($self->{usecache}) {
|
---|
| 5620 | close ZONECACHE; # force the file to be written
|
---|
| 5621 | # catch obvious write errors that leave an empty temp file
|
---|
| 5622 | if (-s $tmpcache) {
|
---|
| 5623 | rename $tmpcache, $cachefile
|
---|
| 5624 | or die "Error overwriting cache file $cachefile with temporary file: $!\n";
|
---|
| 5625 | }
|
---|
[521] | 5626 | }
|
---|
| 5627 |
|
---|
| 5628 | } # if $changed or cache filesize is 0
|
---|
| 5629 |
|
---|
| 5630 | };
|
---|
| 5631 | if ($@) {
|
---|
[566] | 5632 | die "error writing ".($self->{usecache} ? 'new data for ' : '')."$revzone: $@\n";
|
---|
[521] | 5633 | # error! something borked, and we should be able to fall back on the old cache file
|
---|
| 5634 | # report the error, somehow.
|
---|
| 5635 | } else {
|
---|
[523] | 5636 | # mark zone as unmodified. Only do this if no errors, that way
|
---|
[521] | 5637 | # export failures should recover a little more automatically.
|
---|
[523] | 5638 | $zonesth->execute($revid);
|
---|
[368] | 5639 | }
|
---|
[521] | 5640 |
|
---|
[559] | 5641 | if ($self->{usecache}) {
|
---|
| 5642 | # We've already made as sure as we can that a cached zone file is "good",
|
---|
| 5643 | # although possibly stale/obsolete due to errors creating a new one.
|
---|
[566] | 5644 | eval {
|
---|
| 5645 | open CACHE, "<$cachefile" or die $!;
|
---|
| 5646 | print $datafile $_ or die "error copying cached $revzone to master file: $!" while <CACHE>;
|
---|
| 5647 | close CACHE;
|
---|
| 5648 | };
|
---|
| 5649 | die $@ if $@;
|
---|
[559] | 5650 | }
|
---|
| 5651 |
|
---|
[523] | 5652 | } # while ($revsth)
|
---|
[329] | 5653 |
|
---|
[576] | 5654 | $soasth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
[578] | 5655 | "FROM records WHERE domain_id=? AND type=6");
|
---|
[543] | 5656 | $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location,extract(epoch from stamp),expires,stampactive ".
|
---|
[576] | 5657 | "FROM records WHERE domain_id=? AND NOT type=6"); # Just exclude all types relating to rDNS
|
---|
[523] | 5658 | # "FROM records WHERE domain_id=? AND type < 65280"); # Just exclude all types relating to rDNS
|
---|
[576] | 5659 | my $domsth = $dbh->prepare("SELECT domain_id,domain,status,changed FROM domains WHERE status=1 ORDER BY domain_id");
|
---|
[523] | 5660 | $zonesth = $dbh->prepare("UPDATE domains SET changed='n' WHERE domain_id=?");
|
---|
| 5661 | $domsth->execute();
|
---|
| 5662 | while (my ($domid,$dom,$domstat,$changed) = $domsth->fetchrow_array) {
|
---|
[368] | 5663 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
| 5664 | # O_NOFOLLOW
|
---|
| 5665 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
| 5666 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
| 5667 | # still be followed.
|
---|
| 5668 | # but that doesn't help other platforms. :/
|
---|
[523] | 5669 | my $cachefile = "$self->{exportcache}/$dom";
|
---|
| 5670 | my $tmpcache = "$self->{exportcache}/tmp.$dom.$$";
|
---|
[521] | 5671 | eval {
|
---|
[344] | 5672 |
|
---|
[559] | 5673 | # write fresh records if:
|
---|
| 5674 | # - we are not using the cache
|
---|
| 5675 | # - force_refresh is set
|
---|
| 5676 | # - the zone has changed
|
---|
| 5677 | # - the cache file does not exist
|
---|
| 5678 | # - the cache file is empty
|
---|
| 5679 | if (!$self->{usecache} || $self->{force_refresh} || $changed || !-e $cachefile || -z $cachefile) {
|
---|
| 5680 | if ($self->{usecache}) {
|
---|
| 5681 | open ZONECACHE, ">$tmpcache" or die "Error creating temporary file $tmpcache: $!\n";
|
---|
| 5682 | $zonefilehandle = *ZONECACHE;
|
---|
| 5683 | }
|
---|
[329] | 5684 |
|
---|
[576] | 5685 | # need to fetch this separately so the SOA comes first in the flatfile....
|
---|
| 5686 | # Just In Case we need/want to reimport from the flatfile later on.
|
---|
| 5687 | $soasth->execute($domid);
|
---|
| 5688 | my (@zsoa) = $soasth->fetchrow_array();
|
---|
[644] | 5689 | $self->_printrec_tiny($zonefilehandle, $zsoa[7], 'n',\%recflags,$dom,
|
---|
[576] | 5690 | $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],'');
|
---|
| 5691 |
|
---|
[523] | 5692 | $recsth->execute($domid);
|
---|
[543] | 5693 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc,$stamp,$expires,$stampactive) = $recsth->fetchrow_array) {
|
---|
[523] | 5694 | next if $recflags{$recid};
|
---|
[521] | 5695 |
|
---|
[596] | 5696 | # Check for out-of-zone data
|
---|
[655] | 5697 | $host = $dom if $host eq '@';
|
---|
[596] | 5698 | if ($host !~ /$dom$/) {
|
---|
| 5699 | warn "Not exporting out-of-zone record $host $type $val, $ttl (zone $dom)\n";
|
---|
| 5700 | next;
|
---|
| 5701 | }
|
---|
| 5702 |
|
---|
[523] | 5703 | # Spaces are evil.
|
---|
| 5704 | $host =~ s/^\s+//;
|
---|
| 5705 | $host =~ s/\s+$//;
|
---|
| 5706 | if ($typemap{$type} ne 'TXT') {
|
---|
| 5707 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 5708 | $val =~ s/^\s+//;
|
---|
| 5709 | $val =~ s/\s+$//;
|
---|
| 5710 | }
|
---|
| 5711 |
|
---|
[644] | 5712 | $self->_printrec_tiny($zonefilehandle, $recid, 'n', \%recflags,
|
---|
[559] | 5713 | $dom, $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp, $expires, $stampactive);
|
---|
[329] | 5714 |
|
---|
[523] | 5715 | $recflags{$recid} = 1;
|
---|
[450] | 5716 |
|
---|
[521] | 5717 | } # while ($recsth)
|
---|
| 5718 |
|
---|
| 5719 |
|
---|
[559] | 5720 | if ($self->{usecache}) {
|
---|
| 5721 | close ZONECACHE; # force the file to be written
|
---|
| 5722 | # catch obvious write errors that leave an empty temp file
|
---|
| 5723 | if (-s $tmpcache) {
|
---|
| 5724 | rename $tmpcache, $cachefile
|
---|
| 5725 | or die "Error overwriting cache file $cachefile with temporary file: $!\n";
|
---|
| 5726 | }
|
---|
[521] | 5727 | }
|
---|
| 5728 |
|
---|
| 5729 | } # if $changed or cache filesize is 0
|
---|
| 5730 |
|
---|
| 5731 | };
|
---|
| 5732 | if ($@) {
|
---|
[566] | 5733 | die "error writing ".($self->{usecache} ? 'new data for ' : '')."$dom: $@\n";
|
---|
[521] | 5734 | # error! something borked, and we should be able to fall back on the old cache file
|
---|
| 5735 | # report the error, somehow.
|
---|
| 5736 | } else {
|
---|
[523] | 5737 | # mark domain as unmodified. Only do this if no errors, that way
|
---|
[521] | 5738 | # export failures should recover a little more automatically.
|
---|
[523] | 5739 | $zonesth->execute($domid);
|
---|
[368] | 5740 | }
|
---|
[521] | 5741 |
|
---|
[559] | 5742 | if ($self->{usecache}) {
|
---|
| 5743 | # We've already made as sure as we can that a cached zone file is "good",
|
---|
| 5744 | # although possibly stale/obsolete due to errors creating a new one.
|
---|
[566] | 5745 | eval {
|
---|
| 5746 | open CACHE, "<$cachefile" or die $!;
|
---|
| 5747 | print $datafile $_ or die "error copying cached $dom to master file: $!" while <CACHE>;
|
---|
| 5748 | close CACHE;
|
---|
| 5749 | };
|
---|
| 5750 | die $@ if $@;
|
---|
[559] | 5751 | }
|
---|
| 5752 |
|
---|
[329] | 5753 | } # while ($domsth)
|
---|
| 5754 |
|
---|
[566] | 5755 | return 1;
|
---|
[329] | 5756 | } # end __export_tiny()
|
---|
| 5757 |
|
---|
| 5758 |
|
---|
| 5759 | # Utility sub for __export_tiny above
|
---|
| 5760 | sub _printrec_tiny {
|
---|
[644] | 5761 | my $self = shift;
|
---|
[573] | 5762 | my ($datafile, $recid, $revrec, $recflags, $zone, $host, $type, $val, $dist, $weight, $port, $ttl,
|
---|
| 5763 | $loc, $stamp, $expires, $stampactive) = @_;
|
---|
[329] | 5764 |
|
---|
[543] | 5765 | $loc = '' if !$loc; # de-nullify - just in case
|
---|
| 5766 | ##fixme: handle case of record-with-location-that-doesn't-exist better.
|
---|
| 5767 | # note this currently fails safe (tested) - records with a location that
|
---|
| 5768 | # doesn't exist will not be sent to any client
|
---|
| 5769 | # $loc = '' if !$lochash->{$loc};
|
---|
| 5770 |
|
---|
| 5771 |
|
---|
| 5772 | ## Records that are valid only before or after a set time
|
---|
| 5773 |
|
---|
| 5774 | # record due to expire sometime is the complex case. we don't want to just
|
---|
| 5775 | # rely on tinydns' auto-adjusting TTLs, because the default TTL in that case
|
---|
| 5776 | # is one day instead of the SOA minttl as BIND might do.
|
---|
| 5777 |
|
---|
| 5778 | # consider the case where a record is set to expire a week ahead, but the next
|
---|
| 5779 | # day later you want to change it NOW (or as NOWish as you get with your DNS
|
---|
| 5780 | # management practice). but now you're stuck, because someone, somewhere,
|
---|
| 5781 | # has just done a lookup before your latest change was published, and they'll
|
---|
| 5782 | # be caching that old, broken record for 1 day instead of your zone default
|
---|
| 5783 | # TTL.
|
---|
| 5784 |
|
---|
| 5785 | # $stamp-$ttl is the *latest* we can publish the record with the defined TTL
|
---|
| 5786 | # to still have the expiry happen as scheduled, but we need to find some
|
---|
| 5787 | # *earlier* point. We can maybe guess, and 2x TTL is probably reasonable,
|
---|
| 5788 | # but we need info on the export frequency.
|
---|
| 5789 |
|
---|
| 5790 | # export the normal, non-expiring record up until $stamp-<guesstimate>, then
|
---|
| 5791 | # switch to exporting a record with the TAI64 stamp and a 0 TTL so tinydns
|
---|
| 5792 | # takes over TTL management.
|
---|
| 5793 |
|
---|
| 5794 | if ($stampactive) {
|
---|
| 5795 | if ($expires) {
|
---|
| 5796 | # record expires at $stamp; decide if we need to keep the TTL and ignore
|
---|
| 5797 | # the stamp for a time or if we need to change the TTL to 0 and convert
|
---|
| 5798 | # $stamp to TAI64 so tinydns can use $stamp to autoadjust the TTL on the fly.
|
---|
| 5799 | # extra hack, optimally needs more knowledge of data export frequency
|
---|
| 5800 | # smack the idiot customer who insists on 0 TTLs; they can suck up and
|
---|
| 5801 | # deal with a 10-minute TTL. especially on scheduled changes. note this
|
---|
| 5802 | # should be (export freq * 2), but we don't know the actual export frequency.
|
---|
| 5803 | $ttl = 300 if $ttl == 0; #hack phtui
|
---|
| 5804 | my $ahead = (86400 < $ttl*2 ? 86400 : $ttl*2);
|
---|
| 5805 | if ((time() + $ahead) < $stamp) {
|
---|
| 5806 | # more than 2x TTL OR more than one day (whichever is less) from expiry time; publish normal record
|
---|
| 5807 | $stamp = '';
|
---|
| 5808 | } else {
|
---|
| 5809 | # less than 2x TTL from expiry time, let tinydns take over TTL management and publish the TAI64 stamp.
|
---|
| 5810 | $ttl = 0;
|
---|
| 5811 | $stamp = unixtai64($stamp);
|
---|
| 5812 | $stamp =~ s/\@//;
|
---|
| 5813 | }
|
---|
| 5814 | } else {
|
---|
| 5815 | # record is "active after"; convert epoch from database to TAI64, publish, and collect $200.
|
---|
| 5816 | $stamp = unixtai64($stamp);
|
---|
| 5817 | $stamp =~ s/\@//;
|
---|
| 5818 | }
|
---|
| 5819 | } else {
|
---|
| 5820 | # flag for active timestamp is false; don't actually put a timestamp in the output
|
---|
| 5821 | $stamp = '';
|
---|
| 5822 | }
|
---|
| 5823 |
|
---|
| 5824 | # support tinydns' auto-TTL
|
---|
| 5825 | $ttl = '' if $ttl == -1;
|
---|
| 5826 | # these are WAY FREAKING HIGH - higher even than most TLD registry TTLs!
|
---|
| 5827 | # NS 259200 => 3d
|
---|
| 5828 | # all others 86400 => 1d
|
---|
| 5829 |
|
---|
[531] | 5830 | if ($revrec eq 'y') {
|
---|
| 5831 | $val = $zone if $val eq '@';
|
---|
| 5832 | } else {
|
---|
| 5833 | $host = $zone if $host eq '@';
|
---|
| 5834 | }
|
---|
| 5835 |
|
---|
[329] | 5836 | ## Convert a bare number into an octal-coded pair of octets.
|
---|
| 5837 | # Take optional arg to indicate a decimal or hex input. Defaults to hex.
|
---|
| 5838 | sub octalize {
|
---|
| 5839 | my $tmp = shift;
|
---|
| 5840 | my $srctype = shift || 'h'; # default assumes hex string
|
---|
| 5841 | $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
|
---|
| 5842 | $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
|
---|
| 5843 | my @o = ($tmp =~ /^(..)(..)$/); # split into octets
|
---|
[656] | 5844 | return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);
|
---|
[329] | 5845 | }
|
---|
| 5846 |
|
---|
[637] | 5847 | # Utility sub-sub for reverse records; with "any-record-in-any-zone"
|
---|
| 5848 | # we may need to do extra processing on $val to make it publishable.
|
---|
| 5849 | sub __revswap {
|
---|
| 5850 | my $host = shift;
|
---|
| 5851 | my $val = shift;
|
---|
| 5852 | return ($val, $host) if $val =~ /\.arpa/;
|
---|
| 5853 | $val = new NetAddr::IP $val;
|
---|
| 5854 | my $newval = _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 5855 | return ($newval, $host);
|
---|
| 5856 | }
|
---|
| 5857 |
|
---|
[339] | 5858 | ## WARNING: This works to export even the whole Internet's worth of IP space...
|
---|
| 5859 | ## if you have the disk/RAM to handle the dataset, and you call this sub based on /16-sized chunks
|
---|
| 5860 | ## A /16 took ~3 seconds with a handful of separate records; adding a /8 pushed export time out to ~13m:40s
|
---|
| 5861 | ## 0/0 is estimated to take ~54 hours and ~256G of disk
|
---|
| 5862 | ## RAM usage depends on how many non-template entries you have in the set.
|
---|
| 5863 | ## This should probably be done on record addition rather than export; large blocks may need to be done in a
|
---|
| 5864 | ## forked process
|
---|
| 5865 | sub __publish_subnet {
|
---|
[644] | 5866 | my $obj = shift; # *sigh* need to pass in the DNSDB object so we can read a couple of options
|
---|
[339] | 5867 | my $sub = shift;
|
---|
| 5868 | my $recflags = shift;
|
---|
| 5869 | my $hpat = shift;
|
---|
| 5870 | my $fh = shift;
|
---|
| 5871 | my $ttl = shift;
|
---|
| 5872 | my $stamp = shift;
|
---|
| 5873 | my $loc = shift;
|
---|
[637] | 5874 | my $zone = new NetAddr::IP shift;
|
---|
[339] | 5875 | my $ptronly = shift || 0;
|
---|
| 5876 |
|
---|
[637] | 5877 | # do this conversion once, not (number-of-ips-in-subnet) times
|
---|
| 5878 | my $arpabase = _ZONE($zone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
| 5879 |
|
---|
[339] | 5880 | my $iplist = $sub->splitref(32);
|
---|
| 5881 | foreach (@$iplist) {
|
---|
| 5882 | my $ip = $_->addr;
|
---|
| 5883 | # make as if we split the non-octet-aligned block into octet-aligned blocks as with SOA
|
---|
[637] | 5884 | my $lastoct = (split /\./, $ip)[3];
|
---|
[644] | 5885 | next if $ip =~ /\.0$/ && $obj->{template_skip_0};
|
---|
| 5886 | next if $ip =~ /\.255$/ && $obj->{template_skip_255};
|
---|
[635] | 5887 | next if $$recflags{$ip}; # && $self->{skip_bcast_255}
|
---|
[339] | 5888 | $$recflags{$ip}++;
|
---|
[463] | 5889 | next if $hpat eq '%blank%'; # Allows blanking a subnet so no records are published.
|
---|
[339] | 5890 | my $rec = $hpat; # start fresh with the template for each IP
|
---|
[637] | 5891 | ##fixme: there really isn't a good way to handle sub-/24 zones here. This way at least
|
---|
| 5892 | # seems less bad than some alternatives.
|
---|
[339] | 5893 | _template4_expand(\$rec, $ip);
|
---|
[637] | 5894 | if ($ptronly || $zone->masklen > 24) {
|
---|
| 5895 | print $fh "^$lastoct.$arpabase:$rec:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 5896 | if (!$ptronly) {
|
---|
| 5897 | # print a separate A record. Arguably we could use an = record here instead.
|
---|
| 5898 | print $fh "+$rec:$ip:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 5899 | }
|
---|
| 5900 | } else {
|
---|
| 5901 | print $fh "=$rec:$ip:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 5902 | }
|
---|
[339] | 5903 | }
|
---|
| 5904 | }
|
---|
| 5905 |
|
---|
[636] | 5906 | ## And now the meat.
|
---|
| 5907 |
|
---|
[103] | 5908 | ##fixme? append . to all host/val hostnames
|
---|
[637] | 5909 | #print "debug: rawdata: $host $typemap{$type} $val\n";
|
---|
[103] | 5910 |
|
---|
[636] | 5911 | if ($typemap{$type} eq 'SOA') {
|
---|
| 5912 | # host contains pri-ns:responsible
|
---|
| 5913 | # val is abused to contain refresh:retry:expire:minttl
|
---|
[103] | 5914 | ##fixme: "manual" serial vs tinydns-autoserial
|
---|
[636] | 5915 | # let's be explicit about abusing $host and $val
|
---|
| 5916 | my ($email, $primary) = (split /:/, $host)[0,1];
|
---|
| 5917 | my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
|
---|
| 5918 | if ($revrec eq 'y') {
|
---|
[337] | 5919 | ##fixme: have to publish SOA records for each v4 /24 in sub-/16, and each /16 in sub-/8
|
---|
| 5920 | # what about v6?
|
---|
| 5921 | # -> only need SOA for local chunks offset from reverse delegation boundaries, so v6 is fine
|
---|
[636] | 5922 | # anyone who says they need sub-nibble v6 delegations, at this time, needs their head examined.
|
---|
| 5923 | $zone = NetAddr::IP->new($zone);
|
---|
| 5924 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
| 5925 | if (!$zone->{isv6} && ($zone->masklen < 24) && ($zone->masklen % 8 != 0)) {
|
---|
| 5926 | foreach my $szone ($zone->split($zone->masklen + (8 - $zone->masklen % 8))) {
|
---|
| 5927 | $szone = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
| 5928 | print $datafile "Z$szone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n"
|
---|
| 5929 | or die $!;
|
---|
| 5930 | }
|
---|
| 5931 | return; # skips "default" bits just below
|
---|
| 5932 | }
|
---|
| 5933 | $zone = _ZONE($zone, 'ZONE', 'r', '.').($zone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 5934 | }
|
---|
| 5935 | print $datafile "Z$zone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n"
|
---|
| 5936 | or die $!;
|
---|
[103] | 5937 |
|
---|
[636] | 5938 | } elsif ($typemap{$type} eq 'A') {
|
---|
[103] | 5939 |
|
---|
[637] | 5940 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
[636] | 5941 | print $datafile "+$host:$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
[103] | 5942 |
|
---|
[636] | 5943 | } elsif ($typemap{$type} eq 'NS') {
|
---|
[103] | 5944 |
|
---|
[636] | 5945 | if ($revrec eq 'y') {
|
---|
| 5946 | $val = NetAddr::IP->new($val);
|
---|
| 5947 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
| 5948 | if (!$val->{isv6} && ($val->masklen < 24) && ($val->masklen % 8 != 0)) {
|
---|
| 5949 | foreach my $szone ($val->split($val->masklen + (8 - $val->masklen % 8))) {
|
---|
| 5950 | my $szone2 = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
| 5951 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
| 5952 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 5953 | $$recflags{$szone2} = $val->masklen;
|
---|
| 5954 | }
|
---|
| 5955 | } elsif ($val->{isv6} && ($val->masklen < 64) && ($val->masklen % 4 !=0)) {
|
---|
| 5956 | foreach my $szone ($val->split($val->masklen + (4 - $val->masklen % 4))) {
|
---|
| 5957 | my $szone2 = _ZONE($szone, 'ZONE.ip6.arpa', 'r', '.');
|
---|
| 5958 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
| 5959 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 5960 | $$recflags{$szone2} = $val->masklen;
|
---|
| 5961 | }
|
---|
| 5962 | } else {
|
---|
| 5963 | my $val2 = _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 5964 | print $datafile "\&$val2"."::$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 5965 | $$recflags{$val2} = $val->masklen;
|
---|
| 5966 | }
|
---|
| 5967 | } else {
|
---|
| 5968 | print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 5969 | }
|
---|
[103] | 5970 |
|
---|
[636] | 5971 | } elsif ($typemap{$type} eq 'AAAA') {
|
---|
[103] | 5972 |
|
---|
[637] | 5973 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
[636] | 5974 | my $altgrp = 0;
|
---|
| 5975 | my @altconv;
|
---|
| 5976 | # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
|
---|
| 5977 | foreach (split /:/, $val) {
|
---|
| 5978 | if (/^$/) {
|
---|
| 5979 | # flag blank entry; this is a series of 0's of (currently) unknown length
|
---|
| 5980 | $altconv[$altgrp++] = 's';
|
---|
| 5981 | } else {
|
---|
| 5982 | # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
|
---|
| 5983 | $altconv[$altgrp++] = octalize($_)
|
---|
| 5984 | }
|
---|
| 5985 | }
|
---|
| 5986 | my $prefix = ":$host:28:";
|
---|
| 5987 | foreach my $octet (@altconv) {
|
---|
| 5988 | # if not 's', output
|
---|
| 5989 | $prefix .= $octet unless $octet =~ /^s$/;
|
---|
| 5990 | # if 's', output (9-array length)x literal '\000\000'
|
---|
| 5991 | $prefix .= '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
|
---|
| 5992 | }
|
---|
| 5993 | print $datafile "$prefix:$ttl:$stamp:$loc\n" or die $!;
|
---|
[103] | 5994 |
|
---|
[636] | 5995 | } elsif ($typemap{$type} eq 'MX') {
|
---|
[103] | 5996 |
|
---|
[637] | 5997 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
[636] | 5998 | print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n" or die $!;
|
---|
[103] | 5999 |
|
---|
[636] | 6000 | } elsif ($typemap{$type} eq 'TXT') {
|
---|
[103] | 6001 |
|
---|
[637] | 6002 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
[103] | 6003 | ##fixme: split v-e-r-y long TXT strings? will need to do so for BIND export, at least
|
---|
[637] | 6004 | $val =~ s/:/\\072/g; # may need to replace other symbols
|
---|
| 6005 | print $datafile "'$host:$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
[103] | 6006 |
|
---|
| 6007 | # by-hand TXT
|
---|
| 6008 | #:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
|
---|
| 6009 | #@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
|
---|
| 6010 | #'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
|
---|
| 6011 |
|
---|
| 6012 | #txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
|
---|
| 6013 | #: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
|
---|
| 6014 |
|
---|
| 6015 | # very long TXT record as brought in by axfr-get
|
---|
| 6016 | # note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
|
---|
| 6017 | # also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
|
---|
| 6018 | #:longtxt.deepnet.cx:16:
|
---|
| 6019 | #\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
|
---|
| 6020 | #\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.
|
---|
| 6021 | #\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.
|
---|
| 6022 | #:3600
|
---|
| 6023 |
|
---|
[636] | 6024 | } elsif ($typemap{$type} eq 'CNAME') {
|
---|
[103] | 6025 |
|
---|
[637] | 6026 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
| 6027 | print $datafile "C$host:$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
[103] | 6028 |
|
---|
[636] | 6029 | } elsif ($typemap{$type} eq 'SRV') {
|
---|
[103] | 6030 |
|
---|
[637] | 6031 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
| 6032 |
|
---|
[636] | 6033 | # data is two-byte values for priority, weight, port, in that order,
|
---|
| 6034 | # followed by length/string data
|
---|
[103] | 6035 |
|
---|
[637] | 6036 | my $prefix = ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
|
---|
[103] | 6037 |
|
---|
[636] | 6038 | $val .= '.' if $val !~ /\.$/;
|
---|
| 6039 | foreach (split /\./, $val) {
|
---|
[637] | 6040 | $prefix .= sprintf "\\%0.3o%s", length($_), $_ or die $!;
|
---|
[636] | 6041 | }
|
---|
[637] | 6042 | print $datafile "$prefix\\000:$ttl:$stamp:$loc\n" or die $!;
|
---|
[103] | 6043 |
|
---|
[636] | 6044 | } elsif ($typemap{$type} eq 'RP') {
|
---|
[103] | 6045 |
|
---|
[637] | 6046 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
[636] | 6047 | # RP consists of two mostly free-form strings.
|
---|
| 6048 | # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
|
---|
| 6049 | # The second is the "hostname" of a TXT record with more info.
|
---|
| 6050 | my $prefix = ":$host:17:";
|
---|
| 6051 | my ($who,$what) = split /\s/, $val;
|
---|
| 6052 | foreach (split /\./, $who) {
|
---|
| 6053 | $prefix .= sprintf "\\%0.3o%s", length($_), $_;
|
---|
| 6054 | }
|
---|
| 6055 | $prefix .= '\000';
|
---|
| 6056 | foreach (split /\./, $what) {
|
---|
| 6057 | $prefix .= sprintf "\\%0.3o%s", length($_), $_;
|
---|
| 6058 | }
|
---|
| 6059 | print $datafile "$prefix\\000:$ttl:$stamp:$loc\n" or die $!;
|
---|
[103] | 6060 |
|
---|
[636] | 6061 | } elsif ($typemap{$type} eq 'PTR') {
|
---|
[103] | 6062 |
|
---|
[636] | 6063 | $$recflags{$val}++;
|
---|
[637] | 6064 | if ($revrec eq 'y') {
|
---|
| 6065 |
|
---|
| 6066 | if ($val =~ /\.arpa$/) {
|
---|
| 6067 | # someone put in the formal .arpa name. humor them.
|
---|
| 6068 | print $datafile "^$val:$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6069 | } else {
|
---|
| 6070 | $zone = NetAddr::IP->new($zone);
|
---|
| 6071 | if (!$zone->{isv6} && $zone->masklen > 24) {
|
---|
| 6072 | # sub-octet v4 zone
|
---|
| 6073 | ($val) = ($val =~ /\.(\d+)$/);
|
---|
| 6074 | print $datafile "^$val."._ZONE($zone, 'ZONE', 'r', '.').'.in-addr.arpa'.
|
---|
| 6075 | ":$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6076 | } else {
|
---|
| 6077 | # not going to care about strange results if $val is not an IP value and is resolveable in DNS
|
---|
| 6078 | $val = NetAddr::IP->new($val);
|
---|
| 6079 | print $datafile "^".
|
---|
| 6080 | _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
| 6081 | ":$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6082 | }
|
---|
| 6083 | } # non-".arpa" $val
|
---|
| 6084 |
|
---|
[636] | 6085 | } else {
|
---|
[637] | 6086 | # PTRs in forward zones are less bizarre and insane than some other record types
|
---|
| 6087 | # in reverse zones... OTOH we can't validate them any which way, so we cross our
|
---|
| 6088 | # fingers and close our eyes and make it Someone Else's Problem.
|
---|
| 6089 | print $datafile "^$host:$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
[636] | 6090 | }
|
---|
[103] | 6091 |
|
---|
[636] | 6092 | } elsif ($type == 65280) { # A+PTR
|
---|
[334] | 6093 |
|
---|
[636] | 6094 | $$recflags{$val}++;
|
---|
| 6095 | print $datafile "=$host:$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
[334] | 6096 |
|
---|
[636] | 6097 | } elsif ($type == 65281) { # AAAA+PTR
|
---|
[333] | 6098 |
|
---|
[636] | 6099 | $$recflags{$val}++;
|
---|
| 6100 | # treat these as two separate records. since tinydns doesn't have
|
---|
| 6101 | # a native combined type, we have to create them separately anyway.
|
---|
| 6102 | # print both; a dangling record is harmless, and impossible via web
|
---|
| 6103 | # UI anyway
|
---|
[654] | 6104 | $self->_printrec_tiny($datafile,$recid,'n',$recflags, $self->domainName($self->_hostparent($host)),
|
---|
| 6105 | $host, 28, $val, $dist, $weight, $port, $ttl, $loc, $stamp);
|
---|
| 6106 | $self->_printrec_tiny($datafile, $recid, 'y', $recflags, $zone,
|
---|
| 6107 | $host, 12, $val, $dist, $weight, $port, $ttl, $loc, $stamp);
|
---|
| 6108 |
|
---|
[335] | 6109 | ##fixme: add a config flag to indicate use of the patch from http://www.fefe.de/dns/
|
---|
| 6110 | # type 6 is for AAAA+PTR, type 3 is for AAAA
|
---|
[333] | 6111 |
|
---|
[636] | 6112 | } elsif ($type == 65282) { # PTR template
|
---|
[335] | 6113 |
|
---|
[636] | 6114 | # only useful for v4 with standard DNS software, since this expands all
|
---|
| 6115 | # IPs in $zone (or possibly $val?) with autogenerated records
|
---|
| 6116 | $val = NetAddr::IP->new($val);
|
---|
| 6117 | return if $val->{isv6};
|
---|
[336] | 6118 |
|
---|
[636] | 6119 | if ($val->masklen <= 16) {
|
---|
| 6120 | foreach my $sub ($val->split(16)) {
|
---|
[644] | 6121 | $self->__publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, $zone, 1);
|
---|
[636] | 6122 | }
|
---|
| 6123 | } else {
|
---|
[644] | 6124 | $self->__publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, $zone, 1);
|
---|
[636] | 6125 | }
|
---|
[335] | 6126 |
|
---|
[636] | 6127 | } elsif ($type == 65283) { # A+PTR template
|
---|
[335] | 6128 |
|
---|
[636] | 6129 | $val = NetAddr::IP->new($val);
|
---|
| 6130 | # Just In Case. An A+PTR should be impossible to add to a v6 revzone via API.
|
---|
| 6131 | return if $val->{isv6};
|
---|
[339] | 6132 |
|
---|
[636] | 6133 | if ($val->masklen <= 16) {
|
---|
| 6134 | foreach my $sub ($val->split(16)) {
|
---|
[644] | 6135 | $self->__publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, $zone, 0);
|
---|
[636] | 6136 | }
|
---|
| 6137 | } else {
|
---|
[644] | 6138 | $self->__publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, $zone, 0);
|
---|
[636] | 6139 | }
|
---|
[335] | 6140 |
|
---|
[636] | 6141 | } elsif ($type == 65284) { # AAAA+PTR template
|
---|
| 6142 | # Stub for completeness. Could be exported to DNS software that supports
|
---|
| 6143 | # some degree of internal automagic in generic-record-creation
|
---|
| 6144 | # (eg http://search.cpan.org/dist/AllKnowingDNS/ )
|
---|
[333] | 6145 |
|
---|
[636] | 6146 | } elsif ($type == 65285) { # Delegation
|
---|
| 6147 | # This is intended for reverse zones, but may prove useful in forward zones.
|
---|
[345] | 6148 |
|
---|
[636] | 6149 | # All delegations need to create one or more NS records. The NS record handler knows what to do.
|
---|
[644] | 6150 | $self->_printrec_tiny($datafile,$recid,$revrec,$recflags,$zone,$host,$reverse_typemap{'NS'},
|
---|
[636] | 6151 | $val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
| 6152 | if ($revrec eq 'y') {
|
---|
| 6153 | # In the case of a sub-/24 v4 reverse delegation, we need to generate CNAMEs
|
---|
| 6154 | # to redirect all of the individual IP lookups as well.
|
---|
[637] | 6155 | # OR
|
---|
| 6156 | # create NS records for each IP
|
---|
[636] | 6157 | # Not sure how this would actually resolve if a /24 or larger was delegated
|
---|
| 6158 | # one way, and a sub-/24 in that >=/24 was delegated elsewhere...
|
---|
| 6159 | my $dblock = NetAddr::IP->new($val);
|
---|
| 6160 | if (!$dblock->{isv6} && $dblock->masklen > 24) {
|
---|
| 6161 | my @subs = $dblock->split;
|
---|
| 6162 | foreach (@subs) {
|
---|
| 6163 | next if $$recflags{"$_"};
|
---|
| 6164 | my ($oct) = ($_->addr =~ /(\d+)$/);
|
---|
| 6165 | print $datafile "C"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$oct.".
|
---|
| 6166 | _ZONE($dblock, 'ZONE.in-addr.arpa', 'r', '.').":$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6167 | $$recflags{"$_"}++;
|
---|
| 6168 | }
|
---|
| 6169 | }
|
---|
| 6170 | }
|
---|
[345] | 6171 |
|
---|
[364] | 6172 | ##
|
---|
| 6173 | ## Uncommon types. These will need better UI support Any Day Sometime Maybe(TM).
|
---|
| 6174 | ##
|
---|
| 6175 |
|
---|
[636] | 6176 | } elsif ($type == 44) { # SSHFP
|
---|
[637] | 6177 |
|
---|
| 6178 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
| 6179 |
|
---|
[636] | 6180 | my ($algo,$fpt,$fp) = split /\s+/, $val;
|
---|
[364] | 6181 |
|
---|
[636] | 6182 | my $rec = sprintf ":$host:44:\\%0.3o\\%0.3o", $algo, $fpt;
|
---|
| 6183 | while (my ($byte) = ($fp =~ /^(..)/) ) {
|
---|
| 6184 | $rec .= sprintf "\\%0.3o", hex($byte);
|
---|
| 6185 | $fp =~ s/^..//;
|
---|
| 6186 | }
|
---|
| 6187 | print $datafile "$rec:$ttl:$stamp:$loc\n" or die $!;
|
---|
[364] | 6188 |
|
---|
[636] | 6189 | } else {
|
---|
| 6190 | # raw record. we don't know what's in here, so we ASS-U-ME the user has
|
---|
| 6191 | # put it in correctly, since either the user is messing directly with the
|
---|
| 6192 | # database, or the record was imported via AXFR
|
---|
| 6193 | # <split by char>
|
---|
| 6194 | # convert anything not a-zA-Z0-9.- to octal coding
|
---|
[108] | 6195 |
|
---|
| 6196 | ##fixme: add flag to export "unknown" record types - note we'll probably end up
|
---|
| 6197 | # mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
|
---|
[636] | 6198 | #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
|
---|
[108] | 6199 |
|
---|
[636] | 6200 | } # record type if-else
|
---|
[103] | 6201 |
|
---|
[329] | 6202 | } # end _printrec_tiny()
|
---|
[103] | 6203 |
|
---|
| 6204 |
|
---|
[197] | 6205 | ## DNSDB::mailNotify()
|
---|
[283] | 6206 | # Sends notification mail to recipients regarding a DNSDB operation
|
---|
[197] | 6207 | sub mailNotify {
|
---|
[483] | 6208 | my $self = shift;
|
---|
| 6209 | my $dbh = $self->{dbh};
|
---|
[197] | 6210 | my ($subj,$message) = @_;
|
---|
| 6211 |
|
---|
[517] | 6212 | return if $self->{mailhost} eq 'smtp.example.com'; # do nothing if still using default SMTP host.
|
---|
[197] | 6213 |
|
---|
[517] | 6214 | my $mailer = Net::SMTP->new($self->{mailhost}, Hello => "dnsadmin.$self->{domain}");
|
---|
[197] | 6215 |
|
---|
[517] | 6216 | my $mailsender = ($self->{mailsender} ? $self->{mailsender} : $self->{mailnotify});
|
---|
[197] | 6217 |
|
---|
| 6218 | $mailer->mail($mailsender);
|
---|
[517] | 6219 | $mailer->to($self->{mailnotify});
|
---|
| 6220 | $mailer->data("From: \"$self->{mailname}\" <$mailsender>\n",
|
---|
| 6221 | "To: <$self->{mailnotify}>\n",
|
---|
[197] | 6222 | "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
|
---|
| 6223 | "Subject: $subj\n",
|
---|
[529] | 6224 | "X-Mailer: DNSAdmin v".$DNSDB::VERSION." Notify\n",
|
---|
[517] | 6225 | "Organization: $self->{orgname}\n",
|
---|
[197] | 6226 | "\n$message\n");
|
---|
| 6227 | $mailer->quit;
|
---|
| 6228 | }
|
---|
| 6229 |
|
---|
[2] | 6230 | # shut Perl up
|
---|
| 6231 | 1;
|
---|