[2] | 1 | # dns/trunk/DNSDB.pm
|
---|
| 2 | # Abstraction functions for DNS administration
|
---|
[262] | 3 | ##
|
---|
| 4 | # $Id: DNSDB.pm 755 2017-06-02 21:44:00Z kdeugau $
|
---|
[752] | 5 | # Copyright 2008-2017 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',
|
---|
[744] | 148 | record => 'record_id',
|
---|
[295] | 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
|
---|
[708] | 224 | # allow TXT records to be dealt with mostly automatically by DNS server?
|
---|
| 225 | autotxt => 1,
|
---|
[517] | 226 | );
|
---|
| 227 |
|
---|
| 228 | # Config file parse calls.
|
---|
| 229 | # If we are passed a blank argument for $args{configfile},
|
---|
| 230 | # we should NOT parse the default config file - we will
|
---|
| 231 | # rely on hardcoded defaults OR caller-specified values.
|
---|
| 232 | # If we are passed a non-blank argument, parse that file.
|
---|
| 233 | # If no config file is specified, parse the default one.
|
---|
| 234 | my %siteconfig;
|
---|
| 235 | if (defined($args{configfile})) {
|
---|
| 236 | if ($args{configfile}) {
|
---|
| 237 | return if !__cfgload($args{configfile}, \%siteconfig);
|
---|
| 238 | }
|
---|
| 239 | } else {
|
---|
| 240 | return if !__cfgload($defconfig{configfile}, \%siteconfig);
|
---|
[465] | 241 | }
|
---|
[517] | 242 |
|
---|
| 243 | # Assemble the object. Apply configuration hashes in order of precedence.
|
---|
| 244 | my $self = {
|
---|
| 245 | # Hardcoded defaults
|
---|
| 246 | %defconfig,
|
---|
| 247 | # Default config file OR caller-specified one, loaded above
|
---|
| 248 | %siteconfig,
|
---|
| 249 | # Caller-specified arguments
|
---|
| 250 | %args
|
---|
| 251 | };
|
---|
[465] | 252 | bless $self, $class;
|
---|
[517] | 253 |
|
---|
[524] | 254 | # Several settings are booleans. Handle multiple possible ways of setting them.
|
---|
[644] | 255 | for my $boolopt ('log_failures', 'force_refresh', 'lowercase', 'usecache',
|
---|
[708] | 256 | 'template_skip_0', 'template_skip_255', 'autotxt') {
|
---|
[524] | 257 | if ($self->{$boolopt} ne '1' && $self->{$boolopt} ne '0') {
|
---|
| 258 | # true/false, on/off, yes/no all valid.
|
---|
| 259 | if ($self->{$boolopt} =~ /^(?:true|false|t|f|on|off|yes|no)$/) {
|
---|
| 260 | if ($self->{$boolopt} =~ /(?:true|t|on|yes)/) {
|
---|
| 261 | $self->{$boolopt} = 1;
|
---|
| 262 | } else {
|
---|
| 263 | $self->{$boolopt} = 0;
|
---|
| 264 | }
|
---|
| 265 | } else {
|
---|
[583] | 266 | warn "Bad $boolopt setting $self->{$boolopt}, using default\n";
|
---|
| 267 | $self->{$boolopt} = $defconfig{$boolopt};
|
---|
[524] | 268 | }
|
---|
| 269 | }
|
---|
| 270 | }
|
---|
| 271 |
|
---|
[583] | 272 | # Enum-ish option(s)
|
---|
| 273 | if (!grep /$self->{showrev_arpa}/, ('none','zone','record','all')) {
|
---|
| 274 | warn "Bad showrev_arpa setting $self->{showrev_arpa}, using default\n";
|
---|
| 275 | $self->{showrev_arpa} = 'none';
|
---|
| 276 | }
|
---|
| 277 |
|
---|
[517] | 278 | # Try to connect to the DB, and initialize a number of handy globals.
|
---|
[465] | 279 | $self->{dbh} = connectDB($self->{dbname}, $self->{dbuser}, $self->{dbpass}, $self->{dbhost}) or return;
|
---|
| 280 | $self->initGlobals();
|
---|
| 281 |
|
---|
| 282 | return $self;
|
---|
| 283 | }
|
---|
| 284 |
|
---|
| 285 | sub DESTROY {
|
---|
| 286 | my $self = shift;
|
---|
[517] | 287 | $self->{dbh}->disconnect if $self->{dbh};
|
---|
[465] | 288 | }
|
---|
| 289 |
|
---|
[495] | 290 | sub errstr { $DNSDB::errstr; }
|
---|
| 291 |
|
---|
[465] | 292 | ##
|
---|
[225] | 293 | ## utility functions
|
---|
[281] | 294 | ##
|
---|
| 295 |
|
---|
| 296 | ## DNSDB::_rectable()
|
---|
[224] | 297 | # Takes default+rdns flags, returns appropriate table name
|
---|
| 298 | sub _rectable {
|
---|
| 299 | my $def = shift;
|
---|
| 300 | my $rev = shift;
|
---|
| 301 |
|
---|
| 302 | return 'records' if $def ne 'y';
|
---|
| 303 | return 'default_records' if $rev ne 'y';
|
---|
| 304 | return 'default_rev_records';
|
---|
| 305 | } # end _rectable()
|
---|
| 306 |
|
---|
[281] | 307 | ## DNSDB::_recparent()
|
---|
[224] | 308 | # Takes default+rdns flags, returns appropriate parent-id column name
|
---|
| 309 | sub _recparent {
|
---|
| 310 | my $def = shift;
|
---|
| 311 | my $rev = shift;
|
---|
| 312 |
|
---|
| 313 | return 'group_id' if $def eq 'y';
|
---|
| 314 | return 'rdns_id' if $rev eq 'y';
|
---|
| 315 | return 'domain_id';
|
---|
| 316 | } # end _recparent()
|
---|
| 317 |
|
---|
[281] | 318 | ## DNSDB::_ipparent()
|
---|
[226] | 319 | # Check an IP to be added in a reverse zone to see if it's really in the requested parent.
|
---|
[466] | 320 | # Takes default and reverse flags, IP (fragment) to check, parent zone ID,
|
---|
[226] | 321 | # and a reference to a NetAddr::IP object (also used to pass back a fully-reconstructed IP for
|
---|
| 322 | # database insertion)
|
---|
| 323 | sub _ipparent {
|
---|
[466] | 324 | my $self = shift;
|
---|
| 325 | my $dbh = $self->{dbh};
|
---|
[226] | 326 | my $defrec = shift;
|
---|
| 327 | my $revrec = shift;
|
---|
| 328 | my $val = shift;
|
---|
| 329 | my $id = shift;
|
---|
| 330 | my $addr = shift;
|
---|
[224] | 331 |
|
---|
[232] | 332 | return if $revrec ne 'y'; # this sub not useful in forward zones
|
---|
| 333 |
|
---|
| 334 | $$addr = NetAddr::IP->new($$val); #necessary?
|
---|
| 335 |
|
---|
[226] | 336 | # subsub to split, reverse, and overlay an IP fragment on a netblock
|
---|
| 337 | sub __rev_overlay {
|
---|
| 338 | my $splitme = shift; # ':' or '.', m'lud?
|
---|
| 339 | my $parnet = shift;
|
---|
| 340 | my $val = shift;
|
---|
| 341 | my $addr = shift;
|
---|
| 342 |
|
---|
| 343 | my $joinme = $splitme;
|
---|
| 344 | $splitme = '\.' if $splitme eq '.';
|
---|
[232] | 345 | my @working = reverse(split($splitme, $parnet->addr));
|
---|
| 346 | my @parts = reverse(split($splitme, $$val));
|
---|
[226] | 347 | for (my $i = 0; $i <= $#parts; $i++) {
|
---|
| 348 | $working[$i] = $parts[$i];
|
---|
| 349 | }
|
---|
[232] | 350 | my $checkme = NetAddr::IP->new(join($joinme, reverse(@working))) or return 0;
|
---|
| 351 | return 0 unless $checkme->within($parnet);
|
---|
[226] | 352 | $$addr = $checkme; # force "correct" IP to be recorded.
|
---|
| 353 | return 1;
|
---|
| 354 | }
|
---|
| 355 |
|
---|
| 356 | my ($parstr) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id = ?", undef, ($id));
|
---|
| 357 | my $parnet = NetAddr::IP->new($parstr);
|
---|
| 358 |
|
---|
| 359 | # Fail early on v6-in-v4 or v4-in-v6. We're not accepting these ATM.
|
---|
[232] | 360 | return 0 if $parnet->addr =~ /\./ && $$val =~ /:/;
|
---|
| 361 | return 0 if $parnet->addr =~ /:/ && $$val =~ /\./;
|
---|
[226] | 362 |
|
---|
[340] | 363 | if ($$addr && ($$val =~ /^[\da-fA-F][\da-fA-F:]+[\da-fA-F]$/ || $$val =~ m|/\d+$|)) {
|
---|
| 364 | # the only case where NetAddr::IP's acceptance of legitimate IPs is "correct" is for a proper IPv6 address,
|
---|
| 365 | # or a netblock (only expected on templates)
|
---|
[232] | 366 | # the rest we have to restructure before fiddling. *sigh*
|
---|
| 367 | return 1 if $$addr->within($parnet);
|
---|
| 368 | } else {
|
---|
[340] | 369 | # We don't have a complete IP in $$val (yet)... unless we have a netblock
|
---|
[232] | 370 | if ($parnet->addr =~ /:/) {
|
---|
| 371 | $$val =~ s/^:+//; # gotta strip'em all...
|
---|
[226] | 372 | return __rev_overlay(':', $parnet, $val, $addr);
|
---|
| 373 | }
|
---|
[232] | 374 | if ($parnet->addr =~ /\./) {
|
---|
| 375 | $$val =~ s/^\.+//;
|
---|
| 376 | return __rev_overlay('.', $parnet, $val, $addr);
|
---|
| 377 | }
|
---|
[226] | 378 | # should be impossible to get here...
|
---|
| 379 | }
|
---|
| 380 | # ... and here.
|
---|
| 381 | # can't do nuttin' in forward zones
|
---|
| 382 | } # end _ipparent()
|
---|
| 383 |
|
---|
[609] | 384 | ## DNSDB::_maybeip()
|
---|
| 385 | # Wrapper for quick "does this look like an IP address?" regex, so we don't make dumb copy-paste mistakes
|
---|
| 386 | sub _maybeip {
|
---|
| 387 | my $izzit = shift; # reference
|
---|
| 388 | return 1 if $$izzit =~ m,^(?:[\d\./]+|[0-9a-fA-F:/]+)$,;
|
---|
| 389 | }
|
---|
| 390 |
|
---|
[610] | 391 | ## DNSDB::_inrev()
|
---|
| 392 | # Check if a given "hostname" is within a given reverse zone
|
---|
| 393 | # Takes a reference to the "hostname" and the reverse zone CIDR as a NetAddr::IP
|
---|
| 394 | # Returns true/false. Sets $errstr on errors.
|
---|
| 395 | sub _inrev {
|
---|
| 396 | my $self = shift;
|
---|
| 397 | my $dbh = $self->{dbh};
|
---|
| 398 | # References, since we might munge them
|
---|
| 399 | my $fq = shift;
|
---|
| 400 | my $zone = shift;
|
---|
| 401 |
|
---|
| 402 | # set default error
|
---|
| 403 | $errstr = "$$fq not within $zone";
|
---|
| 404 |
|
---|
| 405 | # Unlike forward zones, we will not coerce the data into the reverse zone - an A record
|
---|
| 406 | # in a reverse zone is already silly enough without appending a mess of 1.2.3.in-addr.arpa
|
---|
| 407 | # (or worse, 1.2.3.4.5.6.7.8.ip6.arpa) on the end of the nominal "hostname".
|
---|
| 408 | # We're also going to allow the "hostname" to be stored as .arpa or IP, because of
|
---|
| 409 | # non-IP FQDNs in .arpa
|
---|
| 410 | if ($$fq =~ /\.arpa$/) {
|
---|
| 411 | # "FQDN" could be any syntactically legitimate string, but it must be within the formal
|
---|
| 412 | # .arpa zone. Note we're not validating these for correct reverse-IP values.
|
---|
| 413 | # yes, we really need the v6 branch on the end here.
|
---|
| 414 | $zone = _ZONE($zone, 'ZONE', 'r', '.').($zone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 415 | return unless $$fq =~ /$zone$/;
|
---|
| 416 | } else {
|
---|
| 417 | # in most cases we should be getting a real IP as the "FQDN" to test
|
---|
| 418 | my $addr = new NetAddr::IP $$fq if _maybeip($fq);
|
---|
| 419 |
|
---|
| 420 | # "FQDN" should be a valid IP address. Normalize formatting if so.
|
---|
| 421 | if (!$addr) {
|
---|
| 422 | $errstr = "$$fq is not a valid IP address";
|
---|
| 423 | return;
|
---|
| 424 | }
|
---|
| 425 | return if !$zone->contains($addr);
|
---|
| 426 | ($$fq = $addr) =~ s{/(?:32|128)$}{};
|
---|
| 427 | }
|
---|
| 428 | return 1;
|
---|
| 429 | } # end _inrev()
|
---|
| 430 |
|
---|
[281] | 431 | ## DNSDB::_hostparent()
|
---|
[232] | 432 | # A little different than _ipparent above; this tries to *find* the parent zone of a hostname
|
---|
[466] | 433 | # Takes a hostname.
|
---|
[281] | 434 | # Returns the domain ID of the parent domain if one was found.
|
---|
[232] | 435 | sub _hostparent {
|
---|
[466] | 436 | my $self = shift;
|
---|
| 437 | my $dbh = $self->{dbh};
|
---|
[232] | 438 | my $hname = shift;
|
---|
[347] | 439 |
|
---|
| 440 | $hname =~ s/^\*\.//; # this should be impossible to find in the domains table.
|
---|
[232] | 441 | my @hostbits = split /\./, $hname;
|
---|
[349] | 442 | my $sth = $dbh->prepare("SELECT count(*),domain_id FROM domains WHERE lower(domain) = lower(?) GROUP BY domain_id");
|
---|
[232] | 443 | foreach (@hostbits) {
|
---|
| 444 | $sth->execute($hname);
|
---|
| 445 | my ($found, $parid) = $sth->fetchrow_array;
|
---|
| 446 | if ($found) {
|
---|
| 447 | return $parid;
|
---|
| 448 | }
|
---|
| 449 | $hname =~ s/^$_\.//;
|
---|
| 450 | }
|
---|
| 451 | } # end _hostparent()
|
---|
[228] | 452 |
|
---|
[281] | 453 | ## DNSDB::_log()
|
---|
| 454 | # Log an action
|
---|
[466] | 455 | # Takes a log entry hash containing at least:
|
---|
[282] | 456 | # group_id, log entry
|
---|
[281] | 457 | # and optionally one or more of:
|
---|
[744] | 458 | # domain_id, rdns_id, logparent
|
---|
[282] | 459 | # The %userdata hash provides the user ID, username, and fullname
|
---|
[744] | 460 | # Returns the log entry ID, mainly for use in bulk operations to allow a "parent" log entry
|
---|
| 461 | # and a set of child entries (eg, domain add and the individual default-record-copy entries)
|
---|
[281] | 462 | sub _log {
|
---|
[466] | 463 | my $self = shift;
|
---|
| 464 | my $dbh = $self->{dbh};
|
---|
[281] | 465 |
|
---|
| 466 | my %args = @_;
|
---|
| 467 |
|
---|
| 468 | $args{rdns_id} = 0 if !$args{rdns_id};
|
---|
| 469 | $args{domain_id} = 0 if !$args{domain_id};
|
---|
[744] | 470 | $args{logparent} = 0 if !$args{logparent};
|
---|
[281] | 471 |
|
---|
| 472 | ##fixme: farm out the actual logging to different subs for file, syslog, internal, etc based on config
|
---|
[517] | 473 | # if ($self->{log_channel} eq 'sql') {
|
---|
[744] | 474 | $dbh->do("INSERT INTO log (domain_id,rdns_id,group_id,logparent,entry,user_id,email,name) ".
|
---|
| 475 | "VALUES (?,?,?,?,?,?,?,?)",
|
---|
[281] | 476 | undef,
|
---|
[744] | 477 | ($args{domain_id}, $args{rdns_id}, $args{group_id}, $args{logparent}, $args{entry},
|
---|
[488] | 478 | $self->{loguserid}, $self->{logusername}, $self->{logfullname}) );
|
---|
[744] | 479 |
|
---|
| 480 | my ($log_id) = $dbh->selectrow_array("SELECT currval('log_log_id_seq')");
|
---|
| 481 | return $log_id;
|
---|
| 482 |
|
---|
[517] | 483 | # } elsif ($self->{log_channel} eq 'file') {
|
---|
| 484 | # } elsif ($self->{log_channel} eq 'syslog') {
|
---|
[281] | 485 | # }
|
---|
| 486 | } # end _log
|
---|
| 487 |
|
---|
| 488 |
|
---|
[224] | 489 | ##
|
---|
[228] | 490 | ## Record validation subs.
|
---|
| 491 | ##
|
---|
| 492 |
|
---|
[281] | 493 | ## All of these subs take substantially the same arguments:
|
---|
| 494 | # a hash containing at least the following keys:
|
---|
| 495 | # - defrec (default/live flag)
|
---|
| 496 | # - revrec (forward/reverse flag)
|
---|
| 497 | # - id (parent entity ID)
|
---|
| 498 | # - host (hostname)
|
---|
| 499 | # - rectype
|
---|
| 500 | # - val (IP, hostname [CNAME/MX/SRV] or text)
|
---|
| 501 | # - addr (NetAddr::IP object from val. May be undef.)
|
---|
| 502 | # MX and SRV record validation also expect distance, and SRV records expect weight and port as well.
|
---|
| 503 | # host, rectype, and addr should be references as these may be modified in validation
|
---|
| 504 |
|
---|
[228] | 505 | # A record
|
---|
| 506 | sub _validate_1 {
|
---|
[467] | 507 | my $self = shift;
|
---|
| 508 | my $dbh = $self->{dbh};
|
---|
[229] | 509 |
|
---|
[230] | 510 | my %args = @_;
|
---|
[229] | 511 |
|
---|
[606] | 512 | # only for strict type restrictions
|
---|
| 513 | # return ('FAIL', 'Reverse zones cannot contain A records') if $args{revrec} eq 'y';
|
---|
[229] | 514 |
|
---|
[606] | 515 | if ($args{revrec} eq 'y') {
|
---|
| 516 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 517 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
[229] | 518 |
|
---|
[610] | 519 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
[606] | 520 |
|
---|
[611] | 521 | # ${$args{val}} is either a valid IP or a string ending with the .arpa zone name;
|
---|
| 522 | # now check if it's a well-formed FQDN
|
---|
[613] | 523 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
[612] | 524 | ${$args{val}} =~ /\.arpa$/;
|
---|
[611] | 525 |
|
---|
[606] | 526 | # Check IP is well-formed, and that it's a v4 address
|
---|
| 527 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
|
---|
| 528 | return ('FAIL',"A record must be a valid IPv4 address")
|
---|
[660] | 529 | unless ${$args{host}} =~ m{^\d+\.\d+\.\d+\.\d+(/\d+)?$};
|
---|
[606] | 530 | $args{addr} = new NetAddr::IP ${$args{host}};
|
---|
| 531 | return ('FAIL',"A record must be a valid IPv4 address")
|
---|
| 532 | unless $args{addr} && !$args{addr}->{isv6};
|
---|
| 533 | # coerce IP/value to normalized form for storage
|
---|
| 534 | ${$args{host}} = $args{addr}->addr;
|
---|
| 535 |
|
---|
| 536 | # I'm just going to ignore the utterly barmy idea of an A record in the *default*
|
---|
| 537 | # records for a reverse zone; it's bad enough to find one in funky legacy data.
|
---|
| 538 |
|
---|
| 539 | } else {
|
---|
| 540 | # revrec ne 'y'
|
---|
| 541 |
|
---|
| 542 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 543 | # or the intended parent domain for live records.
|
---|
| 544 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[657] | 545 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i);
|
---|
[606] | 546 |
|
---|
[620] | 547 | # Check if it's a proper formal .arpa name for an IP, and renormalize it to the IP
|
---|
| 548 | # value if so. Done mainly for symmetry with PTR/A+PTR, and saves a conversion on export.
|
---|
| 549 | if (${$args{val}} =~ /\.arpa$/) {
|
---|
| 550 | my ($code,$tmp) = _zone2cidr(${$args{val}});
|
---|
| 551 | if ($code ne 'FAIL') {
|
---|
| 552 | ${$args{val}} = $tmp->addr;
|
---|
| 553 | $args{addr} = $tmp;
|
---|
| 554 | }
|
---|
| 555 | }
|
---|
[606] | 556 | # Check IP is well-formed, and that it's a v4 address
|
---|
| 557 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
|
---|
| 558 | return ('FAIL',"A record must be a valid IPv4 address")
|
---|
[234] | 559 | unless ${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/;
|
---|
[629] | 560 | $args{addr} = new NetAddr::IP ${$args{val}};
|
---|
[606] | 561 | return ('FAIL',"A record must be a valid IPv4 address")
|
---|
[230] | 562 | unless $args{addr} && !$args{addr}->{isv6};
|
---|
[606] | 563 | # coerce IP/value to normalized form for storage
|
---|
| 564 | ${$args{val}} = $args{addr}->addr;
|
---|
| 565 | }
|
---|
[229] | 566 |
|
---|
[228] | 567 | return ('OK','OK');
|
---|
| 568 | } # done A record
|
---|
| 569 |
|
---|
| 570 | # NS record
|
---|
| 571 | sub _validate_2 {
|
---|
[467] | 572 | my $self = shift;
|
---|
| 573 | my $dbh = $self->{dbh};
|
---|
[230] | 574 |
|
---|
| 575 | my %args = @_;
|
---|
| 576 |
|
---|
[616] | 577 | # NS target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 578 | if ($args{revrec} eq 'y') {
|
---|
| 579 | return ('FAIL', "NS records cannot point directly to an IP address")
|
---|
| 580 | if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
| 581 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
| 582 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 583 | } else {
|
---|
| 584 | return ('FAIL', "NS records cannot point directly to an IP address")
|
---|
| 585 | if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
| 586 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
| 587 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 588 | }
|
---|
| 589 |
|
---|
[328] | 590 | # Check that the target of the record is within the parent.
|
---|
| 591 | if ($args{defrec} eq 'n') {
|
---|
| 592 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
| 593 | if ($args{revrec} eq 'y') {
|
---|
[616] | 594 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 595 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
| 596 |
|
---|
| 597 | # Note the NS record may or may not be for the zone itself, it may be a pointer for a subzone
|
---|
| 598 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
| 599 |
|
---|
| 600 | # ${$args{val}} is either a valid IP or a string ending with the .arpa zone name;
|
---|
| 601 | # now check if it's a well-formed FQDN
|
---|
| 602 | ##enhance or ##fixme
|
---|
| 603 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design
|
---|
| 604 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
| 605 | ${$args{val}} =~ /\.arpa$/;
|
---|
[328] | 606 | } else {
|
---|
[616] | 607 | # Forcibly append the domain name if the hostname being added does not end with the current domain name
|
---|
[467] | 608 | my $pname = $self->domainName($args{id});
|
---|
[657] | 609 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i);
|
---|
[328] | 610 | }
|
---|
[230] | 611 | } else {
|
---|
[616] | 612 | # Default reverse NS records should always refer to the implied parent.
|
---|
| 613 | if ($args{revrec} eq 'y') {
|
---|
| 614 | ${$args{val}} = 'ZONE';
|
---|
| 615 | } else {
|
---|
| 616 | ${$args{host}} = 'DOMAIN';
|
---|
| 617 | }
|
---|
[230] | 618 | }
|
---|
| 619 |
|
---|
[228] | 620 | return ('OK','OK');
|
---|
| 621 | } # done NS record
|
---|
| 622 |
|
---|
| 623 | # CNAME record
|
---|
| 624 | sub _validate_5 {
|
---|
[467] | 625 | my $self = shift;
|
---|
| 626 | my $dbh = $self->{dbh};
|
---|
[230] | 627 |
|
---|
| 628 | my %args = @_;
|
---|
| 629 |
|
---|
[618] | 630 | # CNAMEs in reverse zones shouldn't be handled manually, they should be generated on
|
---|
| 631 | # export by use of the "delegation" type. For the masochistic, and those importing
|
---|
| 632 | # legacy data from $deity-knows-where, we'll support them.
|
---|
[230] | 633 |
|
---|
[618] | 634 | if ($args{revrec} eq 'y') {
|
---|
| 635 | # CNAME target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 636 | return ('FAIL', "CNAME records cannot point directly to an IP address")
|
---|
| 637 | if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
[230] | 638 |
|
---|
[618] | 639 | if ($args{defrec} eq 'n') {
|
---|
| 640 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 641 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
| 642 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
[632] | 643 | # CNAMEs can not be used for parent nodes; just leaf nodes with no other record types
|
---|
| 644 | # note that this WILL probably miss some edge cases.
|
---|
| 645 | if (${$args{val}} =~ /^[\d.\/]+$/) {
|
---|
| 646 | # convert IP "hostname" to .arpa
|
---|
| 647 | my $tmphn = _ZONE(NetAddr::IP->new(${$args{val}}), 'ZONE', 'r', '.');
|
---|
| 648 | my $tmpz = _ZONE($revzone, 'ZONE', 'r', '.');
|
---|
| 649 | return ('FAIL', "The bare zone may not be a CNAME") if $tmphn eq $tmpz;
|
---|
[656] | 650 | ##enhance: look up the target name and publish that instead on export
|
---|
[632] | 651 | }
|
---|
[618] | 652 | }
|
---|
| 653 |
|
---|
| 654 | ##enhance or ##fixme
|
---|
| 655 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design
|
---|
| 656 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
| 657 | ${$args{val}} =~ /\.arpa$/;
|
---|
| 658 |
|
---|
| 659 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
| 660 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 661 | } else {
|
---|
| 662 | # CNAME target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 663 | return ('FAIL', "CNAME records cannot point directly to an IP address")
|
---|
| 664 | if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
| 665 |
|
---|
[669] | 666 | # Make sure target is a well-formed hostname
|
---|
| 667 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 668 |
|
---|
[618] | 669 | # Forcibly append the domain name if the hostname being added does not end with the current domain name
|
---|
| 670 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[657] | 671 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/i;
|
---|
[618] | 672 |
|
---|
[632] | 673 | # CNAMEs can not be used for parent nodes; just leaf nodes with no other record types
|
---|
| 674 | # Enforce this for the zone name
|
---|
[653] | 675 | return ('FAIL', "The bare zone name may not be a CNAME") if ${$args{host}} eq $pname || ${$args{host}} =~ /^\@/;
|
---|
[632] | 676 |
|
---|
[618] | 677 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
| 678 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 679 | }
|
---|
| 680 |
|
---|
[228] | 681 | return ('OK','OK');
|
---|
| 682 | } # done CNAME record
|
---|
| 683 |
|
---|
| 684 | # SOA record
|
---|
| 685 | sub _validate_6 {
|
---|
[230] | 686 | # Smart monkeys won't stick their fingers in here; we have
|
---|
| 687 | # separate dedicated routines to deal with SOA records.
|
---|
[228] | 688 | return ('OK','OK');
|
---|
| 689 | } # done SOA record
|
---|
| 690 |
|
---|
| 691 | # PTR record
|
---|
| 692 | sub _validate_12 {
|
---|
[467] | 693 | my $self = shift;
|
---|
| 694 | my $dbh = $self->{dbh};
|
---|
[232] | 695 |
|
---|
| 696 | my %args = @_;
|
---|
[620] | 697 | my $warnflag = '';
|
---|
[232] | 698 |
|
---|
[620] | 699 | if ($args{defrec} eq 'y') {
|
---|
| 700 | if ($args{revrec} eq 'y') {
|
---|
| 701 | if (${$args{val}} =~ /^[\d.]+$/) {
|
---|
| 702 | # v4 or bare number
|
---|
| 703 | if (${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/) {
|
---|
| 704 | # probable full IP. pointless but harmless. validate/normalize.
|
---|
| 705 | my $tmp = NetAddr::IP->new(${$args{val}})->addr
|
---|
| 706 | or return ('FAIL', "${$args{val}} is not a valid IP address");
|
---|
| 707 | ${$args{val}} = $tmp;
|
---|
| 708 | $warnflag = "${$args{val}} will only be added to a small number of zones\n";
|
---|
| 709 | } elsif (${$args{val}} =~ /^\d+$/) {
|
---|
| 710 | # bare number. This can be expanded to either a v4 or v6 zone
|
---|
| 711 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
| 712 | } else {
|
---|
| 713 | # $deity-only-knows what kind of gibberish we've been given. Only usable as a formal .arpa name.
|
---|
| 714 | # Append ARPAZONE to be replaced with the formal .arpa zone name when converted to a live record.
|
---|
| 715 | ${$args{val}} =~ s/\.*$/.ARPAZONE/ unless ${$args{val}} =~ /ARPAZONE$/;
|
---|
| 716 | }
|
---|
| 717 | } elsif (${$args{val}} =~ /^[a-fA-F0-9:]+$/) {
|
---|
| 718 | # v6 or fragment; pray it's not complete gibberish
|
---|
| 719 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
[234] | 720 | } else {
|
---|
[620] | 721 | # $deity-only-knows what kind of gibberish we've been given. Only usable as a formal .arpa name.
|
---|
| 722 | # Append ARPAZONE to be replaced with the formal .arpa zone name when converted to a live record.
|
---|
| 723 | ${$args{val}} .= ".ARPAZONE" unless ${$args{val}} =~ /ARPAZONE$/;
|
---|
[234] | 724 | }
|
---|
[620] | 725 | } else {
|
---|
| 726 | return ('FAIL', "PTR records are not supported in default record sets for forward zones (domains)");
|
---|
[232] | 727 | }
|
---|
[620] | 728 | } else {
|
---|
| 729 | if ($args{revrec} eq 'y') {
|
---|
| 730 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 731 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
[232] | 732 |
|
---|
[620] | 733 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
[249] | 734 |
|
---|
[620] | 735 | if (${$args{val}} =~ /\.arpa$/) {
|
---|
| 736 | # Check that it's well-formed
|
---|
| 737 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 738 |
|
---|
| 739 | # Check if it's a proper formal .arpa name for an IP, and renormalize it to the IP
|
---|
| 740 | # value if so. I can't see why someone would voluntarily work with those instead of
|
---|
| 741 | # the natural IP values but what the hey.
|
---|
| 742 | my ($code,$tmp) = _zone2cidr(${$args{val}});
|
---|
| 743 | ${$args{val}} = $tmp->addr if $code ne 'FAIL';
|
---|
[272] | 744 | } else {
|
---|
[620] | 745 | # not a formal .arpa name, so it should be an IP value. Validate...
|
---|
| 746 | return ('FAIL', "${$args{val}} is not a valid IP value")
|
---|
| 747 | unless ${$args{val}} =~ /^(?:\d+\.\d+\.\d+\.\d+|[a-fA-F0-9:]+)$/;
|
---|
| 748 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
| 749 | or return ('FAIL', "IP/value looks like an IP address but isn't valid");
|
---|
| 750 | # ... and normalize.
|
---|
| 751 | ${$args{val}} = $args{addr}->addr;
|
---|
[272] | 752 | }
|
---|
[620] | 753 | # Validate PTR target for form.
|
---|
[677] | 754 | # %blank% skips the IP when expanding a template record
|
---|
| 755 | return ('FAIL', $errstr)
|
---|
| 756 | unless _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) ||
|
---|
| 757 | lc(${$args{host}}) eq '%blank%';
|
---|
[620] | 758 | } else { # revrec ne 'y'
|
---|
| 759 | # Fetch the domain and append if the passed hostname isn't within it.
|
---|
| 760 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[657] | 761 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i);
|
---|
[620] | 762 | # Validate hostname and target for form
|
---|
| 763 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 764 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
[249] | 765 | }
|
---|
[620] | 766 | }
|
---|
[272] | 767 |
|
---|
[620] | 768 | # Multiple PTR records do NOT generally do what most people believe they do,
|
---|
| 769 | # and tend to fail in the most awkward way possible. Check and warn.
|
---|
| 770 |
|
---|
| 771 | my $chkbase = ${$args{val}};;
|
---|
| 772 | my $hostcol = 'val'; # Reverse zone hostnames are stored "backwards"
|
---|
| 773 | if ($args{revrec} eq 'n') { # PTRs in forward zones should be rare.
|
---|
| 774 | $chkbase = ${$args{host}};
|
---|
| 775 | $hostcol = 'host';
|
---|
[232] | 776 | }
|
---|
[620] | 777 | my @checkvals = ($chkbase);
|
---|
| 778 | if ($chkbase =~ /,/) {
|
---|
| 779 | # push . and :: variants into checkvals if $chkbase has ,
|
---|
| 780 | my $tmp;
|
---|
| 781 | ($tmp = $chkbase) =~ s/,/./;
|
---|
| 782 | push @checkvals, $tmp;
|
---|
| 783 | ($tmp = $chkbase) =~ s/,/::/;
|
---|
| 784 | push @checkvals, $tmp;
|
---|
| 785 | }
|
---|
[232] | 786 |
|
---|
[620] | 787 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE $hostcol = ?");
|
---|
| 788 | foreach my $checkme (@checkvals) {
|
---|
| 789 | if ($args{update}) {
|
---|
| 790 | # $args{update} contains the ID of the record being updated. If the list of records that matches
|
---|
| 791 | # the new hostname specification doesn't include this, the change effectively adds a new PTR that's
|
---|
| 792 | # the same as one or more existing ones.
|
---|
| 793 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 794 | " WHERE val = ?", undef, ($checkme)) };
|
---|
| 795 | $warnflag .= "PTR record for $checkme already exists; adding another will probably not do what you want"
|
---|
| 796 | if @ptrs && (!grep /^$args{update}$/, @ptrs);
|
---|
| 797 | } else {
|
---|
| 798 | # New record. Always warn if a PTR exists
|
---|
[661] | 799 | # Don't warn when a matching A record exists tho
|
---|
[620] | 800 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
[661] | 801 | " WHERE $hostcol = ? AND (type=12 OR type=65280 OR type=65281)", undef, ($checkme));
|
---|
[620] | 802 | $warnflag .= "PTR record for $checkme already exists; adding another will probably not do what you want"
|
---|
| 803 | if $ptrcount;
|
---|
| 804 | }
|
---|
| 805 | }
|
---|
| 806 |
|
---|
| 807 | return ('WARN',$warnflag) if $warnflag;
|
---|
| 808 |
|
---|
[228] | 809 | return ('OK','OK');
|
---|
| 810 | } # done PTR record
|
---|
| 811 |
|
---|
| 812 | # MX record
|
---|
| 813 | sub _validate_15 {
|
---|
[467] | 814 | my $self = shift;
|
---|
| 815 | my $dbh = $self->{dbh};
|
---|
[230] | 816 |
|
---|
| 817 | my %args = @_;
|
---|
| 818 |
|
---|
[622] | 819 | # only for strict type restrictions
|
---|
| 820 | # return ('FAIL', 'Reverse zones cannot contain MX records') if $args{revrec} eq 'y';
|
---|
[230] | 821 |
|
---|
| 822 | return ('FAIL', "Distance is required for MX records") unless defined(${$args{dist}});
|
---|
| 823 | ${$args{dist}} =~ s/\s*//g;
|
---|
| 824 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
|
---|
| 825 |
|
---|
| 826 | ${$args{fields}} = "distance,";
|
---|
| 827 | push @{$args{vallist}}, ${$args{dist}};
|
---|
| 828 |
|
---|
[622] | 829 | if ($args{revrec} eq 'n') {
|
---|
| 830 | # MX target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 831 | return ('FAIL', "MX records cannot point directly to an IP address")
|
---|
| 832 | if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
[230] | 833 |
|
---|
[622] | 834 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 835 | # or the intended parent domain for live records.
|
---|
| 836 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[657] | 837 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i);
|
---|
[653] | 838 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
[622] | 839 | } else {
|
---|
| 840 | # MX target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 841 | return ('FAIL', "MX records cannot point directly to an IP address")
|
---|
[627] | 842 | if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
[273] | 843 |
|
---|
[622] | 844 | # MX records in reverse zones get stricter treatment. The UI bars adding them in
|
---|
| 845 | # reverse record sets, but we "need" to allow editing existing ones. And we'll allow
|
---|
| 846 | # editing them if some loon manually munges one into a default reverse record set.
|
---|
| 847 | if ($args{defrec} eq 'n') {
|
---|
| 848 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 849 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
| 850 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
| 851 | }
|
---|
| 852 |
|
---|
| 853 | ##enhance or ##fixme
|
---|
| 854 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design
|
---|
| 855 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
| 856 | ${$args{val}} =~ /\.arpa$/;
|
---|
| 857 |
|
---|
| 858 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
| 859 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 860 |
|
---|
| 861 | }
|
---|
| 862 |
|
---|
[228] | 863 | return ('OK','OK');
|
---|
| 864 | } # done MX record
|
---|
| 865 |
|
---|
| 866 | # TXT record
|
---|
| 867 | sub _validate_16 {
|
---|
[586] | 868 | my $self = shift;
|
---|
| 869 |
|
---|
| 870 | my %args = @_;
|
---|
| 871 |
|
---|
[623] | 872 | if ($args{revrec} eq 'n') {
|
---|
[586] | 873 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 874 | # or the intended parent domain for live records.
|
---|
| 875 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[657] | 876 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i);
|
---|
[623] | 877 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 878 | } else {
|
---|
| 879 | # We don't coerce reverse "hostnames" into the zone, mainly because we store most sane
|
---|
| 880 | # records as IP values, not .arpa names.
|
---|
| 881 | if ($args{defrec} eq 'n') {
|
---|
| 882 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 883 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
| 884 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
| 885 | }
|
---|
| 886 |
|
---|
| 887 | ##enhance or ##fixme
|
---|
| 888 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design
|
---|
| 889 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
| 890 | ${$args{val}} =~ /\.arpa$/;
|
---|
[586] | 891 | }
|
---|
| 892 |
|
---|
[231] | 893 | # Could arguably put a WARN return here on very long (>512) records
|
---|
[228] | 894 | return ('OK','OK');
|
---|
| 895 | } # done TXT record
|
---|
| 896 |
|
---|
| 897 | # RP record
|
---|
| 898 | sub _validate_17 {
|
---|
[623] | 899 | # Probably have to validate these separately some day. Call _validate_16() above since
|
---|
| 900 | # they're otherwise very similar
|
---|
| 901 | return _validate_16(@_);
|
---|
[228] | 902 | } # done RP record
|
---|
| 903 |
|
---|
| 904 | # AAAA record
|
---|
[626] | 905 | # Almost but not quite an exact duplicate of A record
|
---|
[228] | 906 | sub _validate_28 {
|
---|
[467] | 907 | my $self = shift;
|
---|
| 908 | my $dbh = $self->{dbh};
|
---|
[229] | 909 |
|
---|
[230] | 910 | my %args = @_;
|
---|
[229] | 911 |
|
---|
[626] | 912 | # only for strict type restrictions
|
---|
| 913 | # return ('FAIL', 'Reverse zones cannot contain AAAA records') if $args{revrec} eq 'y';
|
---|
[229] | 914 |
|
---|
[626] | 915 | if ($args{revrec} eq 'y') {
|
---|
| 916 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 917 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
[229] | 918 |
|
---|
[626] | 919 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
| 920 |
|
---|
| 921 | # ${$args{val}} is either a valid IP or a string ending with the .arpa zone name;
|
---|
| 922 | # now check if it's a well-formed FQDN
|
---|
| 923 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
| 924 | ${$args{val}} =~ /\.arpa$/;
|
---|
| 925 |
|
---|
| 926 | # Check IP is well-formed, and that it's a v4 address
|
---|
| 927 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
|
---|
| 928 | return ('FAIL',"AAAA record must be a valid IPv6 address")
|
---|
| 929 | unless ${$args{host}} =~ /^[a-fA-F0-9:]+$/;
|
---|
| 930 | $args{addr} = new NetAddr::IP ${$args{host}};
|
---|
| 931 | return ('FAIL',"AAAA record must be a valid IPv6 address")
|
---|
[230] | 932 | unless $args{addr} && $args{addr}->{isv6};
|
---|
[626] | 933 | # coerce IP/value to normalized form for storage
|
---|
| 934 | ${$args{host}} = $args{addr}->addr;
|
---|
[229] | 935 |
|
---|
[626] | 936 | # I'm just going to ignore the utterly barmy idea of an AAAA record in the *default*
|
---|
| 937 | # records for a reverse zone; it's bad enough to find one in funky legacy data.
|
---|
| 938 |
|
---|
| 939 | } else {
|
---|
| 940 | # revrec ne 'y'
|
---|
| 941 |
|
---|
| 942 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 943 | # or the intended parent domain for live records.
|
---|
| 944 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[657] | 945 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i);
|
---|
[626] | 946 |
|
---|
| 947 | # Check if it's a proper formal .arpa name for an IP, and renormalize it to the IP
|
---|
| 948 | # value if so. Done mainly for symmetry with PTR/AAAA+PTR, and saves a conversion on export.
|
---|
| 949 | if (${$args{val}} =~ /\.arpa$/) {
|
---|
| 950 | my ($code,$tmp) = _zone2cidr(${$args{val}});
|
---|
| 951 | if ($code ne 'FAIL') {
|
---|
| 952 | ${$args{val}} = $tmp->addr;
|
---|
| 953 | $args{addr} = $tmp;
|
---|
| 954 | }
|
---|
| 955 | }
|
---|
| 956 | # Check IP is well-formed, and that it's a v6 address
|
---|
| 957 | return ('FAIL',"AAAA record must be a valid IPv6 address")
|
---|
| 958 | unless ${$args{val}} =~ /^[a-fA-F0-9:]+$/;
|
---|
| 959 | $args{addr} = new NetAddr::IP ${$args{val}};
|
---|
| 960 | return ('FAIL',"AAAA record must be a valid IPv6 address")
|
---|
| 961 | unless $args{addr} && $args{addr}->{isv6};
|
---|
| 962 | # coerce IP/value to normalized form for storage
|
---|
| 963 | ${$args{val}} = $args{addr}->addr;
|
---|
| 964 | }
|
---|
| 965 |
|
---|
[228] | 966 | return ('OK','OK');
|
---|
| 967 | } # done AAAA record
|
---|
| 968 |
|
---|
| 969 | # SRV record
|
---|
| 970 | sub _validate_33 {
|
---|
[467] | 971 | my $self = shift;
|
---|
| 972 | my $dbh = $self->{dbh};
|
---|
[231] | 973 |
|
---|
| 974 | my %args = @_;
|
---|
| 975 |
|
---|
| 976 | # Not absolutely true but WTF use is an SRV record for a reverse zone?
|
---|
[656] | 977 | # return ('FAIL', 'Reverse zones cannot contain SRV records') if $args{revrec} eq 'y';
|
---|
[231] | 978 |
|
---|
[627] | 979 | # Key additional record parts. Always required.
|
---|
| 980 | return ('FAIL',"Distance, port and weight are required for SRV records")
|
---|
| 981 | unless defined(${$args{weight}}) && defined(${$args{port}}) && defined(${$args{dist}});
|
---|
[231] | 982 | ${$args{dist}} =~ s/\s*//g;
|
---|
| 983 | ${$args{weight}} =~ s/\s*//g;
|
---|
| 984 | ${$args{port}} =~ s/\s*//g;
|
---|
[627] | 985 | return ('FAIL',"Distance, port and weight are required, and must be numeric")
|
---|
[231] | 986 | unless ${$args{weight}} =~ /^\d+$/ && ${$args{port}} =~ /^\d+$/;
|
---|
| 987 |
|
---|
| 988 | ${$args{fields}} = "distance,weight,port,";
|
---|
| 989 | push @{$args{vallist}}, (${$args{dist}}, ${$args{weight}}, ${$args{port}});
|
---|
| 990 |
|
---|
[627] | 991 | if ($args{revrec} eq 'n') {
|
---|
| 992 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 993 | # or the intended parent domain for live records.
|
---|
| 994 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[657] | 995 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/i;
|
---|
[627] | 996 |
|
---|
[631] | 997 | ##enhance: Rejig so that we can pass back a WARN red flag, instead of
|
---|
| 998 | # hard-failing, since it seems that purely from the DNS record perspective,
|
---|
| 999 | # SRV records without underscores are syntactically valid
|
---|
[627] | 1000 | # Not strictly true, but SRV records not following this convention won't be found.
|
---|
| 1001 | return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]")
|
---|
[698] | 1002 | unless ${$args{host}} =~ /^_[A-Za-z-]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/;
|
---|
[627] | 1003 |
|
---|
| 1004 | # SRV target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 1005 | return ('FAIL', "SRV records cannot point directly to an IP address")
|
---|
| 1006 | if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
| 1007 | } else {
|
---|
| 1008 | # hm. we can't do anything sane with IP values here; part of the record data is in
|
---|
| 1009 | # fact encoded in the "hostname". enforce .arpa names? OTOH, SRV records in a reverse
|
---|
| 1010 | # zone are pretty silly.
|
---|
| 1011 |
|
---|
[631] | 1012 | ##enhance: Rejig so that we can pass back a WARN red flag, instead of
|
---|
| 1013 | # hard-failing, since it seems that purely from the DNS record perspective,
|
---|
| 1014 | # SRV records without underscores are syntactically valid
|
---|
[627] | 1015 | # Not strictly true, but SRV records not following this convention won't be found.
|
---|
| 1016 | return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]")
|
---|
| 1017 | unless ${$args{val}} =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/;
|
---|
| 1018 |
|
---|
| 1019 | # SRV target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 1020 | return ('FAIL', "SRV records cannot point directly to an IP address")
|
---|
| 1021 | if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
| 1022 |
|
---|
| 1023 | # SRV records in reverse zones get stricter treatment. The UI bars adding them in
|
---|
| 1024 | # reverse record sets, but we "need" to allow editing existing ones. And we'll allow
|
---|
| 1025 | # editing them if some loon manually munges one into a default reverse record set.
|
---|
| 1026 | if ($args{defrec} eq 'n') {
|
---|
| 1027 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 1028 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
| 1029 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
| 1030 | }
|
---|
| 1031 |
|
---|
| 1032 | ##enhance or ##fixme
|
---|
| 1033 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design
|
---|
| 1034 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
| 1035 | ${$args{val}} =~ /\.arpa$/;
|
---|
| 1036 |
|
---|
| 1037 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
| 1038 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 1039 |
|
---|
| 1040 | }
|
---|
| 1041 |
|
---|
[228] | 1042 | return ('OK','OK');
|
---|
| 1043 | } # done SRV record
|
---|
| 1044 |
|
---|
| 1045 | # Now the custom types
|
---|
| 1046 |
|
---|
[232] | 1047 | # A+PTR record. With a very little bit of magic we can also use this sub to validate AAAA+PTR. Whee!
|
---|
[228] | 1048 | sub _validate_65280 {
|
---|
[467] | 1049 | my $self = shift;
|
---|
| 1050 | my $dbh = $self->{dbh};
|
---|
[232] | 1051 |
|
---|
| 1052 | my %args = @_;
|
---|
| 1053 |
|
---|
| 1054 | my $code = 'OK';
|
---|
| 1055 | my $msg = 'OK';
|
---|
| 1056 |
|
---|
| 1057 | if ($args{defrec} eq 'n') {
|
---|
| 1058 | # live record; revrec determines whether we validate the PTR or A component first.
|
---|
[233] | 1059 |
|
---|
[630] | 1060 | # Fail early on non-IP gibberish in ${$args{val}}. Arguably .arpa names might be acceptable
|
---|
| 1061 | # but that gets stupid in forward zones, since these records are shared.
|
---|
| 1062 | return ('FAIL', "$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
[660] | 1063 | if ${$args{rectype}} == 65280 && ${$args{val}} !~ m{^\d+\.\d+\.\d+\.\d+(?:/\d+)?$};
|
---|
[630] | 1064 | return ('FAIL', "$typemap{${$args{rectype}}} record must be a valid IPv6 address")
|
---|
[660] | 1065 | if ${$args{rectype}} == 65281 && ${$args{val}} !~ m{^[a-fA-F0-9:]+(?:/\d+)?$};
|
---|
[630] | 1066 | # If things are not OK, this should prevent Stupid in the error log.
|
---|
| 1067 | $args{addr} = new NetAddr::IP ${$args{val}}
|
---|
| 1068 | or return ('FAIL', "$typemap{${$args{rectype}}} record must be a valid IPv".
|
---|
| 1069 | (${$args{rectype}} == 65280 ? '4' : '6')." address");
|
---|
| 1070 | ${$args{val}} = $args{addr}->addr;
|
---|
| 1071 |
|
---|
[232] | 1072 | if ($args{revrec} eq 'y') {
|
---|
[467] | 1073 | ($code,$msg) = $self->_validate_12(%args);
|
---|
[232] | 1074 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 1075 |
|
---|
[467] | 1076 | # check A+PTR is really v4
|
---|
| 1077 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
| 1078 | if ${$args{rectype}} == 65280 && $args{addr}->{isv6};
|
---|
| 1079 | # check AAAA+PTR is really v6
|
---|
| 1080 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
|
---|
| 1081 | if ${$args{rectype}} == 65281 && !$args{addr}->{isv6};
|
---|
| 1082 |
|
---|
[232] | 1083 | # Check if the reqested domain exists. If not, coerce the type down to PTR and warn.
|
---|
[467] | 1084 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) {
|
---|
[272] | 1085 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
| 1086 | " as PTR instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
[232] | 1087 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
| 1088 | $msg = $addmsg if $code eq 'OK';
|
---|
| 1089 | ${$args{rectype}} = $reverse_typemap{PTR};
|
---|
| 1090 | return ('WARN', $msg);
|
---|
| 1091 | }
|
---|
| 1092 |
|
---|
[242] | 1093 | # Add domain ID to field list and values
|
---|
| 1094 | ${$args{fields}} .= "domain_id,";
|
---|
| 1095 | push @{$args{vallist}}, ${$args{domid}};
|
---|
| 1096 |
|
---|
[232] | 1097 | } else {
|
---|
[467] | 1098 | ($code,$msg) = $self->_validate_1(%args) if ${$args{rectype}} == 65280;
|
---|
| 1099 | ($code,$msg) = $self->_validate_28(%args) if ${$args{rectype}} == 65281;
|
---|
[232] | 1100 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 1101 |
|
---|
| 1102 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
| 1103 | # work here since we don't *know* which parent to put it in.
|
---|
[233] | 1104 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
[232] | 1105 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
| 1106 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
| 1107 | if (!$revid) {
|
---|
[272] | 1108 | $msg = "Record ".($args{update} ? 'updated' : 'added')." as ".(${$args{rectype}} == 65280 ? 'A' : 'AAAA').
|
---|
[232] | 1109 | " instead of $typemap{${$args{rectype}}}; reverse zone not found for ${$args{val}}";
|
---|
| 1110 | ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
| 1111 | return ('WARN', $msg);
|
---|
| 1112 | }
|
---|
| 1113 |
|
---|
| 1114 | # Check for duplicate PTRs. Note we don't have to play games with $code and $msg, because
|
---|
| 1115 | # by definition there can't be duplicate PTRs if the reverse zone isn't managed here.
|
---|
[272] | 1116 | if ($args{update}) {
|
---|
| 1117 | # Record update. There should usually be an existing PTR (the record being updated)
|
---|
| 1118 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 1119 | " WHERE val = ?", undef, (${$args{val}})) };
|
---|
[273] | 1120 | if (@ptrs && (!grep /^$args{update}$/, @ptrs)) {
|
---|
[272] | 1121 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
|
---|
| 1122 | $code = 'WARN';
|
---|
| 1123 | }
|
---|
| 1124 | } else {
|
---|
| 1125 | # New record. Always warn if a PTR exists
|
---|
| 1126 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 1127 | " WHERE val = ?", undef, (${$args{val}}));
|
---|
| 1128 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want"
|
---|
| 1129 | if $ptrcount;
|
---|
| 1130 | $code = 'WARN' if $ptrcount;
|
---|
[232] | 1131 | }
|
---|
| 1132 |
|
---|
[630] | 1133 | # Add the reverse zone ID to the fieldlist
|
---|
[232] | 1134 | ${$args{fields}} .= "rdns_id,";
|
---|
| 1135 | push @{$args{vallist}}, $revid;
|
---|
| 1136 |
|
---|
[653] | 1137 | # Coerce the hostname back to the domain; this is so it displays and manipulates
|
---|
| 1138 | # sanely in the reverse zone.
|
---|
| 1139 | if (${$args{host}} eq '@') {
|
---|
| 1140 | ${$args{host}} = $self->domainName($args{id}); # errors? What errors?
|
---|
| 1141 | }
|
---|
| 1142 | } # revrec ne 'y'
|
---|
| 1143 |
|
---|
[233] | 1144 | } else { # defrec eq 'y'
|
---|
[630] | 1145 |
|
---|
[233] | 1146 | if ($args{revrec} eq 'y') {
|
---|
[467] | 1147 | ($code,$msg) = $self->_validate_12(%args);
|
---|
[233] | 1148 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 1149 | if (${$args{rectype}} == 65280) {
|
---|
| 1150 | return ('FAIL',"A+PTR record must be a valid IPv4 address or fragment")
|
---|
| 1151 | if ${$args{val}} =~ /:/;
|
---|
[234] | 1152 | ${$args{val}} =~ s/^ZONE,/ZONE./; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
[233] | 1153 | } elsif (${$args{rectype}} == 65281) {
|
---|
| 1154 | return ('FAIL',"AAAA+PTR record must be a valid IPv6 address or fragment")
|
---|
| 1155 | if ${$args{val}} =~ /\./;
|
---|
[234] | 1156 | ${$args{val}} =~ s/^ZONE,/ZONE::/; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
[233] | 1157 | }
|
---|
| 1158 | } else {
|
---|
| 1159 | # This is easy. I also can't see a real use-case for A/AAAA+PTR in *all* forward
|
---|
| 1160 | # domains, since you wouldn't be able to substitute both domain and reverse zone
|
---|
| 1161 | # sanely, and you'd end up with guaranteed over-replicated PTR records that would
|
---|
| 1162 | # confuse the hell out of pretty much anything that uses them.
|
---|
[234] | 1163 | ##fixme: make this a config flag?
|
---|
[233] | 1164 | return ('FAIL', "$typemap{${$args{rectype}}} records not allowed in default domains");
|
---|
| 1165 | }
|
---|
[232] | 1166 | }
|
---|
| 1167 |
|
---|
| 1168 | return ($code, $msg);
|
---|
[228] | 1169 | } # done A+PTR record
|
---|
| 1170 |
|
---|
| 1171 | # AAAA+PTR record
|
---|
[232] | 1172 | # A+PTR above has been magicked to handle AAAA+PTR as well.
|
---|
[228] | 1173 | sub _validate_65281 {
|
---|
[232] | 1174 | return _validate_65280(@_);
|
---|
[228] | 1175 | } # done AAAA+PTR record
|
---|
| 1176 |
|
---|
| 1177 | # PTR template record
|
---|
| 1178 | sub _validate_65282 {
|
---|
[467] | 1179 | my $self = shift;
|
---|
| 1180 | my $dbh = $self->{dbh};
|
---|
[340] | 1181 |
|
---|
| 1182 | my %args = @_;
|
---|
| 1183 |
|
---|
| 1184 | # we're *this* >.< close to being able to just call _validate_12... unfortunately we can't, quite.
|
---|
| 1185 | if ($args{revrec} eq 'y') {
|
---|
| 1186 | if ($args{defrec} eq 'n') {
|
---|
[467] | 1187 | return ('FAIL', "Template block ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
| 1188 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
[340] | 1189 | ##fixme: warn if $args{val} is not /31 or larger block?
|
---|
| 1190 | ${$args{val}} = "$args{addr}";
|
---|
| 1191 | } else {
|
---|
| 1192 | if (${$args{val}} =~ /\./) {
|
---|
| 1193 | # looks like a v4 or fragment
|
---|
| 1194 | if (${$args{val}} =~ m|^\d+\.\d+\.\d+\.\d+(?:/\d+)?$|) {
|
---|
| 1195 | # woo! a complete IP! validate it and normalize, or fail.
|
---|
| 1196 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
| 1197 | or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
|
---|
| 1198 | ${$args{val}} = "$args{addr}";
|
---|
| 1199 | } else {
|
---|
| 1200 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
| 1201 | }
|
---|
| 1202 | } elsif (${$args{val}} =~ /[a-f:]/) {
|
---|
| 1203 | # looks like a v6 or fragment
|
---|
| 1204 | ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
|
---|
| 1205 | if ($args{addr}) {
|
---|
| 1206 | if ($args{addr}->addr =~ /^0/) {
|
---|
| 1207 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
| 1208 | } else {
|
---|
| 1209 | ${$args{val}} = "$args{addr}";
|
---|
| 1210 | }
|
---|
| 1211 | }
|
---|
| 1212 | } else {
|
---|
| 1213 | # bare number (probably). These could be v4 or v6, so we'll
|
---|
| 1214 | # expand on these on creation of a reverse zone.
|
---|
| 1215 | ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
|
---|
| 1216 | }
|
---|
| 1217 | }
|
---|
| 1218 | ##fixme: validate %-patterns?
|
---|
| 1219 |
|
---|
| 1220 | # Unlike single PTR records, there is absolutely no way to sanely support multiple
|
---|
| 1221 | # PTR templates for the same block, since they expect to expand to all the individual
|
---|
| 1222 | # IPs on export. Nested templates should be supported though.
|
---|
| 1223 |
|
---|
| 1224 | my @checkvals = (${$args{val}});
|
---|
| 1225 | if (${$args{val}} =~ /,/) {
|
---|
| 1226 | # push . and :: variants into checkvals if val has ,
|
---|
| 1227 | my $tmp;
|
---|
| 1228 | ($tmp = ${$args{val}}) =~ s/,/./;
|
---|
| 1229 | push @checkvals, $tmp;
|
---|
| 1230 | ($tmp = ${$args{val}}) =~ s/,/::/;
|
---|
| 1231 | push @checkvals, $tmp;
|
---|
| 1232 | }
|
---|
| 1233 | ##fixme: this feels wrong still - need to restrict template pseudorecords to One Of Each
|
---|
| 1234 | # Per Netblock such that they don't conflict on export
|
---|
| 1235 | my $typeck;
|
---|
| 1236 | # type 65282 -> ptr template -> look for any of 65282, 65283, 65284
|
---|
| 1237 | $typeck = 'type=65283 OR type=65284' if ${$args{rectype}} == 65282;
|
---|
| 1238 | # type 65283 -> a+ptr template -> v4 -> look for 65282 or 65283
|
---|
| 1239 | $typeck = 'type=65283' if ${$args{rectype}} == 65282;
|
---|
| 1240 | # type 65284 -> aaaa+ptr template -> v6 -> look for 65282 or 65284
|
---|
| 1241 | $typeck = 'type=65284' if ${$args{rectype}} == 65282;
|
---|
| 1242 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ? ".
|
---|
| 1243 | "AND (type=65282 OR $typeck)");
|
---|
| 1244 | foreach my $checkme (@checkvals) {
|
---|
| 1245 | $pcsth->execute($checkme);
|
---|
| 1246 | my ($rc) = $pcsth->fetchrow_array;
|
---|
[442] | 1247 | return ('FAIL', "Only one template pseudorecord may exist for a given IP block") if $rc > 1;
|
---|
[340] | 1248 | }
|
---|
| 1249 |
|
---|
| 1250 | } else {
|
---|
| 1251 | return ('FAIL', "Forward zones cannot contain PTR records");
|
---|
| 1252 | }
|
---|
| 1253 |
|
---|
[228] | 1254 | return ('OK','OK');
|
---|
| 1255 | } # done PTR template record
|
---|
| 1256 |
|
---|
| 1257 | # A+PTR template record
|
---|
| 1258 | sub _validate_65283 {
|
---|
[467] | 1259 | my $self = shift;
|
---|
| 1260 | my $dbh = $self->{dbh};
|
---|
[340] | 1261 |
|
---|
| 1262 | my %args = @_;
|
---|
| 1263 |
|
---|
| 1264 | my ($code,$msg) = ('OK','OK');
|
---|
| 1265 |
|
---|
| 1266 | ##fixme: need to fiddle things since A+PTR templates are acceptable in live
|
---|
| 1267 | # forward zones but not default records
|
---|
| 1268 | if ($args{defrec} eq 'n') {
|
---|
| 1269 | if ($args{revrec} eq 'n') {
|
---|
| 1270 |
|
---|
[653] | 1271 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 1272 | # or the intended parent domain for live records.
|
---|
| 1273 | my $pname = $self->domainName($args{id});
|
---|
[657] | 1274 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/i;
|
---|
[653] | 1275 |
|
---|
| 1276 | # check for form; note this checks both normal and "other" hostnames.
|
---|
| 1277 | return ('FAIL', $errstr)
|
---|
| 1278 | if !_check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 1279 |
|
---|
[340] | 1280 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
| 1281 | # work here since we don't *know* which parent to put it in.
|
---|
| 1282 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
| 1283 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
| 1284 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
| 1285 | # Fail if no match; we can't coerce a PTR-template type down to not include the PTR bit currently.
|
---|
| 1286 | if (!$revid) {
|
---|
| 1287 | $msg = "Can't ".($args{update} ? 'update' : 'add')." ${$args{host}}/${$args{val}} as ".
|
---|
| 1288 | "$typemap{${$args{rectype}}}: reverse zone not found for ${$args{val}}";
|
---|
| 1289 | ##fixme: add A template, AAAA template types?
|
---|
| 1290 | # ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
| 1291 | return ('FAIL', $msg);
|
---|
| 1292 | }
|
---|
| 1293 |
|
---|
| 1294 | # Add reverse zone ID to field list and values
|
---|
| 1295 | ${$args{fields}} .= "rdns_id,";
|
---|
| 1296 | push @{$args{vallist}}, $revid;
|
---|
| 1297 |
|
---|
| 1298 | } else {
|
---|
[467] | 1299 | return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
| 1300 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
[340] | 1301 | ${$args{val}} = "$args{addr}";
|
---|
| 1302 |
|
---|
[467] | 1303 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) {
|
---|
[340] | 1304 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
| 1305 | " as PTR template instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
| 1306 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
| 1307 | $msg = $addmsg if $code eq 'OK';
|
---|
| 1308 | ${$args{rectype}} = 65282;
|
---|
| 1309 | return ('WARN', $msg);
|
---|
| 1310 | }
|
---|
| 1311 |
|
---|
| 1312 | # Add domain ID to field list and values
|
---|
| 1313 | ${$args{fields}} .= "domain_id,";
|
---|
| 1314 | push @{$args{vallist}}, ${$args{domid}};
|
---|
| 1315 | }
|
---|
| 1316 |
|
---|
| 1317 | } else {
|
---|
[467] | 1318 | my ($code,$msg) = $self->_validate_65282(%args);
|
---|
[340] | 1319 | return ($code, $msg) if $code eq 'FAIL';
|
---|
| 1320 | # get domain, check against ${$args{name}}
|
---|
| 1321 | }
|
---|
| 1322 |
|
---|
[228] | 1323 | return ('OK','OK');
|
---|
[624] | 1324 | } # done A+PTR template record
|
---|
[228] | 1325 |
|
---|
| 1326 | # AAAA+PTR template record
|
---|
[624] | 1327 | # Not sure this can be handled sanely due to the size of IPv6 address space
|
---|
[674] | 1328 | # _validate_65283 above should handle v6 template records fine. It's on export we've got trouble.
|
---|
[228] | 1329 | sub _validate_65284 {
|
---|
[674] | 1330 | my $self = shift;
|
---|
| 1331 | my %args = @_;
|
---|
| 1332 |
|
---|
| 1333 | # do a quick check on the form of the hostname part; this is effectively a
|
---|
| 1334 | # "*.0.0.f.ip6.arpa" hostname, not an actual expandable IP template pattern
|
---|
| 1335 | # like with 65283.
|
---|
| 1336 | return ('FAIL', $errstr)
|
---|
| 1337 | if !_check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 1338 | return $self->_validate_65283(%args);
|
---|
[228] | 1339 | } # done AAAA+PTR template record
|
---|
| 1340 |
|
---|
[342] | 1341 | # Delegation record
|
---|
[345] | 1342 | # This is essentially a specialized clone of the NS record, primarily useful
|
---|
| 1343 | # for delegating IPv4 sub-/24 reverse blocks
|
---|
[342] | 1344 | sub _validate_65285 {
|
---|
[467] | 1345 | my $self = shift;
|
---|
| 1346 | my $dbh = $self->{dbh};
|
---|
[345] | 1347 |
|
---|
| 1348 | my %args = @_;
|
---|
| 1349 |
|
---|
| 1350 | # Almost, but not quite, identical to NS record validation.
|
---|
| 1351 |
|
---|
| 1352 | # Check that the target of the record is within the parent.
|
---|
| 1353 | # Yes, host<->val are mixed up here; can't see a way to avoid it. :(
|
---|
| 1354 | if ($args{defrec} eq 'n') {
|
---|
| 1355 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
| 1356 | if ($args{revrec} eq 'y') {
|
---|
| 1357 | my $tmpip = NetAddr::IP->new(${$args{val}});
|
---|
[467] | 1358 | my $pname = $self->revName($args{id});
|
---|
[345] | 1359 | return ('FAIL',"${$args{val}} not within $pname")
|
---|
[467] | 1360 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$tmpip);
|
---|
[345] | 1361 | # Normalize
|
---|
| 1362 | ${$args{val}} = "$tmpip";
|
---|
| 1363 | } else {
|
---|
[467] | 1364 | my $pname = $self->domainName($args{id});
|
---|
[657] | 1365 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/i;
|
---|
[345] | 1366 | }
|
---|
| 1367 | } else {
|
---|
| 1368 | return ('FAIL',"Delegation records are not permitted in default record sets");
|
---|
| 1369 | }
|
---|
[342] | 1370 | return ('OK','OK');
|
---|
[752] | 1371 | } # done delegation record
|
---|
[228] | 1372 |
|
---|
[752] | 1373 | # ALIAS record
|
---|
| 1374 | # A specialized variant of the CNAME, which retrieves the A record list on each
|
---|
| 1375 | # export and publishes the A records instead. Primarily for "root CNAME" or "apex
|
---|
| 1376 | # alias" records. See https://secure.deepnet.cx/trac/dnsadmin/ticket/55.
|
---|
| 1377 | # Not allowed in reverse zones because this is already a hack, and reverse zones
|
---|
| 1378 | # don't get pointed to CNAMEed CDNs the way domains do.
|
---|
| 1379 | sub _validate_65300 {
|
---|
| 1380 | my $self = shift;
|
---|
| 1381 | my $dbh = $self->{dbh};
|
---|
| 1382 |
|
---|
| 1383 | my %args = @_;
|
---|
| 1384 |
|
---|
| 1385 | return ('FAIL',"ALIAS records are not permitted in reverse zones") if $args{revrec} eq 'y';
|
---|
| 1386 |
|
---|
| 1387 | # Make sure target is a well-formed hostname
|
---|
| 1388 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 1389 |
|
---|
| 1390 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 1391 | # or the intended parent domain for live records.
|
---|
| 1392 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[754] | 1393 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i);
|
---|
[752] | 1394 |
|
---|
[754] | 1395 | # Only do the cache thing on live/active records
|
---|
| 1396 | return ('OK','OK') unless $args{defrec} eq 'n';
|
---|
[752] | 1397 |
|
---|
| 1398 | # now we check/update the cached target address info
|
---|
| 1399 | my ($iplist) = $self->{dbh}->selectrow_array("SELECT auxdata FROM records WHERE record_id = ?", undef, $args{recid});
|
---|
| 1400 | my $warnmsg;
|
---|
| 1401 |
|
---|
| 1402 | my $res = Net::DNS::Resolver->new;
|
---|
| 1403 | # Set short timeouts to minimize disruption. If the target's DNS is slow the site will likely be broken anyway.
|
---|
| 1404 | $res->tcp_timeout(2);
|
---|
| 1405 | $res->udp_timeout(2);
|
---|
| 1406 | my $reply = $res->query(${$args{val}});
|
---|
| 1407 | my @newlist;
|
---|
| 1408 | if ($reply) {
|
---|
| 1409 | foreach my $rr ($reply->answer) {
|
---|
| 1410 | next unless $rr->type eq "A";
|
---|
| 1411 | push @newlist, $rr->address;
|
---|
| 1412 | }
|
---|
| 1413 | } else {
|
---|
[753] | 1414 | $warnmsg = "Failure retrieving IP list from DNS for cache validation/update on ALIAS '${$args{host}} -> ${$args{val}}': ".
|
---|
| 1415 | $res->errorstring;
|
---|
[752] | 1416 | }
|
---|
| 1417 |
|
---|
| 1418 | # we don't need this to be perfectly correct IP address order, just consistent.
|
---|
| 1419 | my $liveips = join(':', sort(@newlist));
|
---|
| 1420 |
|
---|
| 1421 | # check to see if there was an OOOOPS checking for updated A records on the target. also make sure we have something cached.
|
---|
| 1422 | if (!$liveips) {
|
---|
| 1423 | if (!$iplist) {
|
---|
| 1424 | # not fatal since we do the lookup on export as well
|
---|
| 1425 | return ('WARN',
|
---|
| 1426 | join("\n", $warnmsg, "No cached data and no live DNS data for ALIAS target ${$args{val}}; record may be SKIPPED on export!") );
|
---|
| 1427 | # } else {
|
---|
| 1428 | # return ('WARN', "No live DNS data for ALIAS target ${$args{val}}; falling back to cache");
|
---|
| 1429 | }
|
---|
| 1430 | }
|
---|
| 1431 |
|
---|
| 1432 | # munge the insert/update fieldlist and data array
|
---|
| 1433 | if ($iplist ne $liveips) {
|
---|
| 1434 | ${$args{fields}} .= "auxdata,";
|
---|
| 1435 | push @{$args{vallist}}, $liveips;
|
---|
| 1436 | }
|
---|
| 1437 |
|
---|
| 1438 | return ('WARN', $warnmsg) if $warnmsg;
|
---|
| 1439 |
|
---|
| 1440 | return ('OK','OK');
|
---|
| 1441 | } # done ALIAS record
|
---|
| 1442 |
|
---|
| 1443 |
|
---|
[617] | 1444 | # Subs not specific to a particular record type
|
---|
[342] | 1445 |
|
---|
[617] | 1446 | # Convert $$host and/or $$val to lowercase as appropriate.
|
---|
| 1447 | # Should only be called if $self->{lowercase} is true.
|
---|
| 1448 | # $rectype is also a reference for caller convenience
|
---|
| 1449 | sub _caseclean {
|
---|
| 1450 | my ($rectype, $host, $val, $defrec, $revrec) = @_;
|
---|
| 1451 |
|
---|
| 1452 | # Can't case-squash default records, due to DOMAIN, ZONE, and ADMINDOMAIN templating
|
---|
| 1453 | return if $defrec eq 'y';
|
---|
| 1454 |
|
---|
| 1455 | if ($typemap{$$rectype} eq 'TXT' || $typemap{$$rectype} eq 'SPF') {
|
---|
| 1456 | # TXT records should preserve user entry in the string.
|
---|
| 1457 | # SPF records are a duplicate of TXT with a new record type value (99)
|
---|
| 1458 | $$host = lc($$host) if $revrec eq 'n'; # only lowercase $$host on live forward TXT; preserve TXT content
|
---|
| 1459 | $$val = lc($$val) if $revrec eq 'y'; # only lowercase $$val on live reverse TXT; preserve TXT content
|
---|
| 1460 | } else {
|
---|
| 1461 | # Non-TXT, live records, are fully case-insensitive
|
---|
| 1462 | $$host = lc($$host);
|
---|
| 1463 | $$val = lc($$val);
|
---|
| 1464 | } # $typemap{$$rectype} else
|
---|
| 1465 |
|
---|
| 1466 | } # _caseclean()
|
---|
| 1467 |
|
---|
| 1468 |
|
---|
[265] | 1469 | ##
|
---|
| 1470 | ## Record data substitution subs
|
---|
| 1471 | ##
|
---|
[228] | 1472 |
|
---|
[298] | 1473 | # Replace ZONE in hostname, or create (most of) the actual proper zone name
|
---|
[265] | 1474 | sub _ZONE {
|
---|
| 1475 | my $zone = shift;
|
---|
| 1476 | my $string = shift;
|
---|
| 1477 | my $fr = shift || 'f'; # flag for forward/reverse order? nb: ignored for IP
|
---|
[298] | 1478 | my $sep = shift || '-'; # Separator character - unlikely we'll ever need more than . or -
|
---|
[265] | 1479 |
|
---|
[298] | 1480 | my $prefix;
|
---|
[265] | 1481 |
|
---|
| 1482 | $string =~ s/,/./ if !$zone->{isv6};
|
---|
| 1483 | $string =~ s/,/::/ if $zone->{isv6};
|
---|
| 1484 |
|
---|
[298] | 1485 | # Subbing ZONE in the host. We need to properly ID the netblock range
|
---|
| 1486 | # The subbed text should have "network IP with trailing zeros stripped" for
|
---|
| 1487 | # blocks lined up on octet (for v4) or hex-quad (for v6) boundaries
|
---|
| 1488 | # For blocks that do NOT line up on these boundaries, we take the most
|
---|
| 1489 | # significant octet or 16-bit chunk of the "broadcast" IP and append it
|
---|
| 1490 | # after a double-dash
|
---|
| 1491 | # ie:
|
---|
| 1492 | # 8.0.0.0/6 -> 8.0.0.0 -> 11.255.255.255; sub should be 8--11
|
---|
| 1493 | # 10.0.0.0/12 -> 10.0.0.0 -> 10.0.0.0 -> 10.15.255.255; sub should be 10-0--15
|
---|
| 1494 | # 192.168.4.0/22 -> 192.168.4.0 -> 192.168.7.255; sub should be 192-168-4--7
|
---|
| 1495 | # 192.168.0.8/29 -> 192.168.0.8 -> 192.168.0.15; sub should be 192-168-0-8--15
|
---|
| 1496 | # Similar for v6
|
---|
[265] | 1497 |
|
---|
[298] | 1498 | if (!$zone->{isv6}) { # IPv4
|
---|
| 1499 |
|
---|
| 1500 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
| 1501 | # a funky subnet that had host bits set.
|
---|
| 1502 | my $bc = $zone->broadcast->addr;
|
---|
| 1503 |
|
---|
| 1504 | if ($zone->masklen > 24) {
|
---|
| 1505 | $bc =~ s/^\d+\.\d+\.\d+\.//;
|
---|
| 1506 | } elsif ($zone->masklen > 16) {
|
---|
| 1507 | $prefix =~ s/\.0$//;
|
---|
| 1508 | $bc =~ s/^\d+\.\d+\.//;
|
---|
| 1509 | } elsif ($zone->masklen > 8) {
|
---|
| 1510 | $bc =~ s/^\d+\.//;
|
---|
| 1511 | $prefix =~ s/\.0\.0$//;
|
---|
| 1512 | } else {
|
---|
| 1513 | $prefix =~ s/\.0\.0\.0$//;
|
---|
| 1514 | }
|
---|
| 1515 | if ($zone->masklen % 8) {
|
---|
| 1516 | $bc =~ s/(\.255)+$//;
|
---|
| 1517 | $prefix .= "--$bc"; #"--".zone->masklen; # use range or mask length?
|
---|
| 1518 | }
|
---|
| 1519 | if ($fr eq 'f') {
|
---|
| 1520 | $prefix =~ s/\.+/$sep/g;
|
---|
| 1521 | } else {
|
---|
| 1522 | $prefix = join($sep, reverse(split(/\./, $prefix)));
|
---|
| 1523 | }
|
---|
| 1524 |
|
---|
| 1525 | } else { # IPv6
|
---|
| 1526 |
|
---|
| 1527 | if ($fr eq 'f') {
|
---|
| 1528 |
|
---|
| 1529 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
| 1530 | # a funky subnet that had host bits set.
|
---|
[265] | 1531 | my $bc = $zone->broadcast->addr;
|
---|
| 1532 | if (($zone->masklen % 16) != 0) {
|
---|
[298] | 1533 | # Strip trailing :0 off $prefix, and :ffff off the broadcast IP
|
---|
| 1534 | for (my $i=0; $i<(7-int($zone->masklen / 16)); $i++) {
|
---|
| 1535 | $prefix =~ s/:0$//;
|
---|
| 1536 | $bc =~ s/:ffff$//;
|
---|
| 1537 | }
|
---|
| 1538 | # Strip the leading 16-bit chunks off the front of the broadcast IP
|
---|
| 1539 | $bc =~ s/^([a-f0-9]+:)+//;
|
---|
| 1540 | # Append the remaining 16-bit chunk to the prefix after "--"
|
---|
| 1541 | $prefix .= "--$bc";
|
---|
[265] | 1542 | } else {
|
---|
[298] | 1543 | # Strip off :0 from the end until we reach the netblock length.
|
---|
| 1544 | for (my $i=0; $i<(8-$zone->masklen / 16); $i++) {
|
---|
[265] | 1545 | $prefix =~ s/:0$//;
|
---|
[298] | 1546 | }
|
---|
[265] | 1547 | }
|
---|
[298] | 1548 | # Actually deal with the separator
|
---|
| 1549 | $prefix =~ s/:/$sep/g;
|
---|
| 1550 |
|
---|
| 1551 | } else { # $fr eq 'f'
|
---|
| 1552 |
|
---|
| 1553 | $prefix = $zone->network->full; # Just In Case someone managed to slip in
|
---|
| 1554 | # a funky subnet that had host bits set.
|
---|
| 1555 | my $bc = $zone->broadcast->full;
|
---|
| 1556 | $prefix =~ s/://g; # clean these out since they're not spaced right for this case
|
---|
| 1557 | $bc =~ s/://g;
|
---|
| 1558 | # Strip trailing 0 off $prefix, and f off the broadcast IP, to match the mask length
|
---|
| 1559 | for (my $i=0; $i<(31-int($zone->masklen / 4)); $i++) {
|
---|
| 1560 | $prefix =~ s/0$//;
|
---|
| 1561 | $bc =~ s/f$//;
|
---|
| 1562 | }
|
---|
| 1563 | # Split and reverse the order of the nibbles in the network/broadcast IPs
|
---|
[332] | 1564 | # trim another 0 for nibble-aligned blocks first, but only if we really have a block, not an IP
|
---|
| 1565 | $prefix =~ s/0$// if $zone->masklen % 4 == 0 && $zone->masklen != 128;
|
---|
[298] | 1566 | my @nbits = reverse split //, $prefix;
|
---|
| 1567 | my @bbits = reverse split //, $bc;
|
---|
| 1568 | # Handle the sub-nibble case. Eww. I feel dirty supporting this...
|
---|
| 1569 | $nbits[0] = "$nbits[0]-$bbits[0]" if ($zone->masklen % 4) != 0;
|
---|
| 1570 | # Glue it back together
|
---|
| 1571 | $prefix = join($sep, @nbits);
|
---|
| 1572 |
|
---|
| 1573 | } # $fr ne 'f'
|
---|
| 1574 |
|
---|
| 1575 | } # $zone->{isv6}
|
---|
| 1576 |
|
---|
| 1577 | # Do the substitution, finally
|
---|
| 1578 | $string =~ s/ZONE/$prefix/;
|
---|
| 1579 | $string =~ s/--/-/ if $sep ne '-'; # - as separator needs extra help for sub-octet v4 netblocks
|
---|
| 1580 | return $string;
|
---|
| 1581 | } # done _ZONE()
|
---|
| 1582 |
|
---|
| 1583 | # Not quite a substitution sub, but placed here as it's basically the inverse of above;
|
---|
| 1584 | # given the .arpa zone name, return the CIDR netblock the zone is for.
|
---|
[304] | 1585 | # Supports v4 non-octet/non-classful netblocks as per the method outlined in the Grasshopper Book (2nd Ed p217-218)
|
---|
[298] | 1586 | # Does NOT support non-quad v6 netblocks via the same scheme; it shouldn't ever be necessary.
|
---|
| 1587 | # Takes a nominal .arpa zone name, returns a success code and NetAddr::IP, or a fail code and message
|
---|
| 1588 | sub _zone2cidr {
|
---|
| 1589 | my $zone = shift;
|
---|
| 1590 |
|
---|
| 1591 | my $cidr;
|
---|
[301] | 1592 | my $tmpcidr;
|
---|
| 1593 | my $warnmsg = '';
|
---|
[298] | 1594 |
|
---|
| 1595 | if ($zone =~ /\.in-addr\.arpa\.?$/) {
|
---|
| 1596 | # v4 revzone, formal zone name type
|
---|
| 1597 | my $tmpzone = $zone;
|
---|
[583] | 1598 | return ('FAIL', "Non-numerics in apparent IPv4 reverse zone name [$tmpzone]")
|
---|
| 1599 | if $tmpzone !~ m{^(?:\d+[/-])?[\d\.]+\.in-addr\.arpa\.?$};
|
---|
[298] | 1600 | $tmpzone =~ s/\.in-addr\.arpa\.?//;
|
---|
| 1601 |
|
---|
| 1602 | # Snag the octet pieces
|
---|
| 1603 | my @octs = split /\./, $tmpzone;
|
---|
| 1604 |
|
---|
| 1605 | # Map result of a range manipulation to a mask length change. Cheaper than finding the 2-root of $octets[0]+1.
|
---|
[304] | 1606 | # Note we will not support /31 blocks, mostly due to issues telling "24-31" -> .24/29 apart from
|
---|
| 1607 | # "24-31" -> .24/31", with a litte bit of "/31 is icky".
|
---|
| 1608 | my %maskmap = ( 3 => 2, 7 => 3, 15 => 4, 31 => 5, 63 => 6, 127 => 7,
|
---|
| 1609 | 30 => 2, 29 => 3, 28 => 4, 27 => 5, 26 => 6, 25 => 7
|
---|
| 1610 | );
|
---|
[298] | 1611 |
|
---|
| 1612 | # Handle "range" blocks, eg, 80-83.168.192.in-addr.arpa (192.168.80.0/22)
|
---|
| 1613 | # Need to take the size of the range to offset the basic octet-based mask length,
|
---|
| 1614 | # and make sure the first number in the range gets used as the network address for the block
|
---|
[304] | 1615 | # Alternate form: The second number is actually the real netmask, not the end of the range.
|
---|
[298] | 1616 | my $masklen = 0;
|
---|
[571] | 1617 | if ($octs[0] =~ m{^((\d+)[/-](\d+))$}) { # take the range...
|
---|
[307] | 1618 | if (24 < $3 && $3 < 31) {
|
---|
[304] | 1619 | # we have a real netmask
|
---|
[307] | 1620 | $masklen = -$maskmap{$3};
|
---|
[304] | 1621 | } else {
|
---|
| 1622 | # we have a range. NB: only real CIDR ranges are supported
|
---|
[307] | 1623 | $masklen -= $maskmap{-(eval $1)}; # find the mask base...
|
---|
[304] | 1624 | }
|
---|
[307] | 1625 | $octs[0] = $2; # set the base octet of the range...
|
---|
[265] | 1626 | }
|
---|
[298] | 1627 | @octs = reverse @octs; # We can reverse the octet pieces now that we've extracted and munged any ranges
|
---|
[265] | 1628 |
|
---|
[304] | 1629 | # arguably we should only allow sub-octet range/mask in-addr.arpa
|
---|
| 1630 | # specifications in the least significant octet, but the code is
|
---|
| 1631 | # simpler if we deal with sub-octet delegations at any level.
|
---|
| 1632 |
|
---|
[298] | 1633 | # Now we find the "true" mask with the aid of the "base" calculated above
|
---|
| 1634 | if ($#octs == 0) {
|
---|
| 1635 | $masklen += 8;
|
---|
| 1636 | $tmpcidr = "$octs[0].0.0.0/$masklen"; # really hope we don't see one of these very often.
|
---|
| 1637 | } elsif ($#octs == 1) {
|
---|
| 1638 | $masklen += 16;
|
---|
| 1639 | $tmpcidr = "$octs[0].$octs[1].0.0/$masklen";
|
---|
| 1640 | } elsif ($#octs == 2) {
|
---|
| 1641 | $masklen += 24;
|
---|
| 1642 | $tmpcidr = "$octs[0].$octs[1].$octs[2].0/$masklen";
|
---|
[265] | 1643 | } else {
|
---|
[298] | 1644 | $masklen += 32;
|
---|
| 1645 | $tmpcidr = "$octs[0].$octs[1].$octs[2].$octs[3]/$masklen";
|
---|
[265] | 1646 | }
|
---|
| 1647 |
|
---|
[583] | 1648 | } elsif ($zone =~ /\.ip6\.arpa\.?$/) {
|
---|
[298] | 1649 | # v6 revzone, formal zone name type
|
---|
| 1650 | my $tmpzone = $zone;
|
---|
[583] | 1651 | ##fixme: if-n-when we decide we can support sub-nibble v6 zone names, we'll need to change this segment
|
---|
| 1652 | return ('FAIL', "Non-hexadecimals in apparent IPv6 reverse zone name [$tmpzone]")
|
---|
| 1653 | if $tmpzone !~ /^[a-fA-F\d\.]+\.ip6\.arpa\.?$/;
|
---|
[298] | 1654 | $tmpzone =~ s/\.ip6\.arpa\.?//;
|
---|
| 1655 | my @quads = reverse(split(/\./, $tmpzone));
|
---|
| 1656 | $warnmsg .= "Apparent sub-/64 IPv6 reverse zone\n" if $#quads > 15;
|
---|
| 1657 | my $nc;
|
---|
| 1658 | foreach (@quads) {
|
---|
[301] | 1659 | $tmpcidr .= $_;
|
---|
[583] | 1660 | $tmpcidr .= ":" if ++$nc % 4 == 0 && $nc < $#quads;
|
---|
[298] | 1661 | }
|
---|
| 1662 | my $nq = 1 if $nc % 4 != 0;
|
---|
| 1663 | my $mask = $nc * 4; # need to do this here because we probably increment it below
|
---|
| 1664 | while ($nc++ % 4 != 0) {
|
---|
[301] | 1665 | $tmpcidr .= "0";
|
---|
[298] | 1666 | }
|
---|
[583] | 1667 | # polish it off with trailing ::/mask if this is a CIDR block instead of an IP
|
---|
| 1668 | $tmpcidr .= "::/$mask" if $mask != 128;
|
---|
[298] | 1669 | }
|
---|
[301] | 1670 |
|
---|
| 1671 | # Just to be sure, use NetAddr::IP to validate. Saves a lot of nasty regex watching for valid octet values.
|
---|
| 1672 | return ('FAIL', "Invalid zone $zone (apparent netblock $tmpcidr)")
|
---|
| 1673 | unless $cidr = NetAddr::IP->new($tmpcidr);
|
---|
| 1674 |
|
---|
| 1675 | if ($warnmsg) {
|
---|
| 1676 | $errstr = $warnmsg;
|
---|
| 1677 | return ('WARN', $cidr);
|
---|
| 1678 | }
|
---|
| 1679 | return ('OK', $cidr);
|
---|
[583] | 1680 | ##fixme: use wantarray() to decide what to return?
|
---|
[298] | 1681 | } # done _zone2cidr()
|
---|
[265] | 1682 |
|
---|
[337] | 1683 | # Record template %-parameter expansion, IPv4. Note that IPv6 doesn't
|
---|
| 1684 | # really have a sane way to handle this type of expansion at the moment
|
---|
| 1685 | # due to the size of the address space.
|
---|
[685] | 1686 | # Takes a reference to a template string to be expanded, an IP to use in the replacement,
|
---|
| 1687 | # an optional netblock for the %ngb (net, gw, bcast) expansion, and an optional index
|
---|
| 1688 | # number for %c "n'th usable IP in block/range" patterns.
|
---|
| 1689 | # Alters the template string referred.
|
---|
[337] | 1690 | sub _template4_expand {
|
---|
[685] | 1691 | # ugh pthui
|
---|
| 1692 | my $self;
|
---|
| 1693 | $self = shift if ref($_[0]) eq 'DNSDB';
|
---|
| 1694 |
|
---|
[337] | 1695 | my $tmpl = shift;
|
---|
| 1696 | my $ip = shift;
|
---|
[685] | 1697 | my $subnet = shift; # for %ngb and %c
|
---|
| 1698 | my $ipindex = shift; # for %c
|
---|
[298] | 1699 |
|
---|
[685] | 1700 | # blank $tmpl on config template_skip_0 or template_skip_255, unless we have a %ngb
|
---|
| 1701 | if ($$tmpl !~ /\%-?n-?g-?b\%/) {
|
---|
| 1702 | if ( ($ip =~ /\.0$/ && $self->{template_skip_0}) ||
|
---|
| 1703 | ($ip =~ /\.255$/ && $self->{template_skip_255}) ) {
|
---|
| 1704 | $$tmpl = '';
|
---|
| 1705 | return;
|
---|
| 1706 | }
|
---|
| 1707 | }
|
---|
| 1708 |
|
---|
[337] | 1709 | my @ipparts = split /\./, $ip;
|
---|
| 1710 | my @iphex;
|
---|
| 1711 | my @ippad;
|
---|
| 1712 | for (@ipparts) {
|
---|
| 1713 | push @iphex, sprintf("%x", $_);
|
---|
[443] | 1714 | push @ippad, sprintf("%0.3u", $_);
|
---|
[337] | 1715 | }
|
---|
| 1716 |
|
---|
[685] | 1717 | # Two or three consecutive separator characters (_ or -) should be rare - users that use them
|
---|
| 1718 | # anywhere other than punycoded internationalized domains get to keep the pieces when it breaks.
|
---|
| 1719 | # We clean up the ones that we may inadvertently generate after replacing %c and %ngb%
|
---|
| 1720 | my ($thrsep) = ($$tmpl =~ /[_-]{3}/);
|
---|
| 1721 | my ($twosep) = ($$tmpl =~ /[_-]{2}/);
|
---|
| 1722 |
|
---|
| 1723 | # Take the simplest path to pattern substitution; replace only exactly the %c or %ngb%
|
---|
| 1724 | # patterns as-is. Then check after to see if we've caused doubled separator characters (- or _)
|
---|
| 1725 | # and eliminate them, but only if the original template didn't have them already. Also
|
---|
| 1726 | # unconditionally drop separator characters immediately before a dot; these do not always
|
---|
| 1727 | # strictly make the label invalid but almost always, and any exceptions should never show up
|
---|
| 1728 | # in a template record that expands to "many" real records anyway.
|
---|
| 1729 |
|
---|
| 1730 | # %ngb and %c require a netblock
|
---|
| 1731 | if ($subnet) {
|
---|
| 1732 | # extract the fragments
|
---|
| 1733 | my ($ngb,$n,$g,$b) = ($$tmpl =~ /(\%(-?n)(-?g)(-?b)\%)/);
|
---|
| 1734 | my ($c) = ($$tmpl =~ /(\%-?c)/); my $nld = ''; my $cld = '';
|
---|
| 1735 | $c = '' if !$c;
|
---|
[741] | 1736 | my ($cn) = ($$tmpl =~ /(\%x)/);
|
---|
[685] | 1737 | my $skipgw = ($c =~ /\%-c/ ? 0 : 1);
|
---|
| 1738 | my $ipkill = 0;
|
---|
| 1739 |
|
---|
[741] | 1740 | if ($cn) {
|
---|
| 1741 | # "natural n'th IP in the block" pattern
|
---|
| 1742 | $$tmpl =~ s/$cn/$ipindex+1/e;
|
---|
| 1743 | }
|
---|
| 1744 |
|
---|
[685] | 1745 | ##fixme: still have one edge case not handled well:
|
---|
| 1746 | # %c%n-gb%
|
---|
| 1747 | # do we drop the record as per -g, or publish the record with an index of 1 as per %c?
|
---|
| 1748 | # arguably this is a "that's a STUPID question!" case
|
---|
| 1749 |
|
---|
| 1750 | if ($c) {
|
---|
| 1751 | # "n'th usable IP in the block" pattern. We need the caller to provide an index
|
---|
| 1752 | # number otherwise we see exponential time growth because we have to iterate over
|
---|
| 1753 | # the whole block to map the IP back to an index. :/
|
---|
| 1754 | # NetAddr::IP does not have a method for asking "what index is IP <foo> at?"
|
---|
| 1755 |
|
---|
| 1756 | # no index, or index == 0, (AKA network address), or IP == broadcast, blank the index fragment
|
---|
| 1757 | if (!$ipindex || ($$subnet->broadcast->addr eq $ip)) {
|
---|
| 1758 | $$tmpl =~ s/$c//;
|
---|
| 1759 | } else {
|
---|
| 1760 | # if we have %c, AKA "skip the gateway", and we're on the nominal gateway IP, blank the index fragment
|
---|
| 1761 | if ($skipgw && $$subnet->first->addr eq $ip) {
|
---|
| 1762 | $$tmpl =~ s/$c//;
|
---|
| 1763 | }
|
---|
| 1764 | # else replace the index fragment with the passed index minus $skipgw, so that we can start the
|
---|
| 1765 | # resulting index at 1 on net+2
|
---|
| 1766 | else {
|
---|
| 1767 | $$tmpl =~ s/$c/($ipindex-$skipgw)/e;
|
---|
| 1768 | }
|
---|
| 1769 | }
|
---|
| 1770 | } # if ($c)
|
---|
| 1771 |
|
---|
| 1772 | if ($ngb) {
|
---|
| 1773 | # individually check the network, standard gateway (net+1) IP, and broadcast IP
|
---|
| 1774 | # blank $$tmpl if n, g, or b was prefixed with - (this allows "hiding" net/gw/bcast entries)
|
---|
| 1775 |
|
---|
| 1776 | if ($$subnet->network->addr eq $ip) {
|
---|
| 1777 | if ($n eq '-n') {
|
---|
| 1778 | $$tmpl = '';
|
---|
| 1779 | } else {
|
---|
| 1780 | $$tmpl =~ s/$ngb/net/;
|
---|
| 1781 | $ipkill = 1;
|
---|
| 1782 | }
|
---|
| 1783 | } elsif ($$subnet->first->addr eq $ip) {
|
---|
| 1784 | if ($g eq '-g') {
|
---|
| 1785 | $$tmpl = '';
|
---|
| 1786 | } else {
|
---|
| 1787 | $$tmpl =~ s/$ngb/gw/;
|
---|
| 1788 | $ipkill = 1;
|
---|
| 1789 | }
|
---|
| 1790 | } elsif ($$subnet->broadcast->addr eq $ip) {
|
---|
| 1791 | if ($b eq '-b') {
|
---|
| 1792 | $$tmpl = '';
|
---|
| 1793 | } else {
|
---|
| 1794 | $$tmpl =~ s/$ngb/bcast/;
|
---|
| 1795 | $ipkill = 1;
|
---|
| 1796 | }
|
---|
| 1797 | } else {
|
---|
| 1798 | $$tmpl =~ s/$ngb//;
|
---|
| 1799 | }
|
---|
| 1800 | }
|
---|
| 1801 |
|
---|
| 1802 | # We don't (usually) want to expand the IP-related patterns on the -net, -gw, or -bcast IPs.
|
---|
| 1803 | # Arguably this is another place for another config knob, or possibly further extension of
|
---|
| 1804 | # the template pattern to control it on a per-subnet basis.
|
---|
| 1805 | if ($ipkill) {
|
---|
| 1806 | # kill common IP patterns
|
---|
| 1807 | $$tmpl =~ s/\%[_.-]?[irdh]//;
|
---|
| 1808 | # kill IP octet patterns
|
---|
| 1809 | $$tmpl =~ s/\%[1234][dh0](?:[_.-]\%[1234][dh0]){0,3}//;
|
---|
| 1810 | }
|
---|
| 1811 |
|
---|
| 1812 | # and now clean up to make sure we leave a valid DNS label... mostly. Should arguably
|
---|
| 1813 | # split on /\./ and process each label separately.
|
---|
| 1814 | $$tmpl =~ s/([_-]){3}/$1/ if !$thrsep;
|
---|
| 1815 | $$tmpl =~ s/([_-]){2}/$1/ if !$twosep;
|
---|
| 1816 | $$tmpl =~ s/[_-]\././;
|
---|
| 1817 |
|
---|
| 1818 | } # if ($subnet)
|
---|
| 1819 |
|
---|
[337] | 1820 | # IP substitutions in template records:
|
---|
| 1821 | #major patterns:
|
---|
| 1822 | #dashed IP, forward and reverse
|
---|
[532] | 1823 | #underscoreed IP, forward and reverse
|
---|
[337] | 1824 | #dotted IP, forward and reverse (even if forward is... dumb)
|
---|
[532] | 1825 | # -> %r for reverse, %i for forward, leading -, _, or . to indicate separator, defaults to -
|
---|
[337] | 1826 | # %r or %-r => %4d-%3d-%2d-%1d
|
---|
[532] | 1827 | # %_r => %4d_%3d_%2d_%1d
|
---|
[337] | 1828 | # %.r => %4d.%3d.%2d.%1d
|
---|
| 1829 | # %i or %-i => %1d-%2d-%3d-%4d
|
---|
[532] | 1830 | # %_i => %1d_%2d_%3d_%4d
|
---|
[337] | 1831 | # %.i => %1d.%2d.%3d.%4d
|
---|
| 1832 | $$tmpl =~ s/\%r/\%4d-\%3d-\%2d-\%1d/g;
|
---|
[532] | 1833 | $$tmpl =~ s/\%([-._])r/\%4d$1\%3d$1\%2d$1\%1d/g;
|
---|
[337] | 1834 | $$tmpl =~ s/\%i/\%1d-\%2d-\%3d-\%4d/g;
|
---|
[532] | 1835 | $$tmpl =~ s/\%([-._])i/\%1d$1\%2d$1\%3d$1\%4d/g;
|
---|
[337] | 1836 |
|
---|
| 1837 | #hex-coded IP
|
---|
| 1838 | # %h
|
---|
| 1839 | $$tmpl =~ s/\%h/$iphex[0]$iphex[1]$iphex[2]$iphex[3]/g;
|
---|
| 1840 |
|
---|
| 1841 | #IP as decimal-coded 32-bit value
|
---|
| 1842 | # %d
|
---|
| 1843 | my $iptmp = $ipparts[0]*256*256*256 + $ipparts[1]*256*256 + $ipparts[2]*256 + $ipparts[3];
|
---|
| 1844 | $$tmpl =~ s/\%d/$iptmp/g;
|
---|
| 1845 |
|
---|
| 1846 | #minor patterns (per-octet)
|
---|
| 1847 | # %[1234][dh0]
|
---|
| 1848 | #octet
|
---|
| 1849 | #hex-coded octet
|
---|
| 1850 | #0-padded octet
|
---|
| 1851 | $$tmpl =~ s/\%([1234])d/$ipparts[$1-1]/g;
|
---|
| 1852 | $$tmpl =~ s/\%([1234])h/$iphex[$1-1]/g;
|
---|
[443] | 1853 | $$tmpl =~ s/\%([1234])0/$ippad[$1-1]/g;
|
---|
[685] | 1854 |
|
---|
[337] | 1855 | } # _template4_expand()
|
---|
| 1856 |
|
---|
[532] | 1857 | # Broad syntactic check on the hostname. Checks for valid characters, correctly-expandable template patterns.
|
---|
| 1858 | # Takes the hostname, type, and live/default and forward/reverse flags
|
---|
| 1859 | # Returns true/false, sets errstr on failures
|
---|
| 1860 | sub _check_hostname_form {
|
---|
| 1861 | my ($hname,$rectype,$defrec,$revrec) = @_;
|
---|
[337] | 1862 |
|
---|
[532] | 1863 | if ($hname =~ /\%/ && ($rectype == 65282 || $rectype == 65283) ) {
|
---|
| 1864 | my $tmphost = $hname;
|
---|
| 1865 | # we don't actually need to test with the real IP passed; that saves a bit of fiddling.
|
---|
[685] | 1866 | DNSDB::_template4_expand(\$tmphost, '10.10.10.10');
|
---|
[653] | 1867 | if ($tmphost =~ /\%/ || lc($tmphost) !~ /^(?:\*\.)?(?:[0-9a-z_.-]+)$/) {
|
---|
[532] | 1868 | $errstr = "Invalid template $hname";
|
---|
| 1869 | return;
|
---|
| 1870 | }
|
---|
[668] | 1871 | } elsif ($rectype == $reverse_typemap{CNAME} && $revrec eq 'y') {
|
---|
[625] | 1872 | # Allow / in reverse CNAME hostnames for sub-/24 delegation
|
---|
| 1873 | if (lc($hname) !~ m|^[0-9a-z_./-]+$|) {
|
---|
| 1874 | # error message is deliberately restrictive; special cases are SPECIAL and not for general use
|
---|
| 1875 | $errstr = "Hostnames may not contain anything other than (0-9 a-z . _)";
|
---|
| 1876 | return;
|
---|
| 1877 | }
|
---|
[532] | 1878 | } elsif ($revrec eq 'y') {
|
---|
| 1879 | # Reverse zones don't support @ in hostnames
|
---|
[625] | 1880 | if (lc($hname) !~ /^(?:\*\.)?[0-9a-z_.-]+$/) {
|
---|
| 1881 | # error message is deliberately restrictive; special cases are SPECIAL and not for general use
|
---|
[532] | 1882 | $errstr = "Hostnames may not contain anything other than (0-9 a-z . _)";
|
---|
| 1883 | return;
|
---|
| 1884 | }
|
---|
| 1885 | } else {
|
---|
[600] | 1886 | if (lc($hname) !~ /^(?:\*\.)?(?:[0-9a-z_.-]+|@)$/) {
|
---|
[532] | 1887 | # Don't mention @, because it would be far too wordy to explain the nuance of @
|
---|
| 1888 | $errstr = "Hostnames may not contain anything other than (0-9 a-z . _)";
|
---|
| 1889 | return;
|
---|
| 1890 | }
|
---|
| 1891 | }
|
---|
| 1892 | return 1;
|
---|
| 1893 | } # _check_hostname_form()
|
---|
| 1894 |
|
---|
| 1895 |
|
---|
[228] | 1896 | ##
|
---|
[2] | 1897 | ## Initialization and cleanup subs
|
---|
| 1898 | ##
|
---|
| 1899 |
|
---|
[128] | 1900 | ## DNSDB::__cfgload()
|
---|
| 1901 | # Private sub to parse a config file and load it into %config
|
---|
[517] | 1902 | # Takes a filename and a hashref to put the parsed entries in
|
---|
[128] | 1903 | sub __cfgload {
|
---|
| 1904 | $errstr = '';
|
---|
| 1905 | my $cfgfile = shift;
|
---|
[517] | 1906 | my $cfg = shift;
|
---|
[131] | 1907 |
|
---|
[128] | 1908 | if (open CFG, "<$cfgfile") {
|
---|
| 1909 | while (<CFG>) {
|
---|
| 1910 | chomp;
|
---|
| 1911 | s/^\s*//;
|
---|
| 1912 | next if /^#/;
|
---|
| 1913 | next if /^$/;
|
---|
| 1914 | # hmm. more complex bits in this file might require [heading] headers, maybe?
|
---|
| 1915 | # $mode = $1 if /^\[(a-z)+]/;
|
---|
| 1916 | # DB connect info
|
---|
[517] | 1917 | $cfg->{dbname} = $1 if /^dbname\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1918 | $cfg->{dbuser} = $1 if /^dbuser\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1919 | $cfg->{dbpass} = $1 if /^dbpass\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1920 | $cfg->{dbhost} = $1 if /^dbhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
[128] | 1921 | # Mail settings
|
---|
[517] | 1922 | $cfg->{mailhost} = $1 if /^mailhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1923 | $cfg->{mailnotify} = $1 if /^mailnotify\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
| 1924 | $cfg->{mailsender} = $1 if /^mailsender\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
| 1925 | $cfg->{mailname} = $1 if /^mailname\s*=\s*([a-z0-9\s_.-]+)/i;
|
---|
| 1926 | $cfg->{orgname} = $1 if /^orgname\s*=\s*([a-z0-9\s_.,'-]+)/i;
|
---|
| 1927 | $cfg->{domain} = $1 if /^domain\s*=\s*([a-z0-9_.-]+)/i;
|
---|
[163] | 1928 | # session - note this is fed directly to CGI::Session
|
---|
[517] | 1929 | $cfg->{timeout} = $1 if /^[tT][iI][mM][eE][oO][uU][tT]\s*=\s*(\d+[smhdwMy]?)/;
|
---|
| 1930 | $cfg->{sessiondir} = $1 if m{^sessiondir\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
[201] | 1931 | # misc
|
---|
[517] | 1932 | $cfg->{log_failures} = $1 if /^log_failures\s*=\s*([a-z01]+)/i;
|
---|
| 1933 | $cfg->{perpage} = $1 if /^perpage\s*=\s*(\d+)/i;
|
---|
| 1934 | $cfg->{exportcache} = $1 if m{^exportcache\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
[559] | 1935 | $cfg->{usecache} = $1 if m{^usecache\s*=\s*([a-z01]+)}i;
|
---|
| 1936 | $cfg->{force_refresh} = $1 if /^force_refresh\s*=\s*([a-z01]+)/i;
|
---|
[542] | 1937 | $cfg->{lowercase} = $1 if /^lowercase\s*=\s*([a-z01]+)/i;
|
---|
[583] | 1938 | $cfg->{showrev_arpa} = $1 if /^showrev_arpa\s*=\s*([a-z]+)/i;
|
---|
[644] | 1939 | $cfg->{template_skip_0} = $1 if /^template_skip_0\s*=\s*([a-z01]+)/i;
|
---|
| 1940 | $cfg->{template_skip_255} = $1 if /^template_skip_255\s*=\s*([a-z01]+)/i;
|
---|
[714] | 1941 | $cfg->{autotxt} = $1 if /^autotxt\s*=\s*([a-z01]+)/i;
|
---|
[517] | 1942 | # not supported in dns.cgi yet
|
---|
| 1943 | # $cfg->{templatedir} = $1 if m{^templatedir\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
| 1944 | # $cfg->{templateoverride} = $1 if m{^templateoverride\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
[400] | 1945 | # RPC options
|
---|
[517] | 1946 | $cfg->{rpcmode} = $1 if /^rpc_mode\s*=\s*(socket|HTTP|XMLRPC)\s*$/i;
|
---|
| 1947 | $cfg->{maxfcgi} = $1 if /^max_fcgi_requests\s*=\s*(\d+)\s*$/i;
|
---|
[465] | 1948 | if (my ($tmp) = /^rpc_iplist\s*=\s*(.+)/i) {
|
---|
| 1949 | my @ips = split /[,\s]+/, $tmp;
|
---|
| 1950 | my $rpcsys = shift @ips;
|
---|
[517] | 1951 | push @{$cfg->{rpcacl}{$rpcsys}}, @ips;
|
---|
[400] | 1952 | }
|
---|
[128] | 1953 | }
|
---|
| 1954 | close CFG;
|
---|
| 1955 | } else {
|
---|
[517] | 1956 | $errstr = "Couldn't load configuration file $cfgfile: $!";
|
---|
[128] | 1957 | return;
|
---|
| 1958 | }
|
---|
| 1959 | return 1;
|
---|
| 1960 | } # end __cfgload()
|
---|
| 1961 |
|
---|
| 1962 |
|
---|
[2] | 1963 | ## DNSDB::connectDB()
|
---|
| 1964 | # Creates connection to DNS database.
|
---|
| 1965 | # Requires the database name, username, and password.
|
---|
[465] | 1966 | # Returns a handle to the db or undef on failure.
|
---|
[2] | 1967 | # Set up for a PostgreSQL db; could be any transactional DBMS with the
|
---|
| 1968 | # right changes.
|
---|
[465] | 1969 | # Called by new(); not intended to be called publicly.
|
---|
[2] | 1970 | sub connectDB {
|
---|
| 1971 | $errstr = '';
|
---|
[15] | 1972 | my $dbname = shift;
|
---|
| 1973 | my $user = shift;
|
---|
| 1974 | my $pass = shift;
|
---|
[2] | 1975 | my $dbh;
|
---|
| 1976 | my $DSN = "DBI:Pg:dbname=$dbname";
|
---|
| 1977 |
|
---|
| 1978 | my $host = shift;
|
---|
| 1979 | $DSN .= ";host=$host" if $host;
|
---|
| 1980 |
|
---|
| 1981 | # Note that we want to autocommit by default, and we will turn it off locally as necessary.
|
---|
| 1982 | # We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
|
---|
| 1983 | $dbh = DBI->connect($DSN, $user, $pass, {
|
---|
| 1984 | AutoCommit => 1,
|
---|
| 1985 | PrintError => 0
|
---|
[465] | 1986 | });
|
---|
| 1987 | if (!$dbh) {
|
---|
| 1988 | $errstr = $DBI::errstr;
|
---|
| 1989 | return;
|
---|
| 1990 | }
|
---|
| 1991 | #) if(!$dbh);
|
---|
[2] | 1992 |
|
---|
[465] | 1993 | local $dbh->{RaiseError} = 1;
|
---|
| 1994 |
|
---|
| 1995 | eval {
|
---|
[212] | 1996 | ##fixme: initialize the DB if we can't find the table (since, by definition, there's
|
---|
| 1997 | # nothing there if we can't select from it...)
|
---|
[465] | 1998 | my $tblsth = $dbh->prepare("SELECT count(*) FROM pg_catalog.pg_class WHERE relkind='r' AND relname=?");
|
---|
| 1999 | my ($tblcount) = $dbh->selectrow_array($tblsth, undef, ('misc'));
|
---|
| 2000 | # return (undef,$DBI::errstr) if $dbh->err;
|
---|
[212] | 2001 |
|
---|
| 2002 | #if ($tblcount == 0) {
|
---|
| 2003 | # # create tables one at a time, checking for each.
|
---|
| 2004 | # return (undef, "check table misc missing");
|
---|
| 2005 | #}
|
---|
| 2006 |
|
---|
| 2007 | # Return here if we can't select.
|
---|
| 2008 | # This should retrieve the dbversion key.
|
---|
[465] | 2009 | my $sth = $dbh->prepare("SELECT key,value FROM misc WHERE misc_id=1");
|
---|
| 2010 | $sth->execute();
|
---|
| 2011 | # return (undef,$DBI::errstr) if ($sth->err);
|
---|
[2] | 2012 |
|
---|
[212] | 2013 | ##fixme: do stuff to the DB on version mismatch
|
---|
| 2014 | # x.y series should upgrade on $DNSDB::VERSION > misc(key=>version)
|
---|
| 2015 | # DB should be downward-compatible; column defaults should give sane (if possibly
|
---|
| 2016 | # useless-and-needs-help) values in columns an older software stack doesn't know about.
|
---|
| 2017 |
|
---|
[2] | 2018 | # See if the select returned anything (or null data). This should
|
---|
| 2019 | # succeed if the select executed, but...
|
---|
[465] | 2020 | $sth->fetchrow();
|
---|
| 2021 | # return (undef,$DBI::errstr) if ($sth->err);
|
---|
[2] | 2022 |
|
---|
[465] | 2023 | $sth->finish;
|
---|
[2] | 2024 |
|
---|
[465] | 2025 | }; # wrapped DB checks
|
---|
| 2026 | if ($@) {
|
---|
| 2027 | $errstr = $@;
|
---|
| 2028 | return;
|
---|
| 2029 | }
|
---|
| 2030 |
|
---|
[2] | 2031 | # If we get here, we should be OK.
|
---|
[465] | 2032 | return $dbh;
|
---|
[2] | 2033 | } # end connectDB
|
---|
| 2034 |
|
---|
| 2035 |
|
---|
| 2036 | ## DNSDB::finish()
|
---|
| 2037 | # Cleans up after database handles and so on.
|
---|
| 2038 | # Requires a database handle
|
---|
| 2039 | sub finish {
|
---|
[465] | 2040 | my $self = shift;
|
---|
| 2041 | $self->{dbh}->disconnect;
|
---|
[2] | 2042 | } # end finish
|
---|
| 2043 |
|
---|
| 2044 |
|
---|
| 2045 | ## DNSDB::initGlobals()
|
---|
| 2046 | # Initialize global variables
|
---|
| 2047 | # NB: this does NOT include web-specific session variables!
|
---|
| 2048 | sub initGlobals {
|
---|
[465] | 2049 | my $self = shift;
|
---|
| 2050 | my $dbh = $self->{dbh};
|
---|
[2] | 2051 |
|
---|
[208] | 2052 | # load record types from database
|
---|
[228] | 2053 | my $sth = $dbh->prepare("SELECT val,name,stdflag FROM rectypes");
|
---|
[2] | 2054 | $sth->execute;
|
---|
[228] | 2055 | while (my ($recval,$recname,$stdflag) = $sth->fetchrow_array()) {
|
---|
[2] | 2056 | $typemap{$recval} = $recname;
|
---|
| 2057 | $reverse_typemap{$recname} = $recval;
|
---|
[228] | 2058 | # now we fill the record validation function hash
|
---|
| 2059 | if ($stdflag < 5) {
|
---|
| 2060 | my $fn = "_validate_$recval";
|
---|
| 2061 | $validators{$recval} = \&$fn;
|
---|
| 2062 | } else {
|
---|
| 2063 | my $fn = "sub { return ('FAIL','Type $recval ($recname) not supported'); }";
|
---|
| 2064 | $validators{$recval} = eval $fn;
|
---|
| 2065 | }
|
---|
[2] | 2066 | }
|
---|
| 2067 | } # end initGlobals
|
---|
| 2068 |
|
---|
| 2069 |
|
---|
[401] | 2070 | ## DNSDB::initRPC()
|
---|
[469] | 2071 | # Takes a remote username and remote fullname.
|
---|
[401] | 2072 | # Sets up the RPC logging-pseudouser if needed.
|
---|
| 2073 | # Sets the %userdata hash for logging.
|
---|
| 2074 | # Returns undef on failure
|
---|
| 2075 | sub initRPC {
|
---|
[469] | 2076 | my $self = shift;
|
---|
| 2077 | my $dbh = $self->{dbh};
|
---|
[401] | 2078 | my %args = @_;
|
---|
| 2079 |
|
---|
| 2080 | return if !$args{username};
|
---|
| 2081 | return if !$args{fullname};
|
---|
| 2082 |
|
---|
[406] | 2083 | $args{username} = "$args{username}/$args{rpcsys}";
|
---|
| 2084 |
|
---|
| 2085 | my $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
|
---|
[404] | 2086 | " FROM users WHERE username=?", undef, ($args{username}) );
|
---|
[406] | 2087 | if (!$tmpuser) {
|
---|
[401] | 2088 | $dbh->do("INSERT INTO users (username,password,firstname,type) VALUES (?,'RPC',?,'R')", undef,
|
---|
| 2089 | ($args{username}, $args{fullname}) );
|
---|
[406] | 2090 | $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
|
---|
[404] | 2091 | " FROM users WHERE username=?", undef, ($args{username}) );
|
---|
[401] | 2092 | }
|
---|
[488] | 2093 | $tmpuser->{lastname} = '' if !$tmpuser->{lastname};
|
---|
| 2094 | $self->{loguserid} = $tmpuser->{userid};
|
---|
| 2095 | $self->{logusername} = $tmpuser->{username};
|
---|
| 2096 | $self->{logfullname} = "$tmpuser->{firstname} $tmpuser->{lastname} ($args{rpcsys})";
|
---|
[406] | 2097 | return 1 if $tmpuser;
|
---|
[401] | 2098 | } # end initRPC()
|
---|
| 2099 |
|
---|
| 2100 |
|
---|
[278] | 2101 | ## DNSDB::login()
|
---|
| 2102 | # Takes a database handle, username and password
|
---|
[316] | 2103 | # Returns a userdata hash (UID, GID, username, fullname parts) if username exists,
|
---|
| 2104 | # password matches the one on file, and account is not disabled
|
---|
[278] | 2105 | # Returns undef otherwise
|
---|
| 2106 | sub login {
|
---|
[469] | 2107 | my $self = shift;
|
---|
| 2108 | my $dbh = $self->{dbh};
|
---|
[278] | 2109 | my $user = shift;
|
---|
| 2110 | my $pass = shift;
|
---|
| 2111 |
|
---|
[316] | 2112 | my $userinfo = $dbh->selectrow_hashref("SELECT user_id,group_id,password,firstname,lastname,status".
|
---|
| 2113 | " FROM users WHERE username=?",
|
---|
[279] | 2114 | undef, ($user) );
|
---|
| 2115 | return if !$userinfo;
|
---|
[316] | 2116 | return if !$userinfo->{status};
|
---|
[278] | 2117 |
|
---|
[279] | 2118 | if ($userinfo->{password} =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
|
---|
[278] | 2119 | # native passwords (crypt-md5)
|
---|
[279] | 2120 | return if $userinfo->{password} ne unix_md5_crypt($pass,$1);
|
---|
| 2121 | } elsif ($userinfo->{password} =~ /^[0-9a-f]{32}$/) {
|
---|
[278] | 2122 | # VegaDNS import (hex-coded MD5)
|
---|
[279] | 2123 | return if $userinfo->{password} ne md5_hex($pass);
|
---|
[278] | 2124 | } else {
|
---|
| 2125 | # plaintext (convenient now and then)
|
---|
[279] | 2126 | return if $userinfo->{password} ne $pass;
|
---|
[278] | 2127 | }
|
---|
| 2128 |
|
---|
[279] | 2129 | return $userinfo;
|
---|
[278] | 2130 | } # end login()
|
---|
| 2131 |
|
---|
| 2132 |
|
---|
[279] | 2133 | ## DNSDB::initActionLog()
|
---|
| 2134 | # Set up action logging. Takes a database handle and user ID
|
---|
| 2135 | # Sets some internal globals and Does The Right Thing to set up a logging channel.
|
---|
| 2136 | # This sets up _log() to spew out log entries to the defined channel without worrying
|
---|
| 2137 | # about having to open a file or a syslog channel
|
---|
| 2138 | ##fixme Need to call _initActionLog_blah() for various logging channels, configured
|
---|
[517] | 2139 | # via dnsdb.conf, in $self->{log_channel} or something
|
---|
[279] | 2140 | # See https://secure.deepnet.cx/trac/dnsadmin/ticket/21
|
---|
| 2141 | sub initActionLog {
|
---|
[469] | 2142 | my $self = shift;
|
---|
| 2143 | my $dbh = $self->{dbh};
|
---|
[279] | 2144 | my $uid = shift;
|
---|
| 2145 |
|
---|
| 2146 | return if !$uid;
|
---|
| 2147 |
|
---|
| 2148 | # snag user info for logging. there's got to be a way to not have to pass this back
|
---|
| 2149 | # and forth from a caller, but web usage means no persistence we can rely on from
|
---|
| 2150 | # the server side.
|
---|
| 2151 | my ($username,$fullname) = $dbh->selectrow_array("SELECT username, firstname || ' ' || lastname".
|
---|
| 2152 | " FROM users WHERE user_id=?", undef, ($uid));
|
---|
| 2153 | ##fixme: errors are unpossible!
|
---|
| 2154 |
|
---|
[488] | 2155 | $self->{logusername} = $username;
|
---|
| 2156 | $self->{loguserid} = $uid;
|
---|
| 2157 | $self->{logfullname} = $fullname;
|
---|
[279] | 2158 |
|
---|
| 2159 | # convert to real check once we have other logging channels
|
---|
[517] | 2160 | # if ($self->{log_channel} eq 'sql') {
|
---|
[279] | 2161 | # Open Log, Sez Me!
|
---|
| 2162 | # }
|
---|
| 2163 |
|
---|
| 2164 | } # end initActionLog
|
---|
| 2165 |
|
---|
| 2166 |
|
---|
[65] | 2167 | ## DNSDB::getPermissions()
|
---|
| 2168 | # Get permissions from DB
|
---|
| 2169 | # Requires DB handle, group or user flag, ID, and hashref.
|
---|
| 2170 | sub getPermissions {
|
---|
[469] | 2171 | my $self = shift;
|
---|
| 2172 | my $dbh = $self->{dbh};
|
---|
| 2173 |
|
---|
[65] | 2174 | my $type = shift;
|
---|
| 2175 | my $id = shift;
|
---|
| 2176 | my $hash = shift;
|
---|
| 2177 |
|
---|
| 2178 | my $sql = qq(
|
---|
| 2179 | SELECT
|
---|
| 2180 | p.admin,p.self_edit,
|
---|
| 2181 | p.group_create,p.group_edit,p.group_delete,
|
---|
| 2182 | p.user_create,p.user_edit,p.user_delete,
|
---|
| 2183 | p.domain_create,p.domain_edit,p.domain_delete,
|
---|
[387] | 2184 | p.record_create,p.record_edit,p.record_delete,p.record_locchg,
|
---|
[382] | 2185 | p.location_create,p.location_edit,p.location_delete,p.location_view
|
---|
[65] | 2186 | FROM permissions p
|
---|
| 2187 | );
|
---|
| 2188 | if ($type eq 'group') {
|
---|
| 2189 | $sql .= qq(
|
---|
| 2190 | JOIN groups g ON g.permission_id=p.permission_id
|
---|
| 2191 | WHERE g.group_id=?
|
---|
| 2192 | );
|
---|
| 2193 | } else {
|
---|
| 2194 | $sql .= qq(
|
---|
| 2195 | JOIN users u ON u.permission_id=p.permission_id
|
---|
| 2196 | WHERE u.user_id=?
|
---|
| 2197 | );
|
---|
| 2198 | }
|
---|
| 2199 |
|
---|
| 2200 | my $sth = $dbh->prepare($sql);
|
---|
| 2201 |
|
---|
[514] | 2202 | ##fixme? we don't trap other plain SELECT errors
|
---|
| 2203 | $sth->execute($id);
|
---|
[65] | 2204 |
|
---|
| 2205 | # my $permref = $sth->fetchrow_hashref;
|
---|
| 2206 | # return $permref;
|
---|
| 2207 | # $hash = $permref;
|
---|
| 2208 | # Eww. Need to learn how to forcibly drop a hashref onto an existing hash.
|
---|
| 2209 | ($hash->{admin},$hash->{self_edit},
|
---|
| 2210 | $hash->{group_create},$hash->{group_edit},$hash->{group_delete},
|
---|
| 2211 | $hash->{user_create},$hash->{user_edit},$hash->{user_delete},
|
---|
| 2212 | $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete},
|
---|
[387] | 2213 | $hash->{record_create},$hash->{record_edit},$hash->{record_delete},$hash->{record_locchg},
|
---|
[382] | 2214 | $hash->{location_create},$hash->{location_edit},$hash->{location_delete},$hash->{location_view}
|
---|
| 2215 | ) = $sth->fetchrow_array;
|
---|
[65] | 2216 |
|
---|
| 2217 | } # end getPermissions()
|
---|
| 2218 |
|
---|
| 2219 |
|
---|
| 2220 | ## DNSDB::changePermissions()
|
---|
| 2221 | # Update an ACL entry
|
---|
| 2222 | # Takes a db handle, type, owner-id, and hashref for the changed permissions.
|
---|
| 2223 | sub changePermissions {
|
---|
[474] | 2224 | my $self = shift;
|
---|
| 2225 | my $dbh = $self->{dbh};
|
---|
[65] | 2226 | my $type = shift;
|
---|
| 2227 | my $id = shift;
|
---|
| 2228 | my $newperms = shift;
|
---|
[87] | 2229 | my $inherit = shift || 0;
|
---|
[65] | 2230 |
|
---|
[294] | 2231 | my $resultmsg = '';
|
---|
[66] | 2232 |
|
---|
[87] | 2233 | # see if we're switching from inherited to custom. for bonus points,
|
---|
| 2234 | # snag the permid and parent permid anyway, since we'll need the permid
|
---|
| 2235 | # to set/alter custom perms, and both if we're switching from custom to
|
---|
| 2236 | # inherited.
|
---|
[294] | 2237 | my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id,".
|
---|
| 2238 | ($type eq 'user' ? 'u.group_id,u.username' : 'u.parent_group_id,u.group_name').
|
---|
[65] | 2239 | " FROM ".($type eq 'user' ? 'users' : 'groups')." u ".
|
---|
[66] | 2240 | " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ".
|
---|
[65] | 2241 | " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?");
|
---|
| 2242 | $sth->execute($id);
|
---|
| 2243 |
|
---|
[294] | 2244 | my ($wasinherited,$permid,$parpermid,$parid,$name) = $sth->fetchrow_array;
|
---|
[66] | 2245 |
|
---|
[78] | 2246 | # hack phtoui
|
---|
| 2247 | # group id 1 is "special" in that it's it's own parent (err... possibly.)
|
---|
| 2248 | # may make its parent id 0 which doesn't exist, and as a bonus is Perl-false.
|
---|
| 2249 | $wasinherited = 0 if ($type eq 'group' && $id == 1);
|
---|
| 2250 |
|
---|
[66] | 2251 | local $dbh->{AutoCommit} = 0;
|
---|
| 2252 | local $dbh->{RaiseError} = 1;
|
---|
| 2253 |
|
---|
| 2254 | # Wrap all the SQL in a transaction
|
---|
| 2255 | eval {
|
---|
[87] | 2256 | if ($inherit) {
|
---|
| 2257 |
|
---|
| 2258 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ".
|
---|
| 2259 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) );
|
---|
| 2260 | $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) );
|
---|
| 2261 |
|
---|
| 2262 | } else {
|
---|
| 2263 |
|
---|
| 2264 | if ($wasinherited) { # munge new permission entry in if we're switching from inherited perms
|
---|
[66] | 2265 | ##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users
|
---|
[87] | 2266 | # ... if'n'when we have groups with fully inherited permissions.
|
---|
| 2267 | # SQL is coo
|
---|
| 2268 | $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ".
|
---|
| 2269 | "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) );
|
---|
| 2270 | ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ".
|
---|
| 2271 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) );
|
---|
| 2272 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ".
|
---|
| 2273 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) );
|
---|
[66] | 2274 | }
|
---|
[78] | 2275 |
|
---|
[87] | 2276 | # and now set the permissions we were passed
|
---|
| 2277 | foreach (@permtypes) {
|
---|
| 2278 | if (defined ($newperms->{$_})) {
|
---|
| 2279 | $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) );
|
---|
| 2280 | }
|
---|
| 2281 | }
|
---|
| 2282 |
|
---|
| 2283 | } # (inherited->)? custom
|
---|
| 2284 |
|
---|
[294] | 2285 | if ($type eq 'user') {
|
---|
| 2286 | $resultmsg = "Updated permissions for user $name";
|
---|
| 2287 | } else {
|
---|
| 2288 | $resultmsg = "Updated default permissions for group $name";
|
---|
| 2289 | }
|
---|
[487] | 2290 | $self->_log(group_id => ($type eq 'user' ? $parid : $id), entry => $resultmsg);
|
---|
[66] | 2291 | $dbh->commit;
|
---|
| 2292 | }; # end eval
|
---|
| 2293 | if ($@) {
|
---|
| 2294 | my $msg = $@;
|
---|
| 2295 | eval { $dbh->rollback; };
|
---|
[294] | 2296 | return ('FAIL',"Error changing permissions: $msg");
|
---|
[66] | 2297 | }
|
---|
| 2298 |
|
---|
[294] | 2299 | return ('OK',$resultmsg);
|
---|
[65] | 2300 | } # end changePermissions()
|
---|
| 2301 |
|
---|
| 2302 |
|
---|
[67] | 2303 | ## DNSDB::comparePermissions()
|
---|
| 2304 | # Compare two permission hashes
|
---|
| 2305 | # Returns '>', '<', '=', '!'
|
---|
| 2306 | sub comparePermissions {
|
---|
[592] | 2307 | my $self = shift;
|
---|
[67] | 2308 | my $p1 = shift;
|
---|
| 2309 | my $p2 = shift;
|
---|
| 2310 |
|
---|
| 2311 | my $retval = '='; # assume equality until proven otherwise
|
---|
| 2312 |
|
---|
| 2313 | no warnings "uninitialized";
|
---|
| 2314 |
|
---|
| 2315 | foreach (@permtypes) {
|
---|
| 2316 | next if $p1->{$_} == $p2->{$_}; # equal is good
|
---|
| 2317 | if ($p1->{$_} && !$p2->{$_}) {
|
---|
| 2318 | if ($retval eq '<') { # if we've already found an unequal pair where
|
---|
| 2319 | $retval = '!'; # $p2 has more access, and we now find a pair
|
---|
| 2320 | last; # where $p1 has more access, the overall access
|
---|
| 2321 | } # is neither greater or lesser, it's unequal.
|
---|
| 2322 | $retval = '>';
|
---|
| 2323 | }
|
---|
| 2324 | if (!$p1->{$_} && $p2->{$_}) {
|
---|
| 2325 | if ($retval eq '>') { # if we've already found an unequal pair where
|
---|
| 2326 | $retval = '!'; # $p1 has more access, and we now find a pair
|
---|
| 2327 | last; # where $p2 has more access, the overall access
|
---|
| 2328 | } # is neither greater or lesser, it's unequal.
|
---|
| 2329 | $retval = '<';
|
---|
| 2330 | }
|
---|
| 2331 | }
|
---|
| 2332 | return $retval;
|
---|
| 2333 | } # end comparePermissions()
|
---|
| 2334 |
|
---|
| 2335 |
|
---|
[112] | 2336 | ## DNSDB::changeGroup()
|
---|
| 2337 | # Change group ID of an entity
|
---|
| 2338 | # Takes a database handle, entity type, entity ID, and new group ID
|
---|
| 2339 | sub changeGroup {
|
---|
[476] | 2340 | my $self = shift;
|
---|
| 2341 | my $dbh = $self->{dbh};
|
---|
[112] | 2342 | my $type = shift;
|
---|
| 2343 | my $id = shift;
|
---|
| 2344 | my $newgrp = shift;
|
---|
| 2345 |
|
---|
| 2346 | ##fixme: fail on not enough args
|
---|
| 2347 | #return ('FAIL', "Missing
|
---|
| 2348 |
|
---|
[295] | 2349 | return ('FAIL', "Can't change the group of a $type")
|
---|
| 2350 | unless grep /^$type$/, ('domain','revzone','user','group'); # could be extended for defrecs?
|
---|
| 2351 |
|
---|
| 2352 | # Collect some names for logging and messages
|
---|
| 2353 | my $entname;
|
---|
[112] | 2354 | if ($type eq 'domain') {
|
---|
[473] | 2355 | $entname = $self->domainName($id);
|
---|
[295] | 2356 | } elsif ($type eq 'revzone') {
|
---|
[473] | 2357 | $entname = $self->revName($id);
|
---|
[112] | 2358 | } elsif ($type eq 'user') {
|
---|
[473] | 2359 | $entname = $self->userFullName($id, '%u');
|
---|
[112] | 2360 | } elsif ($type eq 'group') {
|
---|
[473] | 2361 | $entname = $self->groupName($id);
|
---|
[112] | 2362 | }
|
---|
[295] | 2363 |
|
---|
| 2364 | my ($oldgid) = $dbh->selectrow_array("SELECT group_id FROM $par_tbl{$type} WHERE $id_col{$type}=?",
|
---|
| 2365 | undef, ($id));
|
---|
[473] | 2366 | my $oldgname = $self->groupName($oldgid);
|
---|
| 2367 | my $newgname = $self->groupName($newgrp);
|
---|
[295] | 2368 |
|
---|
| 2369 | return ('FAIL', "Can't move things into a group that doesn't exist") if !$newgname;
|
---|
| 2370 |
|
---|
| 2371 | return ('WARN', "Nothing to do, new group is the same as the old group") if $oldgid == $newgrp;
|
---|
| 2372 |
|
---|
| 2373 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2374 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2375 | local $dbh->{AutoCommit} = 0;
|
---|
| 2376 | local $dbh->{RaiseError} = 1;
|
---|
| 2377 |
|
---|
| 2378 | eval {
|
---|
| 2379 | $dbh->do("UPDATE $par_tbl{$type} SET group_id=? WHERE $id_col{$type}=?", undef, ($newgrp, $id));
|
---|
| 2380 | # Log the change in both the old and new groups
|
---|
[487] | 2381 | $self->_log(group_id => $oldgid, entry => "Moved $type $entname from $oldgname to $newgname");
|
---|
| 2382 | $self->_log(group_id => $newgrp, entry => "Moved $type $entname from $oldgname to $newgname");
|
---|
[295] | 2383 | $dbh->commit;
|
---|
| 2384 | };
|
---|
| 2385 | if ($@) {
|
---|
| 2386 | my $msg = $@;
|
---|
| 2387 | eval { $dbh->rollback; };
|
---|
[517] | 2388 | if ($self->{log_failures}) {
|
---|
[487] | 2389 | $self->_log(group_id => $oldgid, entry => "Error moving $type $entname to $newgname: $msg");
|
---|
[295] | 2390 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2391 | }
|
---|
| 2392 | return ('FAIL',"Error moving $type $entname to $newgname: $msg");
|
---|
| 2393 | }
|
---|
| 2394 |
|
---|
| 2395 | return ('OK',"Moved $type $entname from $oldgname to $newgname");
|
---|
[112] | 2396 | } # end changeGroup()
|
---|
| 2397 |
|
---|
| 2398 |
|
---|
[2] | 2399 | ##
|
---|
| 2400 | ## Processing subs
|
---|
| 2401 | ##
|
---|
| 2402 |
|
---|
| 2403 | ## DNSDB::addDomain()
|
---|
| 2404 | # Add a domain
|
---|
[190] | 2405 | # Takes a database handle, domain name, numeric group, boolean(ish) state (active/inactive),
|
---|
[704] | 2406 | # and a default location indicator
|
---|
[2] | 2407 | # Returns a status code and message
|
---|
| 2408 | sub addDomain {
|
---|
| 2409 | $errstr = '';
|
---|
[477] | 2410 | my $self = shift;
|
---|
| 2411 | my $dbh = $self->{dbh};
|
---|
[2] | 2412 | my $domain = shift;
|
---|
[497] | 2413 | return ('FAIL',"Domain must not be blank\n") if !$domain;
|
---|
[2] | 2414 | my $group = shift;
|
---|
[497] | 2415 | return ('FAIL',"Group must be specified\n") if !defined($group);
|
---|
[2] | 2416 | my $state = shift;
|
---|
[497] | 2417 | return ('FAIL',"Domain status must be specified\n") if !defined($state);
|
---|
[516] | 2418 | my $defloc = shift || '';
|
---|
[2] | 2419 |
|
---|
[116] | 2420 | $state = 1 if $state =~ /^active$/;
|
---|
| 2421 | $state = 1 if $state =~ /^on$/;
|
---|
| 2422 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 2423 | $state = 0 if $state =~ /^off$/;
|
---|
| 2424 |
|
---|
| 2425 | return ('FAIL',"Invalid domain status") if $state !~ /^\d+$/;
|
---|
| 2426 |
|
---|
[542] | 2427 | $domain = lc($domain) if $self->{lowercase};
|
---|
| 2428 |
|
---|
[190] | 2429 | return ('FAIL', "Invalid characters in domain") if $domain !~ /^[a-zA-Z0-9_.-]+$/;
|
---|
| 2430 |
|
---|
[707] | 2431 | my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE lower(domain) = lower(?) AND default_location = ?");
|
---|
[3] | 2432 | my $dom_id;
|
---|
| 2433 |
|
---|
[38] | 2434 | # quick check to start to see if we've already got one
|
---|
[704] | 2435 | $sth->execute($domain, $defloc);
|
---|
[38] | 2436 | ($dom_id) = $sth->fetchrow_array;
|
---|
| 2437 |
|
---|
| 2438 | return ('FAIL', "Domain already exists") if $dom_id;
|
---|
| 2439 |
|
---|
[2] | 2440 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2441 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2442 | local $dbh->{AutoCommit} = 0;
|
---|
| 2443 | local $dbh->{RaiseError} = 1;
|
---|
| 2444 |
|
---|
| 2445 | # Wrap all the SQL in a transaction
|
---|
| 2446 | eval {
|
---|
| 2447 | # insert the domain...
|
---|
[516] | 2448 | $dbh->do("INSERT INTO domains (domain,group_id,status,default_location) VALUES (?,?,?,?)", undef,
|
---|
| 2449 | ($domain, $group, $state, $defloc));
|
---|
[2] | 2450 |
|
---|
| 2451 | # get the ID...
|
---|
[707] | 2452 | ($dom_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?) AND default_location = ?",
|
---|
[704] | 2453 | undef, ($domain, $defloc));
|
---|
[2] | 2454 |
|
---|
[744] | 2455 | my $logparent = $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
[487] | 2456 | entry => "Added ".($state ? 'active' : 'inactive')." domain $domain");
|
---|
[190] | 2457 |
|
---|
[2] | 2458 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
[190] | 2459 | my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
[516] | 2460 | my $sth_in = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,distance,weight,port,ttl,location)".
|
---|
| 2461 | " VALUES ($dom_id,?,?,?,?,?,?,?,?)");
|
---|
[190] | 2462 | $sth->execute($group);
|
---|
[516] | 2463 | while (my ($host, $type, $val, $dist, $weight, $port, $ttl) = $sth->fetchrow_array()) {
|
---|
[2] | 2464 | $host =~ s/DOMAIN/$domain/g;
|
---|
[37] | 2465 | $val =~ s/DOMAIN/$domain/g;
|
---|
[617] | 2466 | _caseclean(\$type, \$host, \$val, 'n', 'n') if $self->{lowercase};
|
---|
[516] | 2467 | $sth_in->execute($host, $type, $val, $dist, $weight, $port, $ttl, $defloc);
|
---|
[190] | 2468 | if ($typemap{$type} eq 'SOA') {
|
---|
| 2469 | my @tmp1 = split /:/, $host;
|
---|
| 2470 | my @tmp2 = split /:/, $val;
|
---|
[744] | 2471 | $self->_log(domain_id => $dom_id, group_id => $group, logparent => $logparent,
|
---|
[284] | 2472 | entry => "[new $domain] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
[487] | 2473 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl");
|
---|
[190] | 2474 | } else {
|
---|
| 2475 | my $logentry = "[new $domain] Added record '$host $typemap{$type}";
|
---|
| 2476 | $logentry .= " [distance $dist]" if $typemap{$type} eq 'MX';
|
---|
| 2477 | $logentry .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$type} eq 'SRV';
|
---|
[744] | 2478 | $self->_log(domain_id => $dom_id, group_id => $group, logparent => $logparent,
|
---|
[487] | 2479 | entry => $logentry." $val', TTL $ttl");
|
---|
[190] | 2480 | }
|
---|
[2] | 2481 | }
|
---|
| 2482 |
|
---|
| 2483 | # once we get here, we should have suceeded.
|
---|
| 2484 | $dbh->commit;
|
---|
| 2485 | }; # end eval
|
---|
| 2486 |
|
---|
| 2487 | if ($@) {
|
---|
| 2488 | my $msg = $@;
|
---|
| 2489 | eval { $dbh->rollback; };
|
---|
[487] | 2490 | $self->_log(group_id => $group, entry => "Failed adding domain $domain ($msg)")
|
---|
[517] | 2491 | if $self->{log_failures};
|
---|
[284] | 2492 | $dbh->commit; # since we enabled transactions earlier
|
---|
[193] | 2493 | return ('FAIL',$msg);
|
---|
[2] | 2494 | } else {
|
---|
[3] | 2495 | return ('OK',$dom_id);
|
---|
[2] | 2496 | }
|
---|
| 2497 | } # end addDomain
|
---|
| 2498 |
|
---|
| 2499 |
|
---|
[274] | 2500 | ## DNSDB::delZone()
|
---|
| 2501 | # Delete a forward or reverse zone.
|
---|
| 2502 | # Takes a database handle, zone ID, and forward/reverse flag.
|
---|
[3] | 2503 | # for now, just delete the records, then the domain.
|
---|
| 2504 | # later we may want to archive it in some way instead (status code 2, for example?)
|
---|
[274] | 2505 | sub delZone {
|
---|
[477] | 2506 | my $self = shift;
|
---|
| 2507 | my $dbh = $self->{dbh};
|
---|
[274] | 2508 | my $zoneid = shift;
|
---|
| 2509 | my $revrec = shift;
|
---|
[3] | 2510 |
|
---|
| 2511 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2512 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2513 | local $dbh->{AutoCommit} = 0;
|
---|
| 2514 | local $dbh->{RaiseError} = 1;
|
---|
| 2515 |
|
---|
[687] | 2516 | return ('FAIL', 'Need a zone identifier to look up') if !$zoneid;
|
---|
| 2517 |
|
---|
[285] | 2518 | my $msg = '';
|
---|
[23] | 2519 | my $failmsg = '';
|
---|
[473] | 2520 | my $zone = ($revrec eq 'n' ? $self->domainName($zoneid) : $self->revName($zoneid));
|
---|
[23] | 2521 |
|
---|
[343] | 2522 | return ('FAIL', ($revrec eq 'n' ? 'Domain' : 'Reverse zone')." ID $zoneid doesn't exist") if !$zone;
|
---|
| 2523 |
|
---|
[517] | 2524 | # Set this up here since we may use if if $self->{log_failures} is enabled
|
---|
[285] | 2525 | my %loghash;
|
---|
| 2526 | $loghash{domain_id} = $zoneid if $revrec eq 'n';
|
---|
| 2527 | $loghash{rdns_id} = $zoneid if $revrec eq 'y';
|
---|
[473] | 2528 | $loghash{group_id} = $self->parentID(
|
---|
| 2529 | id => $zoneid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec);
|
---|
[285] | 2530 |
|
---|
[3] | 2531 | # Wrap all the SQL in a transaction
|
---|
| 2532 | eval {
|
---|
[274] | 2533 | # Disentangle custom record types before removing the
|
---|
| 2534 | # ones that are only in the zone to be deleted
|
---|
| 2535 | if ($revrec eq 'n') {
|
---|
| 2536 | my $sth = $dbh->prepare("UPDATE records SET type=?,domain_id=0 WHERE domain_id=? AND type=?");
|
---|
| 2537 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
| 2538 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65280);
|
---|
| 2539 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65281);
|
---|
| 2540 | $sth->execute(65282, $zoneid, 65283);
|
---|
| 2541 | $sth->execute(65282, $zoneid, 65284);
|
---|
| 2542 | $failmsg = "Failure removing domain records";
|
---|
| 2543 | $dbh->do("DELETE FROM records WHERE domain_id=?", undef, ($zoneid));
|
---|
| 2544 | $failmsg = "Failure removing domain";
|
---|
| 2545 | $dbh->do("DELETE FROM domains WHERE domain_id=?", undef, ($zoneid));
|
---|
| 2546 | } else {
|
---|
| 2547 | my $sth = $dbh->prepare("UPDATE records SET type=?,rdns_id=0 WHERE rdns_id=? AND type=?");
|
---|
| 2548 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
| 2549 | $sth->execute($reverse_typemap{A}, $zoneid, 65280);
|
---|
| 2550 | $sth->execute($reverse_typemap{AAAA}, $zoneid, 65281);
|
---|
| 2551 | # We don't have an "A template" or "AAAA template" type, although it might be useful for symmetry.
|
---|
[345] | 2552 | # $sth->execute(65286?, $zoneid, 65283);
|
---|
| 2553 | # $sth->execute(65286?, $zoneid, 65284);
|
---|
[274] | 2554 | $failmsg = "Failure removing reverse records";
|
---|
| 2555 | $dbh->do("DELETE FROM records WHERE rdns_id=?", undef, ($zoneid));
|
---|
| 2556 | $failmsg = "Failure removing reverse zone";
|
---|
| 2557 | $dbh->do("DELETE FROM revzones WHERE rdns_id=?", undef, ($zoneid));
|
---|
| 2558 | }
|
---|
[3] | 2559 |
|
---|
[285] | 2560 | $msg = "Deleted ".($revrec eq 'n' ? 'domain' : 'reverse zone')." $zone";
|
---|
| 2561 | $loghash{entry} = $msg;
|
---|
[487] | 2562 | $self->_log(%loghash);
|
---|
[285] | 2563 |
|
---|
[3] | 2564 | # once we get here, we should have suceeded.
|
---|
[23] | 2565 | $dbh->commit;
|
---|
[3] | 2566 | }; # end eval
|
---|
| 2567 |
|
---|
| 2568 | if ($@) {
|
---|
[285] | 2569 | $msg = $@;
|
---|
[3] | 2570 | eval { $dbh->rollback; };
|
---|
[295] | 2571 | $loghash{entry} = "Error deleting $zone: $msg ($failmsg)";
|
---|
[517] | 2572 | if ($self->{log_failures}) {
|
---|
[487] | 2573 | $self->_log(%loghash);
|
---|
[295] | 2574 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2575 | }
|
---|
| 2576 | return ('FAIL', $loghash{entry});
|
---|
[3] | 2577 | } else {
|
---|
[295] | 2578 | return ('OK', $msg);
|
---|
[3] | 2579 | }
|
---|
| 2580 |
|
---|
[274] | 2581 | } # end delZone()
|
---|
[3] | 2582 |
|
---|
| 2583 |
|
---|
[2] | 2584 | ## DNSDB::domainName()
|
---|
| 2585 | # Return the domain name based on a domain ID
|
---|
| 2586 | # Takes a database handle and the domain ID
|
---|
| 2587 | # Returns the domain name or undef on failure
|
---|
| 2588 | sub domainName {
|
---|
| 2589 | $errstr = '';
|
---|
[473] | 2590 | my $self = shift;
|
---|
| 2591 | my $dbh = $self->{dbh};
|
---|
[2] | 2592 | my $domid = shift;
|
---|
[91] | 2593 | my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
|
---|
[2] | 2594 | $errstr = $DBI::errstr if !$domname;
|
---|
| 2595 | return $domname if $domname;
|
---|
[91] | 2596 | } # end domainName()
|
---|
[2] | 2597 |
|
---|
| 2598 |
|
---|
[224] | 2599 | ## DNSDB::revName()
|
---|
| 2600 | # Return the reverse zone name based on an rDNS ID
|
---|
[583] | 2601 | # Takes a database handle and the rDNS ID, and an optional flag to force return of the CIDR zone
|
---|
| 2602 | # instead of the formal .arpa zone name
|
---|
[224] | 2603 | # Returns the reverse zone name or undef on failure
|
---|
| 2604 | sub revName {
|
---|
| 2605 | $errstr = '';
|
---|
[473] | 2606 | my $self = shift;
|
---|
| 2607 | my $dbh = $self->{dbh};
|
---|
[224] | 2608 | my $revid = shift;
|
---|
[583] | 2609 | my $cidrflag = shift || 'n';
|
---|
[224] | 2610 | my ($revname) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id=?", undef, ($revid) );
|
---|
| 2611 | $errstr = $DBI::errstr if !$revname;
|
---|
[583] | 2612 | my $tmp = new NetAddr::IP $revname;
|
---|
| 2613 | $revname = _ZONE($tmp, 'ZONE', 'r', '.').($tmp->{isv6} ? '.ip6.arpa' : '.in-addr.arpa')
|
---|
| 2614 | if ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all') && $cidrflag eq 'n';
|
---|
[224] | 2615 | return $revname if $revname;
|
---|
| 2616 | } # end revName()
|
---|
| 2617 |
|
---|
| 2618 |
|
---|
[91] | 2619 | ## DNSDB::domainID()
|
---|
| 2620 | # Takes a database handle and domain name
|
---|
| 2621 | # Returns the domain ID number
|
---|
| 2622 | sub domainID {
|
---|
| 2623 | $errstr = '';
|
---|
[473] | 2624 | my $self = shift;
|
---|
| 2625 | my $dbh = $self->{dbh};
|
---|
[91] | 2626 | my $domain = shift;
|
---|
[719] | 2627 | my $location = shift;
|
---|
| 2628 |
|
---|
| 2629 | # Note that location may be *empty*, but it may not be *undefined*
|
---|
| 2630 | if (!defined($location)) {
|
---|
| 2631 | $errstr = "Missing location";
|
---|
| 2632 | return;
|
---|
| 2633 | }
|
---|
| 2634 |
|
---|
| 2635 | my ($domid) = $dbh->selectrow_array(
|
---|
| 2636 | "SELECT domain_id FROM domains WHERE lower(domain) = lower(?) AND default_location = ?",
|
---|
| 2637 | undef, ($domain, $location) );
|
---|
[501] | 2638 | if (!$domid) {
|
---|
| 2639 | if ($dbh->err) {
|
---|
| 2640 | $errstr = $DBI::errstr;
|
---|
| 2641 | } else {
|
---|
| 2642 | $errstr = "Domain $domain not present";
|
---|
| 2643 | }
|
---|
| 2644 | }
|
---|
[91] | 2645 | return $domid if $domid;
|
---|
| 2646 | } # end domainID()
|
---|
| 2647 |
|
---|
| 2648 |
|
---|
[276] | 2649 | ## DNSDB::revID()
|
---|
| 2650 | # Takes a database handle and reverse zone name
|
---|
| 2651 | # Returns the rDNS ID number
|
---|
| 2652 | sub revID {
|
---|
| 2653 | $errstr = '';
|
---|
[473] | 2654 | my $self = shift;
|
---|
| 2655 | my $dbh = $self->{dbh};
|
---|
[276] | 2656 | my $revzone = shift;
|
---|
[719] | 2657 | my $location = shift;
|
---|
| 2658 |
|
---|
| 2659 | # Note that location may be *empty*, but it may not be *undefined*
|
---|
| 2660 | if (!defined($location)) {
|
---|
| 2661 | $errstr = "Missing location";
|
---|
| 2662 | return;
|
---|
| 2663 | }
|
---|
| 2664 |
|
---|
| 2665 | my ($revid) = $dbh->selectrow_array(
|
---|
| 2666 | "SELECT rdns_id FROM revzones WHERE revnet = ? AND default_location = ?",
|
---|
| 2667 | undef, ($revzone, $location) );
|
---|
[501] | 2668 | if (!$revid) {
|
---|
| 2669 | if ($dbh->err) {
|
---|
| 2670 | $errstr = $DBI::errstr;
|
---|
| 2671 | } else {
|
---|
| 2672 | $errstr = "Reverse zone $revzone not present";
|
---|
| 2673 | }
|
---|
| 2674 | }
|
---|
[276] | 2675 | return $revid if $revid;
|
---|
| 2676 | } # end revID()
|
---|
| 2677 |
|
---|
| 2678 |
|
---|
[260] | 2679 | ## DNSDB::addRDNS
|
---|
| 2680 | # Adds a reverse DNS zone
|
---|
[286] | 2681 | # Takes a database handle, CIDR block, reverse DNS pattern, numeric group,
|
---|
| 2682 | # and boolean(ish) state (active/inactive)
|
---|
[260] | 2683 | # Returns a status code and message
|
---|
| 2684 | sub addRDNS {
|
---|
[477] | 2685 | my $self = shift;
|
---|
| 2686 | my $dbh = $self->{dbh};
|
---|
[583] | 2687 | my $zone = shift;
|
---|
[446] | 2688 |
|
---|
[583] | 2689 | # Autodetect formal .arpa zones
|
---|
| 2690 | if ($zone =~ /\.arpa\.?$/) {
|
---|
| 2691 | my $code;
|
---|
| 2692 | ($code,$zone) = _zone2cidr($zone);
|
---|
| 2693 | return ('FAIL', $zone) if $code eq 'FAIL';
|
---|
| 2694 | }
|
---|
| 2695 | $zone = NetAddr::IP->new($zone);
|
---|
| 2696 |
|
---|
[260] | 2697 | return ('FAIL',"Zone name must be a valid CIDR netblock") unless ($zone && $zone->addr !~ /^0/);
|
---|
[270] | 2698 | my $revpatt = shift; # construct a custom (A/AAAA+)? PTR template record
|
---|
[260] | 2699 | my $group = shift;
|
---|
| 2700 | my $state = shift;
|
---|
[446] | 2701 | my $defloc = shift || '';
|
---|
[260] | 2702 |
|
---|
| 2703 | $state = 1 if $state =~ /^active$/;
|
---|
| 2704 | $state = 1 if $state =~ /^on$/;
|
---|
| 2705 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 2706 | $state = 0 if $state =~ /^off$/;
|
---|
| 2707 |
|
---|
| 2708 | return ('FAIL',"Invalid zone status") if $state !~ /^\d+$/;
|
---|
| 2709 |
|
---|
| 2710 | # quick check to start to see if we've already got one
|
---|
[704] | 2711 | my ($rdns_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet = ? AND default_location = ?",
|
---|
| 2712 | undef, ("$zone", $defloc));
|
---|
[260] | 2713 |
|
---|
| 2714 | return ('FAIL', "Zone already exists") if $rdns_id;
|
---|
| 2715 |
|
---|
| 2716 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2717 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2718 | local $dbh->{AutoCommit} = 0;
|
---|
| 2719 | local $dbh->{RaiseError} = 1;
|
---|
| 2720 |
|
---|
[264] | 2721 | my $warnstr = '';
|
---|
[270] | 2722 | my $defttl = 3600; # 1 hour should be reasonable. And unless things have gone horribly
|
---|
| 2723 | # wrong, we should have a value to override this anyway.
|
---|
[264] | 2724 |
|
---|
[260] | 2725 | # Wrap all the SQL in a transaction
|
---|
| 2726 | eval {
|
---|
[446] | 2727 | # insert the zone...
|
---|
| 2728 | $dbh->do("INSERT INTO revzones (revnet,group_id,status,default_location) VALUES (?,?,?,?)", undef,
|
---|
| 2729 | ($zone, $group, $state, $defloc) );
|
---|
[260] | 2730 |
|
---|
| 2731 | # get the ID...
|
---|
| 2732 | ($rdns_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
| 2733 |
|
---|
[487] | 2734 | $self->_log(rdns_id => $rdns_id, group_id => $group,
|
---|
| 2735 | entry => "Added ".($state ? 'active' : 'inactive')." reverse zone $zone");
|
---|
[260] | 2736 |
|
---|
| 2737 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
| 2738 | my $sth = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
[446] | 2739 | my $sth_in = $dbh->prepare("INSERT INTO records (rdns_id,domain_id,host,type,val,ttl,location)".
|
---|
| 2740 | " VALUES ($rdns_id,?,?,?,?,?,?)");
|
---|
[260] | 2741 | $sth->execute($group);
|
---|
| 2742 | while (my ($host,$type,$val,$ttl) = $sth->fetchrow_array()) {
|
---|
[264] | 2743 | # Silently skip v4/v6 mismatches. This is not an error, this is expected.
|
---|
| 2744 | if ($zone->{isv6}) {
|
---|
| 2745 | next if ($type == 65280 || $type == 65283);
|
---|
| 2746 | } else {
|
---|
| 2747 | next if ($type == 65281 || $type == 65284);
|
---|
| 2748 | }
|
---|
[269] | 2749 |
|
---|
[517] | 2750 | $host =~ s/ADMINDOMAIN/$self->{domain}/g;
|
---|
[264] | 2751 |
|
---|
[265] | 2752 | # Check to make sure the IP stubs will fit in the zone. Under most usage failures here should be rare.
|
---|
| 2753 | # On failure, tack a note on to a warning string and continue without adding this record.
|
---|
| 2754 | # While we're at it, we substitute $zone for ZONE in the value.
|
---|
| 2755 | if ($val eq 'ZONE') {
|
---|
[444] | 2756 | # If we've got a pattern, we skip the default record version on (A+)PTR-template types
|
---|
| 2757 | next if $revpatt && ($type == 65282 || $type == 65283);
|
---|
[269] | 2758 | ##fixme? do we care if we have multiple whole-zone templates?
|
---|
[265] | 2759 | $val = $zone->network;
|
---|
| 2760 | } elsif ($val =~ /ZONE/) {
|
---|
| 2761 | my $tmpval = $val;
|
---|
| 2762 | $tmpval =~ s/ZONE//;
|
---|
[269] | 2763 | # Bend the rules and allow single-trailing-number PTR or PTR template records to be inserted
|
---|
| 2764 | # as either v4 or v6. May make this an off-by-default config flag
|
---|
| 2765 | # Note that the origin records that may trigger this **SHOULD** already have ZONE,\d
|
---|
| 2766 | if ($type == 12 || $type == 65282) {
|
---|
| 2767 | $tmpval =~ s/[,.]/::/ if ($tmpval =~ /^[,.]\d+$/ && $zone->{isv6});
|
---|
| 2768 | $tmpval =~ s/[,:]+/./ if ($tmpval =~ /^(?:,|::)\d+$/ && !$zone->{isv6});
|
---|
| 2769 | }
|
---|
[265] | 2770 | my $addr;
|
---|
[471] | 2771 | if ($self->_ipparent('n', 'y', \$tmpval, $rdns_id, \$addr)) {
|
---|
[265] | 2772 | $val = $addr->addr;
|
---|
| 2773 | } else {
|
---|
[269] | 2774 | $warnstr .= "\nDefault record '$val $typemap{$type} $host' doesn't fit in $zone, skipping";
|
---|
[264] | 2775 | next;
|
---|
| 2776 | }
|
---|
| 2777 | }
|
---|
| 2778 |
|
---|
[328] | 2779 | # Substitute $zone for ZONE in the hostname, but only for non-NS records.
|
---|
| 2780 | # NS records get this substitution on the value instead.
|
---|
| 2781 | $host = _ZONE($zone, $host) if $type != 2;
|
---|
[265] | 2782 |
|
---|
[269] | 2783 | # Fill in the forward domain ID if we can find it, otherwise:
|
---|
| 2784 | # Coerce type down to PTR or PTR template if we can't
|
---|
| 2785 | my $domid = 0;
|
---|
| 2786 | if ($type >= 65280) {
|
---|
[471] | 2787 | if (!($domid = $self->_hostparent($host))) {
|
---|
[269] | 2788 | $warnstr .= "\nRecord added as PTR instead of $typemap{$type}; domain not found for $host";
|
---|
| 2789 | $type = $reverse_typemap{PTR};
|
---|
| 2790 | $domid = 0; # just to be explicit.
|
---|
| 2791 | }
|
---|
| 2792 | }
|
---|
| 2793 |
|
---|
[617] | 2794 | _caseclean(\$type, \$host, \$val, 'n', 'y') if $self->{lowercase};
|
---|
| 2795 |
|
---|
[446] | 2796 | $sth_in->execute($domid,$host,$type,$val,$ttl,$defloc);
|
---|
[269] | 2797 |
|
---|
[260] | 2798 | if ($typemap{$type} eq 'SOA') {
|
---|
| 2799 | my @tmp1 = split /:/, $host;
|
---|
| 2800 | my @tmp2 = split /:/, $val;
|
---|
[487] | 2801 | $self->_log(rdns_id => $rdns_id, group_id => $group,
|
---|
[286] | 2802 | entry => "[new $zone] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
[487] | 2803 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl");
|
---|
[270] | 2804 | $defttl = $tmp2[3];
|
---|
[260] | 2805 | } else {
|
---|
[446] | 2806 | my $logentry = "[new $zone] Added record '$host $typemap{$type} $val', TTL $ttl";
|
---|
[480] | 2807 | $logentry .= ", default location ".$self->getLoc($defloc)->{description} if $defloc;
|
---|
[487] | 2808 | $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group, entry => $logentry);
|
---|
[260] | 2809 | }
|
---|
| 2810 | }
|
---|
| 2811 |
|
---|
[270] | 2812 | # Generate record based on provided pattern.
|
---|
| 2813 | if ($revpatt) {
|
---|
| 2814 | my $host;
|
---|
| 2815 | my $type = ($zone->{isv6} ? 65284 : 65283);
|
---|
| 2816 | my $val = $zone->network;
|
---|
[269] | 2817 |
|
---|
[270] | 2818 | # Substitute $zone for ZONE in the hostname.
|
---|
| 2819 | $host = _ZONE($zone, $revpatt);
|
---|
| 2820 |
|
---|
| 2821 | my $domid = 0;
|
---|
[471] | 2822 | if (!($domid = $self->_hostparent($host))) {
|
---|
[270] | 2823 | $warnstr .= "\nDefault pattern added as PTR template instead of $typemap{$type}; domain not found for $host";
|
---|
| 2824 | $type = 65282;
|
---|
| 2825 | $domid = 0; # just to be explicit.
|
---|
| 2826 | }
|
---|
| 2827 |
|
---|
[446] | 2828 | $sth_in->execute($domid,$host,$type,$val,$defttl,$defloc);
|
---|
[286] | 2829 | my $logentry = "[new $zone] Added record '$host $typemap{$type}";
|
---|
[487] | 2830 | $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group,
|
---|
| 2831 | entry => $logentry." $val', TTL $defttl from pattern");
|
---|
[270] | 2832 | }
|
---|
| 2833 |
|
---|
[264] | 2834 | # If there are warnings (presumably about default records skipped for cause) log them
|
---|
[487] | 2835 | $self->_log(rdns_id => $rdns_id, group_id => $group, entry => "Warning(s) adding $zone:$warnstr")
|
---|
[264] | 2836 | if $warnstr;
|
---|
[269] | 2837 |
|
---|
[260] | 2838 | # once we get here, we should have suceeded.
|
---|
| 2839 | $dbh->commit;
|
---|
| 2840 | }; # end eval
|
---|
| 2841 |
|
---|
| 2842 | if ($@) {
|
---|
| 2843 | my $msg = $@;
|
---|
| 2844 | eval { $dbh->rollback; };
|
---|
[487] | 2845 | $self->_log(group_id => $group, entry => "Failed adding reverse zone $zone ($msg)")
|
---|
[517] | 2846 | if $self->{log_failures};
|
---|
[286] | 2847 | $dbh->commit; # since we enabled transactions earlier
|
---|
[260] | 2848 | return ('FAIL',$msg);
|
---|
| 2849 | } else {
|
---|
[286] | 2850 | my $retcode = 'OK';
|
---|
| 2851 | if ($warnstr) {
|
---|
| 2852 | $resultstr = $warnstr;
|
---|
| 2853 | $retcode = 'WARN';
|
---|
| 2854 | }
|
---|
| 2855 | return ($retcode, $rdns_id);
|
---|
[260] | 2856 | }
|
---|
| 2857 |
|
---|
| 2858 | } # end addRDNS()
|
---|
| 2859 |
|
---|
| 2860 |
|
---|
[237] | 2861 | ## DNSDB::getZoneCount
|
---|
| 2862 | # Get count of zones in group or groups
|
---|
| 2863 | # Takes a database handle and hash containing:
|
---|
| 2864 | # - the "current" group
|
---|
| 2865 | # - an array of "acceptable" groups
|
---|
| 2866 | # - a flag for forward/reverse zones
|
---|
| 2867 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
| 2868 | # Returns an integer count of the resulting zone list.
|
---|
| 2869 | sub getZoneCount {
|
---|
[477] | 2870 | my $self = shift;
|
---|
| 2871 | my $dbh = $self->{dbh};
|
---|
[237] | 2872 |
|
---|
| 2873 | my %args = @_;
|
---|
| 2874 |
|
---|
[509] | 2875 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 2876 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 2877 | $errstr = "Bad or missing curgroup argument";
|
---|
| 2878 | return;
|
---|
| 2879 | }
|
---|
| 2880 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 2881 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 2882 | $errstr = "Bad childlist argument";
|
---|
| 2883 | return;
|
---|
| 2884 | }
|
---|
| 2885 |
|
---|
[237] | 2886 | my @filterargs;
|
---|
[239] | 2887 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2888 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2889 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
[237] | 2890 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2891 |
|
---|
| 2892 | my $sql;
|
---|
| 2893 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
| 2894 | if ($args{revrec} eq 'n') {
|
---|
| 2895 | $sql = "SELECT count(*) FROM domains".
|
---|
| 2896 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2897 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
| 2898 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
| 2899 | } else {
|
---|
| 2900 | $sql = "SELECT count(*) FROM revzones".
|
---|
| 2901 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
[583] | 2902 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2903 | # if ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all') {
|
---|
| 2904 | # Just In Case the UI is using formal .arpa notation, and someone enters something reversed,
|
---|
| 2905 | # we want to match both the formal and natural zone name
|
---|
| 2906 | $sql .= ($args{filter} ? " AND (CAST(revnet AS VARCHAR) ~* ? OR CAST(revnet AS VARCHAR) ~* ?)" : '');
|
---|
| 2907 | push @filterargs, join('[.]',reverse(split(/\[\.\]/,$args{filter}))) if $args{filter};
|
---|
| 2908 | # } else {
|
---|
| 2909 | # $sql .= ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2910 | # }
|
---|
[237] | 2911 | }
|
---|
| 2912 | my ($count) = $dbh->selectrow_array($sql, undef, @filterargs);
|
---|
| 2913 | return $count;
|
---|
| 2914 | } # end getZoneCount()
|
---|
| 2915 |
|
---|
| 2916 |
|
---|
| 2917 | ## DNSDB::getZoneList()
|
---|
| 2918 | # Get a list of zones in the specified group(s)
|
---|
| 2919 | # Takes the same arguments as getZoneCount() above
|
---|
| 2920 | # Returns a reference to an array of hashrefs suitable for feeding to HTML::Template
|
---|
| 2921 | sub getZoneList {
|
---|
[477] | 2922 | my $self = shift;
|
---|
| 2923 | my $dbh = $self->{dbh};
|
---|
[237] | 2924 |
|
---|
| 2925 | my %args = @_;
|
---|
| 2926 |
|
---|
| 2927 | my @zonelist;
|
---|
| 2928 |
|
---|
[475] | 2929 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
[239] | 2930 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[237] | 2931 |
|
---|
[509] | 2932 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 2933 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 2934 | $errstr = "Bad or missing curgroup argument";
|
---|
| 2935 | return;
|
---|
| 2936 | }
|
---|
| 2937 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 2938 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 2939 | $errstr = "Bad childlist argument";
|
---|
| 2940 | return;
|
---|
| 2941 | }
|
---|
| 2942 |
|
---|
[237] | 2943 | my @filterargs;
|
---|
[239] | 2944 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2945 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2946 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
[237] | 2947 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2948 |
|
---|
| 2949 | my $sql;
|
---|
| 2950 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
| 2951 | if ($args{revrec} eq 'n') {
|
---|
[475] | 2952 | $args{sortby} = 'domain' if !$args{sortby} || !grep /^$args{sortby}$/, ('domain','group','status');
|
---|
[704] | 2953 | $sql = q(SELECT
|
---|
| 2954 | domain_id AS zoneid,
|
---|
| 2955 | domain AS zone,
|
---|
| 2956 | status,
|
---|
| 2957 | groups.group_name AS group,
|
---|
| 2958 | l.description AS location
|
---|
| 2959 | FROM domains
|
---|
| 2960 | LEFT JOIN locations l ON domains.default_location=l.location
|
---|
| 2961 | INNER JOIN groups ON domains.group_id=groups.group_id ).
|
---|
| 2962 | "WHERE domains.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
[237] | 2963 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
| 2964 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
| 2965 | } else {
|
---|
[239] | 2966 | ##fixme: arguably startwith here is irrelevant. depends on the UI though.
|
---|
[475] | 2967 | $args{sortby} = 'revnet' if !$args{sortby} || !grep /^$args{sortby}$/, ('revnet','group','status');
|
---|
[704] | 2968 | $sql = q(SELECT
|
---|
| 2969 | rdns_id AS zoneid,
|
---|
| 2970 | revnet AS zone,
|
---|
| 2971 | status,
|
---|
| 2972 | groups.group_name AS group,
|
---|
| 2973 | l.description AS location
|
---|
| 2974 | FROM revzones
|
---|
| 2975 | LEFT JOIN locations l ON revzones.default_location=l.location
|
---|
| 2976 | INNER JOIN groups ON revzones.group_id=groups.group_id ).
|
---|
[237] | 2977 | " WHERE revzones.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
[583] | 2978 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2979 | # if ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all') {
|
---|
| 2980 | # Just In Case the UI is using formal .arpa notation, and someone enters something reversed,
|
---|
| 2981 | # we want to match both the formal and natural zone name
|
---|
| 2982 | $sql .= ($args{filter} ? " AND (CAST(revnet AS VARCHAR) ~* ? OR CAST(revnet AS VARCHAR) ~* ?)" : '');
|
---|
| 2983 | push @filterargs, join('[.]',reverse(split(/\[\.\]/,$args{filter}))) if $args{filter};
|
---|
| 2984 | # } else {
|
---|
| 2985 | # $sql .= ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2986 | # }
|
---|
[237] | 2987 | }
|
---|
| 2988 | # A common tail.
|
---|
[239] | 2989 | $sql .= " ORDER BY ".($args{sortby} eq 'group' ? 'groups.group_name' : $args{sortby})." $args{sortorder} ".
|
---|
[517] | 2990 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage}".
|
---|
| 2991 | " OFFSET ".$args{offset}*$self->{perpage});
|
---|
[237] | 2992 |
|
---|
[583] | 2993 | my @working;
|
---|
| 2994 | my $zsth = $dbh->prepare($sql);
|
---|
| 2995 | $zsth->execute(@filterargs);
|
---|
| 2996 | while (my $zone = $zsth->fetchrow_hashref) {
|
---|
| 2997 | if ($args{revrec} eq 'y' && ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all')) {
|
---|
| 2998 | my $tmp = new NetAddr::IP $zone->{zone};
|
---|
| 2999 | $zone->{zone} = DNSDB::_ZONE($tmp, 'ZONE', 'r', '.').($tmp->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 3000 | }
|
---|
| 3001 | push @working, $zone;
|
---|
| 3002 | }
|
---|
| 3003 | return \@working;
|
---|
[237] | 3004 | } # end getZoneList()
|
---|
| 3005 |
|
---|
| 3006 |
|
---|
[383] | 3007 | ## DNSDB::getZoneLocation()
|
---|
[387] | 3008 | # Retrieve the default location for a zone.
|
---|
[383] | 3009 | # Takes a database handle, forward/reverse flag, and zone ID
|
---|
| 3010 | sub getZoneLocation {
|
---|
[477] | 3011 | my $self = shift;
|
---|
| 3012 | my $dbh = $self->{dbh};
|
---|
[383] | 3013 | my $revrec = shift;
|
---|
| 3014 | my $zoneid = shift;
|
---|
| 3015 |
|
---|
| 3016 | my ($loc) = $dbh->selectrow_array("SELECT default_location FROM ".
|
---|
| 3017 | ($revrec eq 'n' ? 'domains WHERE domain_id = ?' : 'revzones WHERE rdns_id = ?'),
|
---|
| 3018 | undef, ($zoneid));
|
---|
| 3019 | return $loc;
|
---|
| 3020 | } # end getZoneLocation()
|
---|
| 3021 |
|
---|
| 3022 |
|
---|
[18] | 3023 | ## DNSDB::addGroup()
|
---|
| 3024 | # Add a group
|
---|
[66] | 3025 | # Takes a database handle, group name, parent group, hashref for permissions,
|
---|
[292] | 3026 | # and optional template-vs-cloneme flag for the default records
|
---|
[18] | 3027 | # Returns a status code and message
|
---|
| 3028 | sub addGroup {
|
---|
| 3029 | $errstr = '';
|
---|
[476] | 3030 | my $self = shift;
|
---|
| 3031 | my $dbh = $self->{dbh};
|
---|
[20] | 3032 | my $groupname = shift;
|
---|
| 3033 | my $pargroup = shift;
|
---|
[66] | 3034 | my $permissions = shift;
|
---|
[18] | 3035 |
|
---|
[66] | 3036 | # 0 indicates "custom", hardcoded.
|
---|
[18] | 3037 | # Any other value clones that group's default records, if it exists.
|
---|
[66] | 3038 | my $inherit = shift || 0;
|
---|
| 3039 | ##fixme: need a flag to indicate clone records or <?> ?
|
---|
[18] | 3040 |
|
---|
| 3041 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3042 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3043 | local $dbh->{AutoCommit} = 0;
|
---|
| 3044 | local $dbh->{RaiseError} = 1;
|
---|
| 3045 |
|
---|
[292] | 3046 | my ($group_id) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($groupname));
|
---|
[38] | 3047 |
|
---|
| 3048 | return ('FAIL', "Group already exists") if $group_id;
|
---|
| 3049 |
|
---|
[18] | 3050 | # Wrap all the SQL in a transaction
|
---|
| 3051 | eval {
|
---|
[292] | 3052 | $dbh->do("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)", undef, ($pargroup, $groupname) );
|
---|
[18] | 3053 |
|
---|
[292] | 3054 | my ($groupid) = $dbh->selectrow_array("SELECT currval('groups_group_id_seq')");
|
---|
[18] | 3055 |
|
---|
[292] | 3056 | # We work through the whole set of permissions instead of specifying them so
|
---|
| 3057 | # that when we add a new permission, we don't have to change the code anywhere
|
---|
| 3058 | # that doesn't explicitly deal with that specific permission.
|
---|
| 3059 | my @permvals;
|
---|
| 3060 | foreach (@permtypes) {
|
---|
| 3061 | if (!defined ($permissions->{$_})) {
|
---|
| 3062 | push @permvals, 0;
|
---|
| 3063 | } else {
|
---|
| 3064 | push @permvals, $permissions->{$_};
|
---|
[66] | 3065 | }
|
---|
[292] | 3066 | }
|
---|
| 3067 | $dbh->do("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")",
|
---|
| 3068 | undef, ($groupid, @permvals) );
|
---|
| 3069 | my ($permid) = $dbh->selectrow_array("SELECT currval('permissions_permission_id_seq')");
|
---|
| 3070 | $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
|
---|
[66] | 3071 |
|
---|
[292] | 3072 | # Default records
|
---|
[255] | 3073 | my $sthf = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
|
---|
[20] | 3074 | "VALUES ($groupid,?,?,?,?,?,?,?)");
|
---|
[255] | 3075 | my $sthr = $dbh->prepare("INSERT INTO default_rev_records (group_id,host,type,val,ttl) ".
|
---|
| 3076 | "VALUES ($groupid,?,?,?,?)");
|
---|
[66] | 3077 | if ($inherit) {
|
---|
[87] | 3078 | # Duplicate records from parent. Actually relying on inherited records feels
|
---|
| 3079 | # very fragile, and it would be problematic to roll over at a later time.
|
---|
[18] | 3080 | my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
[87] | 3081 | $sth2->execute($pargroup);
|
---|
[18] | 3082 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
[255] | 3083 | $sthf->execute(@clonedata);
|
---|
[18] | 3084 | }
|
---|
[255] | 3085 | # And now the reverse records
|
---|
[292] | 3086 | $sth2 = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
[255] | 3087 | $sth2->execute($pargroup);
|
---|
| 3088 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
| 3089 | $sthr->execute(@clonedata);
|
---|
| 3090 | }
|
---|
[18] | 3091 | } else {
|
---|
[66] | 3092 | ##fixme: Hardcoding is Bad, mmmmkaaaay?
|
---|
[18] | 3093 | # reasonable basic defaults for SOA, MX, NS, and minimal hosting
|
---|
| 3094 | # could load from a config file, but somewhere along the line we need hardcoded bits.
|
---|
[255] | 3095 | $sthf->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
|
---|
| 3096 | $sthf->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
|
---|
| 3097 | $sthf->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
|
---|
| 3098 | $sthf->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
|
---|
| 3099 | $sthf->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
|
---|
| 3100 | $sthf->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
|
---|
| 3101 | # reasonable basic defaults for generic reverse zone. Same as initial SQL tabledef.
|
---|
| 3102 | $sthr->execute('hostmaster.ADMINDOMAIN:ns1.ADMINDOMAIN', 6, '10800:3600:604800:10800', 86400);
|
---|
| 3103 | $sthr->execute('unused-%r.ADMINDOMAIN', 65283, 'ZONE', 3600);
|
---|
[18] | 3104 | }
|
---|
| 3105 |
|
---|
[487] | 3106 | $self->_log(group_id => $pargroup, entry => "Added group $groupname");
|
---|
[292] | 3107 |
|
---|
[18] | 3108 | # once we get here, we should have suceeded.
|
---|
| 3109 | $dbh->commit;
|
---|
| 3110 | }; # end eval
|
---|
| 3111 |
|
---|
| 3112 | if ($@) {
|
---|
| 3113 | my $msg = $@;
|
---|
| 3114 | eval { $dbh->rollback; };
|
---|
[517] | 3115 | if ($self->{log_failures}) {
|
---|
[487] | 3116 | $self->_log(group_id => $pargroup, entry => "Failed to add group $groupname: $msg");
|
---|
[292] | 3117 | $dbh->commit;
|
---|
| 3118 | }
|
---|
[18] | 3119 | return ('FAIL',$msg);
|
---|
| 3120 | }
|
---|
| 3121 |
|
---|
[292] | 3122 | return ('OK','OK');
|
---|
[18] | 3123 | } # end addGroup()
|
---|
| 3124 |
|
---|
| 3125 |
|
---|
[22] | 3126 | ## DNSDB::delGroup()
|
---|
| 3127 | # Delete a group.
|
---|
| 3128 | # Takes a group ID
|
---|
| 3129 | # Returns a status code and message
|
---|
| 3130 | sub delGroup {
|
---|
[476] | 3131 | my $self = shift;
|
---|
| 3132 | my $dbh = $self->{dbh};
|
---|
[22] | 3133 | my $groupid = shift;
|
---|
| 3134 |
|
---|
| 3135 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3136 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3137 | local $dbh->{AutoCommit} = 0;
|
---|
| 3138 | local $dbh->{RaiseError} = 1;
|
---|
| 3139 |
|
---|
| 3140 | ##fixme: locate "knowable" error conditions and deal with them before the eval
|
---|
[23] | 3141 | # ... or inside, whatever.
|
---|
[22] | 3142 | # -> domains still exist in group
|
---|
| 3143 | # -> ...
|
---|
[23] | 3144 | my $failmsg = '';
|
---|
[293] | 3145 | my $resultmsg = '';
|
---|
[22] | 3146 |
|
---|
[293] | 3147 | # collect some pieces for logging and error messages
|
---|
[473] | 3148 | my $groupname = $self->groupName($groupid);
|
---|
| 3149 | my $parid = $self->parentID(id => $groupid, type => 'group');
|
---|
[293] | 3150 |
|
---|
[22] | 3151 | # Wrap all the SQL in a transaction
|
---|
| 3152 | eval {
|
---|
[293] | 3153 | # Check for Things in the group
|
---|
| 3154 | $failmsg = "Can't remove group $groupname";
|
---|
| 3155 | my ($grpcnt) = $dbh->selectrow_array("SELECT count(*) FROM groups WHERE parent_group_id=?", undef, ($groupid));
|
---|
| 3156 | die "$grpcnt groups still in group\n" if $grpcnt;
|
---|
| 3157 | my ($domcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($groupid));
|
---|
[23] | 3158 | die "$domcnt domains still in group\n" if $domcnt;
|
---|
[512] | 3159 | my ($revcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($groupid));
|
---|
| 3160 | die "$revcnt reverse zones still in group\n" if $revcnt;
|
---|
[293] | 3161 | my ($usercnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($groupid));
|
---|
| 3162 | die "$usercnt users still in group\n" if $usercnt;
|
---|
[23] | 3163 |
|
---|
[293] | 3164 | $failmsg = "Failed to delete default records for $groupname";
|
---|
| 3165 | $dbh->do("DELETE from default_records WHERE group_id=?", undef, ($groupid));
|
---|
| 3166 | $failmsg = "Failed to delete default reverse records for $groupname";
|
---|
| 3167 | $dbh->do("DELETE from default_rev_records WHERE group_id=?", undef, ($groupid));
|
---|
| 3168 | $failmsg = "Failed to remove group $groupname";
|
---|
| 3169 | $dbh->do("DELETE from groups WHERE group_id=?", undef, ($groupid));
|
---|
[22] | 3170 |
|
---|
[487] | 3171 | $self->_log(group_id => $parid, entry => "Deleted group $groupname");
|
---|
[293] | 3172 | $resultmsg = "Deleted group $groupname";
|
---|
| 3173 |
|
---|
[22] | 3174 | # once we get here, we should have suceeded.
|
---|
| 3175 | $dbh->commit;
|
---|
| 3176 | }; # end eval
|
---|
| 3177 |
|
---|
| 3178 | if ($@) {
|
---|
| 3179 | my $msg = $@;
|
---|
| 3180 | eval { $dbh->rollback; };
|
---|
[517] | 3181 | if ($self->{log_failures}) {
|
---|
[487] | 3182 | $self->_log(group_id => $parid, entry => "$failmsg: $msg");
|
---|
[293] | 3183 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 3184 | }
|
---|
[23] | 3185 | return ('FAIL',"$failmsg: $msg");
|
---|
[22] | 3186 | }
|
---|
[293] | 3187 |
|
---|
| 3188 | return ('OK',$resultmsg);
|
---|
[22] | 3189 | } # end delGroup()
|
---|
| 3190 |
|
---|
| 3191 |
|
---|
[19] | 3192 | ## DNSDB::getChildren()
|
---|
| 3193 | # Get a list of all groups whose parent^n is group <n>
|
---|
[24] | 3194 | # Takes a database handle, group ID, reference to an array to put the group IDs in,
|
---|
| 3195 | # and an optional flag to return only immediate children or all children-of-children
|
---|
| 3196 | # default to returning all children
|
---|
[19] | 3197 | # Calls itself
|
---|
| 3198 | sub getChildren {
|
---|
| 3199 | $errstr = '';
|
---|
[476] | 3200 | my $self = shift;
|
---|
| 3201 | my $dbh = $self->{dbh};
|
---|
[20] | 3202 | my $rootgroup = shift;
|
---|
| 3203 | my $groupdest = shift;
|
---|
[24] | 3204 | my $immed = shift || 'all';
|
---|
[19] | 3205 |
|
---|
| 3206 | # special break for default group; otherwise we get stuck.
|
---|
[20] | 3207 | if ($rootgroup == 1) {
|
---|
[19] | 3208 | # by definition, group 1 is the Root Of All Groups
|
---|
[24] | 3209 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
|
---|
[331] | 3210 | ($immed ne 'all' ? " AND parent_group_id=1" : '')." ORDER BY group_name");
|
---|
[19] | 3211 | $sth->execute;
|
---|
| 3212 | while (my @this = $sth->fetchrow_array) {
|
---|
[20] | 3213 | push @$groupdest, @this;
|
---|
[19] | 3214 | }
|
---|
| 3215 | } else {
|
---|
[331] | 3216 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=? ORDER BY group_name");
|
---|
[20] | 3217 | $sth->execute($rootgroup);
|
---|
[19] | 3218 | return if $sth->rows == 0;
|
---|
[20] | 3219 | my @grouplist;
|
---|
| 3220 | while (my ($group) = $sth->fetchrow_array) {
|
---|
| 3221 | push @$groupdest, $group;
|
---|
[476] | 3222 | $self->getChildren($group, $groupdest) if $immed eq 'all';
|
---|
[19] | 3223 | }
|
---|
| 3224 | }
|
---|
| 3225 | } # end getChildren()
|
---|
| 3226 |
|
---|
| 3227 |
|
---|
[20] | 3228 | ## DNSDB::groupName()
|
---|
[17] | 3229 | # Return the group name based on a group ID
|
---|
| 3230 | # Takes a database handle and the group ID
|
---|
| 3231 | # Returns the group name or undef on failure
|
---|
[20] | 3232 | sub groupName {
|
---|
[13] | 3233 | $errstr = '';
|
---|
[473] | 3234 | my $self = shift;
|
---|
| 3235 | my $dbh = $self->{dbh};
|
---|
[20] | 3236 | my $groupid = shift;
|
---|
| 3237 | my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
|
---|
| 3238 | $sth->execute($groupid);
|
---|
| 3239 | my ($groupname) = $sth->fetchrow_array();
|
---|
| 3240 | $errstr = $DBI::errstr if !$groupname;
|
---|
| 3241 | return $groupname if $groupname;
|
---|
| 3242 | } # end groupName
|
---|
[13] | 3243 |
|
---|
| 3244 |
|
---|
[314] | 3245 | ## DNSDB::getGroupCount()
|
---|
| 3246 | # Get count of subgroups in group or groups
|
---|
| 3247 | # Takes a database handle and hash containing:
|
---|
| 3248 | # - the "current" group
|
---|
| 3249 | # - an array of "acceptable" groups
|
---|
| 3250 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
| 3251 | # Returns an integer count of the resulting group list.
|
---|
| 3252 | sub getGroupCount {
|
---|
[476] | 3253 | my $self = shift;
|
---|
| 3254 | my $dbh = $self->{dbh};
|
---|
[314] | 3255 |
|
---|
| 3256 | my %args = @_;
|
---|
| 3257 |
|
---|
[509] | 3258 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 3259 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 3260 | $errstr = "Bad or missing curgroup argument";
|
---|
| 3261 | return;
|
---|
| 3262 | }
|
---|
| 3263 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 3264 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 3265 | $errstr = "Bad childlist argument";
|
---|
| 3266 | return;
|
---|
| 3267 | }
|
---|
| 3268 |
|
---|
[314] | 3269 | my @filterargs;
|
---|
| 3270 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3271 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3272 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3273 |
|
---|
| 3274 | my $sql = "SELECT count(*) FROM groups ".
|
---|
| 3275 | "WHERE parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3276 | ($args{startwith} ? " AND group_name ~* ?" : '').
|
---|
| 3277 | ($args{filter} ? " AND group_name ~* ?" : '');
|
---|
| 3278 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 3279 | $errstr = $dbh->errstr if !$count;
|
---|
| 3280 | return $count;
|
---|
| 3281 | } # end getGroupCount
|
---|
| 3282 |
|
---|
| 3283 |
|
---|
| 3284 | ## DNSDB::getGroupList()
|
---|
| 3285 | # Get a list of sub^n-groups in the specified group(s)
|
---|
| 3286 | # Takes the same arguments as getGroupCount() above
|
---|
| 3287 | # Returns an arrayref containing hashrefs suitable for feeding straight to HTML::Template
|
---|
| 3288 | sub getGroupList {
|
---|
[476] | 3289 | my $self = shift;
|
---|
| 3290 | my $dbh = $self->{dbh};
|
---|
[314] | 3291 |
|
---|
| 3292 | my %args = @_;
|
---|
| 3293 |
|
---|
[509] | 3294 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 3295 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 3296 | $errstr = "Bad or missing curgroup argument";
|
---|
| 3297 | return;
|
---|
| 3298 | }
|
---|
| 3299 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 3300 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 3301 | $errstr = "Bad childlist argument";
|
---|
| 3302 | return;
|
---|
| 3303 | }
|
---|
| 3304 |
|
---|
[314] | 3305 | my @filterargs;
|
---|
| 3306 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3307 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3308 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3309 |
|
---|
| 3310 | # protection against bad or missing arguments
|
---|
[508] | 3311 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
| 3312 | $args{sortby} = 'group' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
[397] | 3313 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[314] | 3314 |
|
---|
| 3315 | # munge sortby for columns in database
|
---|
| 3316 | $args{sortby} = 'g.group_name' if $args{sortby} eq 'group';
|
---|
| 3317 | $args{sortby} = 'g2.group_name' if $args{sortby} eq 'parent';
|
---|
| 3318 |
|
---|
[385] | 3319 | my $sql = q(SELECT g.group_id AS groupid, g.group_name AS groupname, g2.group_name AS pgroup
|
---|
[314] | 3320 | FROM groups g
|
---|
| 3321 | INNER JOIN groups g2 ON g2.group_id=g.parent_group_id
|
---|
| 3322 | ).
|
---|
[385] | 3323 | " WHERE g.parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
[314] | 3324 | ($args{startwith} ? " AND g.group_name ~* ?" : '').
|
---|
| 3325 | ($args{filter} ? " AND g.group_name ~* ?" : '').
|
---|
| 3326 | " GROUP BY g.group_id, g.group_name, g2.group_name ".
|
---|
| 3327 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
[517] | 3328 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
[314] | 3329 | my $glist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 3330 | $errstr = $dbh->errstr if !$glist;
|
---|
[385] | 3331 |
|
---|
| 3332 | # LEFT JOINs make the result set balloon beyond sanity just to include counts;
|
---|
| 3333 | # this means there's lots of crunching needed to trim the result set back down.
|
---|
| 3334 | # So instead we track the order of the groups, and push the counts into the
|
---|
| 3335 | # arrayref result separately.
|
---|
| 3336 | ##fixme: put this whole sub in a transaction? might be
|
---|
| 3337 | # needed for accurate results on very busy systems.
|
---|
[386] | 3338 | ##fixme: large group lists need prepared statements?
|
---|
| 3339 | #my $ucsth = $dbh->prepare("SELECT count(*) FROM users WHERE group_id=?");
|
---|
| 3340 | #my $dcsth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
|
---|
| 3341 | #my $rcsth = $dbh->prepare("SELECT count(*) FROM revzones WHERE group_id=?");
|
---|
[385] | 3342 | foreach (@{$glist}) {
|
---|
[386] | 3343 | my ($ucnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 3344 | $$_{nusers} = $ucnt;
|
---|
| 3345 | my ($dcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 3346 | $$_{ndomains} = $dcnt;
|
---|
| 3347 | my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 3348 | $$_{nrevzones} = $rcnt;
|
---|
[385] | 3349 | }
|
---|
| 3350 |
|
---|
[314] | 3351 | return $glist;
|
---|
| 3352 | } # end getGroupList
|
---|
| 3353 |
|
---|
| 3354 |
|
---|
[118] | 3355 | ## DNSDB::groupID()
|
---|
| 3356 | # Return the group ID based on the group name
|
---|
| 3357 | # Takes a database handle and the group name
|
---|
| 3358 | # Returns the group ID or undef on failure
|
---|
| 3359 | sub groupID {
|
---|
| 3360 | $errstr = '';
|
---|
[473] | 3361 | my $self = shift;
|
---|
| 3362 | my $dbh = $self->{dbh};
|
---|
[118] | 3363 | my $group = shift;
|
---|
[406] | 3364 | my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($group) );
|
---|
[118] | 3365 | $errstr = $DBI::errstr if !$grpid;
|
---|
| 3366 | return $grpid if $grpid;
|
---|
| 3367 | } # end groupID()
|
---|
| 3368 |
|
---|
| 3369 |
|
---|
[24] | 3370 | ## DNSDB::addUser()
|
---|
[87] | 3371 | # Add a user.
|
---|
| 3372 | # Takes a DB handle, username, group ID, password, state (active/inactive).
|
---|
| 3373 | # Optionally accepts:
|
---|
| 3374 | # user type (user/admin) - defaults to user
|
---|
| 3375 | # permissions string - defaults to inherit from group
|
---|
| 3376 | # three valid forms:
|
---|
| 3377 | # i - Inherit permissions
|
---|
| 3378 | # c:<user_id> - Clone permissions from <user_id>
|
---|
| 3379 | # C:<permission list> - Set these specific permissions
|
---|
| 3380 | # first name - defaults to username
|
---|
| 3381 | # last name - defaults to blank
|
---|
| 3382 | # phone - defaults to blank (could put other data within column def)
|
---|
[90] | 3383 | # Returns (OK,<uid>) on success, (FAIL,<message>) on failure
|
---|
[24] | 3384 | sub addUser {
|
---|
| 3385 | $errstr = '';
|
---|
[479] | 3386 | my $self = shift;
|
---|
| 3387 | my $dbh = $self->{dbh};
|
---|
[24] | 3388 | my $username = shift;
|
---|
| 3389 | my $group = shift;
|
---|
| 3390 | my $pass = shift;
|
---|
| 3391 | my $state = shift;
|
---|
[25] | 3392 |
|
---|
[90] | 3393 | return ('FAIL', "Missing one or more required entries") if !defined($state);
|
---|
| 3394 | return ('FAIL', "Username must not be blank") if !$username;
|
---|
[87] | 3395 |
|
---|
[408] | 3396 | # Munge in some alternate state values
|
---|
| 3397 | $state = 1 if $state =~ /^active$/;
|
---|
| 3398 | $state = 1 if $state =~ /^on$/;
|
---|
| 3399 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 3400 | $state = 0 if $state =~ /^off$/;
|
---|
| 3401 |
|
---|
[25] | 3402 | my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
|
---|
| 3403 |
|
---|
[67] | 3404 | my $permstring = shift || 'i'; # default is to inhert permissions from group
|
---|
| 3405 |
|
---|
[25] | 3406 | my $fname = shift || $username;
|
---|
[24] | 3407 | my $lname = shift || '';
|
---|
[25] | 3408 | my $phone = shift || ''; # not going format-check
|
---|
[24] | 3409 |
|
---|
[38] | 3410 | my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
|
---|
[24] | 3411 | my $user_id;
|
---|
| 3412 |
|
---|
[38] | 3413 | # quick check to start to see if we've already got one
|
---|
| 3414 | $sth->execute($username);
|
---|
| 3415 | ($user_id) = $sth->fetchrow_array;
|
---|
| 3416 |
|
---|
| 3417 | return ('FAIL', "User already exists") if $user_id;
|
---|
| 3418 |
|
---|
[24] | 3419 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3420 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3421 | local $dbh->{AutoCommit} = 0;
|
---|
| 3422 | local $dbh->{RaiseError} = 1;
|
---|
| 3423 |
|
---|
| 3424 | # Wrap all the SQL in a transaction
|
---|
| 3425 | eval {
|
---|
[87] | 3426 | # insert the user... note we set inherited perms by default since
|
---|
| 3427 | # it's simple and cleans up some other bits of state
|
---|
[592] | 3428 | ##fixme: need better handling of case of inherited or missing (!!) permissions entries
|
---|
[87] | 3429 | my $sth = $dbh->prepare("INSERT INTO users ".
|
---|
| 3430 | "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
|
---|
| 3431 | "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
|
---|
| 3432 | $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);
|
---|
[24] | 3433 |
|
---|
| 3434 | # get the ID...
|
---|
[94] | 3435 | ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");
|
---|
[24] | 3436 |
|
---|
[87] | 3437 | # Permissions! Gotta set'em all!
|
---|
[401] | 3438 | die "Invalid permission string $permstring\n"
|
---|
[87] | 3439 | if $permstring !~ /^(?:
|
---|
| 3440 | i # inherit
|
---|
| 3441 | |c:\d+ # clone
|
---|
| 3442 | # custom. no, the leading , is not a typo
|
---|
[391] | 3443 | |C:(?:,(?:group|user|domain|record|location|self)_(?:edit|create|delete|locchg|view))*
|
---|
[87] | 3444 | )$/x;
|
---|
| 3445 | # bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
|
---|
| 3446 | if ($permstring ne 'i') {
|
---|
| 3447 | # for cloned or custom permissions, we have to create a new permissions entry.
|
---|
| 3448 | my $clonesrc = $group;
|
---|
| 3449 | if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
|
---|
| 3450 | $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
|
---|
| 3451 | "SELECT $permlist,? FROM permissions WHERE permission_id=".
|
---|
| 3452 | "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
|
---|
| 3453 | undef, ($user_id,$clonesrc) );
|
---|
| 3454 | $dbh->do("UPDATE users SET permission_id=".
|
---|
| 3455 | "(SELECT permission_id FROM permissions WHERE user_id=?) ".
|
---|
| 3456 | "WHERE user_id=?", undef, ($user_id, $user_id) );
|
---|
| 3457 | }
|
---|
| 3458 | if ($permstring =~ /^C:/) {
|
---|
| 3459 | # finally for custom permissions, we set the passed-in permissions (and unset
|
---|
| 3460 | # any that might have been brought in by the clone operation above)
|
---|
| 3461 | my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
|
---|
| 3462 | undef, ($user_id) );
|
---|
| 3463 | foreach (@permtypes) {
|
---|
| 3464 | if ($permstring =~ /,$_/) {
|
---|
| 3465 | $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
|
---|
| 3466 | } else {
|
---|
| 3467 | $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
|
---|
| 3468 | }
|
---|
| 3469 | }
|
---|
| 3470 | }
|
---|
| 3471 |
|
---|
| 3472 | $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
|
---|
| 3473 |
|
---|
[25] | 3474 | ##fixme: add another table to hold name/email for log table?
|
---|
| 3475 |
|
---|
[487] | 3476 | $self->_log(group_id => $group, entry => "Added user $username ($fname $lname)");
|
---|
[24] | 3477 | # once we get here, we should have suceeded.
|
---|
| 3478 | $dbh->commit;
|
---|
| 3479 | }; # end eval
|
---|
| 3480 |
|
---|
| 3481 | if ($@) {
|
---|
| 3482 | my $msg = $@;
|
---|
| 3483 | eval { $dbh->rollback; };
|
---|
[517] | 3484 | if ($self->{log_failures}) {
|
---|
[487] | 3485 | $self->_log(group_id => $group, entry => "Error adding user $username: $msg");
|
---|
[294] | 3486 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 3487 | }
|
---|
| 3488 | return ('FAIL',"Error adding user $username: $msg");
|
---|
[24] | 3489 | }
|
---|
[294] | 3490 |
|
---|
| 3491 | return ('OK',"User $username ($fname $lname) added");
|
---|
[24] | 3492 | } # end addUser
|
---|
| 3493 |
|
---|
| 3494 |
|
---|
[325] | 3495 | ## DNSDB::getUserCount()
|
---|
| 3496 | # Get count of users in group
|
---|
| 3497 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
| 3498 | # - a reference list of secondary groups
|
---|
| 3499 | # - a filter string
|
---|
| 3500 | # - a "Starts with" string
|
---|
| 3501 | sub getUserCount {
|
---|
[479] | 3502 | my $self = shift;
|
---|
| 3503 | my $dbh = $self->{dbh};
|
---|
[325] | 3504 |
|
---|
| 3505 | my %args = @_;
|
---|
| 3506 |
|
---|
[509] | 3507 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 3508 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 3509 | $errstr = "Bad or missing curgroup argument";
|
---|
| 3510 | return;
|
---|
| 3511 | }
|
---|
| 3512 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 3513 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 3514 | $errstr = "Bad childlist argument";
|
---|
| 3515 | return;
|
---|
| 3516 | }
|
---|
| 3517 |
|
---|
[325] | 3518 | my @filterargs;
|
---|
| 3519 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3520 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3521 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3522 |
|
---|
| 3523 | my $sql = "SELECT count(*) FROM users ".
|
---|
| 3524 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3525 | ($args{startwith} ? " AND username ~* ?" : '').
|
---|
[730] | 3526 | ($args{filter} ? " AND username ~* ?" : '').
|
---|
| 3527 | " AND NOT type = 'R' ";
|
---|
[325] | 3528 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 3529 | $errstr = $dbh->errstr if !$count;
|
---|
| 3530 | return $count;
|
---|
| 3531 | } # end getUserCount()
|
---|
| 3532 |
|
---|
| 3533 |
|
---|
| 3534 | ## DNSDB::getUserList()
|
---|
| 3535 | # Get list of users
|
---|
| 3536 | # Takes the same arguments as getUserCount() above, plus optional:
|
---|
| 3537 | # - sort field
|
---|
| 3538 | # - sort order
|
---|
| 3539 | # - offset/return-all-everything flag (defaults to $perpage records)
|
---|
| 3540 | sub getUserList {
|
---|
[479] | 3541 | my $self = shift;
|
---|
| 3542 | my $dbh = $self->{dbh};
|
---|
[325] | 3543 |
|
---|
| 3544 | my %args = @_;
|
---|
| 3545 |
|
---|
[509] | 3546 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 3547 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 3548 | $errstr = "Bad or missing curgroup argument";
|
---|
| 3549 | return;
|
---|
| 3550 | }
|
---|
| 3551 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 3552 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 3553 | $errstr = "Bad childlist argument";
|
---|
| 3554 | return;
|
---|
| 3555 | }
|
---|
| 3556 |
|
---|
[325] | 3557 | my @filterargs;
|
---|
| 3558 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3559 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3560 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3561 |
|
---|
| 3562 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
| 3563 | my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
| 3564 | fname => 'fname');
|
---|
| 3565 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 3566 |
|
---|
| 3567 | # protection against bad or missing arguments
|
---|
[508] | 3568 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
| 3569 | $args{sortby} = 'u.username' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
[397] | 3570 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[325] | 3571 |
|
---|
| 3572 | my $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ".
|
---|
| 3573 | "FROM users u ".
|
---|
| 3574 | "INNER JOIN groups g ON u.group_id=g.group_id ".
|
---|
| 3575 | "WHERE u.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3576 | ($args{startwith} ? " AND u.username ~* ?" : '').
|
---|
| 3577 | ($args{filter} ? " AND u.username ~* ?" : '').
|
---|
[401] | 3578 | " AND NOT u.type = 'R' ".
|
---|
[325] | 3579 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
[517] | 3580 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
[325] | 3581 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 3582 | $errstr = $dbh->errstr if !$ulist;
|
---|
| 3583 | return $ulist;
|
---|
| 3584 | } # end getUserList()
|
---|
| 3585 |
|
---|
| 3586 |
|
---|
[326] | 3587 | ## DNSDB::getUserDropdown()
|
---|
| 3588 | # Get a list of usernames for use in a dropdown menu.
|
---|
| 3589 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
| 3590 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
| 3591 | sub getUserDropdown {
|
---|
[479] | 3592 | my $self = shift;
|
---|
| 3593 | my $dbh = $self->{dbh};
|
---|
[326] | 3594 | my $grp = shift;
|
---|
| 3595 | my $sel = shift || 0;
|
---|
| 3596 |
|
---|
[720] | 3597 | my $sth = $dbh->prepare("SELECT username,user_id FROM users WHERE group_id=? AND password <> 'RPC'");
|
---|
[326] | 3598 | $sth->execute($grp);
|
---|
| 3599 |
|
---|
| 3600 | my @userlist;
|
---|
| 3601 | while (my ($username,$uid) = $sth->fetchrow_array) {
|
---|
| 3602 | my %row = (
|
---|
| 3603 | username => $username,
|
---|
| 3604 | uid => $uid,
|
---|
| 3605 | selected => ($sel == $uid ? 1 : 0)
|
---|
| 3606 | );
|
---|
| 3607 | push @userlist, \%row;
|
---|
| 3608 | }
|
---|
| 3609 | return \@userlist;
|
---|
| 3610 | } # end getUserDropdown()
|
---|
| 3611 |
|
---|
| 3612 |
|
---|
[83] | 3613 | ## DNSDB:: updateUser()
|
---|
[90] | 3614 | # Update general data about user
|
---|
[83] | 3615 | sub updateUser {
|
---|
[479] | 3616 | my $self = shift;
|
---|
| 3617 | my $dbh = $self->{dbh};
|
---|
[118] | 3618 |
|
---|
| 3619 | ##fixme: tweak calling convention so that we can update any given bit of data
|
---|
[83] | 3620 | my $uid = shift;
|
---|
| 3621 | my $username = shift;
|
---|
| 3622 | my $group = shift;
|
---|
| 3623 | my $pass = shift;
|
---|
| 3624 | my $state = shift;
|
---|
[87] | 3625 | my $type = shift || 'u';
|
---|
[83] | 3626 | my $fname = shift || $username;
|
---|
| 3627 | my $lname = shift || '';
|
---|
| 3628 | my $phone = shift || ''; # not going format-check
|
---|
| 3629 |
|
---|
[294] | 3630 | my $resultmsg = '';
|
---|
[83] | 3631 |
|
---|
[411] | 3632 | # Munge in some alternate state values
|
---|
| 3633 | $state = 1 if $state =~ /^active$/;
|
---|
| 3634 | $state = 1 if $state =~ /^on$/;
|
---|
| 3635 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 3636 | $state = 0 if $state =~ /^off$/;
|
---|
| 3637 |
|
---|
[83] | 3638 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3639 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3640 | local $dbh->{AutoCommit} = 0;
|
---|
| 3641 | local $dbh->{RaiseError} = 1;
|
---|
| 3642 |
|
---|
| 3643 | my $sth;
|
---|
| 3644 |
|
---|
| 3645 | # Password can be left blank; if so we assume there's one on file.
|
---|
| 3646 | # Actual blank passwords are bad, mm'kay?
|
---|
| 3647 | if (!$pass) {
|
---|
[294] | 3648 | ($pass) = $dbh->selectrow_array("SELECT password FROM users WHERE user_id=?", undef, ($uid));
|
---|
[83] | 3649 | } else {
|
---|
| 3650 | $pass = unix_md5_crypt($pass);
|
---|
| 3651 | }
|
---|
| 3652 |
|
---|
| 3653 | eval {
|
---|
[294] | 3654 | $dbh->do("UPDATE users SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?".
|
---|
| 3655 | " WHERE user_id=?", undef, ($username, $pass, $fname, $lname, $phone, $type, $state, $uid));
|
---|
| 3656 | $resultmsg = "Updated user info for $username ($fname $lname)";
|
---|
[487] | 3657 | $self->_log(group_id => $group, entry => $resultmsg);
|
---|
[83] | 3658 | $dbh->commit;
|
---|
| 3659 | };
|
---|
| 3660 | if ($@) {
|
---|
| 3661 | my $msg = $@;
|
---|
| 3662 | eval { $dbh->rollback; };
|
---|
[517] | 3663 | if ($self->{log_failures}) {
|
---|
[487] | 3664 | $self->_log(group_id => $group, entry => "Error updating user $username: $msg");
|
---|
[294] | 3665 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 3666 | }
|
---|
| 3667 | return ('FAIL',"Error updating user $username: $msg");
|
---|
[83] | 3668 | }
|
---|
[294] | 3669 |
|
---|
| 3670 | return ('OK',$resultmsg);
|
---|
[83] | 3671 | } # end updateUser()
|
---|
| 3672 |
|
---|
| 3673 |
|
---|
[24] | 3674 | ## DNSDB::delUser()
|
---|
[297] | 3675 | # Delete a user.
|
---|
| 3676 | # Takes a database handle and user ID
|
---|
| 3677 | # Returns a success/failure code and matching message
|
---|
[24] | 3678 | sub delUser {
|
---|
[479] | 3679 | my $self = shift;
|
---|
| 3680 | my $dbh = $self->{dbh};
|
---|
[25] | 3681 | my $userid = shift;
|
---|
| 3682 |
|
---|
[297] | 3683 | return ('FAIL',"Bad userid") if !defined($userid);
|
---|
[25] | 3684 |
|
---|
[479] | 3685 | my $userdata = $self->getUserData($userid);
|
---|
[25] | 3686 |
|
---|
[297] | 3687 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3688 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3689 | local $dbh->{AutoCommit} = 0;
|
---|
| 3690 | local $dbh->{RaiseError} = 1;
|
---|
[25] | 3691 |
|
---|
[297] | 3692 | eval {
|
---|
| 3693 | $dbh->do("DELETE FROM users WHERE user_id=?", undef, ($userid));
|
---|
[487] | 3694 | $self->_log(group_id => $userdata->{group_id},
|
---|
[297] | 3695 | entry => "Deleted user ID $userid/".$userdata->{username}.
|
---|
[487] | 3696 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")");
|
---|
[297] | 3697 | $dbh->commit;
|
---|
| 3698 | };
|
---|
| 3699 | if ($@) {
|
---|
| 3700 | my $msg = $@;
|
---|
| 3701 | eval { $dbh->rollback; };
|
---|
[517] | 3702 | if ($self->{log_failures}) {
|
---|
[487] | 3703 | $self->_log(group_id => $userdata->{group_id}, entry => "Error deleting user ID ".
|
---|
| 3704 | "$userid/".$userdata->{username}.": $msg");
|
---|
[297] | 3705 | $dbh->commit;
|
---|
| 3706 | }
|
---|
| 3707 | return ('FAIL',"Error deleting user $userid/".$userdata->{username}.": $msg");
|
---|
| 3708 | }
|
---|
| 3709 |
|
---|
| 3710 | return ('OK',"Deleted user ".$userdata->{username}." (".$userdata->{firstname}." ".$userdata->{lastname}.")");
|
---|
[24] | 3711 | } # end delUser
|
---|
| 3712 |
|
---|
| 3713 |
|
---|
[25] | 3714 | ## DNSDB::userFullName()
|
---|
| 3715 | # Return a pretty string!
|
---|
| 3716 | # Takes a user_id and optional printf-ish string to indicate which pieces where:
|
---|
| 3717 | # %u for the username
|
---|
| 3718 | # %f for the first name
|
---|
| 3719 | # %l for the last name
|
---|
| 3720 | # All other text in the passed string will be left as-is.
|
---|
| 3721 | ##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
|
---|
| 3722 | sub userFullName {
|
---|
| 3723 | $errstr = '';
|
---|
[473] | 3724 | my $self = shift;
|
---|
| 3725 | my $dbh = $self->{dbh};
|
---|
[25] | 3726 | my $userid = shift;
|
---|
| 3727 | my $fullformat = shift || '%f %l (%u)';
|
---|
| 3728 | my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
|
---|
| 3729 | $sth->execute($userid);
|
---|
| 3730 | my ($uname,$fname,$lname) = $sth->fetchrow_array();
|
---|
| 3731 | $errstr = $DBI::errstr if !$uname;
|
---|
| 3732 |
|
---|
[732] | 3733 | no warnings qw (uninitialized);
|
---|
[25] | 3734 | $fullformat =~ s/\%u/$uname/g;
|
---|
| 3735 | $fullformat =~ s/\%f/$fname/g;
|
---|
| 3736 | $fullformat =~ s/\%l/$lname/g;
|
---|
| 3737 |
|
---|
| 3738 | return $fullformat;
|
---|
| 3739 | } # end userFullName
|
---|
| 3740 |
|
---|
| 3741 |
|
---|
[51] | 3742 | ## DNSDB::userStatus()
|
---|
| 3743 | # Sets and/or returns a user's status
|
---|
| 3744 | # Takes a database handle, user ID and optionally a status argument
|
---|
| 3745 | # Returns undef on errors.
|
---|
| 3746 | sub userStatus {
|
---|
[479] | 3747 | my $self = shift;
|
---|
| 3748 | my $dbh = $self->{dbh};
|
---|
[51] | 3749 | my $id = shift;
|
---|
[296] | 3750 | my $newstatus = shift || 'mu';
|
---|
[51] | 3751 |
|
---|
| 3752 | return undef if $id !~ /^\d+$/;
|
---|
| 3753 |
|
---|
[479] | 3754 | my $userdata = $self->getUserData($id);
|
---|
[51] | 3755 |
|
---|
[296] | 3756 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3757 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3758 | local $dbh->{AutoCommit} = 0;
|
---|
| 3759 | local $dbh->{RaiseError} = 1;
|
---|
| 3760 |
|
---|
| 3761 | if ($newstatus ne 'mu') {
|
---|
| 3762 | # ooo, fun! let's see what we were passed for status
|
---|
| 3763 | eval {
|
---|
| 3764 | $newstatus = 0 if $newstatus eq 'useroff';
|
---|
| 3765 | $newstatus = 1 if $newstatus eq 'useron';
|
---|
| 3766 | $dbh->do("UPDATE users SET status=? WHERE user_id=?", undef, ($newstatus, $id));
|
---|
| 3767 |
|
---|
[297] | 3768 | $resultstr = ($newstatus ? 'Enabled' : 'Disabled')." user ".$userdata->{username}.
|
---|
| 3769 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")";
|
---|
[296] | 3770 |
|
---|
| 3771 | my %loghash;
|
---|
[473] | 3772 | $loghash{group_id} = $self->parentID(id => $id, type => 'user');
|
---|
[296] | 3773 | $loghash{entry} = $resultstr;
|
---|
[487] | 3774 | $self->_log(%loghash);
|
---|
[296] | 3775 |
|
---|
| 3776 | $dbh->commit;
|
---|
| 3777 | };
|
---|
| 3778 | if ($@) {
|
---|
| 3779 | my $msg = $@;
|
---|
| 3780 | eval { $dbh->rollback; };
|
---|
| 3781 | $resultstr = '';
|
---|
| 3782 | $errstr = $msg;
|
---|
| 3783 | ##fixme: failure logging?
|
---|
| 3784 | return;
|
---|
[51] | 3785 | }
|
---|
| 3786 | }
|
---|
| 3787 |
|
---|
[296] | 3788 | my ($status) = $dbh->selectrow_array("SELECT status FROM users WHERE user_id=?", undef, ($id));
|
---|
[51] | 3789 | return $status;
|
---|
| 3790 | } # end userStatus()
|
---|
| 3791 |
|
---|
| 3792 |
|
---|
[83] | 3793 | ## DNSDB::getUserData()
|
---|
| 3794 | # Get misc user data for display
|
---|
| 3795 | sub getUserData {
|
---|
[479] | 3796 | my $self = shift;
|
---|
| 3797 | my $dbh = $self->{dbh};
|
---|
[83] | 3798 | my $uid = shift;
|
---|
| 3799 |
|
---|
| 3800 | my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
|
---|
| 3801 | "FROM users WHERE user_id=?");
|
---|
| 3802 | $sth->execute($uid);
|
---|
| 3803 | return $sth->fetchrow_hashref();
|
---|
| 3804 | } # end getUserData()
|
---|
| 3805 |
|
---|
| 3806 |
|
---|
[370] | 3807 | ## DNSDB::addLoc()
|
---|
[375] | 3808 | # Add a new location.
|
---|
| 3809 | # Takes a database handle, group ID, short and long description, and a comma-separated
|
---|
| 3810 | # list of IP addresses.
|
---|
| 3811 | # Returns ('OK',<location>) on success, ('FAIL',<failmsg>) on failure
|
---|
| 3812 | sub addLoc {
|
---|
[480] | 3813 | my $self = shift;
|
---|
| 3814 | my $dbh = $self->{dbh};
|
---|
[709] | 3815 | my %args = @_;
|
---|
[370] | 3816 |
|
---|
[709] | 3817 | my $grp = $args{group};
|
---|
| 3818 | my $shdesc = $args{desc};
|
---|
| 3819 | my $comments = $args{comments};
|
---|
| 3820 | my $iplist = $args{iplist};
|
---|
| 3821 |
|
---|
[375] | 3822 | # $shdesc gets set to the generated location ID if possible, but these can be de-undefined here.
|
---|
| 3823 | $comments = '' if !$comments;
|
---|
| 3824 | $iplist = '' if !$iplist;
|
---|
| 3825 |
|
---|
[709] | 3826 | # allow requesting a specific location entry.
|
---|
| 3827 | my $loc = $args{loc};
|
---|
[375] | 3828 |
|
---|
| 3829 | # Generate a location ID. This is, by spec, a two-character widget. We'll use [a-z][a-z]
|
---|
| 3830 | # for now; 676 locations should satisfy all but the largest of the huge networks.
|
---|
| 3831 |
|
---|
[709] | 3832 | # just to be as clear as possible; as per http://cr.yp.to/djbdns/tinydns-data.html:
|
---|
[699] | 3833 |
|
---|
| 3834 | #For versions 1.04 and above: You may include a client location on each line. The line is ignored for clients
|
---|
| 3835 | #outside that location. Client locations are specified by % lines:
|
---|
| 3836 | #
|
---|
| 3837 | # %lo:ipprefix
|
---|
| 3838 | #
|
---|
| 3839 | #means that IP addresses starting with ipprefix are in location lo. lo is a sequence of one or two ASCII letters.
|
---|
| 3840 |
|
---|
[709] | 3841 | # this has been confirmed by experiment; locations "lo", "Lo", and "lO" are all distinct.
|
---|
[699] | 3842 |
|
---|
[375] | 3843 | # add just after "my $origloc = $loc;":
|
---|
| 3844 | # # These expand the possible space from 26^2 to 52^2 [* note in testing only 2052 were achieved],
|
---|
| 3845 | # # and wrap it around.
|
---|
| 3846 | # # Yes, they skip a couple of possibles. No, I don't care.
|
---|
| 3847 | # $loc = 'aA' if $loc eq 'zz';
|
---|
| 3848 | # $loc = 'Aa' if $loc eq 'zZ';
|
---|
| 3849 | # $loc = 'ZA' if $loc eq 'Zz';
|
---|
| 3850 | # $loc = 'aa' if $loc eq 'ZZ';
|
---|
| 3851 |
|
---|
| 3852 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3853 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3854 | local $dbh->{AutoCommit} = 0;
|
---|
| 3855 | local $dbh->{RaiseError} = 1;
|
---|
| 3856 |
|
---|
| 3857 | ##fixme: There is probably a far better way to do this. Sequential increments
|
---|
| 3858 | # are marginally less stupid that pure random generation though, and the existence
|
---|
| 3859 | # check makes sure we don't stomp on an imported one.
|
---|
| 3860 |
|
---|
| 3861 | eval {
|
---|
| 3862 | # Get the "last" location. Note this is the only use for loc_id, because selecting on location Does Funky Things
|
---|
[709] | 3863 | my ($newloc) = $dbh->selectrow_array("SELECT location FROM locations ORDER BY loc_id DESC LIMIT 1");
|
---|
| 3864 |
|
---|
| 3865 | no warnings qw(uninitialized);
|
---|
| 3866 |
|
---|
| 3867 | my $ecnt = $dbh->prepare("SELECT count(*) FROM locations WHERE location LIKE ?");
|
---|
| 3868 |
|
---|
| 3869 | if ($loc) {
|
---|
| 3870 | $ecnt->execute($loc);
|
---|
| 3871 | if (($ecnt->fetchrow_array())[0]) {
|
---|
| 3872 | # too bad, so sad, requested location is unavailable.
|
---|
| 3873 | ##fixme: known failure case: caller requests a location ID that is not two characters.
|
---|
| 3874 | die "Requested location is already defined\n" if $args{reqonly};
|
---|
| 3875 | # fall back to autoincrement
|
---|
| 3876 | }
|
---|
| 3877 | $newloc = $loc;
|
---|
| 3878 | }
|
---|
| 3879 |
|
---|
| 3880 | # Either the requested location ID is unavailable and the caller isn't too attached
|
---|
| 3881 | # to it, OR, the caller hasn't specified a location ID. (The second case should be
|
---|
| 3882 | # far more common.) Find the "next available" location identifier.
|
---|
| 3883 |
|
---|
| 3884 | ($newloc) = ($newloc =~ /^(..)/) if $newloc;
|
---|
| 3885 | my $origloc = $newloc;
|
---|
| 3886 | $newloc = 'aa' if !$newloc;
|
---|
[375] | 3887 | # Make a change...
|
---|
| 3888 | # ... and keep changing if it exists
|
---|
[709] | 3889 | while ($dbh->selectrow_array("SELECT count(*) FROM locations WHERE location LIKE ?", undef, ($newloc.'%'))) {
|
---|
| 3890 | $newloc++;
|
---|
| 3891 | ($newloc) = ($newloc =~ /^(..)/);
|
---|
| 3892 | die "too many locations in use, can't add another one\n" if $newloc eq $origloc;
|
---|
[375] | 3893 | ##fixme: really need to handle this case faster somehow
|
---|
| 3894 | #if $loc eq $origloc die "<thwap> bad admin: all locations used, your network is too fragmented";
|
---|
| 3895 | }
|
---|
[709] | 3896 | # And now we should have a unique location.
|
---|
| 3897 | $shdesc = $newloc if !$shdesc;
|
---|
[375] | 3898 | $dbh->do("INSERT INTO locations (location, group_id, iplist, description, comments) VALUES (?,?,?,?,?)",
|
---|
[709] | 3899 | undef, ($newloc, $grp, $iplist, $shdesc, $comments) );
|
---|
[487] | 3900 | $self->_log(entry => "Added location ($shdesc, '$iplist')");
|
---|
[709] | 3901 | $loc = $newloc;
|
---|
[377] | 3902 | $dbh->commit;
|
---|
[375] | 3903 | };
|
---|
| 3904 | if ($@) {
|
---|
| 3905 | my $msg = $@;
|
---|
| 3906 | eval { $dbh->rollback; };
|
---|
[517] | 3907 | if ($self->{log_failures}) {
|
---|
[375] | 3908 | $shdesc = $loc if !$shdesc;
|
---|
[487] | 3909 | $self->_log(entry => "Failed adding location ($shdesc, '$iplist'): $msg");
|
---|
[375] | 3910 | $dbh->commit;
|
---|
| 3911 | }
|
---|
| 3912 | return ('FAIL',$msg);
|
---|
| 3913 | }
|
---|
| 3914 |
|
---|
| 3915 | return ('OK',$loc);
|
---|
[377] | 3916 | } # end addLoc()
|
---|
[375] | 3917 |
|
---|
| 3918 |
|
---|
[370] | 3919 | ## DNSDB::updateLoc()
|
---|
[428] | 3920 | # Update details of a location.
|
---|
| 3921 | # Takes a database handle, location ID, group ID, short description,
|
---|
| 3922 | # long comments/notes, and comma/space-separated IP list
|
---|
| 3923 | # Returns a result code and message
|
---|
[377] | 3924 | sub updateLoc {
|
---|
[480] | 3925 | my $self = shift;
|
---|
| 3926 | my $dbh = $self->{dbh};
|
---|
[377] | 3927 | my $loc = shift;
|
---|
| 3928 | my $grp = shift;
|
---|
| 3929 | my $shdesc = shift;
|
---|
| 3930 | my $comments = shift;
|
---|
| 3931 | my $iplist = shift;
|
---|
[370] | 3932 |
|
---|
[377] | 3933 | $shdesc = '' if !$shdesc;
|
---|
| 3934 | $comments = '' if !$comments;
|
---|
| 3935 | $iplist = '' if !$iplist;
|
---|
| 3936 |
|
---|
| 3937 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3938 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3939 | local $dbh->{AutoCommit} = 0;
|
---|
| 3940 | local $dbh->{RaiseError} = 1;
|
---|
| 3941 |
|
---|
[480] | 3942 | my $oldloc = $self->getLoc($loc);
|
---|
[377] | 3943 | my $okmsg = "Updated location (".$oldloc->{description}.", '".$oldloc->{iplist}."') to ($shdesc, '$iplist')";
|
---|
| 3944 |
|
---|
| 3945 | eval {
|
---|
| 3946 | $dbh->do("UPDATE locations SET group_id=?,iplist=?,description=?,comments=? WHERE location=?",
|
---|
| 3947 | undef, ($grp, $iplist, $shdesc, $comments, $loc) );
|
---|
[487] | 3948 | $self->_log(entry => $okmsg);
|
---|
[377] | 3949 | $dbh->commit;
|
---|
| 3950 | };
|
---|
| 3951 | if ($@) {
|
---|
| 3952 | my $msg = $@;
|
---|
| 3953 | eval { $dbh->rollback; };
|
---|
[517] | 3954 | if ($self->{log_failures}) {
|
---|
[377] | 3955 | $shdesc = $loc if !$shdesc;
|
---|
[487] | 3956 | $self->_log(entry => "Failed updating location ($shdesc, '$iplist'): $msg");
|
---|
[377] | 3957 | $dbh->commit;
|
---|
| 3958 | }
|
---|
| 3959 | return ('FAIL',$msg);
|
---|
| 3960 | }
|
---|
| 3961 |
|
---|
| 3962 | return ('OK',$okmsg);
|
---|
| 3963 | } # end updateLoc()
|
---|
| 3964 |
|
---|
| 3965 |
|
---|
[370] | 3966 | ## DNSDB::delLoc()
|
---|
[428] | 3967 | sub delLoc {
|
---|
[480] | 3968 | my $self = shift;
|
---|
| 3969 | my $dbh = $self->{dbh};
|
---|
[428] | 3970 | my $loc = shift;
|
---|
[370] | 3971 |
|
---|
[428] | 3972 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3973 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3974 | local $dbh->{AutoCommit} = 0;
|
---|
| 3975 | local $dbh->{RaiseError} = 1;
|
---|
[370] | 3976 |
|
---|
[480] | 3977 | my $oldloc = $self->getLoc($loc);
|
---|
[428] | 3978 | my $olddesc = ($oldloc->{description} ? $oldloc->{description} : $loc);
|
---|
| 3979 | my $okmsg = "Deleted location ($olddesc, '".$oldloc->{iplist}."')";
|
---|
| 3980 |
|
---|
| 3981 | eval {
|
---|
| 3982 | # Check for records with this location first. Deleting a location without deleting records
|
---|
| 3983 | # tagged for that location will render them unpublished without other warning.
|
---|
| 3984 | my ($r) = $dbh->selectrow_array("SELECT record_id FROM records WHERE location=? LIMIT 1", undef, ($loc) );
|
---|
| 3985 | die "Records still exist in location $olddesc\n" if $r;
|
---|
| 3986 | $dbh->do("DELETE FROM locations WHERE location=?", undef, ($loc) );
|
---|
[487] | 3987 | $self->_log(entry => $okmsg);
|
---|
[428] | 3988 | $dbh->commit;
|
---|
| 3989 | };
|
---|
| 3990 | if ($@) {
|
---|
| 3991 | my $msg = $@;
|
---|
| 3992 | eval { $dbh->rollback; };
|
---|
[517] | 3993 | if ($self->{log_failures}) {
|
---|
[487] | 3994 | $self->_log(entry => "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
|
---|
[428] | 3995 | $dbh->commit;
|
---|
| 3996 | }
|
---|
| 3997 | return ('FAIL', "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
|
---|
| 3998 | }
|
---|
| 3999 |
|
---|
| 4000 | return ('OK',$okmsg);
|
---|
| 4001 | } # end delLoc()
|
---|
| 4002 |
|
---|
| 4003 |
|
---|
[375] | 4004 | ## DNSDB::getLoc()
|
---|
[428] | 4005 | # Get details about a location/view
|
---|
| 4006 | # Takes a database handle and location ID.
|
---|
| 4007 | # Returns a reference to a hash containing the group ID, IP list, description, and comments/notes
|
---|
[375] | 4008 | sub getLoc {
|
---|
[480] | 4009 | my $self = shift;
|
---|
| 4010 | my $dbh = $self->{dbh};
|
---|
[375] | 4011 | my $loc = shift;
|
---|
| 4012 |
|
---|
| 4013 | my $sth = $dbh->prepare("SELECT group_id,iplist,description,comments FROM locations WHERE location=?");
|
---|
| 4014 | $sth->execute($loc);
|
---|
| 4015 | return $sth->fetchrow_hashref();
|
---|
| 4016 | } # end getLoc()
|
---|
| 4017 |
|
---|
| 4018 |
|
---|
[370] | 4019 | ## DNSDB::getLocCount()
|
---|
| 4020 | # Get count of locations/views
|
---|
| 4021 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
| 4022 | # - a reference list of secondary groups
|
---|
| 4023 | # - a filter string
|
---|
| 4024 | # - a "Starts with" string
|
---|
| 4025 | sub getLocCount {
|
---|
[480] | 4026 | my $self = shift;
|
---|
| 4027 | my $dbh = $self->{dbh};
|
---|
[370] | 4028 |
|
---|
| 4029 | my %args = @_;
|
---|
| 4030 |
|
---|
[509] | 4031 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 4032 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 4033 | $errstr = "Bad or missing curgroup argument";
|
---|
| 4034 | return;
|
---|
| 4035 | }
|
---|
| 4036 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 4037 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 4038 | $errstr = "Bad childlist argument";
|
---|
| 4039 | return;
|
---|
| 4040 | }
|
---|
| 4041 |
|
---|
[370] | 4042 | my @filterargs;
|
---|
| 4043 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 4044 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 4045 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 4046 |
|
---|
| 4047 | my $sql = "SELECT count(*) FROM locations ".
|
---|
| 4048 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 4049 | ($args{startwith} ? " AND description ~* ?" : '').
|
---|
| 4050 | ($args{filter} ? " AND description ~* ?" : '');
|
---|
| 4051 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 4052 | $errstr = $dbh->errstr if !$count;
|
---|
| 4053 | return $count;
|
---|
| 4054 | } # end getLocCount()
|
---|
| 4055 |
|
---|
| 4056 |
|
---|
| 4057 | ## DNSDB::getLocList()
|
---|
| 4058 | sub getLocList {
|
---|
[480] | 4059 | my $self = shift;
|
---|
| 4060 | my $dbh = $self->{dbh};
|
---|
[370] | 4061 |
|
---|
| 4062 | my %args = @_;
|
---|
| 4063 |
|
---|
[509] | 4064 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 4065 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 4066 | $errstr = "Bad or missing curgroup argument";
|
---|
| 4067 | return;
|
---|
| 4068 | }
|
---|
| 4069 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 4070 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 4071 | $errstr = "Bad childlist argument";
|
---|
| 4072 | return;
|
---|
| 4073 | }
|
---|
| 4074 |
|
---|
[370] | 4075 | my @filterargs;
|
---|
| 4076 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 4077 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 4078 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 4079 |
|
---|
| 4080 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
| 4081 | # my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
| 4082 | # fname => 'fname');
|
---|
| 4083 | # $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 4084 |
|
---|
| 4085 | # protection against bad or missing arguments
|
---|
[508] | 4086 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
| 4087 | $args{sortby} = 'l.description' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
[397] | 4088 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[370] | 4089 |
|
---|
| 4090 | my $sql = "SELECT l.location, l.description, l.iplist, g.group_name ".
|
---|
| 4091 | "FROM locations l ".
|
---|
| 4092 | "INNER JOIN groups g ON l.group_id=g.group_id ".
|
---|
| 4093 | "WHERE l.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 4094 | ($args{startwith} ? " AND l.description ~* ?" : '').
|
---|
| 4095 | ($args{filter} ? " AND l.description ~* ?" : '').
|
---|
| 4096 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
[517] | 4097 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
[370] | 4098 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 4099 | $errstr = $dbh->errstr if !$ulist;
|
---|
| 4100 | return $ulist;
|
---|
| 4101 | } # end getLocList()
|
---|
| 4102 |
|
---|
| 4103 |
|
---|
| 4104 | ## DNSDB::getLocDropdown()
|
---|
[383] | 4105 | # Get a list of location names for use in a dropdown menu.
|
---|
| 4106 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
| 4107 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
| 4108 | sub getLocDropdown {
|
---|
[480] | 4109 | my $self = shift;
|
---|
| 4110 | my $dbh = $self->{dbh};
|
---|
[383] | 4111 | my $grp = shift;
|
---|
| 4112 | my $sel = shift || '';
|
---|
[370] | 4113 |
|
---|
[383] | 4114 | my $sth = $dbh->prepare(qq(
|
---|
| 4115 | SELECT description,location FROM locations
|
---|
| 4116 | WHERE group_id=?
|
---|
| 4117 | ORDER BY description
|
---|
| 4118 | ) );
|
---|
| 4119 | $sth->execute($grp);
|
---|
[370] | 4120 |
|
---|
[383] | 4121 | my @loclist;
|
---|
[446] | 4122 | push @loclist, { locname => "(Default/All)", loc => '', selected => ($sel ? 0 : ($sel eq '' ? 1 : 0)) };
|
---|
[383] | 4123 | while (my ($locname, $loc) = $sth->fetchrow_array) {
|
---|
| 4124 | my %row = (
|
---|
| 4125 | locname => $locname,
|
---|
| 4126 | loc => $loc,
|
---|
| 4127 | selected => ($sel eq $loc ? 1 : 0)
|
---|
| 4128 | );
|
---|
| 4129 | push @loclist, \%row;
|
---|
| 4130 | }
|
---|
| 4131 | return \@loclist;
|
---|
| 4132 | } # end getLocDropdown()
|
---|
| 4133 |
|
---|
| 4134 |
|
---|
[2] | 4135 | ## DNSDB::getSOA()
|
---|
| 4136 | # Return all suitable fields from an SOA record in separate elements of a hash
|
---|
[224] | 4137 | # Takes a database handle, default/live flag, domain/reverse flag, and parent ID
|
---|
[2] | 4138 | sub getSOA {
|
---|
| 4139 | $errstr = '';
|
---|
[481] | 4140 | my $self = shift;
|
---|
| 4141 | my $dbh = $self->{dbh};
|
---|
[2] | 4142 | my $def = shift;
|
---|
[224] | 4143 | my $rev = shift;
|
---|
[2] | 4144 | my $id = shift;
|
---|
| 4145 |
|
---|
[224] | 4146 | # (ab)use distance and weight columns to store SOA data? can't for default_rev_records...
|
---|
| 4147 | # - should really attach serial to the zone parent somewhere
|
---|
[101] | 4148 |
|
---|
[224] | 4149 | my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev).
|
---|
| 4150 | " WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}";
|
---|
[311] | 4151 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
| 4152 | return if !$ret;
|
---|
[246] | 4153 | ##fixme: stick a flag somewhere if the record doesn't exist. by the API, this is an impossible case, but...
|
---|
[2] | 4154 |
|
---|
[311] | 4155 | ($ret->{contact},$ret->{prins}) = split /:/, $ret->{host};
|
---|
| 4156 | delete $ret->{host};
|
---|
| 4157 | ($ret->{refresh},$ret->{retry},$ret->{expire},$ret->{minttl}) = split /:/, $ret->{val};
|
---|
| 4158 | delete $ret->{val};
|
---|
[2] | 4159 |
|
---|
[311] | 4160 | return $ret;
|
---|
[2] | 4161 | } # end getSOA()
|
---|
| 4162 |
|
---|
| 4163 |
|
---|
[246] | 4164 | ## DNSDB::updateSOA()
|
---|
| 4165 | # Update the specified SOA record
|
---|
| 4166 | # Takes a database handle, default/live flag, forward/reverse flag, and SOA data hash
|
---|
[277] | 4167 | # Returns a two-element list with a result code and message
|
---|
[246] | 4168 | sub updateSOA {
|
---|
[473] | 4169 | my $self = shift;
|
---|
| 4170 | my $dbh = $self->{dbh};
|
---|
[246] | 4171 | my $defrec = shift;
|
---|
[248] | 4172 | my $revrec = shift;
|
---|
[246] | 4173 |
|
---|
| 4174 | my %soa = @_;
|
---|
| 4175 |
|
---|
[473] | 4176 | my $oldsoa = $self->getSOA($defrec, $revrec, $soa{id});
|
---|
[277] | 4177 |
|
---|
[311] | 4178 | my $msg;
|
---|
| 4179 | my %logdata;
|
---|
| 4180 | if ($defrec eq 'n') {
|
---|
| 4181 | $logdata{domain_id} = $soa{id} if $revrec eq 'n';
|
---|
| 4182 | $logdata{rdns_id} = $soa{id} if $revrec eq 'y';
|
---|
[473] | 4183 | $logdata{group_id} = $self->parentID(id => $soa{id}, revrec => $revrec,
|
---|
| 4184 | type => ($revrec eq 'n' ? 'domain' : 'revzone') );
|
---|
[311] | 4185 | } else {
|
---|
| 4186 | $logdata{group_id} = $soa{id};
|
---|
| 4187 | }
|
---|
[473] | 4188 | my $parname = ($defrec eq 'y' ? $self->groupName($soa{id}) :
|
---|
| 4189 | ($revrec eq 'n' ? $self->domainName($soa{id}) : $self->revName($soa{id})) );
|
---|
[311] | 4190 |
|
---|
[277] | 4191 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4192 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4193 | local $dbh->{AutoCommit} = 0;
|
---|
| 4194 | local $dbh->{RaiseError} = 1;
|
---|
| 4195 |
|
---|
| 4196 | eval {
|
---|
[565] | 4197 | if (!$oldsoa) {
|
---|
| 4198 | # old SOA record is missing for some reason. create a new one.
|
---|
[583] | 4199 | my $sql = "INSERT INTO "._rectable($defrec, $revrec)." ("._recparent($defrec, $revrec).
|
---|
| 4200 | ", host, type, val, ttl) VALUES (?,?,6,?,?)";
|
---|
[565] | 4201 | $dbh->do($sql, undef, ($soa{id}, "$soa{contact}:$soa{prins}",
|
---|
| 4202 | "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}", $soa{ttl}) );
|
---|
| 4203 | $msg = ($defrec eq 'y' ? ($revrec eq 'y' ? 'Default reverse ' : 'Default ') : '').
|
---|
| 4204 | "SOA missing for $parname; added (ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
|
---|
| 4205 | " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})";
|
---|
| 4206 | } else {
|
---|
| 4207 | my $sql = "UPDATE "._rectable($defrec, $revrec)." SET host=?, val=?, ttl=? WHERE record_id=? AND type=6";
|
---|
| 4208 | $dbh->do($sql, undef, ("$soa{contact}:$soa{prins}", "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}",
|
---|
[311] | 4209 | $soa{ttl}, $oldsoa->{record_id}) );
|
---|
[565] | 4210 | $msg = "Updated ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse ' : 'default ') : '').
|
---|
[311] | 4211 | "SOA for $parname: ".
|
---|
| 4212 | "(ns $oldsoa->{prins}, contact $oldsoa->{contact}, refresh $oldsoa->{refresh},".
|
---|
| 4213 | " retry $oldsoa->{retry}, expire $oldsoa->{expire}, minTTL $oldsoa->{minttl}, TTL $oldsoa->{ttl}) to ".
|
---|
[277] | 4214 | "(ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
|
---|
| 4215 | " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})";
|
---|
[565] | 4216 | }
|
---|
[311] | 4217 | $logdata{entry} = $msg;
|
---|
[487] | 4218 | $self->_log(%logdata);
|
---|
[277] | 4219 |
|
---|
| 4220 | $dbh->commit;
|
---|
| 4221 | };
|
---|
| 4222 | if ($@) {
|
---|
| 4223 | $msg = $@;
|
---|
| 4224 | eval { $dbh->rollback; };
|
---|
[311] | 4225 | $logdata{entry} = "Error updating ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse zone ' : 'default ') : '').
|
---|
| 4226 | "SOA record for $parname: $msg";
|
---|
[517] | 4227 | if ($self->{log_failures}) {
|
---|
[487] | 4228 | $self->_log(%logdata);
|
---|
[311] | 4229 | $dbh->commit;
|
---|
| 4230 | }
|
---|
| 4231 | return ('FAIL', $logdata{entry});
|
---|
[277] | 4232 | } else {
|
---|
| 4233 | return ('OK', $msg);
|
---|
| 4234 | }
|
---|
[246] | 4235 | } # end updateSOA()
|
---|
| 4236 |
|
---|
| 4237 |
|
---|
[2] | 4238 | ## DNSDB::getRecLine()
|
---|
| 4239 | # Return all data fields for a zone record in separate elements of a hash
|
---|
[243] | 4240 | # Takes a database handle, default/live flag, forward/reverse flag, and record ID
|
---|
[2] | 4241 | sub getRecLine {
|
---|
| 4242 | $errstr = '';
|
---|
[481] | 4243 | my $self = shift;
|
---|
| 4244 | my $dbh = $self->{dbh};
|
---|
[243] | 4245 | my $defrec = shift;
|
---|
| 4246 | my $revrec = shift;
|
---|
[2] | 4247 | my $id = shift;
|
---|
| 4248 |
|
---|
[543] | 4249 | ##fixme: do we need a knob to twist to switch between unix epoch and postgres time string?
|
---|
[429] | 4250 | my $sql = "SELECT record_id,host,type,val,ttl".
|
---|
| 4251 | ($defrec eq 'n' ? ',location' : '').
|
---|
| 4252 | ($revrec eq 'n' ? ',distance,weight,port' : '').
|
---|
[543] | 4253 | (($defrec eq 'y') ? ',group_id FROM ' : ',domain_id,rdns_id,stamp,stamp < now() AS ispast,expires,stampactive FROM ').
|
---|
[243] | 4254 | _rectable($defrec,$revrec)." WHERE record_id=?";
|
---|
[123] | 4255 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
[2] | 4256 |
|
---|
[90] | 4257 | if ($dbh->err) {
|
---|
[2] | 4258 | $errstr = $DBI::errstr;
|
---|
| 4259 | return undef;
|
---|
| 4260 | }
|
---|
| 4261 |
|
---|
[123] | 4262 | if (!$ret) {
|
---|
| 4263 | $errstr = "No such record";
|
---|
| 4264 | return undef;
|
---|
| 4265 | }
|
---|
| 4266 |
|
---|
[243] | 4267 | # explicitly set a parent id
|
---|
| 4268 | if ($defrec eq 'y') {
|
---|
| 4269 | $ret->{parid} = $ret->{group_id};
|
---|
| 4270 | } else {
|
---|
| 4271 | $ret->{parid} = (($revrec eq 'n') ? $ret->{domain_id} : $ret->{rdns_id});
|
---|
| 4272 | # and a secondary if we have a custom type that lives in both a forward and reverse zone
|
---|
| 4273 | $ret->{secid} = (($revrec eq 'y') ? $ret->{domain_id} : $ret->{rdns_id}) if $ret->{type} > 65279;
|
---|
| 4274 | }
|
---|
[451] | 4275 | $ret->{address} = $ret->{val}; # because.
|
---|
[90] | 4276 |
|
---|
| 4277 | return $ret;
|
---|
[2] | 4278 | }
|
---|
| 4279 |
|
---|
| 4280 |
|
---|
| 4281 | ##fixme: should use above (getRecLine()) to get lines for below?
|
---|
[495] | 4282 | ## DNSDB::getRecList()
|
---|
| 4283 | # Return records for a group or zone
|
---|
| 4284 | # Takes a default/live flag, group or zone ID, start,
|
---|
[2] | 4285 | # number of records, sort field, and sort order
|
---|
| 4286 | # Returns a reference to an array of hashes
|
---|
[495] | 4287 | sub getRecList {
|
---|
[2] | 4288 | $errstr = '';
|
---|
[481] | 4289 | my $self = shift;
|
---|
| 4290 | my $dbh = $self->{dbh};
|
---|
[2] | 4291 |
|
---|
[397] | 4292 | my %args = @_;
|
---|
[4] | 4293 |
|
---|
[666] | 4294 | $args{revrec} = 'n' if !$args{revrec};
|
---|
| 4295 | $args{defrec} = 'n' if !$args{defrec};
|
---|
| 4296 |
|
---|
[716] | 4297 | # RPC callers generally want the "true" IP. Flag argument for those to bypass showrev_arpa
|
---|
| 4298 | ##fixme: this will still blow up if some idiot has actually stored .arpa names in the DB.
|
---|
| 4299 | # ... do we care?
|
---|
| 4300 | $args{rpc} = 0 if !$args{rpc};
|
---|
| 4301 |
|
---|
[397] | 4302 | # protection against bad or missing arguments
|
---|
[508] | 4303 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
[510] | 4304 | my $defsort;
|
---|
| 4305 | $defsort = 'host' if $args{revrec} eq 'n'; # default sort by host on domain record list
|
---|
| 4306 | $defsort = 'val' if $args{revrec} eq 'y'; # default sort by IP on revzone record list
|
---|
[513] | 4307 | $args{sortby} = '' if !$args{sortby};
|
---|
[508] | 4308 | $args{sortby} = $defsort if !$args{revrec};
|
---|
[512] | 4309 | $args{sortby} = $defsort if $args{sortby} !~ /^[\w_,.]+$/;
|
---|
[397] | 4310 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[517] | 4311 | my $perpage = ($args{nrecs} ? $args{nrecs} : $self->{perpage});
|
---|
[397] | 4312 |
|
---|
[543] | 4313 | ##fixme: do we need a knob to twist to switch from unix epoch to postgres time string?
|
---|
[666] | 4314 | my @bindvars;
|
---|
| 4315 | my $sql = "SELECT r.record_id,";
|
---|
| 4316 | # only include the parent info if we don't already know which parent we're in
|
---|
| 4317 | $sql .= "r.domain_id,r.rdns_id," unless $args{id};
|
---|
| 4318 | $sql .= "r.host,r.type,r.val,r.ttl";
|
---|
[543] | 4319 | $sql .= ",l.description AS locname,stamp,r.stamp < now() AS ispast,r.expires,r.stampactive"
|
---|
| 4320 | if $args{defrec} eq 'n';
|
---|
[397] | 4321 | $sql .= ",r.distance,r.weight,r.port" if $args{revrec} eq 'n';
|
---|
| 4322 | $sql .= " FROM "._rectable($args{defrec},$args{revrec})." r ";
|
---|
[104] | 4323 | $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
|
---|
[397] | 4324 | $sql .= "LEFT JOIN locations l ON r.location=l.location " if $args{defrec} eq 'n';
|
---|
[666] | 4325 | $sql .= "WHERE NOT r.type=$reverse_typemap{SOA}";
|
---|
| 4326 |
|
---|
| 4327 | # "normal" record list
|
---|
| 4328 | if ($args{id}) {
|
---|
| 4329 | $sql .= " AND "._recparent($args{defrec},$args{revrec})." = ?";
|
---|
| 4330 | push @bindvars, $args{id};
|
---|
| 4331 | }
|
---|
| 4332 |
|
---|
| 4333 | # Filtering on host/val (mainly normal record list)
|
---|
[614] | 4334 | if ($args{filter}) {
|
---|
| 4335 | $sql .= " AND (r.host ~* ? OR r.val ~* ? OR r.host ~* ? OR r.val ~* ?)";
|
---|
| 4336 | my $tmp = join('.',reverse(split(/\./,$args{filter})));
|
---|
[666] | 4337 | push @bindvars, ($args{filter},$args{filter});
|
---|
[614] | 4338 | push @bindvars, ($tmp, $tmp);
|
---|
| 4339 | }
|
---|
[666] | 4340 |
|
---|
| 4341 | # Filtering on other fields
|
---|
[715] | 4342 | foreach (qw(type distance weight port ttl description location)) {
|
---|
[666] | 4343 | if ($args{$_}) {
|
---|
[716] | 4344 | $sql .= " AND r.$_ ~* ?";
|
---|
[666] | 4345 | push @bindvars, $args{$_};
|
---|
| 4346 | }
|
---|
| 4347 | }
|
---|
| 4348 |
|
---|
| 4349 | # whee! multisort means just passing comma-separated fields in sortby!
|
---|
| 4350 | my $newsort = '';
|
---|
| 4351 | foreach my $sf (split /,/, $args{sortby}) {
|
---|
| 4352 | $sf = "r.$sf";
|
---|
| 4353 | # sort on IP, correctly
|
---|
| 4354 | $sf =~ s/r\.val/inetlazy(r.val)/;
|
---|
| 4355 | # hmm. do we really need to limit this?
|
---|
| 4356 | # if $args{revrec} eq 'y' && $args{defrec} eq 'n';
|
---|
| 4357 | $sf =~ s/r\.type/t.alphaorder/; # subtly different from sorting on rectypes.name
|
---|
| 4358 | $newsort .= ",$sf";
|
---|
| 4359 | }
|
---|
| 4360 | $newsort =~ s/^,//;
|
---|
| 4361 | ##enhance: pass in ascending/descending sort per-field
|
---|
[420] | 4362 | $sql .= " ORDER BY $newsort $args{sortorder}";
|
---|
[324] | 4363 | # ensure consistent ordering by sorting on record_id too
|
---|
[397] | 4364 | $sql .= ", record_id $args{sortorder}";
|
---|
[666] | 4365 |
|
---|
| 4366 | # Offset/pagination
|
---|
[501] | 4367 | $sql .= ($args{offset} eq 'all' ? '' : " LIMIT $perpage OFFSET ".$args{offset}*$perpage);
|
---|
[4] | 4368 |
|
---|
[583] | 4369 | my @working;
|
---|
| 4370 | my $recsth = $dbh->prepare($sql);
|
---|
| 4371 | $recsth->execute(@bindvars);
|
---|
| 4372 | while (my $rec = $recsth->fetchrow_hashref) {
|
---|
[716] | 4373 | if (!$args{rpc} && $args{revrec} eq 'y' && $args{defrec} eq 'n' &&
|
---|
[607] | 4374 | ($self->{showrev_arpa} eq 'record' || $self->{showrev_arpa} eq 'all') &&
|
---|
| 4375 | $rec->{val} !~ /\.arpa$/ ) {
|
---|
[608] | 4376 | # skip all reverse zone .arpa "hostnames" since they're already .arpa names.
|
---|
[583] | 4377 | ##enhance: extend {showrev_arpa} eq 'record' to specify record types
|
---|
[633] | 4378 | my $tmpip = new NetAddr::IP $rec->{val} if $rec->{val} =~ /^(?:[\d.\/]+|[a-fA-F0-9:\/]+)$/;
|
---|
[607] | 4379 | $rec->{val} = DNSDB::_ZONE($tmpip, 'ZONE', 'r', '.').($tmpip->{isv6} ? '.ip6.arpa' : '.in-addr.arpa') if $tmpip;
|
---|
[583] | 4380 | }
|
---|
| 4381 | push @working, $rec;
|
---|
| 4382 | }
|
---|
| 4383 | return \@working;
|
---|
[495] | 4384 | } # end getRecList()
|
---|
[2] | 4385 |
|
---|
| 4386 |
|
---|
[91] | 4387 | ## DNSDB::getRecCount()
|
---|
[224] | 4388 | # Return count of non-SOA records in zone (or default records in a group)
|
---|
| 4389 | # Takes a database handle, default/live flag, reverse/forward flag, group/domain ID,
|
---|
| 4390 | # and optional filtering modifier
|
---|
[91] | 4391 | # Returns the count
|
---|
| 4392 | sub getRecCount {
|
---|
[481] | 4393 | my $self = shift;
|
---|
| 4394 | my $dbh = $self->{dbh};
|
---|
[91] | 4395 |
|
---|
[666] | 4396 | my %args = @_;
|
---|
[135] | 4397 |
|
---|
[666] | 4398 | $args{defrec} = 'n' if !$args{defrec};
|
---|
| 4399 | $args{revrec} = 'n' if !$args{revrec};
|
---|
| 4400 |
|
---|
| 4401 | my @bindvars;
|
---|
[224] | 4402 | my $sql = "SELECT count(*) FROM ".
|
---|
[666] | 4403 | _rectable($args{defrec},$args{revrec}).
|
---|
[689] | 4404 | " r WHERE NOT type=$reverse_typemap{SOA}";
|
---|
[666] | 4405 | if ($args{id}) {
|
---|
| 4406 | $sql .= " AND "._recparent($args{defrec},$args{revrec})." = ?";
|
---|
| 4407 | push @bindvars, $args{id};
|
---|
| 4408 | }
|
---|
| 4409 |
|
---|
| 4410 | # Filtering on host/val (mainly normal record list)
|
---|
| 4411 | if ($args{filter}) {
|
---|
[614] | 4412 | $sql .= " AND (r.host ~* ? OR r.val ~* ? OR r.host ~* ? OR r.val ~* ?)";
|
---|
[666] | 4413 | my $tmp = join('.',reverse(split(/\./,$args{filter})));
|
---|
| 4414 | push @bindvars, ($args{filter},$args{filter});
|
---|
[614] | 4415 | push @bindvars, ($tmp, $tmp);
|
---|
| 4416 | }
|
---|
[584] | 4417 |
|
---|
[666] | 4418 | # Filtering on other fields
|
---|
| 4419 | foreach (qw(type distance weight port ttl description)) {
|
---|
| 4420 | if ($args{$_}) {
|
---|
| 4421 | $sql .= " AND $_ ~* ?";
|
---|
| 4422 | push @bindvars, $args{$_};
|
---|
| 4423 | }
|
---|
| 4424 | }
|
---|
| 4425 |
|
---|
[224] | 4426 | my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) );
|
---|
[91] | 4427 |
|
---|
| 4428 | return $count;
|
---|
| 4429 |
|
---|
| 4430 | } # end getRecCount()
|
---|
| 4431 |
|
---|
| 4432 |
|
---|
[3] | 4433 | ## DNSDB::addRec()
|
---|
[2] | 4434 | # Add a new record to a domain or a group's default records
|
---|
| 4435 | # Takes a database handle, default/live flag, group/domain ID,
|
---|
| 4436 | # host, type, value, and TTL
|
---|
| 4437 | # Some types require additional detail: "distance" for MX and SRV,
|
---|
| 4438 | # and weight/port for SRV
|
---|
| 4439 | # Returns a status code and detail message in case of error
|
---|
[234] | 4440 | ##fixme: pass a hash with the record data, not a series of separate values
|
---|
[2] | 4441 | sub addRec {
|
---|
| 4442 | $errstr = '';
|
---|
[481] | 4443 | my $self = shift;
|
---|
| 4444 | my $dbh = $self->{dbh};
|
---|
[2] | 4445 | my $defrec = shift;
|
---|
[226] | 4446 | my $revrec = shift;
|
---|
| 4447 | my $id = shift; # parent (group_id for defrecs, rdns_id for reverse records,
|
---|
| 4448 | # domain_id for domain records)
|
---|
[2] | 4449 |
|
---|
| 4450 | my $host = shift;
|
---|
[234] | 4451 | my $rectype = shift; # reference so we can coerce it if "+"-types can't find both zones
|
---|
[2] | 4452 | my $val = shift;
|
---|
| 4453 | my $ttl = shift;
|
---|
[389] | 4454 | my $location = shift;
|
---|
| 4455 | $location = '' if !$location;
|
---|
[2] | 4456 |
|
---|
[658] | 4457 | my $expires = shift || '';
|
---|
[543] | 4458 | $expires = 1 if $expires eq 'until'; # Turn some special values into the appropriate booleans.
|
---|
| 4459 | $expires = 0 if $expires eq 'after';
|
---|
| 4460 | my $stamp = shift;
|
---|
| 4461 | $stamp = '' if !$stamp; # Timestamp should be a string at this point.
|
---|
| 4462 |
|
---|
[674] | 4463 | # extra safety net - apparently RPC can squeak this by. O_o
|
---|
| 4464 | return ('FAIL', "host must contain a value") if !$$host;
|
---|
| 4465 | return ('FAIL', "val must contain a value") if !$$val;
|
---|
| 4466 |
|
---|
[417] | 4467 | # Spaces are evil.
|
---|
| 4468 | $$host =~ s/^\s+//;
|
---|
| 4469 | $$host =~ s/\s+$//;
|
---|
[418] | 4470 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
[417] | 4471 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 4472 | $$val =~ s/^\s+//;
|
---|
| 4473 | $$val =~ s/\s+$//;
|
---|
| 4474 | }
|
---|
| 4475 |
|
---|
[617] | 4476 | _caseclean($rectype, $host, $val, $defrec, $revrec) if $self->{lowercase};
|
---|
[542] | 4477 |
|
---|
[226] | 4478 | # prep for validation
|
---|
[609] | 4479 | my $addr = NetAddr::IP->new($$val) if _maybeip($val);
|
---|
[252] | 4480 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
[226] | 4481 |
|
---|
| 4482 | my $domid = 0;
|
---|
| 4483 | my $revid = 0;
|
---|
| 4484 |
|
---|
| 4485 | my $retcode = 'OK'; # assume everything will go OK
|
---|
| 4486 | my $retmsg = '';
|
---|
| 4487 |
|
---|
| 4488 | # do simple validation first
|
---|
[559] | 4489 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^-?\d+$/;
|
---|
[226] | 4490 |
|
---|
[234] | 4491 | # Collect these even if we're only doing a simple A record so we can call *any* validation sub
|
---|
| 4492 | my $dist = shift;
|
---|
[281] | 4493 | my $weight = shift;
|
---|
[234] | 4494 | my $port = shift;
|
---|
[226] | 4495 |
|
---|
[234] | 4496 | my $fields;
|
---|
| 4497 | my @vallist;
|
---|
[226] | 4498 |
|
---|
[234] | 4499 | # Call the validation sub for the type requested.
|
---|
[481] | 4500 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec, id => $id,
|
---|
[249] | 4501 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
[234] | 4502 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
[481] | 4503 | fields => \$fields, vallist => \@vallist);
|
---|
[129] | 4504 |
|
---|
[234] | 4505 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
[209] | 4506 |
|
---|
[234] | 4507 | # Set up database fields and bind parameters
|
---|
[481] | 4508 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
| 4509 | push @vallist, ($$host,$$rectype,$$val,$ttl,$id);
|
---|
| 4510 |
|
---|
| 4511 | if ($defrec eq 'n') {
|
---|
[543] | 4512 | # locations are not for default records, silly coder!
|
---|
[481] | 4513 | $fields .= ",location";
|
---|
| 4514 | push @vallist, $location;
|
---|
[543] | 4515 | # timestamps are rare.
|
---|
| 4516 | if ($stamp) {
|
---|
| 4517 | $fields .= ",stamp,expires,stampactive";
|
---|
| 4518 | push @vallist, $stamp, $expires, 'y';
|
---|
| 4519 | } else {
|
---|
| 4520 | $fields .= ",stampactive";
|
---|
| 4521 | push @vallist, 'n';
|
---|
| 4522 | }
|
---|
[481] | 4523 | }
|
---|
[543] | 4524 |
|
---|
| 4525 | # a little magic to get the right number of ? placeholders based on how many values we're providing
|
---|
[234] | 4526 | my $vallen = '?'.(',?'x$#vallist);
|
---|
[2] | 4527 |
|
---|
[287] | 4528 | # Put together the success log entry. We have to use this horrible kludge
|
---|
| 4529 | # because domain_id and rdns_id may or may not be present, and if they are,
|
---|
| 4530 | # they're not at a guaranteed consistent index in the array. wheee!
|
---|
| 4531 | my %logdata;
|
---|
| 4532 | my @ftmp = split /,/, $fields;
|
---|
| 4533 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
| 4534 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
| 4535 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
| 4536 | }
|
---|
| 4537 | $logdata{group_id} = $id if $defrec eq 'y';
|
---|
[473] | 4538 | $logdata{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec)
|
---|
[287] | 4539 | if $defrec eq 'n';
|
---|
[328] | 4540 | $logdata{entry} = "Added ".($defrec eq 'y' ? 'default record' : 'record');
|
---|
[621] | 4541 | # Log reverse records to match the formal .arpa tree
|
---|
| 4542 | if ($revrec eq 'y') {
|
---|
[328] | 4543 | $logdata{entry} .= " '$$val $typemap{$$rectype} $$host";
|
---|
| 4544 | } else {
|
---|
| 4545 | $logdata{entry} .= " '$$host $typemap{$$rectype} $$val";
|
---|
| 4546 | }
|
---|
| 4547 |
|
---|
[287] | 4548 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
| 4549 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]"
|
---|
| 4550 | if $typemap{$$rectype} eq 'SRV';
|
---|
[425] | 4551 | $logdata{entry} .= "', TTL $ttl";
|
---|
[480] | 4552 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location;
|
---|
[642] | 4553 | $logdata{entry} .= ($expires ? ', expires at ' : ', valid after ').$stamp if $stamp;
|
---|
[287] | 4554 |
|
---|
[90] | 4555 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4556 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4557 | local $dbh->{AutoCommit} = 0;
|
---|
| 4558 | local $dbh->{RaiseError} = 1;
|
---|
[2] | 4559 |
|
---|
[90] | 4560 | eval {
|
---|
[236] | 4561 | $dbh->do("INSERT INTO "._rectable($defrec, $revrec)." ($fields) VALUES ($vallen)",
|
---|
[90] | 4562 | undef, @vallist);
|
---|
[487] | 4563 | $self->_log(%logdata);
|
---|
[90] | 4564 | $dbh->commit;
|
---|
| 4565 | };
|
---|
| 4566 | if ($@) {
|
---|
| 4567 | my $msg = $@;
|
---|
| 4568 | eval { $dbh->rollback; };
|
---|
[517] | 4569 | if ($self->{log_failures}) {
|
---|
[289] | 4570 | $logdata{entry} = "Failed adding ".($defrec eq 'y' ? 'default ' : '').
|
---|
| 4571 | "record '$$host $typemap{$$rectype} $$val', TTL $ttl ($msg)";
|
---|
[487] | 4572 | $self->_log(%logdata);
|
---|
[289] | 4573 | $dbh->commit;
|
---|
| 4574 | }
|
---|
[90] | 4575 | return ('FAIL',$msg);
|
---|
| 4576 | }
|
---|
[2] | 4577 |
|
---|
[287] | 4578 | $resultstr = $logdata{entry};
|
---|
[226] | 4579 | return ($retcode, $retmsg);
|
---|
[90] | 4580 |
|
---|
[2] | 4581 | } # end addRec()
|
---|
| 4582 |
|
---|
| 4583 |
|
---|
[16] | 4584 | ## DNSDB::updateRec()
|
---|
| 4585 | # Update a record
|
---|
[273] | 4586 | # Takes a database handle, default and reverse flags, record ID, immediate parent ID, and new record data.
|
---|
| 4587 | # Returns a status code and message
|
---|
[16] | 4588 | sub updateRec {
|
---|
| 4589 | $errstr = '';
|
---|
[17] | 4590 |
|
---|
[481] | 4591 | my $self = shift;
|
---|
| 4592 | my $dbh = $self->{dbh};
|
---|
[679] | 4593 |
|
---|
[16] | 4594 | my $defrec = shift;
|
---|
[272] | 4595 | my $revrec = shift;
|
---|
[16] | 4596 | my $id = shift;
|
---|
[272] | 4597 | my $parid = shift; # immediate parent entity that we're descending from to update the record
|
---|
[16] | 4598 |
|
---|
[273] | 4599 | # all records have these
|
---|
[16] | 4600 | my $host = shift;
|
---|
[272] | 4601 | my $hostbk = $$host; # Keep a backup copy of the original, so we can WARN if the update mangles the domain
|
---|
| 4602 | my $rectype = shift;
|
---|
[16] | 4603 | my $val = shift;
|
---|
| 4604 | my $ttl = shift;
|
---|
[389] | 4605 | my $location = shift; # may be empty/null/undef depending on caller
|
---|
| 4606 | $location = '' if !$location;
|
---|
[16] | 4607 |
|
---|
[658] | 4608 | my $expires = shift || '';
|
---|
[543] | 4609 | $expires = 1 if $expires eq 'until'; # Turn some special values into the appropriate booleans.
|
---|
| 4610 | $expires = 0 if $expires eq 'after';
|
---|
| 4611 | my $stamp = shift;
|
---|
| 4612 | $stamp = '' if !$stamp; # Timestamp should be a string at this point.
|
---|
| 4613 |
|
---|
[510] | 4614 | # just set it to an empty string; failures will be caught later.
|
---|
| 4615 | $$host = '' if !$$host;
|
---|
| 4616 |
|
---|
[417] | 4617 | # Spaces are evil.
|
---|
| 4618 | $$host =~ s/^\s+//;
|
---|
| 4619 | $$host =~ s/\s+$//;
|
---|
[418] | 4620 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
[417] | 4621 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 4622 | $$val =~ s/^\s+//;
|
---|
| 4623 | $$val =~ s/\s+$//;
|
---|
| 4624 | }
|
---|
| 4625 |
|
---|
[617] | 4626 | _caseclean($rectype, $host, $val, $defrec, $revrec) if $self->{lowercase};
|
---|
[542] | 4627 |
|
---|
[272] | 4628 | # prep for validation
|
---|
[609] | 4629 | my $addr = NetAddr::IP->new($$val) if _maybeip($val);
|
---|
[272] | 4630 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
[16] | 4631 |
|
---|
[272] | 4632 | my $domid = 0;
|
---|
| 4633 | my $revid = 0;
|
---|
| 4634 |
|
---|
| 4635 | my $retcode = 'OK'; # assume everything will go OK
|
---|
| 4636 | my $retmsg = '';
|
---|
| 4637 |
|
---|
[273] | 4638 | # do simple validation first
|
---|
[559] | 4639 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^-?\d+$/;
|
---|
[272] | 4640 |
|
---|
[273] | 4641 | # only MX and SRV will use these
|
---|
[288] | 4642 | my $dist = shift || 0;
|
---|
| 4643 | my $weight = shift || 0;
|
---|
| 4644 | my $port = shift || 0;
|
---|
[16] | 4645 |
|
---|
[272] | 4646 | my $fields;
|
---|
| 4647 | my @vallist;
|
---|
[16] | 4648 |
|
---|
[273] | 4649 | # get old record data so we have the right parent ID
|
---|
| 4650 | # and for logging (eventually)
|
---|
[481] | 4651 | my $oldrec = $self->getRecLine($defrec, $revrec, $id);
|
---|
[223] | 4652 |
|
---|
[272] | 4653 | # Call the validation sub for the type requested.
|
---|
| 4654 | # Note the ID to pass here is the *parent*, not the record
|
---|
[481] | 4655 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec,
|
---|
[272] | 4656 | id => ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})),
|
---|
| 4657 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
| 4658 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
| 4659 | fields => \$fields, vallist => \@vallist,
|
---|
[481] | 4660 | update => $id);
|
---|
[272] | 4661 |
|
---|
| 4662 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
| 4663 |
|
---|
[273] | 4664 | # Set up database fields and bind parameters. Note only the optional fields
|
---|
| 4665 | # (distance, weight, port, secondary parent ID) are added in the validation call above
|
---|
[448] | 4666 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
| 4667 | push @vallist, ($$host,$$rectype,$$val,$ttl,
|
---|
[273] | 4668 | ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})) );
|
---|
[272] | 4669 |
|
---|
[448] | 4670 | if ($defrec eq 'n') {
|
---|
[543] | 4671 | # locations are not for default records, silly coder!
|
---|
[448] | 4672 | $fields .= ",location";
|
---|
| 4673 | push @vallist, $location;
|
---|
[543] | 4674 | # timestamps are rare.
|
---|
| 4675 | if ($stamp) {
|
---|
| 4676 | $fields .= ",stamp,expires,stampactive";
|
---|
| 4677 | push @vallist, $stamp, $expires, 'y';
|
---|
| 4678 | } else {
|
---|
| 4679 | $fields .= ",stampactive";
|
---|
| 4680 | push @vallist, 'n';
|
---|
| 4681 | }
|
---|
[448] | 4682 | }
|
---|
| 4683 |
|
---|
[273] | 4684 | # hack hack PTHUI
|
---|
| 4685 | # need to forcibly make sure we disassociate a record with a parent it's no longer related to.
|
---|
| 4686 | # eg, PTR records may not have a domain parent, or A/AAAA records may not have a revzone parent.
|
---|
[605] | 4687 | # needed for crossover types that got coerced down to "standard" types due to data changes
|
---|
| 4688 | # need to *avoid* funky records being updated like A/AAAA records in revzones, or PTRs in forward zones.
|
---|
| 4689 | if ($defrec eq 'n' && $oldrec->{type} > 65000) {
|
---|
[273] | 4690 | if ($$rectype == $reverse_typemap{PTR}) {
|
---|
| 4691 | $fields .= ",domain_id";
|
---|
| 4692 | push @vallist, 0;
|
---|
| 4693 | }
|
---|
| 4694 | if ($$rectype == $reverse_typemap{A} || $$rectype == $reverse_typemap{AAAA}) {
|
---|
| 4695 | $fields .= ",rdns_id";
|
---|
| 4696 | push @vallist, 0;
|
---|
| 4697 | }
|
---|
| 4698 | }
|
---|
[345] | 4699 | # fix fat-finger-originated record type changes
|
---|
[605] | 4700 | if ($$rectype == 65285) { # delegation
|
---|
[345] | 4701 | $fields .= ",rdns_id" if $revrec eq 'n';
|
---|
| 4702 | $fields .= ",domain_id" if $revrec eq 'y';
|
---|
| 4703 | push @vallist, 0;
|
---|
| 4704 | }
|
---|
[605] | 4705 | # ... and now make sure we *do* associate a record with the "calling" parent
|
---|
[341] | 4706 | if ($defrec eq 'n') {
|
---|
| 4707 | $domid = $parid if $revrec eq 'n';
|
---|
| 4708 | $revid = $parid if $revrec eq 'y';
|
---|
| 4709 | }
|
---|
[272] | 4710 |
|
---|
[288] | 4711 | # Put together the success log entry. Horrible kludge from addRec() copied as-is since
|
---|
| 4712 | # we don't know whether the passed arguments or retrieved values for domain_id and rdns_id
|
---|
| 4713 | # will be maintained (due to "not-in-zone" validation changes)
|
---|
| 4714 | my %logdata;
|
---|
[341] | 4715 | $logdata{domain_id} = $domid;
|
---|
| 4716 | $logdata{rdns_id} = $revid;
|
---|
[288] | 4717 | my @ftmp = split /,/, $fields;
|
---|
| 4718 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
| 4719 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
| 4720 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
| 4721 | }
|
---|
| 4722 | $logdata{group_id} = $parid if $defrec eq 'y';
|
---|
[473] | 4723 | $logdata{group_id} = $self->parentID(id => $parid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec)
|
---|
[288] | 4724 | if $defrec eq 'n';
|
---|
[328] | 4725 | $logdata{entry} = "Updated ".($defrec eq 'y' ? 'default record' : 'record')." from\n";
|
---|
[621] | 4726 | # Log reverse records "naturally", since they're stored, um, unnaturally.
|
---|
| 4727 | if ($revrec eq 'y') {
|
---|
[328] | 4728 | $logdata{entry} .= " '$oldrec->{val} $typemap{$oldrec->{type}} $oldrec->{host}";
|
---|
| 4729 | } else {
|
---|
| 4730 | $logdata{entry} .= " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
| 4731 | }
|
---|
[288] | 4732 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
| 4733 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
| 4734 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
[425] | 4735 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
[480] | 4736 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location};
|
---|
[543] | 4737 | $logdata{entry} .= ($oldrec->{expires} ? ', expires at ' : ', valid after ').$oldrec->{stamp}
|
---|
| 4738 | if $oldrec->{stampactive};
|
---|
[425] | 4739 | $logdata{entry} .= "\nto\n";
|
---|
[621] | 4740 | # Log reverse records "naturally", since they're stored, um, unnaturally.
|
---|
| 4741 | if ($revrec eq 'y') {
|
---|
[328] | 4742 | $logdata{entry} .= "'$$val $typemap{$$rectype} $$host";
|
---|
| 4743 | } else {
|
---|
| 4744 | $logdata{entry} .= "'$$host $typemap{$$rectype} $$val";
|
---|
| 4745 | }
|
---|
[288] | 4746 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
| 4747 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$$rectype} eq 'SRV';
|
---|
[425] | 4748 | $logdata{entry} .= "', TTL $ttl";
|
---|
[480] | 4749 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location;
|
---|
[642] | 4750 | $logdata{entry} .= ($expires ? ', expires at ' : ', valid after ').$stamp if $stamp;
|
---|
[288] | 4751 |
|
---|
[90] | 4752 | local $dbh->{AutoCommit} = 0;
|
---|
| 4753 | local $dbh->{RaiseError} = 1;
|
---|
| 4754 |
|
---|
[341] | 4755 | # Fiddle the field list into something suitable for updates
|
---|
| 4756 | $fields =~ s/,/=?,/g;
|
---|
| 4757 | $fields .= "=?";
|
---|
| 4758 |
|
---|
[90] | 4759 | eval {
|
---|
[273] | 4760 | $dbh->do("UPDATE "._rectable($defrec,$revrec)." SET $fields WHERE record_id=?", undef, (@vallist, $id) );
|
---|
[487] | 4761 | $self->_log(%logdata);
|
---|
[130] | 4762 | $dbh->commit;
|
---|
[90] | 4763 | };
|
---|
| 4764 | if ($@) {
|
---|
| 4765 | my $msg = $@;
|
---|
[288] | 4766 | eval { $dbh->rollback; };
|
---|
[517] | 4767 | if ($self->{log_failures}) {
|
---|
[289] | 4768 | $logdata{entry} = "Failed updating ".($defrec eq 'y' ? 'default ' : '').
|
---|
| 4769 | "record '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
[487] | 4770 | $self->_log(%logdata);
|
---|
[289] | 4771 | $dbh->commit;
|
---|
| 4772 | }
|
---|
[90] | 4773 | return ('FAIL', $msg);
|
---|
| 4774 | }
|
---|
| 4775 |
|
---|
[288] | 4776 | $resultstr = $logdata{entry};
|
---|
[272] | 4777 | return ($retcode, $retmsg);
|
---|
[16] | 4778 | } # end updateRec()
|
---|
| 4779 |
|
---|
| 4780 |
|
---|
[459] | 4781 | ## DNSDB::downconvert()
|
---|
| 4782 | # A mostly internal (not exported) semiutilty sub to downconvert from pseudotype <x>
|
---|
| 4783 | # to a compatible component type. Only a handful of operations are valid, anything
|
---|
| 4784 | # else is a null-op.
|
---|
| 4785 | # Takes the record ID and the new type. Returns boolean.
|
---|
| 4786 | sub downconvert {
|
---|
[481] | 4787 | my $self = shift;
|
---|
| 4788 | my $dbh = $self->{dbh};
|
---|
[459] | 4789 | my $recid = shift;
|
---|
| 4790 | my $newtype = shift;
|
---|
| 4791 |
|
---|
| 4792 | # also, only work on live records; little to no value trying to do this on default records.
|
---|
[481] | 4793 | my $rec = $self->getRecLine('n', 'y', $recid);
|
---|
[459] | 4794 |
|
---|
| 4795 | # hm?
|
---|
| 4796 | #return 1 if !$rec;
|
---|
| 4797 |
|
---|
| 4798 | return 1 if $rec->{type} < 65000; # Only the reverse-record pseudotypes can be downconverted
|
---|
| 4799 | return 1 if $rec->{type} == 65282; # Nowhere to go
|
---|
| 4800 |
|
---|
| 4801 | my $delpar;
|
---|
| 4802 | my @sqlargs;
|
---|
| 4803 | if ($rec->{type} == 65280) {
|
---|
| 4804 | return 1 if $newtype != 1 && $newtype != 12;
|
---|
| 4805 | $delpar = ($newtype == 1 ? 'rdns_id' : 'domain_id');
|
---|
| 4806 | push @sqlargs, 0, $newtype, $recid;
|
---|
| 4807 | } elsif ($rec->{type} == 65281) {
|
---|
| 4808 | return 1 if $newtype != 28 && $newtype != 12;
|
---|
| 4809 | $delpar = ($newtype == 28 ? 'rdns_id' : 'domain_id');
|
---|
| 4810 | push @sqlargs, 0, $newtype, $recid;
|
---|
| 4811 | } elsif ($rec->{type} == 65283) {
|
---|
| 4812 | return 1 if $newtype != 65282;
|
---|
| 4813 | $delpar = 'rdns_id';
|
---|
| 4814 | } elsif ($rec->{type} == 65284) {
|
---|
| 4815 | return 1 if $newtype != 65282;
|
---|
| 4816 | $delpar = 'rdns_id';
|
---|
| 4817 | } else {
|
---|
| 4818 | # Your llama is on fire.
|
---|
| 4819 | }
|
---|
| 4820 |
|
---|
| 4821 | local $dbh->{AutoCommit} = 0;
|
---|
| 4822 | local $dbh->{RaiseError} = 1;
|
---|
| 4823 |
|
---|
| 4824 | eval {
|
---|
| 4825 | $dbh->do("UPDATE records SET $delpar = ?, type = ? WHERE record_id = ?", undef, @sqlargs);
|
---|
[665] | 4826 | $self->_log(domain_id => $rec->{domain_id}, rdns_id => $rec->{rdns_id},
|
---|
| 4827 | group_id => $self->parentID(id => $rec->{rdns_id}, type => 'revzone', revrec => 'y'),
|
---|
| 4828 | entry => "'$rec->{host} $typemap{$rec->{type}} $rec->{val}' downconverted to ".
|
---|
| 4829 | "'$rec->{host} $typemap{$newtype} $rec->{val}'");
|
---|
[459] | 4830 | $dbh->commit;
|
---|
| 4831 | };
|
---|
| 4832 | if ($@) {
|
---|
| 4833 | $errstr = $@;
|
---|
| 4834 | eval { $dbh->rollback; };
|
---|
| 4835 | return 0;
|
---|
| 4836 | }
|
---|
| 4837 | return 1;
|
---|
| 4838 | } # end downconvert()
|
---|
| 4839 |
|
---|
| 4840 |
|
---|
[3] | 4841 | ## DNSDB::delRec()
|
---|
| 4842 | # Delete a record.
|
---|
[667] | 4843 | # Takes a default/live flag, forward/reverse flag, and the ID of the record to delete.
|
---|
[3] | 4844 | sub delRec {
|
---|
| 4845 | $errstr = '';
|
---|
[481] | 4846 | my $self = shift;
|
---|
| 4847 | my $dbh = $self->{dbh};
|
---|
[3] | 4848 | my $defrec = shift;
|
---|
[243] | 4849 | my $revrec = shift;
|
---|
[3] | 4850 | my $id = shift;
|
---|
| 4851 |
|
---|
[481] | 4852 | my $oldrec = $self->getRecLine($defrec, $revrec, $id);
|
---|
[3] | 4853 |
|
---|
[290] | 4854 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4855 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4856 | local $dbh->{AutoCommit} = 0;
|
---|
| 4857 | local $dbh->{RaiseError} = 1;
|
---|
[3] | 4858 |
|
---|
[290] | 4859 | # Put together the log entry
|
---|
| 4860 | my %logdata;
|
---|
| 4861 | $logdata{domain_id} = $oldrec->{domain_id};
|
---|
| 4862 | $logdata{rdns_id} = $oldrec->{rdns_id};
|
---|
| 4863 | $logdata{group_id} = $oldrec->{group_id} if $defrec eq 'y';
|
---|
[667] | 4864 | $logdata{group_id} = $self->parentID(id => ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id}),
|
---|
| 4865 | type => 'domain', revrec => $revrec)
|
---|
[290] | 4866 | if $defrec eq 'n';
|
---|
| 4867 | $logdata{entry} = "Deleted ".($defrec eq 'y' ? 'default record ' : 'record ').
|
---|
| 4868 | "'$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
| 4869 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
| 4870 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
| 4871 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
[425] | 4872 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
[480] | 4873 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location};
|
---|
[290] | 4874 |
|
---|
| 4875 | eval {
|
---|
| 4876 | my $sth = $dbh->do("DELETE FROM "._rectable($defrec,$revrec)." WHERE record_id=?", undef, ($id));
|
---|
[487] | 4877 | $self->_log(%logdata);
|
---|
[290] | 4878 | $dbh->commit;
|
---|
| 4879 | };
|
---|
| 4880 | if ($@) {
|
---|
| 4881 | my $msg = $@;
|
---|
| 4882 | eval { $dbh->rollback; };
|
---|
[517] | 4883 | if ($self->{log_failures}) {
|
---|
[290] | 4884 | $logdata{entry} = "Error deleting ".($defrec eq 'y' ? 'default record' : 'record').
|
---|
| 4885 | " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
[487] | 4886 | $self->_log(%logdata);
|
---|
[290] | 4887 | $dbh->commit;
|
---|
| 4888 | }
|
---|
| 4889 | return ('FAIL', $msg);
|
---|
| 4890 | }
|
---|
| 4891 |
|
---|
| 4892 | return ('OK',$logdata{entry});
|
---|
[3] | 4893 | } # end delRec()
|
---|
| 4894 |
|
---|
| 4895 |
|
---|
[323] | 4896 | ## DNSDB::getLogCount()
|
---|
| 4897 | # Get a count of log entries
|
---|
| 4898 | # Takes a database handle and a hash containing at least:
|
---|
[733] | 4899 | # - Entity identifier and entity type as the primary log "slice"
|
---|
[323] | 4900 | sub getLogCount {
|
---|
[483] | 4901 | my $self = shift;
|
---|
[733] | 4902 | return $self->getLogEntries(@_, count => 1);
|
---|
[323] | 4903 | } # end getLogCount()
|
---|
| 4904 |
|
---|
| 4905 |
|
---|
| 4906 | ## DNSDB::getLogEntries()
|
---|
| 4907 | # Get a list of log entries
|
---|
| 4908 | # Takes arguments as with getLogCount() above, plus optional:
|
---|
[733] | 4909 | # - "count" flag
|
---|
| 4910 | # OR
|
---|
[323] | 4911 | # - sort field
|
---|
| 4912 | # - sort order
|
---|
| 4913 | # - offset for pagination
|
---|
| 4914 | sub getLogEntries {
|
---|
[483] | 4915 | my $self = shift;
|
---|
| 4916 | my $dbh = $self->{dbh};
|
---|
[323] | 4917 |
|
---|
| 4918 | my %args = @_;
|
---|
| 4919 |
|
---|
| 4920 | my @filterargs;
|
---|
| 4921 |
|
---|
[733] | 4922 | # fail if the prime id type is missing or invalid
|
---|
| 4923 | $errstr = "Missing primary log slice type";
|
---|
[323] | 4924 | return if !$args{logtype};
|
---|
| 4925 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
| 4926 | $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
|
---|
[733] | 4927 | $errstr = "Invalid primary log slice type";
|
---|
[323] | 4928 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
|
---|
| 4929 |
|
---|
[733] | 4930 | # fail if we don't have a prime ID to look for log entries for
|
---|
| 4931 | $errstr = "Missing ID for primary log slice";
|
---|
| 4932 | return if !($args{id} || $args{fname});
|
---|
| 4933 |
|
---|
[323] | 4934 | # Sorting defaults
|
---|
[508] | 4935 | $args{sortorder} = 'DESC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
| 4936 | $args{sortby} = 'stamp' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
[397] | 4937 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[323] | 4938 |
|
---|
[733] | 4939 | my %sortmap = (fname => 'name', username => 'email', entry => 'entry', stamp => 'stamp',
|
---|
| 4940 | revzone => 'revnet', domain => 'domain');
|
---|
[323] | 4941 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 4942 |
|
---|
[733] | 4943 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 4944 | my $sql;
|
---|
| 4945 | if ($args{count}) {
|
---|
| 4946 | $sql = "SELECT count(*) FROM log l ";
|
---|
| 4947 | } else {
|
---|
[744] | 4948 | $sql = "SELECT l.log_id AS logparent, l.user_id AS userid, l.name AS userfname, d.domain, l.domain_id, ".
|
---|
| 4949 | "r.revnet AS revzone, ".
|
---|
[733] | 4950 | "l.rdns_id, l.entry AS logentry, date_trunc('second',l.stamp) AS logtime ".
|
---|
| 4951 | "FROM log l ".
|
---|
| 4952 | "LEFT JOIN domains d ON l.domain_id = d.domain_id ".
|
---|
| 4953 | "LEFT JOIN revzones r ON l.rdns_id = r.rdns_id ";
|
---|
| 4954 | }
|
---|
| 4955 |
|
---|
| 4956 | # decide which ID argument to use. Only use the "full name" if no normal ID is present
|
---|
| 4957 | my $idarg;
|
---|
| 4958 | if ($args{id}) {
|
---|
| 4959 | $sql .= "WHERE l.$id_col{$args{logtype}} = ? ";
|
---|
| 4960 | $idarg = $args{id};
|
---|
| 4961 | } else {
|
---|
| 4962 | $sql .= "WHERE l.name = ? ";
|
---|
| 4963 | $idarg = $args{fname};
|
---|
| 4964 | }
|
---|
| 4965 |
|
---|
[744] | 4966 | # trim log "subentries" - we'll figure out where to stash these later
|
---|
| 4967 | $sql .= " AND logparent = 0";
|
---|
| 4968 |
|
---|
[733] | 4969 | # add the entry filter, if any
|
---|
| 4970 | $sql .= ($args{filter} ? " AND entry ~* ?" : '');
|
---|
| 4971 |
|
---|
| 4972 | # Limit scope based on group. Mainly useful for ltype==user, so subgroup
|
---|
| 4973 | # users can see what the deities in parent groups have done to their domains.
|
---|
| 4974 | if ($args{group} != 1) {
|
---|
| 4975 | my @grouplist;
|
---|
| 4976 | $self->getChildren($args{group}, \@grouplist);
|
---|
| 4977 | my $groupset = join(',', $args{group}, @grouplist);
|
---|
| 4978 | $sql .= " AND l.group_id IN ($groupset)";
|
---|
| 4979 | }
|
---|
| 4980 |
|
---|
| 4981 | if ($args{count}) {
|
---|
| 4982 | my ($count) = $dbh->selectrow_array($sql, undef, ($idarg, @filterargs) );
|
---|
| 4983 | $errstr = $dbh->errstr if !$count;
|
---|
| 4984 | return $count;
|
---|
| 4985 | } else {
|
---|
| 4986 | $sql .= " ORDER BY $args{sortby} $args{sortorder}, log_id $args{sortorder}".
|
---|
[517] | 4987 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
[744] | 4988 | my @loglist;
|
---|
| 4989 | my $sth = $dbh->prepare($sql);
|
---|
| 4990 | my $logchild = $dbh->prepare("SELECT entry FROM log WHERE logparent = ? ORDER BY log_id");
|
---|
| 4991 | $sth->execute($idarg, @filterargs);
|
---|
| 4992 | while (my $row = $sth->fetchrow_hashref) {
|
---|
| 4993 | $logchild->execute($row->{logparent});
|
---|
| 4994 | my $childlist = $logchild->fetchall_arrayref({});
|
---|
| 4995 | $row->{childentries} = $childlist;
|
---|
| 4996 | push @loglist, $row;
|
---|
| 4997 | }
|
---|
| 4998 | return \@loglist;
|
---|
[733] | 4999 | }
|
---|
| 5000 |
|
---|
| 5001 | # Your llama is on fire
|
---|
| 5002 |
|
---|
[323] | 5003 | } # end getLogEntries()
|
---|
| 5004 |
|
---|
| 5005 |
|
---|
[723] | 5006 | # a collection of joins for the record search
|
---|
| 5007 | our $recsearchsqlbase = q(
|
---|
[722] | 5008 | FROM records r
|
---|
| 5009 | LEFT JOIN domains d ON r.domain_id = d.domain_id
|
---|
| 5010 | LEFT JOIN groups g1 ON d.group_id = g1.group_id
|
---|
| 5011 | LEFT JOIN revzones z ON r.rdns_id = z.rdns_id
|
---|
| 5012 | LEFT JOIN groups g2 on z.group_id = g2.group_id
|
---|
| 5013 | JOIN rectypes t ON r.type = t.val
|
---|
| 5014 | LEFT JOIN locations l ON r.location = l.location
|
---|
| 5015 | WHERE r.type <> 6 AND (r.host ~* ? OR r.val ~* ?)
|
---|
| 5016 | );
|
---|
| 5017 |
|
---|
[723] | 5018 |
|
---|
| 5019 | ## DNSDB::recSearchCount()
|
---|
| 5020 | # Get a total count for a global record search
|
---|
| 5021 | # Takes a hash with the search string and the login group of the user
|
---|
| 5022 | sub recSearchCount {
|
---|
| 5023 | my $self = shift;
|
---|
| 5024 | my $dbh = $self->{dbh};
|
---|
| 5025 | my %args = @_;
|
---|
| 5026 |
|
---|
| 5027 | my $sql = "SELECT count(*)".$recsearchsqlbase;
|
---|
| 5028 |
|
---|
| 5029 | # Limit scope based on group
|
---|
| 5030 | if ($args{group} != 1) {
|
---|
| 5031 | my @grouplist;
|
---|
| 5032 | $self->getChildren($args{group}, \@grouplist);
|
---|
| 5033 | my $groupset = join(',', $args{group}, @grouplist);
|
---|
| 5034 | # oh my aching HEAD. there has to be a better way to do conditions on joined tables...
|
---|
| 5035 | $sql .= "AND (
|
---|
| 5036 | (g1.group_id IN ($groupset) AND g2.group_id IN ($groupset)) OR
|
---|
| 5037 | (g1.group_id IN ($groupset) AND g2.group_id IS NULL) OR
|
---|
| 5038 | (g1.group_id IS NULL AND g2.group_id IN ($groupset))
|
---|
| 5039 | )
|
---|
[722] | 5040 | ";
|
---|
[723] | 5041 | }
|
---|
[722] | 5042 |
|
---|
[723] | 5043 | my $count = $dbh->selectrow_array($sql, undef, $args{searchfor}, $args{searchfor});
|
---|
| 5044 | $errstr = $dbh->errstr if !$count;
|
---|
| 5045 | return $count;
|
---|
[722] | 5046 |
|
---|
[723] | 5047 | } # end recSearchCount()
|
---|
[722] | 5048 |
|
---|
| 5049 |
|
---|
[723] | 5050 | ## DNSDB::recSearch()
|
---|
| 5051 | # Find records matching the search string
|
---|
| 5052 | # Takes a hash with the search string, login group of the user, pagination offset, sort field,
|
---|
| 5053 | # and sort direction
|
---|
| 5054 | # Returns a reference to a list of hashrefs
|
---|
| 5055 | sub recSearch {
|
---|
| 5056 | my $self = shift;
|
---|
| 5057 | my $dbh = $self->{dbh};
|
---|
| 5058 | my %args = @_;
|
---|
| 5059 |
|
---|
| 5060 | my $sql = q(SELECT
|
---|
| 5061 | r.domain_id, d.domain, g1.group_name AS domgroup,
|
---|
| 5062 | r.rdns_id, z.revnet AS revzone, g2.group_name AS revgroup,
|
---|
| 5063 | r.host, t.name AS rectype, r.val, l.description AS location, r.record_id).
|
---|
| 5064 | $recsearchsqlbase;
|
---|
| 5065 |
|
---|
| 5066 | # Limit scope based on group
|
---|
| 5067 | if ($args{group} != 1) {
|
---|
| 5068 | my @grouplist;
|
---|
| 5069 | $self->getChildren($args{group}, \@grouplist);
|
---|
| 5070 | my $groupset = join(',', $args{group}, @grouplist);
|
---|
| 5071 | # oh my aching HEAD. there has to be a better way to do conditions on joined tables...
|
---|
| 5072 | $sql .= "AND (
|
---|
| 5073 | (g1.group_id IN ($groupset) AND g2.group_id IN ($groupset)) OR
|
---|
| 5074 | (g1.group_id IN ($groupset) AND g2.group_id IS NULL) OR
|
---|
| 5075 | (g1.group_id IS NULL AND g2.group_id IN ($groupset))
|
---|
| 5076 | )
|
---|
| 5077 | ";
|
---|
| 5078 | }
|
---|
| 5079 |
|
---|
| 5080 | # mixed tables means this isn't a simple prefix like the regular record list filter. :/
|
---|
| 5081 | my %sortmap = (
|
---|
| 5082 | domain => 'd.domain',
|
---|
| 5083 | revzone => 'z.revnet',
|
---|
| 5084 | host => 'r.host',
|
---|
| 5085 | type => 't.name',
|
---|
| 5086 | val => 'inetlazy(r.val)',
|
---|
| 5087 | location => 'r.location',
|
---|
| 5088 | );
|
---|
| 5089 |
|
---|
| 5090 | # Sorting defaults
|
---|
| 5091 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
| 5092 | $args{sortby} = 'r.host' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
| 5093 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
| 5094 |
|
---|
| 5095 | $args{sortby} = $sortmap{$args{sortby}} if $args{sortby} !~ /\./;
|
---|
| 5096 |
|
---|
| 5097 | # Add sort and offset to SQL
|
---|
| 5098 | $sql .= "ORDER BY $args{sortby} $args{sortorder},record_id ASC\n";
|
---|
| 5099 | $sql .= ($args{offset} eq 'all' ? '' : "LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
| 5100 |
|
---|
| 5101 | ##fixme: should probably sent the warning somewhere else
|
---|
[747] | 5102 | my $ret = $dbh->selectall_arrayref($sql, { Slice => {} }, $args{searchfor}, $args{searchfor})
|
---|
[723] | 5103 | or warn $dbh->errstr;
|
---|
[747] | 5104 | return $ret;
|
---|
[723] | 5105 |
|
---|
[722] | 5106 | } # end recSearch()
|
---|
| 5107 |
|
---|
| 5108 |
|
---|
[673] | 5109 | ## DNSDB::getRevPattern()
|
---|
[452] | 5110 | # Get the narrowest template pattern applicable to a passed CIDR address (may be a netblock or an IP)
|
---|
| 5111 | sub getRevPattern {
|
---|
[483] | 5112 | my $self = shift;
|
---|
| 5113 | my $dbh = $self->{dbh};
|
---|
[452] | 5114 | my $cidr = shift;
|
---|
[701] | 5115 | my %args = @_;
|
---|
| 5116 | $args{group} = 1 if !$args{group}; # just in case
|
---|
| 5117 | $args{location} = '' if !$args{location};
|
---|
[452] | 5118 |
|
---|
[462] | 5119 | # for speed! Casting and comparing even ~7K records takes ~2.5s, so narrow it down to one revzone first.
|
---|
[664] | 5120 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >>= ?",
|
---|
| 5121 | undef, ($cidr) );
|
---|
[462] | 5122 |
|
---|
| 5123 | ##fixme? may need to narrow things down more by octet-chopping and doing text comparisons before casting.
|
---|
| 5124 | my ($revpatt) = $dbh->selectrow_array("SELECT host FROM records ".
|
---|
[701] | 5125 | "WHERE (type in (12,65280,65281,65282,65283,65284)) AND rdns_id = ? ".
|
---|
| 5126 | "AND location = ? AND inetlazy(val) >>= ? ".
|
---|
| 5127 | "ORDER BY inetlazy(val) DESC LIMIT 1",
|
---|
| 5128 | undef, ($revid, $args{location}, $cidr) );
|
---|
| 5129 |
|
---|
[452] | 5130 | return $revpatt;
|
---|
| 5131 | } # end getRevPattern()
|
---|
| 5132 |
|
---|
| 5133 |
|
---|
[673] | 5134 | ## DNSDB::getRevSet()
|
---|
| 5135 | # Return the unique per-IP reverse hostnames, if any, for the passed
|
---|
| 5136 | # CIDR address (may be a netblock or an IP)
|
---|
| 5137 | sub getRevSet {
|
---|
| 5138 | my $self = shift;
|
---|
| 5139 | my $dbh = $self->{dbh};
|
---|
| 5140 | my $cidr = shift;
|
---|
[701] | 5141 | my %args = @_;
|
---|
| 5142 | $args{group} = 1 if !$args{group}; # just in case
|
---|
| 5143 | $args{location} = '' if !$args{location};
|
---|
[673] | 5144 |
|
---|
| 5145 | # for speed! Casting and comparing even ~7K records takes ~2.5s, so narrow it down to one revzone first.
|
---|
| 5146 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >>= ?",
|
---|
| 5147 | undef, ($cidr) );
|
---|
| 5148 |
|
---|
| 5149 | $cidr = new NetAddr::IP $cidr;
|
---|
| 5150 | if ($cidr->num > 256) { # should also catch v6!
|
---|
| 5151 | # Even reverse entries for a v4 /24 of IPs is a bit much. I don't expect
|
---|
| 5152 | # there to be a sane reason to retrive more than a /27 at once, really.
|
---|
| 5153 | # v6 is going to be hairy no matter how you slice it.
|
---|
| 5154 | $errstr = "Reverse hostname detail range too large";
|
---|
| 5155 | return;
|
---|
| 5156 | }
|
---|
| 5157 |
|
---|
| 5158 | my $sth = $dbh->prepare("SELECT val, host FROM records ".
|
---|
[701] | 5159 | "WHERE (type in (12,65280,65281,65282,65283,65284)) AND rdns_id = ? AND location = ? AND inetlazy(val) = ?");
|
---|
[673] | 5160 |
|
---|
| 5161 | my @ret;
|
---|
| 5162 | foreach my $ip (@{$cidr->splitref()}) {
|
---|
[701] | 5163 | $sth->execute($revid, $args{location}, $ip);
|
---|
[673] | 5164 | my @data = $sth->fetchrow_array();
|
---|
| 5165 | my %row;
|
---|
| 5166 | if (@data) {
|
---|
| 5167 | $row{r_ip} = $data[0];
|
---|
| 5168 | $row{iphost} = $data[1];
|
---|
| 5169 | } else {
|
---|
| 5170 | $row{r_ip} = $ip->addr;
|
---|
| 5171 | $row{iphost} = '';
|
---|
| 5172 | }
|
---|
| 5173 | push @ret, \%row;
|
---|
| 5174 | }
|
---|
| 5175 |
|
---|
| 5176 | return \@ret;
|
---|
| 5177 | } # end getRevSet()
|
---|
| 5178 |
|
---|
| 5179 |
|
---|
[225] | 5180 | ## DNSDB::getTypelist()
|
---|
| 5181 | # Get a list of record types for various UI dropdowns
|
---|
| 5182 | # Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A)
|
---|
| 5183 | # Returns an arrayref to list of hashrefs perfect for HTML::Template
|
---|
| 5184 | sub getTypelist {
|
---|
[483] | 5185 | my $self = shift;
|
---|
| 5186 | my $dbh = $self->{dbh};
|
---|
[225] | 5187 | my $recgroup = shift;
|
---|
| 5188 | my $type = shift || $reverse_typemap{A};
|
---|
| 5189 |
|
---|
| 5190 | # also accepting $webvar{revrec}!
|
---|
| 5191 | $recgroup = 'f' if $recgroup eq 'n';
|
---|
| 5192 | $recgroup = 'r' if $recgroup eq 'y';
|
---|
| 5193 |
|
---|
| 5194 | my $sql = "SELECT val,name FROM rectypes WHERE ";
|
---|
| 5195 | if ($recgroup eq 'r') {
|
---|
| 5196 | # reverse zone types
|
---|
| 5197 | $sql .= "stdflag=2 OR stdflag=3";
|
---|
| 5198 | } elsif ($recgroup eq 'l') {
|
---|
| 5199 | # DNS lookup types. Note we avoid our custom types >= 65280, since those are entirely internal.
|
---|
| 5200 | $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280";
|
---|
| 5201 | } else {
|
---|
| 5202 | # default; forward zone types. technically $type eq 'f' but not worth the error message.
|
---|
| 5203 | $sql .= "stdflag=1 OR stdflag=2";
|
---|
[506] | 5204 | $sql .= " AND val < 65280" if $recgroup eq 'fo'; # An extra flag to trim off the pseudotypes as well.
|
---|
[225] | 5205 | }
|
---|
| 5206 | $sql .= " ORDER BY listorder";
|
---|
| 5207 |
|
---|
| 5208 | my $sth = $dbh->prepare($sql);
|
---|
| 5209 | $sth->execute;
|
---|
| 5210 | my @typelist;
|
---|
[603] | 5211 | # track whether the passed type is in the list at all. allows you to edit a record
|
---|
| 5212 | # that wouldn't otherwise be generally available in that zone (typically, reverse zones)
|
---|
| 5213 | # without changing its type (accidentally or otherwise)
|
---|
| 5214 | my $selflag = 0;
|
---|
[225] | 5215 | while (my ($rval,$rname) = $sth->fetchrow_array()) {
|
---|
| 5216 | my %row = ( recval => $rval, recname => $rname );
|
---|
[603] | 5217 | if ($rval == $type) {
|
---|
| 5218 | $row{tselect} = 1;
|
---|
| 5219 | $selflag = 1;
|
---|
| 5220 | }
|
---|
[225] | 5221 | push @typelist, \%row;
|
---|
| 5222 | }
|
---|
| 5223 |
|
---|
[603] | 5224 | # add the passed type if it wasn't in the list
|
---|
| 5225 | if (!$selflag) {
|
---|
| 5226 | my %row = ( recval => $type, recname => $typemap{$type}, tselect => 1 );
|
---|
| 5227 | push @typelist, \%row;
|
---|
| 5228 | }
|
---|
| 5229 |
|
---|
[225] | 5230 | # Add SOA on lookups since it's not listed in other dropdowns.
|
---|
| 5231 | if ($recgroup eq 'l') {
|
---|
| 5232 | my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
|
---|
| 5233 | $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
|
---|
| 5234 | push @typelist, \%row;
|
---|
| 5235 | }
|
---|
| 5236 |
|
---|
| 5237 | return \@typelist;
|
---|
| 5238 | } # end getTypelist()
|
---|
| 5239 |
|
---|
| 5240 |
|
---|
[254] | 5241 | ## DNSDB::parentID()
|
---|
| 5242 | # Get ID of entity that is nearest parent to requested id
|
---|
| 5243 | # Takes a database handle and a hash of entity ID, entity type, optional parent type flag
|
---|
| 5244 | # (domain/reverse zone or group), and optional default/live and forward/reverse flags
|
---|
| 5245 | # Returns the ID or undef on failure
|
---|
| 5246 | sub parentID {
|
---|
[473] | 5247 | my $self = shift;
|
---|
| 5248 | my $dbh = $self->{dbh};
|
---|
[116] | 5249 |
|
---|
[254] | 5250 | my %args = @_;
|
---|
[116] | 5251 |
|
---|
[254] | 5252 | # clean up defrec and revrec. default to live record, forward zone
|
---|
| 5253 | $args{defrec} = 'n' if !$args{defrec};
|
---|
| 5254 | $args{revrec} = 'n' if !$args{revrec};
|
---|
[116] | 5255 |
|
---|
[667] | 5256 | # clean up the parent-type. Set it to group if not set
|
---|
| 5257 | $args{partype} = 'group' if !$args{partype};
|
---|
| 5258 |
|
---|
| 5259 | # allow callers to be lazy with type
|
---|
| 5260 | $args{type} = 'revzone' if $args{type} eq 'domain' && $args{revrec} eq 'y';
|
---|
| 5261 |
|
---|
| 5262 | if ($par_type{$args{partype}} eq 'domain' || $par_type{$args{partype}} eq 'revzone') {
|
---|
[254] | 5263 | # only live records can have a domain/zone parent
|
---|
| 5264 | return unless ($args{type} eq 'record' && $args{defrec} eq 'n');
|
---|
| 5265 | my $result = $dbh->selectrow_hashref("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
| 5266 | " FROM records WHERE record_id = ?",
|
---|
| 5267 | undef, ($args{id}) ) or return;
|
---|
| 5268 | return $result;
|
---|
| 5269 | } else {
|
---|
| 5270 | # snag some arguments that will either fall through or be overwritten to save some code duplication
|
---|
| 5271 | my $tmpid = $args{id};
|
---|
| 5272 | my $type = $args{type};
|
---|
| 5273 | if ($type eq 'record' && $args{defrec} eq 'n') {
|
---|
| 5274 | # Live records go through the records table first.
|
---|
| 5275 | ($tmpid) = $dbh->selectrow_array("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
| 5276 | " FROM records WHERE record_id = ?",
|
---|
| 5277 | undef, ($args{id}) ) or return;
|
---|
| 5278 | $type = ($args{revrec} eq 'n' ? 'domain' : 'revzone');
|
---|
| 5279 | }
|
---|
| 5280 | my ($result) = $dbh->selectrow_array("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
|
---|
| 5281 | undef, ($tmpid) );
|
---|
| 5282 | return $result;
|
---|
| 5283 | }
|
---|
| 5284 | # should be impossible to get here with even remotely sane arguments
|
---|
| 5285 | return;
|
---|
| 5286 | } # end parentID()
|
---|
[116] | 5287 |
|
---|
| 5288 |
|
---|
[117] | 5289 | ## DNSDB::isParent()
|
---|
| 5290 | # Returns true if $id1 is a parent of $id2, false otherwise
|
---|
| 5291 | sub isParent {
|
---|
[470] | 5292 | my $self = shift;
|
---|
| 5293 | my $dbh = $self->{dbh};
|
---|
[117] | 5294 | my $id1 = shift;
|
---|
| 5295 | my $type1 = shift;
|
---|
| 5296 | my $id2 = shift;
|
---|
| 5297 | my $type2 = shift;
|
---|
| 5298 | ##todo: immediate, secondary, full (default)
|
---|
| 5299 |
|
---|
[157] | 5300 | # Return false on invalid types
|
---|
[244] | 5301 | return 0 if !grep /^$type1$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
| 5302 | return 0 if !grep /^$type2$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
[157] | 5303 |
|
---|
[117] | 5304 | # Return false on impossible relations
|
---|
| 5305 | return 0 if $type1 eq 'record'; # nothing may be a child of a record
|
---|
| 5306 | return 0 if $type1 eq 'defrec'; # nothing may be a child of a record
|
---|
[244] | 5307 | return 0 if $type1 eq 'defrevrec'; # nothing may be a child of a record
|
---|
[117] | 5308 | return 0 if $type1 eq 'user'; # nothing may be child of a user
|
---|
| 5309 | return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record
|
---|
[244] | 5310 | return 0 if $type1 eq 'revzone' && $type2 ne 'record';# reverse zone may not be a parent of anything other than a record
|
---|
[117] | 5311 |
|
---|
[186] | 5312 | # ennnhhhh.... if we're passed an id of 0, it will never be found. usual
|
---|
| 5313 | # case would be the UI creating a new <thing>, and so we don't have an ID for
|
---|
| 5314 | # <thing> to look up yet. in that case the UI should check the parent as well.
|
---|
| 5315 | return 0 if $id1 == 0; # nothing can have a parent id of 0
|
---|
| 5316 | return 1 if $id2 == 0; # anything could have a child id of 0 (or "unknown")
|
---|
| 5317 |
|
---|
[117] | 5318 | # group 1 is the ultimate root parent
|
---|
| 5319 | return 1 if $type1 eq 'group' && $id1 == 1;
|
---|
| 5320 |
|
---|
[155] | 5321 | # groups are always (a) parent of themselves
|
---|
| 5322 | return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2;
|
---|
| 5323 |
|
---|
[117] | 5324 | my $id = $id2;
|
---|
| 5325 | my $type = $type2;
|
---|
| 5326 | my $foundparent = 0;
|
---|
[155] | 5327 |
|
---|
[244] | 5328 | # Records are the only entity with two possible parents. We need to split the parent checks on
|
---|
| 5329 | # domain/rdns.
|
---|
| 5330 | if ($type eq 'record') {
|
---|
| 5331 | my ($dom,$rdns) = $dbh->selectrow_array("SELECT domain_id,rdns_id FROM records WHERE record_id=?",
|
---|
| 5332 | undef, ($id));
|
---|
| 5333 | # check immediate parent against request
|
---|
| 5334 | return 1 if $type1 eq 'domain' && $id1 == $dom;
|
---|
| 5335 | return 1 if $type1 eq 'revzone' && $id1 == $rdns;
|
---|
| 5336 | # if request is group, check *both* parents. Only check if the parent is nonzero though.
|
---|
[470] | 5337 | return 1 if $dom && $self->isParent($id1, $type1, $dom, 'domain');
|
---|
| 5338 | return 1 if $rdns && $self->isParent($id1, $type1, $rdns, 'revzone');
|
---|
[244] | 5339 | # exit here since we've executed the loop below by proxy in the above recursive calls.
|
---|
| 5340 | return 0;
|
---|
| 5341 | }
|
---|
| 5342 |
|
---|
| 5343 | # almost the same loop as getParents() above
|
---|
[186] | 5344 | my $limiter = 0;
|
---|
[117] | 5345 | while (1) {
|
---|
[155] | 5346 | my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
|
---|
[117] | 5347 | my $result = $dbh->selectrow_hashref($sql,
|
---|
[157] | 5348 | undef, ($id) );
|
---|
[186] | 5349 | if (!$result) {
|
---|
| 5350 | $limiter++;
|
---|
[244] | 5351 | ##fixme: how often will this happen on a live site? fail at max limiter <n>?
|
---|
[541] | 5352 | # 2013/10/22 only seems to happen when you request an entity that doesn't exist.
|
---|
[186] | 5353 | warn "no results looking for $sql with id $id (depth $limiter)\n";
|
---|
| 5354 | last;
|
---|
| 5355 | }
|
---|
[157] | 5356 | if ($result && $result->{$par_col{$type}} == $id1) {
|
---|
[117] | 5357 | $foundparent = 1;
|
---|
| 5358 | last;
|
---|
[157] | 5359 | } else {
|
---|
| 5360 | ##fixme: do we care about trying to return a "no such record/domain/user/group" error?
|
---|
[244] | 5361 | # should be impossible to create an inconsistent DB just with API calls.
|
---|
[157] | 5362 | warn $dbh->errstr." $sql, $id" if $dbh->errstr;
|
---|
[117] | 5363 | }
|
---|
| 5364 | # group 1 is its own parent. need this here more to break strange loops than for detecting a parent
|
---|
| 5365 | last if $result->{$par_col{$type}} == 1;
|
---|
[152] | 5366 | $id = $result->{$par_col{$type}};
|
---|
[117] | 5367 | $type = $par_type{$type};
|
---|
| 5368 | }
|
---|
| 5369 |
|
---|
| 5370 | return $foundparent;
|
---|
| 5371 | } # end isParent()
|
---|
| 5372 |
|
---|
| 5373 |
|
---|
[275] | 5374 | ## DNSDB::zoneStatus()
|
---|
| 5375 | # Returns and optionally sets a zone's status
|
---|
| 5376 | # Takes a database handle, domain/revzone ID, forward/reverse flag, and optionally a status argument
|
---|
| 5377 | # Returns status, or undef on errors.
|
---|
| 5378 | sub zoneStatus {
|
---|
[477] | 5379 | my $self = shift;
|
---|
| 5380 | my $dbh = $self->{dbh};
|
---|
[3] | 5381 | my $id = shift;
|
---|
[275] | 5382 | my $revrec = shift;
|
---|
| 5383 | my $newstatus = shift || 'mu';
|
---|
[3] | 5384 |
|
---|
| 5385 | return undef if $id !~ /^\d+$/;
|
---|
| 5386 |
|
---|
[283] | 5387 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 5388 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 5389 | local $dbh->{AutoCommit} = 0;
|
---|
| 5390 | local $dbh->{RaiseError} = 1;
|
---|
| 5391 |
|
---|
[275] | 5392 | if ($newstatus ne 'mu') {
|
---|
[283] | 5393 | # ooo, fun! let's see what we were passed for status
|
---|
| 5394 | eval {
|
---|
| 5395 | $newstatus = 0 if $newstatus eq 'domoff';
|
---|
| 5396 | $newstatus = 1 if $newstatus eq 'domon';
|
---|
| 5397 | $dbh->do("UPDATE ".($revrec eq 'n' ? 'domains' : 'revzones')." SET status=? WHERE ".
|
---|
[275] | 5398 | ($revrec eq 'n' ? 'domain_id' : 'rdns_id')."=?", undef, ($newstatus,$id) );
|
---|
[283] | 5399 |
|
---|
| 5400 | ##fixme switch to more consise "Enabled <domain"/"Disabled <domain>" as with users?
|
---|
[473] | 5401 | $resultstr = "Changed ".($revrec eq 'n' ? $self->domainName($id) : $self->revName($id)).
|
---|
[283] | 5402 | " state to ".($newstatus ? 'active' : 'inactive');
|
---|
| 5403 |
|
---|
| 5404 | my %loghash;
|
---|
| 5405 | $loghash{domain_id} = $id if $revrec eq 'n';
|
---|
| 5406 | $loghash{rdns_id} = $id if $revrec eq 'y';
|
---|
[473] | 5407 | $loghash{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec);
|
---|
[283] | 5408 | $loghash{entry} = $resultstr;
|
---|
[487] | 5409 | $self->_log(%loghash);
|
---|
[283] | 5410 |
|
---|
| 5411 | $dbh->commit;
|
---|
| 5412 | };
|
---|
| 5413 | if ($@) {
|
---|
| 5414 | my $msg = $@;
|
---|
| 5415 | eval { $dbh->rollback; };
|
---|
| 5416 | $resultstr = '';
|
---|
| 5417 | $errstr = $msg;
|
---|
| 5418 | return;
|
---|
| 5419 | }
|
---|
[3] | 5420 | }
|
---|
| 5421 |
|
---|
[275] | 5422 | my ($status) = $dbh->selectrow_array("SELECT status FROM ".
|
---|
| 5423 | ($revrec eq 'n' ? "domains WHERE domain_id=?" : "revzones WHERE rdns_id=?"),
|
---|
| 5424 | undef, ($id) );
|
---|
[3] | 5425 | return $status;
|
---|
[275] | 5426 | } # end zoneStatus()
|
---|
[3] | 5427 |
|
---|
| 5428 |
|
---|
[452] | 5429 | ## DNSDB::getZonesByCIDR()
|
---|
| 5430 | # Get a list of zone names and IDs that records for a passed CIDR block are within.
|
---|
[710] | 5431 | # Optionally restrict to a specific location/view
|
---|
[715] | 5432 | # Optionally leave off the default_location field
|
---|
[452] | 5433 | sub getZonesByCIDR {
|
---|
[477] | 5434 | my $self = shift;
|
---|
| 5435 | my $dbh = $self->{dbh};
|
---|
[452] | 5436 | my %args = @_;
|
---|
[715] | 5437 | $args{return_location} = 1 if !defined($args{return_location});
|
---|
[452] | 5438 |
|
---|
[715] | 5439 | my $sql = "SELECT rdns_id,revnet".($args{return_location} ? ',default_location' : '').
|
---|
| 5440 | " FROM revzones WHERE (revnet >>= ? OR revnet <<= ?)".
|
---|
| 5441 | (defined($args{location}) ? " AND default_location = ?" : '');
|
---|
[710] | 5442 | my @svals = ($args{cidr}, $args{cidr});
|
---|
[715] | 5443 | push @svals, $args{location} if defined $args{location};
|
---|
[710] | 5444 |
|
---|
| 5445 | my $result = $dbh->selectall_arrayref($sql, { Slice => {} }, @svals );
|
---|
[452] | 5446 | return $result;
|
---|
| 5447 | } # end getZonesByCIDR()
|
---|
| 5448 |
|
---|
| 5449 |
|
---|
[33] | 5450 | ## DNSDB::importAXFR
|
---|
| 5451 | # Import a domain via AXFR
|
---|
[37] | 5452 | # Takes AXFR host, domain to transfer, group to put the domain in,
|
---|
[484] | 5453 | # and an optional hash containing:
|
---|
| 5454 | # status - active/inactive state flag (defaults to active)
|
---|
| 5455 | # rwsoa - overwrite-SOA flag (defaults to off)
|
---|
| 5456 | # rwns - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
|
---|
| 5457 | # merge - flag to automerge A or AAAA records with matching PTR records
|
---|
[37] | 5458 | # Returns a status code (OK, WARN, or FAIL) and message - message should be blank
|
---|
| 5459 | # if status is OK, but WARN includes conditions that are not fatal but should
|
---|
| 5460 | # really be reported.
|
---|
[33] | 5461 | sub importAXFR {
|
---|
[484] | 5462 | my $self = shift;
|
---|
| 5463 | my $dbh = $self->{dbh};
|
---|
[35] | 5464 | my $ifrom_in = shift;
|
---|
[301] | 5465 | my $zone = shift;
|
---|
[33] | 5466 | my $group = shift;
|
---|
[484] | 5467 |
|
---|
| 5468 | my %args = @_;
|
---|
| 5469 |
|
---|
[33] | 5470 | ##fixme: add mode to delete&replace, merge+overwrite, merge new?
|
---|
| 5471 |
|
---|
[484] | 5472 | $args{status} = (defined($args{status}) ? $args{status} : 0);
|
---|
| 5473 | $args{status} = 1 if $args{status} eq 'on';
|
---|
| 5474 |
|
---|
[37] | 5475 | my $nrecs = 0;
|
---|
| 5476 | my $soaflag = 0;
|
---|
| 5477 | my $nsflag = 0;
|
---|
| 5478 | my $warnmsg = '';
|
---|
| 5479 | my $ifrom;
|
---|
[33] | 5480 |
|
---|
[301] | 5481 | my $rev = 'n';
|
---|
[302] | 5482 | my $code = 'OK';
|
---|
| 5483 | my $msg = 'foobar?';
|
---|
[301] | 5484 |
|
---|
[35] | 5485 | # choke on possible bad setting in ifrom
|
---|
[37] | 5486 | # IPv4 and v6, and valid hostnames!
|
---|
[35] | 5487 | ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
| 5488 | return ('FAIL', "Bad AXFR source host $ifrom")
|
---|
| 5489 | unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
| 5490 |
|
---|
[301] | 5491 | my $errmsg;
|
---|
| 5492 |
|
---|
| 5493 | my $zone_id;
|
---|
| 5494 | my $domain_id = 0;
|
---|
| 5495 | my $rdns_id = 0;
|
---|
| 5496 | my $cidr;
|
---|
| 5497 |
|
---|
| 5498 | # magic happens! detect if we're importing a domain or a reverse zone
|
---|
| 5499 | # while we're at it, figure out what the CIDR netblock is (if we got a .arpa)
|
---|
| 5500 | # or what the formal .arpa zone is (if we got a CIDR netblock)
|
---|
| 5501 | # Handles sub-octet v4 zones in the format specified in the Cricket Book, 2nd Ed, p217-218
|
---|
| 5502 |
|
---|
[601] | 5503 | if ($zone =~ m{(?:\.arpa\.?|/\d+|^[\d.]+|^[a-fA-F0-9:]+)$}) {
|
---|
[301] | 5504 | # we seem to have a reverse zone
|
---|
| 5505 | $rev = 'y';
|
---|
| 5506 |
|
---|
| 5507 | if ($zone =~ /\.arpa\.?$/) {
|
---|
| 5508 | # we have a formal reverse zone. call _zone2cidr and get the CIDR block.
|
---|
| 5509 | ($code,$msg) = _zone2cidr($zone);
|
---|
| 5510 | return ($code, $msg) if $code eq 'FAIL';
|
---|
| 5511 | $cidr = $msg;
|
---|
| 5512 | } elsif ($zone =~ m|^[\d.]+/\d+$|) {
|
---|
| 5513 | # v4 revzone, CIDR netblock
|
---|
| 5514 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 5515 | $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
[601] | 5516 | } elsif ($zone =~ /^[\d.]+$/) {
|
---|
| 5517 | # v4 revzone, leading-octet format
|
---|
| 5518 | my $mask = 32;
|
---|
| 5519 | while ($zone !~ /^\d+\.\d+\.\d+\.\d+$/) {
|
---|
| 5520 | $zone .= '.0';
|
---|
| 5521 | $mask -= 8;
|
---|
| 5522 | }
|
---|
| 5523 | $zone .= "/$mask";
|
---|
| 5524 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 5525 | $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
[301] | 5526 | } elsif ($zone =~ m|^[a-fA-F\d:]+/\d+$|) {
|
---|
| 5527 | # v6 revzone, CIDR netblock
|
---|
| 5528 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 5529 | return ('FAIL', "$zone is not a nibble-aligned block") if $cidr->masklen % 4 != 0;
|
---|
| 5530 | $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.');
|
---|
[601] | 5531 | } elsif ($zone =~ /^[a-fA-F\d:]+$/) {
|
---|
| 5532 | # v6 revzone, leading-group format
|
---|
| 5533 | $zone =~ s/::$//;
|
---|
| 5534 | my $mask = 128;
|
---|
| 5535 | while ($zone !~ /^(?:[a-fA-F\d]{1,4}:){7}[a-fA-F\d]$/) {
|
---|
| 5536 | $zone .= ":0";
|
---|
| 5537 | $mask -= 16;
|
---|
| 5538 | }
|
---|
| 5539 | $zone .= "/$mask";
|
---|
| 5540 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 5541 | $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.');
|
---|
[301] | 5542 | } else {
|
---|
| 5543 | # there is. no. else!
|
---|
[601] | 5544 | return ('FAIL', "Unknown zone name format '$zone'");
|
---|
[301] | 5545 | }
|
---|
| 5546 |
|
---|
[601] | 5547 | # several places this can be triggered from; better to do it once.
|
---|
| 5548 | $warnmsg .= "Apparent sub-/64 IPv6 reverse zone\n" if $cidr->masklen > 64;
|
---|
| 5549 |
|
---|
[301] | 5550 | # quick check to start to see if we've already got one
|
---|
| 5551 |
|
---|
| 5552 | ($zone_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?",
|
---|
| 5553 | undef, ("$cidr"));
|
---|
| 5554 | $rdns_id = $zone_id;
|
---|
| 5555 | } else {
|
---|
| 5556 | # default to domain
|
---|
[349] | 5557 | ($zone_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
[301] | 5558 | undef, ($zone));
|
---|
| 5559 | $domain_id = $zone_id;
|
---|
| 5560 | }
|
---|
| 5561 |
|
---|
| 5562 | return ('FAIL', ($rev eq 'n' ? 'Domain' : 'Reverse zone')." already exists") if $zone_id;
|
---|
| 5563 |
|
---|
[303] | 5564 | # little local utility sub to swap $val and $host for revzone records.
|
---|
| 5565 | sub _revswap {
|
---|
| 5566 | my $rechost = shift;
|
---|
| 5567 | my $recdata = shift;
|
---|
| 5568 |
|
---|
| 5569 | if ($rechost =~ /\.in-addr\.arpa\.?$/) {
|
---|
| 5570 | $rechost =~ s/\.in-addr\.arpa\.?$//;
|
---|
| 5571 | $rechost = join '.', reverse split /\./, $rechost;
|
---|
| 5572 | } else {
|
---|
| 5573 | $rechost =~ s/\.ip6\.arpa\.?$//;
|
---|
| 5574 | my @nibs = reverse split /\./, $rechost;
|
---|
| 5575 | $rechost = '';
|
---|
| 5576 | my $nc;
|
---|
| 5577 | foreach (@nibs) {
|
---|
[634] | 5578 | # # fail on multicharacter nibbles; it's syntactically valid but no standard lookup
|
---|
| 5579 | # # will ever reach it, because it doesn't directly represent a real IP address.
|
---|
| 5580 | # return ('FAIL', "Invalid reverse v6 entry") if $_ !~ /^.$/;
|
---|
[303] | 5581 | $rechost.= $_;
|
---|
| 5582 | $rechost .= ":" if ++$nc % 4 == 0 && $nc < 32;
|
---|
| 5583 | }
|
---|
[307] | 5584 | $rechost .= ":" if $nc < 32 && $rechost !~ /\*$/; # close netblock records?
|
---|
| 5585 | ##fixme: there's a case that ends up with a partial entry here:
|
---|
| 5586 | # ip:add:re:ss::
|
---|
| 5587 | # can't reproduce after letting it sit overnight after discovery. :(
|
---|
| 5588 | #print "$rechost\n";
|
---|
[303] | 5589 | # canonicalize with NetAddr::IP
|
---|
| 5590 | $rechost = NetAddr::IP->new($rechost)->addr unless $rechost =~ /\*$/;
|
---|
| 5591 | }
|
---|
| 5592 | return ($recdata,$rechost)
|
---|
| 5593 | }
|
---|
| 5594 |
|
---|
| 5595 |
|
---|
[33] | 5596 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 5597 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 5598 | local $dbh->{AutoCommit} = 0;
|
---|
| 5599 | local $dbh->{RaiseError} = 1;
|
---|
| 5600 |
|
---|
[301] | 5601 | my $sth;
|
---|
| 5602 | eval {
|
---|
[34] | 5603 |
|
---|
[744] | 5604 | my $logparent;
|
---|
| 5605 |
|
---|
[301] | 5606 | if ($rev eq 'n') {
|
---|
[33] | 5607 | ##fixme: serial
|
---|
[484] | 5608 | $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef,
|
---|
[710] | 5609 | ($zone, $group, $args{status}) ) or die $dbh->errstr;
|
---|
[301] | 5610 | # get domain id so we can do the records
|
---|
| 5611 | ($zone_id) = $dbh->selectrow_array("SELECT currval('domains_domain_id_seq')");
|
---|
| 5612 | $domain_id = $zone_id;
|
---|
[744] | 5613 | $logparent = $self->_log(group_id => $group, domain_id => $domain_id,
|
---|
[487] | 5614 | entry => "[Added ".($args{status} ? 'active' : 'inactive')." domain $zone via AXFR]");
|
---|
[301] | 5615 | } else {
|
---|
| 5616 | ##fixme: serial
|
---|
[484] | 5617 | $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef,
|
---|
| 5618 | ($cidr,$group,$args{status}) );
|
---|
[301] | 5619 | # get revzone id so we can do the records
|
---|
| 5620 | ($zone_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
| 5621 | $rdns_id = $zone_id;
|
---|
[744] | 5622 | $logparent = $self->_log(group_id => $group, rdns_id => $rdns_id,
|
---|
[487] | 5623 | entry => "[Added ".($args{status} ? 'active' : 'inactive')." reverse zone $cidr via AXFR]");
|
---|
[301] | 5624 | }
|
---|
[33] | 5625 |
|
---|
[35] | 5626 | ## bizarre DBI<->Net::DNS interaction bug:
|
---|
| 5627 | ## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
|
---|
[37] | 5628 | ## fixed, apparently I was doing *something* odd, but not certain what it was that
|
---|
| 5629 | ## caused a commit instead of barfing
|
---|
[35] | 5630 |
|
---|
[34] | 5631 | my $res = Net::DNS::Resolver->new;
|
---|
[35] | 5632 | $res->nameservers($ifrom);
|
---|
[301] | 5633 | $res->axfr_start($zone)
|
---|
[35] | 5634 | or die "Couldn't begin AXFR\n";
|
---|
[34] | 5635 |
|
---|
[301] | 5636 | $sth = $dbh->prepare("INSERT INTO records (domain_id,rdns_id,host,type,val,distance,weight,port,ttl)".
|
---|
| 5637 | " VALUES (?,?,?,?,?,?,?,?,?)");
|
---|
| 5638 |
|
---|
[307] | 5639 | # Stash info about sub-octet v4 revzones here so we don't have
|
---|
| 5640 | # to store the CNAMEs used to delegate a suboctet zone
|
---|
| 5641 | # $suboct{zone}{ns}[] -> array of nameservers
|
---|
| 5642 | # $suboct{zone}{cname}[] -> array of extant CNAMEs (Just In Case someone did something bizarre)
|
---|
| 5643 | ## commented pending actual use of this data. for now, we'll just
|
---|
| 5644 | ## auto-(re)create the CNAMEs in revzones on export
|
---|
| 5645 | # my %suboct;
|
---|
| 5646 |
|
---|
[35] | 5647 | while (my $rr = $res->axfr_next()) {
|
---|
[301] | 5648 |
|
---|
[596] | 5649 | # Discard out-of-zone records. After trying for a while to replicate this with
|
---|
| 5650 | # *nix-based DNS servers, it appears that only MS DNS is prone to including these
|
---|
| 5651 | # in the AXFR data in the first place, and possibly only older versions at that...
|
---|
| 5652 | # so it can't be reasonably tested. Yay Microsoft.
|
---|
| 5653 | if ($rr->name !~ /$zone$/i) {
|
---|
| 5654 | $warnmsg .= "Discarding out-of-zone record ".$rr->string."\n";
|
---|
| 5655 | }
|
---|
| 5656 |
|
---|
[301] | 5657 | my $val;
|
---|
| 5658 | my $distance = 0;
|
---|
| 5659 | my $weight = 0;
|
---|
| 5660 | my $port = 0;
|
---|
[303] | 5661 | my $logfrag = '';
|
---|
[301] | 5662 |
|
---|
[602] | 5663 | # Collect some record parts
|
---|
[33] | 5664 | my $type = $rr->type;
|
---|
[301] | 5665 | my $host = $rr->name;
|
---|
[484] | 5666 | my $ttl = ($args{newttl} ? $args{newttl} : $rr->ttl); # allow force-override TTLs
|
---|
[35] | 5667 |
|
---|
[602] | 5668 | # Info flags for SOA and NS records
|
---|
[37] | 5669 | $soaflag = 1 if $type eq 'SOA';
|
---|
| 5670 | $nsflag = 1 if $type eq 'NS';
|
---|
[35] | 5671 |
|
---|
[34] | 5672 | # "Primary" types:
|
---|
| 5673 | # A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
|
---|
| 5674 | # maybe KEY
|
---|
| 5675 |
|
---|
[302] | 5676 | # BIND supports:
|
---|
| 5677 | # [standard]
|
---|
| 5678 | # A AAAA CNAME MX NS PTR SOA TXT
|
---|
| 5679 | # [variously experimental, obsolete, or obscure]
|
---|
| 5680 | # 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
|
---|
| 5681 | # ... if one can ever find the right magic to format them correctly
|
---|
| 5682 |
|
---|
| 5683 | # Net::DNS supports:
|
---|
| 5684 | # RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
|
---|
| 5685 | # EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
|
---|
| 5686 | # DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
|
---|
| 5687 |
|
---|
[35] | 5688 | # nasty big ugly case-like thing here, since we have to do *some* different
|
---|
| 5689 | # processing depending on the record. le sigh.
|
---|
| 5690 |
|
---|
[602] | 5691 | # do the initial processing as if the record was in a forward zone. If we're
|
---|
| 5692 | # doing a revzone, we can flip $host and $val as needed, once, after this
|
---|
| 5693 | # monster if-elsif-...-elsif-else. This actually simplifies things a lot.
|
---|
| 5694 |
|
---|
[105] | 5695 | ##fixme: what record types other than TXT can/will have >255-byte payloads?
|
---|
| 5696 |
|
---|
[34] | 5697 | if ($type eq 'A') {
|
---|
[301] | 5698 | $val = $rr->address;
|
---|
[34] | 5699 | } elsif ($type eq 'NS') {
|
---|
[635] | 5700 | # hmm. should we warn here if subdomain NS'es are left alone? OTOH, those should rarely be rewritten anyway.
|
---|
[602] | 5701 | next if ($args{rwns} && ($host eq $zone));
|
---|
| 5702 | $val = $rr->nsdname;
|
---|
[639] | 5703 | $warnmsg .= "Suspect record '".$rr->string."' may not be imported correctly: NS records may not be bare IP addresses\n"
|
---|
| 5704 | if $val =~ /^(?:(?:\d+\.){3}\d+|[a-fA-F0-9:]+)$/;
|
---|
[35] | 5705 | $nsflag = 1;
|
---|
[34] | 5706 | } elsif ($type eq 'CNAME') {
|
---|
[602] | 5707 | $val = $rr->cname;
|
---|
[639] | 5708 | $warnmsg .= "Suspect record '".$rr->string."' may not be imported correctly: CNAME records may not be bare IP addresses\n"
|
---|
| 5709 | if $val =~ /^(?:(?:\d+\.){3}\d+|[a-fA-F0-9:]+)$/;
|
---|
[34] | 5710 | } elsif ($type eq 'SOA') {
|
---|
[484] | 5711 | next if $args{rwsoa};
|
---|
[307] | 5712 | $host = $rr->rname.":".$rr->mname;
|
---|
[301] | 5713 | $val = $rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum;
|
---|
[35] | 5714 | $soaflag = 1;
|
---|
[34] | 5715 | } elsif ($type eq 'PTR') {
|
---|
[602] | 5716 | $val = $rr->ptrdname;
|
---|
[34] | 5717 | } elsif ($type eq 'MX') {
|
---|
[301] | 5718 | $val = $rr->exchange;
|
---|
| 5719 | $distance = $rr->preference;
|
---|
[34] | 5720 | } elsif ($type eq 'TXT') {
|
---|
| 5721 | ##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
|
---|
| 5722 | ## but don't really seem enthusiastic about it.
|
---|
[303] | 5723 | #print "should use rdatastr:\n\t".$rr->rdatastr."\n or char_str_list:\n\t".join(' ',$rr->char_str_list())."\n";
|
---|
| 5724 | # rdatastr returns a BIND-targetted logical string, including opening and closing quotes
|
---|
| 5725 | # char_str_list returns a list of the individual string fragments in the record
|
---|
[307] | 5726 | # txtdata returns the more useful all-in-one form (since we want to push such protocol
|
---|
| 5727 | # details as far down the stack as we can)
|
---|
[303] | 5728 | # NB: this may turn out to be more troublesome if we ever have need of >512-byte TXT records.
|
---|
[602] | 5729 | $val = $rr->txtdata;
|
---|
[34] | 5730 | } elsif ($type eq 'SPF') {
|
---|
| 5731 | ##fixme: and the same caveat here, since it is apparently a clone of ::TXT
|
---|
[301] | 5732 | $val = $rr->txtdata;
|
---|
[34] | 5733 | } elsif ($type eq 'AAAA') {
|
---|
[301] | 5734 | $val = $rr->address;
|
---|
[34] | 5735 | } elsif ($type eq 'SRV') {
|
---|
[301] | 5736 | $val = $rr->target;
|
---|
| 5737 | $distance = $rr->priority;
|
---|
| 5738 | $weight = $rr->weight;
|
---|
| 5739 | $port = $rr->port;
|
---|
[639] | 5740 | $warnmsg .= "Suspect record '".$rr->string."' may not be imported correctly: SRV records may not be bare IP addresses\n"
|
---|
| 5741 | if $val =~ /^(?:(?:\d+\.){3}\d+|[a-fA-F0-9:]+)$/;
|
---|
[34] | 5742 | } elsif ($type eq 'KEY') {
|
---|
[35] | 5743 | # we don't actually know what to do with these...
|
---|
[301] | 5744 | $val = $rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname;
|
---|
[35] | 5745 | } else {
|
---|
[301] | 5746 | $val = $rr->rdatastr;
|
---|
[35] | 5747 | # Finding a different record type is not fatal.... just problematic.
|
---|
[37] | 5748 | # We may not be able to export it correctly.
|
---|
[35] | 5749 | $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
|
---|
[33] | 5750 | }
|
---|
| 5751 |
|
---|
[602] | 5752 | if ($rev eq 'y' && $type ne 'SOA') {
|
---|
| 5753 | # up to this point we haven't meddled with the record's hostname part or rdata part.
|
---|
| 5754 | # for reverse records, (except SOA) we must swap the two.
|
---|
| 5755 | $host = $val;
|
---|
| 5756 | $val = $rr->name;
|
---|
| 5757 | my ($tmpcode,$tmpmsg) = _zone2cidr($val);
|
---|
| 5758 | if ($tmpcode eq 'FAIL') {
|
---|
| 5759 | # $val did not have a valid IP value. It's syntactically valid but WTF?
|
---|
| 5760 | $warnmsg .= "Suspect record '".$rr->string."' may not be imported correctly: $tmpmsg\n";
|
---|
| 5761 | } else {
|
---|
| 5762 | # $val has a valid IP value. See if we can store it as that IP value.
|
---|
| 5763 | # Note we're enumerating do-nothing cases for clarity.
|
---|
| 5764 | ##enhance: this is where we will implement the more subtle variations on #53
|
---|
| 5765 | if ($type ne 'PTR' && $type ne 'NS' && $type ne 'CNAME' && $type ne 'TXT') {
|
---|
| 5766 | # case: the record is "weird" - ie, not a PTR, NS, CNAME, or TXT
|
---|
| 5767 | # $warnmsg .= "Discarding suspect record '".$rr->string."'\n" if $self->{strict} eq 'full';
|
---|
| 5768 | } elsif ($type eq 'PTR' && $tmpmsg->masklen != 32 && $tmpmsg->masklen != 128) {
|
---|
| 5769 | # case: PTR with netblock value, not IP value
|
---|
| 5770 | # eg, "@ PTR foo" in zone f.e.e.b.d.a.e.d.ip6.arpa should not be
|
---|
| 5771 | # stored/displayed as dead:beef::/32 PTR foo
|
---|
| 5772 |
|
---|
| 5773 | ## hrm. WTF is this case for, anyway? Needs testing to check the logic.
|
---|
| 5774 | # } elsif ( ($type eq 'PTR' || $type eq 'NS' || $type eq 'CNAME' || $type eq 'TXT') &&
|
---|
| 5775 | # ($tmpmsg->masklen != $cidr->masklen)
|
---|
| 5776 | # ) {
|
---|
| 5777 | # # leave $val as-is if the record is "normal" (a PTR, NS, CNAME, or TXT),
|
---|
| 5778 | # # and the mask does not match the zone
|
---|
| 5779 | #$warnmsg .= "WTF case: $host $type $val\n";
|
---|
| 5780 | # # $warnmsg .= "Discarding suspect record '".$rr->string."'\n" if $self->{strict} eq 'full';
|
---|
| 5781 |
|
---|
| 5782 | } else {
|
---|
| 5783 | $val = $tmpmsg;
|
---|
| 5784 | $val =~ s/\/(?:32|128)$//; # automagically converts $val back to a string before s///
|
---|
| 5785 | #$val =~ s/:0$//g;
|
---|
| 5786 | }
|
---|
| 5787 | }
|
---|
| 5788 | # magic? convert * records to PTR template (not sure this actually makes sense)
|
---|
| 5789 | #if ($val =~ /^\*/) {
|
---|
| 5790 | # $val =~ s/\*\.//;
|
---|
| 5791 | # ($tmpcode,$tmpmsg) = _zone2cidr($val);
|
---|
| 5792 | # if ($tmpcode eq 'FAIL') {
|
---|
| 5793 | # $val = "*.$val";
|
---|
| 5794 | # $warnmsg .= "Suspect record '".$rr->string."' may not be converted to PTR template correctly: $tmpmsg\n";
|
---|
| 5795 | # } else {
|
---|
| 5796 | # $type = 'PTR template';
|
---|
| 5797 | # $val = $tmpmsg; if $tmp
|
---|
| 5798 | # $val =~ s/\/(?:32|128)$//; # automagically converts $val back to a string before s///
|
---|
| 5799 | # }
|
---|
| 5800 | #}
|
---|
| 5801 | } # non-SOA revrec $host/$val inversion and munging
|
---|
| 5802 |
|
---|
[303] | 5803 | my $logentry = "[AXFR ".($rev eq 'n' ? $zone : $cidr)."] ";
|
---|
[34] | 5804 |
|
---|
[484] | 5805 | if ($args{merge}) {
|
---|
[307] | 5806 | if ($rev eq 'n') {
|
---|
| 5807 | # importing a domain; we have A and AAAA records that could be merged with matching PTR records
|
---|
| 5808 | my $etype;
|
---|
| 5809 | my ($erdns,$erid,$ettl) = $dbh->selectrow_array("SELECT rdns_id,record_id,ttl FROM records ".
|
---|
| 5810 | "WHERE host=? AND val=? AND type=12",
|
---|
| 5811 | undef, ($host, $val) );
|
---|
| 5812 | if ($erid) {
|
---|
| 5813 | if ($type eq 'A') { # PTR -> A+PTR
|
---|
| 5814 | $etype = 65280;
|
---|
| 5815 | $logentry .= "Merged A record with existing PTR record '$host A+PTR $val', TTL $ettl";
|
---|
| 5816 | }
|
---|
| 5817 | if ($type eq 'AAAA') { # PTR -> AAAA+PTR
|
---|
| 5818 | $etype = 65281;
|
---|
| 5819 | $logentry .= "Merged AAAA record with existing PTR record '$host AAAA+PTR $val', TTL $ettl";
|
---|
| 5820 | }
|
---|
| 5821 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
| 5822 | $dbh->do("UPDATE records SET domain_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
| 5823 | ($domain_id, $ettl, $etype, $erid));
|
---|
| 5824 | $nrecs++;
|
---|
[487] | 5825 | $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $erdns, entry => $logentry);
|
---|
[307] | 5826 | next; # while axfr_next
|
---|
| 5827 | }
|
---|
| 5828 | } # $rev eq 'n'
|
---|
| 5829 | else {
|
---|
| 5830 | # importing a revzone, we have PTR records that could be merged with matching A/AAAA records
|
---|
| 5831 | my ($domid,$erid,$ettl,$etype) = $dbh->selectrow_array("SELECT domain_id,record_id,ttl,type FROM records ".
|
---|
| 5832 | "WHERE host=? AND val=? AND (type=1 OR type=28)",
|
---|
| 5833 | undef, ($host, $val) );
|
---|
| 5834 | if ($erid) {
|
---|
| 5835 | if ($etype == 1) { # A -> A+PTR
|
---|
| 5836 | $etype = 65280;
|
---|
| 5837 | $logentry .= "Merged PTR record with existing matching A record '$host A+PTR $val', TTL $ettl";
|
---|
| 5838 | }
|
---|
| 5839 | if ($etype == 28) { # AAAA -> AAAA+PTR
|
---|
| 5840 | $etype = 65281;
|
---|
| 5841 | $logentry .= "Merged PTR record with existing matching AAAA record '$host AAAA+PTR $val', TTL $ettl";
|
---|
| 5842 | }
|
---|
| 5843 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
| 5844 | $dbh->do("UPDATE records SET rdns_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
| 5845 | ($rdns_id, $ettl, $etype, $erid));
|
---|
| 5846 | $nrecs++;
|
---|
[487] | 5847 | $self->_log(group_id => $group, domain_id => $domid, rdns_id => $rdns_id, entry => $logentry);
|
---|
[307] | 5848 | next; # while axfr_next
|
---|
| 5849 | }
|
---|
| 5850 | } # $rev eq 'y'
|
---|
[484] | 5851 | } # if $args{merge}
|
---|
[34] | 5852 |
|
---|
[302] | 5853 | # Insert the new record
|
---|
[301] | 5854 | $sth->execute($domain_id, $rdns_id, $host, $reverse_typemap{$type}, $val,
|
---|
| 5855 | $distance, $weight, $port, $ttl);
|
---|
| 5856 |
|
---|
[37] | 5857 | $nrecs++;
|
---|
[34] | 5858 |
|
---|
[301] | 5859 | if ($type eq 'SOA') {
|
---|
[484] | 5860 | # also !$args{rwsoa}, but if that's set, it should be impossible to get here.
|
---|
[301] | 5861 | my @tmp1 = split /:/, $host;
|
---|
| 5862 | my @tmp2 = split /:/, $val;
|
---|
| 5863 | $logentry .= "Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
| 5864 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl";
|
---|
[303] | 5865 | } elsif ($logfrag) {
|
---|
| 5866 | # special case for log entries we need to meddle with a little.
|
---|
| 5867 | $logentry .= $logfrag;
|
---|
[301] | 5868 | } else {
|
---|
[602] | 5869 | $logentry .= "Added record '".($rev eq 'y' ? $val : $host)." $type";
|
---|
[301] | 5870 | $logentry .= " [distance $distance]" if $type eq 'MX';
|
---|
| 5871 | $logentry .= " [priority $distance] [weight $weight] [port $port]" if $type eq 'SRV';
|
---|
[602] | 5872 | $logentry .= " ".($rev eq 'y' ? $host : $val)."', TTL $ttl";
|
---|
[301] | 5873 | }
|
---|
[744] | 5874 | $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $rdns_id,
|
---|
| 5875 | logparent => $logparent, entry => $logentry);
|
---|
[301] | 5876 |
|
---|
[37] | 5877 | } # while axfr_next
|
---|
| 5878 |
|
---|
[307] | 5879 | # Detect and handle delegated subzones
|
---|
| 5880 | # Placeholder for when we decide what to actually do with this, see previous comments in NS and CNAME handling.
|
---|
| 5881 | #foreach (keys %suboct) {
|
---|
| 5882 | # print "found ".($suboct{$_}{ns} ? @{$suboct{$_}{ns}} : '0')." NS records and ".
|
---|
| 5883 | # ($suboct{$_}{cname} ? @{$suboct{$_}{cname}} : '0')." CNAMEs for $_\n";
|
---|
| 5884 | #}
|
---|
| 5885 |
|
---|
[37] | 5886 | # Overwrite SOA record
|
---|
[484] | 5887 | if ($args{rwsoa}) {
|
---|
[37] | 5888 | $soaflag = 1;
|
---|
[573] | 5889 | my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM "._rectable('y', $rev)." WHERE group_id=? AND type=?");
|
---|
| 5890 | my $sthputsoa = $dbh->prepare("INSERT INTO records (".
|
---|
| 5891 | ($rev eq 'n' ? 'domain_id' : 'rdns_id').",host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
[37] | 5892 | $sthgetsoa->execute($group,$reverse_typemap{SOA});
|
---|
| 5893 | while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
|
---|
[573] | 5894 | if ($rev eq 'n') {
|
---|
| 5895 | $host =~ s/DOMAIN/$zone/g;
|
---|
| 5896 | $val =~ s/DOMAIN/$zone/g; # arguably useless
|
---|
| 5897 | } else {
|
---|
| 5898 | $host =~ s/ADMINDOMAIN/$self->{domain}/g;
|
---|
| 5899 | }
|
---|
[301] | 5900 | $sthputsoa->execute($zone_id,$host,$reverse_typemap{SOA},$val,$ttl);
|
---|
[34] | 5901 | }
|
---|
[37] | 5902 | }
|
---|
[34] | 5903 |
|
---|
[573] | 5904 | # Add standard NS records. The old one(s) should have been skipped by this point.
|
---|
[484] | 5905 | if ($args{rwns}) {
|
---|
[37] | 5906 | $nsflag = 1;
|
---|
[573] | 5907 | my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM "._rectable('y',$rev)." WHERE group_id=? AND type=?");
|
---|
| 5908 | my $sthputns = $dbh->prepare("INSERT INTO records (".
|
---|
| 5909 | ($rev eq 'n' ? 'domain_id' : 'rdns_id').",host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
[37] | 5910 | $sthgetns->execute($group,$reverse_typemap{NS});
|
---|
| 5911 | while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
|
---|
[573] | 5912 | if ($rev eq 'n') {
|
---|
| 5913 | $host =~ s/DOMAIN/$zone/g;
|
---|
| 5914 | $val =~ s/DOMAIN/$zone/g; #hmm.
|
---|
| 5915 | } else {
|
---|
| 5916 | $host =~ s/ADMINDOMAIN/$self->{domain}/g; #hmm.
|
---|
| 5917 | $val =~ s/ZONE/$cidr/g;
|
---|
| 5918 | }
|
---|
[301] | 5919 | $sthputns->execute($zone_id,$host,$reverse_typemap{NS},$val,$ttl);
|
---|
[37] | 5920 | }
|
---|
| 5921 | }
|
---|
[34] | 5922 |
|
---|
[35] | 5923 | die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
|
---|
| 5924 | die "Bad zone: No SOA record!\n" if !$soaflag;
|
---|
| 5925 | die "Bad zone: No NS records!\n" if !$nsflag;
|
---|
| 5926 |
|
---|
[37] | 5927 | $dbh->commit;
|
---|
[35] | 5928 |
|
---|
[33] | 5929 | };
|
---|
| 5930 |
|
---|
| 5931 | if ($@) {
|
---|
| 5932 | my $msg = $@;
|
---|
| 5933 | eval { $dbh->rollback; };
|
---|
[34] | 5934 | return ('FAIL',$msg." $warnmsg");
|
---|
[33] | 5935 | } else {
|
---|
[35] | 5936 | return ('WARN', $warnmsg) if $warnmsg;
|
---|
[91] | 5937 | return ('OK',"Imported OK");
|
---|
[33] | 5938 | }
|
---|
| 5939 |
|
---|
[37] | 5940 | # it should be impossible to get here.
|
---|
[34] | 5941 | return ('WARN',"OOOK!");
|
---|
[33] | 5942 | } # end importAXFR()
|
---|
| 5943 |
|
---|
| 5944 |
|
---|
[302] | 5945 | ## DNSDB::importBIND()
|
---|
| 5946 | sub importBIND {
|
---|
| 5947 | } # end importBIND()
|
---|
| 5948 |
|
---|
| 5949 |
|
---|
| 5950 | ## DNSDB::import_tinydns()
|
---|
| 5951 | sub import_tinydns {
|
---|
| 5952 | } # end import_tinydns()
|
---|
| 5953 |
|
---|
| 5954 |
|
---|
[103] | 5955 | ## DNSDB::export()
|
---|
| 5956 | # Export the DNS database, or a part of it
|
---|
[485] | 5957 | # Takes a string indicating the export type, plus optional arguments depending on type
|
---|
[103] | 5958 | # Writes zone data to targets as appropriate for type
|
---|
| 5959 | sub export {
|
---|
[485] | 5960 | my $self = shift;
|
---|
[103] | 5961 | my $target = shift;
|
---|
| 5962 |
|
---|
| 5963 | if ($target eq 'tiny') {
|
---|
[567] | 5964 | eval {
|
---|
| 5965 | $self->__export_tiny(@_);
|
---|
| 5966 | };
|
---|
| 5967 | if ($@) {
|
---|
| 5968 | $errstr = $@;
|
---|
| 5969 | return undef;
|
---|
| 5970 | }
|
---|
[103] | 5971 | }
|
---|
| 5972 | # elsif ($target eq 'foo') {
|
---|
[485] | 5973 | # __export_foo(@_);
|
---|
[103] | 5974 | #}
|
---|
| 5975 | # etc
|
---|
| 5976 |
|
---|
[567] | 5977 | return 1;
|
---|
[103] | 5978 | } # end export()
|
---|
| 5979 |
|
---|
| 5980 |
|
---|
| 5981 | ## DNSDB::__export_tiny
|
---|
| 5982 | # Internal sub to implement tinyDNS (compatible) export
|
---|
[485] | 5983 | # Takes filehandle to write export to, optional argument(s)
|
---|
[103] | 5984 | # to determine which data gets exported
|
---|
| 5985 | sub __export_tiny {
|
---|
[485] | 5986 | my $self = shift;
|
---|
| 5987 | my $dbh = $self->{dbh};
|
---|
[103] | 5988 | my $datafile = shift;
|
---|
[559] | 5989 | my $zonefilehandle = $datafile; # makes cache/no-cache a little simpler
|
---|
[103] | 5990 |
|
---|
| 5991 | ##fixme: slurp up further options to specify particular zone(s) to export
|
---|
| 5992 |
|
---|
| 5993 | ##fixme: fail if $datafile isn't an open, writable file
|
---|
| 5994 |
|
---|
[566] | 5995 | # Error check - does the cache dir exist, if we're using one?
|
---|
| 5996 | if ($self->{usecache}) {
|
---|
| 5997 | die "Cache directory does not exist\n" if !-e $self->{exportcache};
|
---|
| 5998 | die "$self->{exportcache} is not a directory\n" if !-d $self->{exportcache};
|
---|
| 5999 | die "$self->{exportcache} must be both readable and writable\n"
|
---|
| 6000 | if !-r $self->{exportcache} || !-w $self->{exportcache};
|
---|
| 6001 | }
|
---|
| 6002 |
|
---|
[103] | 6003 | # easy case - export all evarything
|
---|
| 6004 | # not-so-easy case - export item(s) specified
|
---|
| 6005 | # todo: figure out what kind of list we use to export items
|
---|
| 6006 |
|
---|
[329] | 6007 | # raw packet in unknown format: first byte indicates length
|
---|
| 6008 | # of remaining data, allows up to 255 raw bytes
|
---|
| 6009 |
|
---|
[566] | 6010 | # note: the only I/O failures we seem to be able to actually catch
|
---|
| 6011 | # here are "closed filehandle" errors. we're probably not writing
|
---|
| 6012 | # enough data at this point to properly trigger an "out of space"
|
---|
| 6013 | # error. :/
|
---|
| 6014 | eval {
|
---|
| 6015 | use warnings FATAL => ('io');
|
---|
| 6016 | # Locations/views - worth including in the caching setup?
|
---|
| 6017 | my $lochash = $dbh->selectall_hashref("SELECT location,iplist FROM locations", 'location');
|
---|
| 6018 | foreach my $location (keys %$lochash) {
|
---|
| 6019 | foreach my $ipprefix (split /[,\s]+/, $lochash->{$location}{iplist}) {
|
---|
| 6020 | $ipprefix =~ s/\s+//g;
|
---|
| 6021 | $ipprefix = new NetAddr::IP $ipprefix;
|
---|
[449] | 6022 | ##fixme: how to handle IPv6?
|
---|
| 6023 | next if $ipprefix->{isv6};
|
---|
[566] | 6024 | # have to account for /nn CIDR entries. tinydns only speaks octet-sliced prefix.
|
---|
| 6025 | if ($ipprefix->masklen <= 8) {
|
---|
| 6026 | foreach ($ipprefix->split(8)) {
|
---|
| 6027 | my $tmp = $_->addr;
|
---|
| 6028 | $tmp =~ s/\.\d+\.\d+\.\d+$//;
|
---|
| 6029 | print $datafile "%$location:$tmp\n";
|
---|
| 6030 | }
|
---|
| 6031 | } elsif ($ipprefix->masklen <= 16) {
|
---|
| 6032 | foreach ($ipprefix->split(16)) {
|
---|
| 6033 | my $tmp = $_->addr;
|
---|
| 6034 | $tmp =~ s/\.\d+\.\d+$//;
|
---|
| 6035 | print $datafile "%$location:$tmp\n";
|
---|
| 6036 | }
|
---|
| 6037 | } elsif ($ipprefix->masklen <= 24) {
|
---|
| 6038 | foreach ($ipprefix->split(24)) {
|
---|
| 6039 | my $tmp = $_->addr;
|
---|
| 6040 | $tmp =~ s/\.\d+$//;
|
---|
| 6041 | print $datafile "%$location:$tmp\n";
|
---|
| 6042 | }
|
---|
| 6043 | } else {
|
---|
| 6044 | foreach ($ipprefix->split(32)) {
|
---|
| 6045 | print $datafile "%$location:".$_->addr."\n";
|
---|
| 6046 | }
|
---|
[449] | 6047 | }
|
---|
| 6048 | }
|
---|
[566] | 6049 | print $datafile "%$location\n" if !$lochash->{$location}{iplist};
|
---|
[372] | 6050 | }
|
---|
[566] | 6051 | };
|
---|
| 6052 | if ($@) {
|
---|
| 6053 | die "Error writing locations to master file: $@, $!\n";
|
---|
[372] | 6054 | }
|
---|
| 6055 |
|
---|
[329] | 6056 | # tracking hash so we don't double-export A+PTR or AAAA+PTR records.
|
---|
| 6057 | my %recflags;
|
---|
| 6058 |
|
---|
[523] | 6059 | # For reasons unknown, we can't sanely UNION these statements. Feh.
|
---|
| 6060 | # Supposedly it should work though (note last 3 lines):
|
---|
| 6061 | ## PG manual
|
---|
| 6062 | #UNION Clause
|
---|
| 6063 | #
|
---|
| 6064 | #The UNION clause has this general form:
|
---|
| 6065 | #
|
---|
| 6066 | # select_statement UNION [ ALL ] select_statement
|
---|
| 6067 | #
|
---|
| 6068 | #select_statement is any SELECT statement without an ORDER BY, LIMIT, FOR UPDATE, or FOR SHARE clause. (ORDER BY
|
---|
| 6069 | #and LIMIT can be attached to a subexpression if it is enclosed in parentheses. Without parentheses, these
|
---|
| 6070 | #clauses will be taken to apply to the result of the UNION, not to its right-hand input expression.)
|
---|
| 6071 | my $soasth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
| 6072 | "FROM records WHERE rdns_id=? AND type=6");
|
---|
[543] | 6073 | my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location,extract(epoch from stamp),expires,stampactive ".
|
---|
[576] | 6074 | "FROM records WHERE rdns_id=? AND NOT type=6 ".
|
---|
[599] | 6075 | "ORDER BY masklen(inetlazy(val)) DESC, inetlazy(val)");
|
---|
[523] | 6076 | my $revsth = $dbh->prepare("SELECT rdns_id,revnet,status,changed FROM revzones WHERE status=1 ".
|
---|
[566] | 6077 | "ORDER BY masklen(revnet) DESC, rdns_id");
|
---|
[523] | 6078 | my $zonesth = $dbh->prepare("UPDATE revzones SET changed='n' WHERE rdns_id=?");
|
---|
| 6079 | $revsth->execute();
|
---|
| 6080 | while (my ($revid,$revzone,$revstat,$changed) = $revsth->fetchrow_array) {
|
---|
[368] | 6081 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
| 6082 | # O_NOFOLLOW
|
---|
| 6083 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
| 6084 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
| 6085 | # still be followed.
|
---|
| 6086 | # but that doesn't help other platforms. :/
|
---|
[523] | 6087 | my $tmpzone = NetAddr::IP->new($revzone);
|
---|
| 6088 | ##fixme: locations/views? subnet mask? need to avoid possible collisions with zone/superzone
|
---|
| 6089 | ## (eg /20 vs /24, starting on .0.0)
|
---|
| 6090 | my $cz = $tmpzone->network->addr."-".$tmpzone->masklen;
|
---|
| 6091 | my $cachefile = "$self->{exportcache}/$cz";
|
---|
| 6092 | my $tmpcache = "$self->{exportcache}/tmp.$cz.$$";
|
---|
[521] | 6093 | eval {
|
---|
[108] | 6094 |
|
---|
[559] | 6095 | # write fresh records if:
|
---|
| 6096 | # - we are not using the cache
|
---|
| 6097 | # - force_refresh is set
|
---|
| 6098 | # - the zone has changed
|
---|
| 6099 | # - the cache file does not exist
|
---|
| 6100 | # - the cache file is empty
|
---|
| 6101 | if (!$self->{usecache} || $self->{force_refresh} || $changed || !-e $cachefile || -z $cachefile) {
|
---|
| 6102 | if ($self->{usecache}) {
|
---|
| 6103 | open ZONECACHE, ">$tmpcache" or die "Error creating temporary file $tmpcache: $!\n";
|
---|
| 6104 | $zonefilehandle = *ZONECACHE;
|
---|
| 6105 | }
|
---|
[521] | 6106 |
|
---|
[523] | 6107 | # need to fetch this separately since the rest of the records all (should) have real IPs in val
|
---|
| 6108 | $soasth->execute($revid);
|
---|
| 6109 | my (@zsoa) = $soasth->fetchrow_array();
|
---|
[644] | 6110 | $self->_printrec_tiny($zonefilehandle, $zsoa[7], 'y',\%recflags,$revzone,
|
---|
[523] | 6111 | $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],'');
|
---|
| 6112 |
|
---|
| 6113 | $recsth->execute($revid);
|
---|
[596] | 6114 | my $fullzone = _ZONE($tmpzone, 'ZONE', 'r', '.').($tmpzone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 6115 |
|
---|
[573] | 6116 | while (my ($host, $type, $val, $dist, $weight, $port, $ttl, $recid, $loc, $stamp, $expires, $stampactive)
|
---|
| 6117 | = $recsth->fetchrow_array) {
|
---|
[523] | 6118 | next if $recflags{$recid};
|
---|
[521] | 6119 |
|
---|
[596] | 6120 | # Check for out-of-zone data
|
---|
| 6121 | if ($val =~ /\.arpa$/) {
|
---|
| 6122 | # val is non-IP
|
---|
| 6123 | if ($val !~ /$fullzone$/) {
|
---|
| 6124 | warn "Not exporting out-of-zone record $val $typemap{$type} $host, $ttl (zone $tmpzone)\n";
|
---|
| 6125 | next;
|
---|
| 6126 | }
|
---|
| 6127 | } else {
|
---|
| 6128 | my $ipval = new NetAddr::IP $val;
|
---|
| 6129 | if (!$tmpzone->contains($ipval)) {
|
---|
| 6130 | warn "Not exporting out-of-zone record $val $typemap{$type} $host, $ttl (zone $tmpzone)\n";
|
---|
| 6131 | next;
|
---|
| 6132 | }
|
---|
| 6133 | } # is $val a raw .arpa name?
|
---|
| 6134 |
|
---|
[597] | 6135 | # Spaces are evil.
|
---|
| 6136 | $val =~ s/^\s+//;
|
---|
| 6137 | $val =~ s/\s+$//;
|
---|
| 6138 | if ($typemap{$type} ne 'TXT') {
|
---|
| 6139 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 6140 | $host =~ s/^\s+//;
|
---|
| 6141 | $host =~ s/\s+$//;
|
---|
| 6142 | }
|
---|
[372] | 6143 |
|
---|
[644] | 6144 | $self->_printrec_tiny($zonefilehandle, $recid, 'y', \%recflags, $revzone,
|
---|
[559] | 6145 | $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp, $expires, $stampactive);
|
---|
[450] | 6146 |
|
---|
[523] | 6147 | $recflags{$recid} = 1;
|
---|
[368] | 6148 |
|
---|
[521] | 6149 | } # while ($recsth)
|
---|
| 6150 |
|
---|
[559] | 6151 | if ($self->{usecache}) {
|
---|
| 6152 | close ZONECACHE; # force the file to be written
|
---|
| 6153 | # catch obvious write errors that leave an empty temp file
|
---|
| 6154 | if (-s $tmpcache) {
|
---|
| 6155 | rename $tmpcache, $cachefile
|
---|
| 6156 | or die "Error overwriting cache file $cachefile with temporary file: $!\n";
|
---|
| 6157 | }
|
---|
[521] | 6158 | }
|
---|
| 6159 |
|
---|
| 6160 | } # if $changed or cache filesize is 0
|
---|
| 6161 |
|
---|
| 6162 | };
|
---|
| 6163 | if ($@) {
|
---|
[566] | 6164 | die "error writing ".($self->{usecache} ? 'new data for ' : '')."$revzone: $@\n";
|
---|
[521] | 6165 | # error! something borked, and we should be able to fall back on the old cache file
|
---|
| 6166 | # report the error, somehow.
|
---|
| 6167 | } else {
|
---|
[523] | 6168 | # mark zone as unmodified. Only do this if no errors, that way
|
---|
[521] | 6169 | # export failures should recover a little more automatically.
|
---|
[523] | 6170 | $zonesth->execute($revid);
|
---|
[368] | 6171 | }
|
---|
[521] | 6172 |
|
---|
[559] | 6173 | if ($self->{usecache}) {
|
---|
| 6174 | # We've already made as sure as we can that a cached zone file is "good",
|
---|
| 6175 | # although possibly stale/obsolete due to errors creating a new one.
|
---|
[566] | 6176 | eval {
|
---|
| 6177 | open CACHE, "<$cachefile" or die $!;
|
---|
| 6178 | print $datafile $_ or die "error copying cached $revzone to master file: $!" while <CACHE>;
|
---|
| 6179 | close CACHE;
|
---|
| 6180 | };
|
---|
| 6181 | die $@ if $@;
|
---|
[559] | 6182 | }
|
---|
| 6183 |
|
---|
[523] | 6184 | } # while ($revsth)
|
---|
[329] | 6185 |
|
---|
[576] | 6186 | $soasth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
[578] | 6187 | "FROM records WHERE domain_id=? AND type=6");
|
---|
[543] | 6188 | $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location,extract(epoch from stamp),expires,stampactive ".
|
---|
[576] | 6189 | "FROM records WHERE domain_id=? AND NOT type=6"); # Just exclude all types relating to rDNS
|
---|
[523] | 6190 | # "FROM records WHERE domain_id=? AND type < 65280"); # Just exclude all types relating to rDNS
|
---|
[576] | 6191 | my $domsth = $dbh->prepare("SELECT domain_id,domain,status,changed FROM domains WHERE status=1 ORDER BY domain_id");
|
---|
[523] | 6192 | $zonesth = $dbh->prepare("UPDATE domains SET changed='n' WHERE domain_id=?");
|
---|
| 6193 | $domsth->execute();
|
---|
| 6194 | while (my ($domid,$dom,$domstat,$changed) = $domsth->fetchrow_array) {
|
---|
[368] | 6195 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
| 6196 | # O_NOFOLLOW
|
---|
| 6197 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
| 6198 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
| 6199 | # still be followed.
|
---|
| 6200 | # but that doesn't help other platforms. :/
|
---|
[523] | 6201 | my $cachefile = "$self->{exportcache}/$dom";
|
---|
| 6202 | my $tmpcache = "$self->{exportcache}/tmp.$dom.$$";
|
---|
[521] | 6203 | eval {
|
---|
[344] | 6204 |
|
---|
[559] | 6205 | # write fresh records if:
|
---|
| 6206 | # - we are not using the cache
|
---|
| 6207 | # - force_refresh is set
|
---|
| 6208 | # - the zone has changed
|
---|
| 6209 | # - the cache file does not exist
|
---|
| 6210 | # - the cache file is empty
|
---|
[755] | 6211 | # - the zone contains ALIAS pseudorecords, which need to cascade changes from the upstream CNAME farm at every opportunity
|
---|
| 6212 | if ( ($dbh->selectrow_array("SELECT count(*) FROM records WHERE domain_id = ? AND type=65300", undef, $domid))[0] ) {
|
---|
| 6213 | $changed = 1; # abuse this flag for zones with ALIAS records
|
---|
| 6214 | }
|
---|
[559] | 6215 | if (!$self->{usecache} || $self->{force_refresh} || $changed || !-e $cachefile || -z $cachefile) {
|
---|
| 6216 | if ($self->{usecache}) {
|
---|
| 6217 | open ZONECACHE, ">$tmpcache" or die "Error creating temporary file $tmpcache: $!\n";
|
---|
| 6218 | $zonefilehandle = *ZONECACHE;
|
---|
| 6219 | }
|
---|
[329] | 6220 |
|
---|
[576] | 6221 | # need to fetch this separately so the SOA comes first in the flatfile....
|
---|
| 6222 | # Just In Case we need/want to reimport from the flatfile later on.
|
---|
| 6223 | $soasth->execute($domid);
|
---|
| 6224 | my (@zsoa) = $soasth->fetchrow_array();
|
---|
[644] | 6225 | $self->_printrec_tiny($zonefilehandle, $zsoa[7], 'n',\%recflags,$dom,
|
---|
[576] | 6226 | $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],'');
|
---|
| 6227 |
|
---|
[523] | 6228 | $recsth->execute($domid);
|
---|
[543] | 6229 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc,$stamp,$expires,$stampactive) = $recsth->fetchrow_array) {
|
---|
[523] | 6230 | next if $recflags{$recid};
|
---|
[521] | 6231 |
|
---|
[596] | 6232 | # Check for out-of-zone data
|
---|
[655] | 6233 | $host = $dom if $host eq '@';
|
---|
[663] | 6234 | if ($host !~ /$dom$/i) {
|
---|
[596] | 6235 | warn "Not exporting out-of-zone record $host $type $val, $ttl (zone $dom)\n";
|
---|
| 6236 | next;
|
---|
| 6237 | }
|
---|
| 6238 |
|
---|
[523] | 6239 | # Spaces are evil.
|
---|
| 6240 | $host =~ s/^\s+//;
|
---|
| 6241 | $host =~ s/\s+$//;
|
---|
| 6242 | if ($typemap{$type} ne 'TXT') {
|
---|
| 6243 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 6244 | $val =~ s/^\s+//;
|
---|
| 6245 | $val =~ s/\s+$//;
|
---|
| 6246 | }
|
---|
| 6247 |
|
---|
[644] | 6248 | $self->_printrec_tiny($zonefilehandle, $recid, 'n', \%recflags,
|
---|
[559] | 6249 | $dom, $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp, $expires, $stampactive);
|
---|
[329] | 6250 |
|
---|
[523] | 6251 | $recflags{$recid} = 1;
|
---|
[450] | 6252 |
|
---|
[521] | 6253 | } # while ($recsth)
|
---|
| 6254 |
|
---|
| 6255 |
|
---|
[559] | 6256 | if ($self->{usecache}) {
|
---|
| 6257 | close ZONECACHE; # force the file to be written
|
---|
| 6258 | # catch obvious write errors that leave an empty temp file
|
---|
| 6259 | if (-s $tmpcache) {
|
---|
| 6260 | rename $tmpcache, $cachefile
|
---|
| 6261 | or die "Error overwriting cache file $cachefile with temporary file: $!\n";
|
---|
| 6262 | }
|
---|
[521] | 6263 | }
|
---|
| 6264 |
|
---|
| 6265 | } # if $changed or cache filesize is 0
|
---|
| 6266 |
|
---|
| 6267 | };
|
---|
| 6268 | if ($@) {
|
---|
[566] | 6269 | die "error writing ".($self->{usecache} ? 'new data for ' : '')."$dom: $@\n";
|
---|
[521] | 6270 | # error! something borked, and we should be able to fall back on the old cache file
|
---|
| 6271 | # report the error, somehow.
|
---|
| 6272 | } else {
|
---|
[523] | 6273 | # mark domain as unmodified. Only do this if no errors, that way
|
---|
[521] | 6274 | # export failures should recover a little more automatically.
|
---|
[523] | 6275 | $zonesth->execute($domid);
|
---|
[368] | 6276 | }
|
---|
[521] | 6277 |
|
---|
[559] | 6278 | if ($self->{usecache}) {
|
---|
| 6279 | # We've already made as sure as we can that a cached zone file is "good",
|
---|
| 6280 | # although possibly stale/obsolete due to errors creating a new one.
|
---|
[566] | 6281 | eval {
|
---|
| 6282 | open CACHE, "<$cachefile" or die $!;
|
---|
| 6283 | print $datafile $_ or die "error copying cached $dom to master file: $!" while <CACHE>;
|
---|
| 6284 | close CACHE;
|
---|
| 6285 | };
|
---|
| 6286 | die $@ if $@;
|
---|
[559] | 6287 | }
|
---|
| 6288 |
|
---|
[329] | 6289 | } # while ($domsth)
|
---|
| 6290 |
|
---|
[566] | 6291 | return 1;
|
---|
[329] | 6292 | } # end __export_tiny()
|
---|
| 6293 |
|
---|
| 6294 |
|
---|
| 6295 | # Utility sub for __export_tiny above
|
---|
| 6296 | sub _printrec_tiny {
|
---|
[644] | 6297 | my $self = shift;
|
---|
[573] | 6298 | my ($datafile, $recid, $revrec, $recflags, $zone, $host, $type, $val, $dist, $weight, $port, $ttl,
|
---|
| 6299 | $loc, $stamp, $expires, $stampactive) = @_;
|
---|
[329] | 6300 |
|
---|
[543] | 6301 | $loc = '' if !$loc; # de-nullify - just in case
|
---|
| 6302 | ##fixme: handle case of record-with-location-that-doesn't-exist better.
|
---|
| 6303 | # note this currently fails safe (tested) - records with a location that
|
---|
| 6304 | # doesn't exist will not be sent to any client
|
---|
| 6305 | # $loc = '' if !$lochash->{$loc};
|
---|
| 6306 |
|
---|
| 6307 |
|
---|
| 6308 | ## Records that are valid only before or after a set time
|
---|
| 6309 |
|
---|
| 6310 | # record due to expire sometime is the complex case. we don't want to just
|
---|
| 6311 | # rely on tinydns' auto-adjusting TTLs, because the default TTL in that case
|
---|
| 6312 | # is one day instead of the SOA minttl as BIND might do.
|
---|
| 6313 |
|
---|
| 6314 | # consider the case where a record is set to expire a week ahead, but the next
|
---|
| 6315 | # day later you want to change it NOW (or as NOWish as you get with your DNS
|
---|
| 6316 | # management practice). but now you're stuck, because someone, somewhere,
|
---|
| 6317 | # has just done a lookup before your latest change was published, and they'll
|
---|
| 6318 | # be caching that old, broken record for 1 day instead of your zone default
|
---|
| 6319 | # TTL.
|
---|
| 6320 |
|
---|
| 6321 | # $stamp-$ttl is the *latest* we can publish the record with the defined TTL
|
---|
| 6322 | # to still have the expiry happen as scheduled, but we need to find some
|
---|
| 6323 | # *earlier* point. We can maybe guess, and 2x TTL is probably reasonable,
|
---|
| 6324 | # but we need info on the export frequency.
|
---|
| 6325 |
|
---|
| 6326 | # export the normal, non-expiring record up until $stamp-<guesstimate>, then
|
---|
| 6327 | # switch to exporting a record with the TAI64 stamp and a 0 TTL so tinydns
|
---|
| 6328 | # takes over TTL management.
|
---|
| 6329 |
|
---|
| 6330 | if ($stampactive) {
|
---|
| 6331 | if ($expires) {
|
---|
| 6332 | # record expires at $stamp; decide if we need to keep the TTL and ignore
|
---|
| 6333 | # the stamp for a time or if we need to change the TTL to 0 and convert
|
---|
| 6334 | # $stamp to TAI64 so tinydns can use $stamp to autoadjust the TTL on the fly.
|
---|
| 6335 | # extra hack, optimally needs more knowledge of data export frequency
|
---|
| 6336 | # smack the idiot customer who insists on 0 TTLs; they can suck up and
|
---|
| 6337 | # deal with a 10-minute TTL. especially on scheduled changes. note this
|
---|
| 6338 | # should be (export freq * 2), but we don't know the actual export frequency.
|
---|
| 6339 | $ttl = 300 if $ttl == 0; #hack phtui
|
---|
| 6340 | my $ahead = (86400 < $ttl*2 ? 86400 : $ttl*2);
|
---|
| 6341 | if ((time() + $ahead) < $stamp) {
|
---|
| 6342 | # more than 2x TTL OR more than one day (whichever is less) from expiry time; publish normal record
|
---|
| 6343 | $stamp = '';
|
---|
| 6344 | } else {
|
---|
| 6345 | # less than 2x TTL from expiry time, let tinydns take over TTL management and publish the TAI64 stamp.
|
---|
| 6346 | $ttl = 0;
|
---|
| 6347 | $stamp = unixtai64($stamp);
|
---|
| 6348 | $stamp =~ s/\@//;
|
---|
| 6349 | }
|
---|
| 6350 | } else {
|
---|
| 6351 | # record is "active after"; convert epoch from database to TAI64, publish, and collect $200.
|
---|
| 6352 | $stamp = unixtai64($stamp);
|
---|
| 6353 | $stamp =~ s/\@//;
|
---|
| 6354 | }
|
---|
| 6355 | } else {
|
---|
| 6356 | # flag for active timestamp is false; don't actually put a timestamp in the output
|
---|
| 6357 | $stamp = '';
|
---|
| 6358 | }
|
---|
| 6359 |
|
---|
| 6360 | # support tinydns' auto-TTL
|
---|
| 6361 | $ttl = '' if $ttl == -1;
|
---|
| 6362 | # these are WAY FREAKING HIGH - higher even than most TLD registry TTLs!
|
---|
| 6363 | # NS 259200 => 3d
|
---|
| 6364 | # all others 86400 => 1d
|
---|
| 6365 |
|
---|
[531] | 6366 | if ($revrec eq 'y') {
|
---|
| 6367 | $val = $zone if $val eq '@';
|
---|
| 6368 | } else {
|
---|
| 6369 | $host = $zone if $host eq '@';
|
---|
| 6370 | }
|
---|
| 6371 |
|
---|
[329] | 6372 | ## Convert a bare number into an octal-coded pair of octets.
|
---|
| 6373 | # Take optional arg to indicate a decimal or hex input. Defaults to hex.
|
---|
| 6374 | sub octalize {
|
---|
| 6375 | my $tmp = shift;
|
---|
| 6376 | my $srctype = shift || 'h'; # default assumes hex string
|
---|
| 6377 | $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
|
---|
| 6378 | $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
|
---|
| 6379 | my @o = ($tmp =~ /^(..)(..)$/); # split into octets
|
---|
[656] | 6380 | return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);
|
---|
[329] | 6381 | }
|
---|
| 6382 |
|
---|
[637] | 6383 | # Utility sub-sub for reverse records; with "any-record-in-any-zone"
|
---|
| 6384 | # we may need to do extra processing on $val to make it publishable.
|
---|
| 6385 | sub __revswap {
|
---|
| 6386 | my $host = shift;
|
---|
| 6387 | my $val = shift;
|
---|
| 6388 | return ($val, $host) if $val =~ /\.arpa/;
|
---|
| 6389 | $val = new NetAddr::IP $val;
|
---|
| 6390 | my $newval = _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 6391 | return ($newval, $host);
|
---|
| 6392 | }
|
---|
| 6393 |
|
---|
[339] | 6394 | ## WARNING: This works to export even the whole Internet's worth of IP space...
|
---|
| 6395 | ## if you have the disk/RAM to handle the dataset, and you call this sub based on /16-sized chunks
|
---|
| 6396 | ## A /16 took ~3 seconds with a handful of separate records; adding a /8 pushed export time out to ~13m:40s
|
---|
| 6397 | ## 0/0 is estimated to take ~54 hours and ~256G of disk
|
---|
| 6398 | ## RAM usage depends on how many non-template entries you have in the set.
|
---|
| 6399 | ## This should probably be done on record addition rather than export; large blocks may need to be done in a
|
---|
| 6400 | ## forked process
|
---|
| 6401 | sub __publish_subnet {
|
---|
[685] | 6402 | my $self = shift; # *sigh* need to pass in the DNSDB object so we can read a couple of options
|
---|
[339] | 6403 | my $sub = shift;
|
---|
| 6404 | my $recflags = shift;
|
---|
| 6405 | my $hpat = shift;
|
---|
| 6406 | my $fh = shift;
|
---|
| 6407 | my $ttl = shift;
|
---|
| 6408 | my $stamp = shift;
|
---|
| 6409 | my $loc = shift;
|
---|
[637] | 6410 | my $zone = new NetAddr::IP shift;
|
---|
[339] | 6411 | my $ptronly = shift || 0;
|
---|
| 6412 |
|
---|
[637] | 6413 | # do this conversion once, not (number-of-ips-in-subnet) times
|
---|
| 6414 | my $arpabase = _ZONE($zone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
| 6415 |
|
---|
[339] | 6416 | my $iplist = $sub->splitref(32);
|
---|
[685] | 6417 | my $ipindex = -1;
|
---|
[339] | 6418 | foreach (@$iplist) {
|
---|
| 6419 | my $ip = $_->addr;
|
---|
[685] | 6420 | $ipindex++;
|
---|
[339] | 6421 | # make as if we split the non-octet-aligned block into octet-aligned blocks as with SOA
|
---|
[637] | 6422 | my $lastoct = (split /\./, $ip)[3];
|
---|
[635] | 6423 | next if $$recflags{$ip}; # && $self->{skip_bcast_255}
|
---|
[339] | 6424 | $$recflags{$ip}++;
|
---|
[463] | 6425 | next if $hpat eq '%blank%'; # Allows blanking a subnet so no records are published.
|
---|
[339] | 6426 | my $rec = $hpat; # start fresh with the template for each IP
|
---|
[637] | 6427 | ##fixme: there really isn't a good way to handle sub-/24 zones here. This way at least
|
---|
[685] | 6428 | # seems less bad than some alternatives.
|
---|
| 6429 | $self->_template4_expand(\$rec, $ip, \$sub, $ipindex);
|
---|
| 6430 | # _template4_expand may blank $rec; if so, don't publish a record
|
---|
| 6431 | next if !$rec;
|
---|
[637] | 6432 | if ($ptronly || $zone->masklen > 24) {
|
---|
| 6433 | print $fh "^$lastoct.$arpabase:$rec:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6434 | if (!$ptronly) {
|
---|
| 6435 | # print a separate A record. Arguably we could use an = record here instead.
|
---|
| 6436 | print $fh "+$rec:$ip:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6437 | }
|
---|
| 6438 | } else {
|
---|
| 6439 | print $fh "=$rec:$ip:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6440 | }
|
---|
[339] | 6441 | }
|
---|
[679] | 6442 | } # __publish_subnet
|
---|
[339] | 6443 |
|
---|
[636] | 6444 | ## And now the meat.
|
---|
| 6445 |
|
---|
[103] | 6446 | ##fixme? append . to all host/val hostnames
|
---|
[637] | 6447 | #print "debug: rawdata: $host $typemap{$type} $val\n";
|
---|
[103] | 6448 |
|
---|
[636] | 6449 | if ($typemap{$type} eq 'SOA') {
|
---|
| 6450 | # host contains pri-ns:responsible
|
---|
| 6451 | # val is abused to contain refresh:retry:expire:minttl
|
---|
[103] | 6452 | ##fixme: "manual" serial vs tinydns-autoserial
|
---|
[636] | 6453 | # let's be explicit about abusing $host and $val
|
---|
| 6454 | my ($email, $primary) = (split /:/, $host)[0,1];
|
---|
| 6455 | my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
|
---|
| 6456 | if ($revrec eq 'y') {
|
---|
[337] | 6457 | ##fixme: have to publish SOA records for each v4 /24 in sub-/16, and each /16 in sub-/8
|
---|
| 6458 | # what about v6?
|
---|
| 6459 | # -> only need SOA for local chunks offset from reverse delegation boundaries, so v6 is fine
|
---|
[636] | 6460 | # anyone who says they need sub-nibble v6 delegations, at this time, needs their head examined.
|
---|
| 6461 | $zone = NetAddr::IP->new($zone);
|
---|
| 6462 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
| 6463 | if (!$zone->{isv6} && ($zone->masklen < 24) && ($zone->masklen % 8 != 0)) {
|
---|
| 6464 | foreach my $szone ($zone->split($zone->masklen + (8 - $zone->masklen % 8))) {
|
---|
| 6465 | $szone = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
| 6466 | print $datafile "Z$szone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n"
|
---|
| 6467 | or die $!;
|
---|
| 6468 | }
|
---|
| 6469 | return; # skips "default" bits just below
|
---|
| 6470 | }
|
---|
| 6471 | $zone = _ZONE($zone, 'ZONE', 'r', '.').($zone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 6472 | }
|
---|
| 6473 | print $datafile "Z$zone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n"
|
---|
| 6474 | or die $!;
|
---|
[103] | 6475 |
|
---|
[636] | 6476 | } elsif ($typemap{$type} eq 'A') {
|
---|
[103] | 6477 |
|
---|
[637] | 6478 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
[636] | 6479 | print $datafile "+$host:$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
[103] | 6480 |
|
---|
[636] | 6481 | } elsif ($typemap{$type} eq 'NS') {
|
---|
[103] | 6482 |
|
---|
[636] | 6483 | if ($revrec eq 'y') {
|
---|
| 6484 | $val = NetAddr::IP->new($val);
|
---|
| 6485 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
| 6486 | if (!$val->{isv6} && ($val->masklen < 24) && ($val->masklen % 8 != 0)) {
|
---|
| 6487 | foreach my $szone ($val->split($val->masklen + (8 - $val->masklen % 8))) {
|
---|
| 6488 | my $szone2 = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
| 6489 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
| 6490 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6491 | $$recflags{$szone2} = $val->masklen;
|
---|
| 6492 | }
|
---|
| 6493 | } elsif ($val->{isv6} && ($val->masklen < 64) && ($val->masklen % 4 !=0)) {
|
---|
| 6494 | foreach my $szone ($val->split($val->masklen + (4 - $val->masklen % 4))) {
|
---|
| 6495 | my $szone2 = _ZONE($szone, 'ZONE.ip6.arpa', 'r', '.');
|
---|
| 6496 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
| 6497 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6498 | $$recflags{$szone2} = $val->masklen;
|
---|
| 6499 | }
|
---|
| 6500 | } else {
|
---|
| 6501 | my $val2 = _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 6502 | print $datafile "\&$val2"."::$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6503 | $$recflags{$val2} = $val->masklen;
|
---|
| 6504 | }
|
---|
| 6505 | } else {
|
---|
| 6506 | print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6507 | }
|
---|
[103] | 6508 |
|
---|
[636] | 6509 | } elsif ($typemap{$type} eq 'AAAA') {
|
---|
[103] | 6510 |
|
---|
[637] | 6511 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
[636] | 6512 | my $altgrp = 0;
|
---|
| 6513 | my @altconv;
|
---|
| 6514 | # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
|
---|
| 6515 | foreach (split /:/, $val) {
|
---|
| 6516 | if (/^$/) {
|
---|
| 6517 | # flag blank entry; this is a series of 0's of (currently) unknown length
|
---|
| 6518 | $altconv[$altgrp++] = 's';
|
---|
| 6519 | } else {
|
---|
| 6520 | # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
|
---|
| 6521 | $altconv[$altgrp++] = octalize($_)
|
---|
| 6522 | }
|
---|
| 6523 | }
|
---|
| 6524 | my $prefix = ":$host:28:";
|
---|
| 6525 | foreach my $octet (@altconv) {
|
---|
| 6526 | # if not 's', output
|
---|
| 6527 | $prefix .= $octet unless $octet =~ /^s$/;
|
---|
| 6528 | # if 's', output (9-array length)x literal '\000\000'
|
---|
| 6529 | $prefix .= '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
|
---|
| 6530 | }
|
---|
| 6531 | print $datafile "$prefix:$ttl:$stamp:$loc\n" or die $!;
|
---|
[103] | 6532 |
|
---|
[636] | 6533 | } elsif ($typemap{$type} eq 'MX') {
|
---|
[103] | 6534 |
|
---|
[637] | 6535 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
[636] | 6536 | print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n" or die $!;
|
---|
[103] | 6537 |
|
---|
[636] | 6538 | } elsif ($typemap{$type} eq 'TXT') {
|
---|
[103] | 6539 |
|
---|
[637] | 6540 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
[703] | 6541 | # le sigh. Some idiot DNS implementations don't seem to like tinydns autosplitting
|
---|
| 6542 | # long TXT records at 127 characters instead of 255. Hand-crafting a record seems
|
---|
| 6543 | # to paper over the remote stupid. We will NOT try to split on whitespace; the
|
---|
| 6544 | # contents of a TXT record are opaque and clients who can't deal are even more broken
|
---|
| 6545 | # than the ones that don't like them split at 127 characters... because BIND tries
|
---|
| 6546 | # to "intelligently" split TXT data, and abso-by-damn-lutely generates chunks <255
|
---|
| 6547 | # characters, and anything that can't interpret BIND's DNS responses has no business
|
---|
| 6548 | # trying to interpret DNS data at all.
|
---|
[103] | 6549 |
|
---|
[708] | 6550 | if ($self->{autotxt}) {
|
---|
| 6551 | # let tinydns deal with splitting the record. note tinydns autosplits at 127
|
---|
| 6552 | # characters, not 255. Because Reasons.
|
---|
| 6553 | $val =~ s/:/\\072/g; # may need to replace other symbols
|
---|
| 6554 | print $datafile "'$host:$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6555 | } else {
|
---|
| 6556 | print $datafile ":$host:16:";
|
---|
| 6557 | my @txtsegs = $val =~ /.{1,255}/g;
|
---|
| 6558 | foreach (@txtsegs) {
|
---|
| 6559 | my $len = length($_);
|
---|
| 6560 | s/:/\\072/g;
|
---|
| 6561 | printf $datafile "\\%0.3o%s", $len, $_;
|
---|
| 6562 | }
|
---|
| 6563 | print $datafile ":$ttl:$stamp:$loc\n";
|
---|
[703] | 6564 | }
|
---|
| 6565 |
|
---|
[103] | 6566 | # by-hand TXT
|
---|
| 6567 | #:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
|
---|
| 6568 | #@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
|
---|
| 6569 | #'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
|
---|
| 6570 |
|
---|
| 6571 | #txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
|
---|
| 6572 | #: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
|
---|
| 6573 |
|
---|
| 6574 | # very long TXT record as brought in by axfr-get
|
---|
| 6575 | # note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
|
---|
| 6576 | # also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
|
---|
| 6577 | #:longtxt.deepnet.cx:16:
|
---|
| 6578 | #\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
|
---|
| 6579 | #\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.
|
---|
| 6580 | #\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.
|
---|
| 6581 | #:3600
|
---|
| 6582 |
|
---|
[636] | 6583 | } elsif ($typemap{$type} eq 'CNAME') {
|
---|
[103] | 6584 |
|
---|
[637] | 6585 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
| 6586 | print $datafile "C$host:$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
[103] | 6587 |
|
---|
[636] | 6588 | } elsif ($typemap{$type} eq 'SRV') {
|
---|
[103] | 6589 |
|
---|
[637] | 6590 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
| 6591 |
|
---|
[636] | 6592 | # data is two-byte values for priority, weight, port, in that order,
|
---|
| 6593 | # followed by length/string data
|
---|
[103] | 6594 |
|
---|
[637] | 6595 | my $prefix = ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
|
---|
[103] | 6596 |
|
---|
[636] | 6597 | $val .= '.' if $val !~ /\.$/;
|
---|
| 6598 | foreach (split /\./, $val) {
|
---|
[637] | 6599 | $prefix .= sprintf "\\%0.3o%s", length($_), $_ or die $!;
|
---|
[636] | 6600 | }
|
---|
[637] | 6601 | print $datafile "$prefix\\000:$ttl:$stamp:$loc\n" or die $!;
|
---|
[103] | 6602 |
|
---|
[636] | 6603 | } elsif ($typemap{$type} eq 'RP') {
|
---|
[103] | 6604 |
|
---|
[637] | 6605 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
[636] | 6606 | # RP consists of two mostly free-form strings.
|
---|
| 6607 | # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
|
---|
| 6608 | # The second is the "hostname" of a TXT record with more info.
|
---|
| 6609 | my $prefix = ":$host:17:";
|
---|
| 6610 | my ($who,$what) = split /\s/, $val;
|
---|
| 6611 | foreach (split /\./, $who) {
|
---|
| 6612 | $prefix .= sprintf "\\%0.3o%s", length($_), $_;
|
---|
| 6613 | }
|
---|
| 6614 | $prefix .= '\000';
|
---|
| 6615 | foreach (split /\./, $what) {
|
---|
| 6616 | $prefix .= sprintf "\\%0.3o%s", length($_), $_;
|
---|
| 6617 | }
|
---|
| 6618 | print $datafile "$prefix\\000:$ttl:$stamp:$loc\n" or die $!;
|
---|
[103] | 6619 |
|
---|
[636] | 6620 | } elsif ($typemap{$type} eq 'PTR') {
|
---|
[103] | 6621 |
|
---|
[636] | 6622 | $$recflags{$val}++;
|
---|
[637] | 6623 | if ($revrec eq 'y') {
|
---|
| 6624 |
|
---|
| 6625 | if ($val =~ /\.arpa$/) {
|
---|
| 6626 | # someone put in the formal .arpa name. humor them.
|
---|
| 6627 | print $datafile "^$val:$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6628 | } else {
|
---|
| 6629 | $zone = NetAddr::IP->new($zone);
|
---|
| 6630 | if (!$zone->{isv6} && $zone->masklen > 24) {
|
---|
| 6631 | # sub-octet v4 zone
|
---|
| 6632 | ($val) = ($val =~ /\.(\d+)$/);
|
---|
| 6633 | print $datafile "^$val."._ZONE($zone, 'ZONE', 'r', '.').'.in-addr.arpa'.
|
---|
| 6634 | ":$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6635 | } else {
|
---|
| 6636 | # not going to care about strange results if $val is not an IP value and is resolveable in DNS
|
---|
| 6637 | $val = NetAddr::IP->new($val);
|
---|
| 6638 | print $datafile "^".
|
---|
| 6639 | _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
| 6640 | ":$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6641 | }
|
---|
| 6642 | } # non-".arpa" $val
|
---|
| 6643 |
|
---|
[636] | 6644 | } else {
|
---|
[637] | 6645 | # PTRs in forward zones are less bizarre and insane than some other record types
|
---|
| 6646 | # in reverse zones... OTOH we can't validate them any which way, so we cross our
|
---|
| 6647 | # fingers and close our eyes and make it Someone Else's Problem.
|
---|
| 6648 | print $datafile "^$host:$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
[636] | 6649 | }
|
---|
[103] | 6650 |
|
---|
[636] | 6651 | } elsif ($type == 65280) { # A+PTR
|
---|
[334] | 6652 |
|
---|
[636] | 6653 | $$recflags{$val}++;
|
---|
| 6654 | print $datafile "=$host:$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
[334] | 6655 |
|
---|
[636] | 6656 | } elsif ($type == 65281) { # AAAA+PTR
|
---|
[333] | 6657 |
|
---|
[636] | 6658 | $$recflags{$val}++;
|
---|
| 6659 | # treat these as two separate records. since tinydns doesn't have
|
---|
| 6660 | # a native combined type, we have to create them separately anyway.
|
---|
| 6661 | # print both; a dangling record is harmless, and impossible via web
|
---|
| 6662 | # UI anyway
|
---|
[654] | 6663 | $self->_printrec_tiny($datafile,$recid,'n',$recflags, $self->domainName($self->_hostparent($host)),
|
---|
| 6664 | $host, 28, $val, $dist, $weight, $port, $ttl, $loc, $stamp);
|
---|
| 6665 | $self->_printrec_tiny($datafile, $recid, 'y', $recflags, $zone,
|
---|
| 6666 | $host, 12, $val, $dist, $weight, $port, $ttl, $loc, $stamp);
|
---|
| 6667 |
|
---|
[335] | 6668 | ##fixme: add a config flag to indicate use of the patch from http://www.fefe.de/dns/
|
---|
| 6669 | # type 6 is for AAAA+PTR, type 3 is for AAAA
|
---|
[333] | 6670 |
|
---|
[636] | 6671 | } elsif ($type == 65282) { # PTR template
|
---|
[335] | 6672 |
|
---|
[636] | 6673 | # only useful for v4 with standard DNS software, since this expands all
|
---|
| 6674 | # IPs in $zone (or possibly $val?) with autogenerated records
|
---|
| 6675 | $val = NetAddr::IP->new($val);
|
---|
| 6676 | return if $val->{isv6};
|
---|
[336] | 6677 |
|
---|
[636] | 6678 | if ($val->masklen <= 16) {
|
---|
| 6679 | foreach my $sub ($val->split(16)) {
|
---|
[644] | 6680 | $self->__publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, $zone, 1);
|
---|
[636] | 6681 | }
|
---|
| 6682 | } else {
|
---|
[644] | 6683 | $self->__publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, $zone, 1);
|
---|
[636] | 6684 | }
|
---|
[335] | 6685 |
|
---|
[636] | 6686 | } elsif ($type == 65283) { # A+PTR template
|
---|
[335] | 6687 |
|
---|
[636] | 6688 | $val = NetAddr::IP->new($val);
|
---|
| 6689 | # Just In Case. An A+PTR should be impossible to add to a v6 revzone via API.
|
---|
| 6690 | return if $val->{isv6};
|
---|
[339] | 6691 |
|
---|
[679] | 6692 | if ($val->masklen < 16) {
|
---|
[636] | 6693 | foreach my $sub ($val->split(16)) {
|
---|
[644] | 6694 | $self->__publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, $zone, 0);
|
---|
[636] | 6695 | }
|
---|
| 6696 | } else {
|
---|
[644] | 6697 | $self->__publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, $zone, 0);
|
---|
[636] | 6698 | }
|
---|
[335] | 6699 |
|
---|
[636] | 6700 | } elsif ($type == 65284) { # AAAA+PTR template
|
---|
| 6701 | # Stub for completeness. Could be exported to DNS software that supports
|
---|
| 6702 | # some degree of internal automagic in generic-record-creation
|
---|
| 6703 | # (eg http://search.cpan.org/dist/AllKnowingDNS/ )
|
---|
[333] | 6704 |
|
---|
[636] | 6705 | } elsif ($type == 65285) { # Delegation
|
---|
| 6706 | # This is intended for reverse zones, but may prove useful in forward zones.
|
---|
[345] | 6707 |
|
---|
[636] | 6708 | # All delegations need to create one or more NS records. The NS record handler knows what to do.
|
---|
[644] | 6709 | $self->_printrec_tiny($datafile,$recid,$revrec,$recflags,$zone,$host,$reverse_typemap{'NS'},
|
---|
[636] | 6710 | $val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
| 6711 | if ($revrec eq 'y') {
|
---|
| 6712 | # In the case of a sub-/24 v4 reverse delegation, we need to generate CNAMEs
|
---|
| 6713 | # to redirect all of the individual IP lookups as well.
|
---|
[637] | 6714 | # OR
|
---|
| 6715 | # create NS records for each IP
|
---|
[636] | 6716 | # Not sure how this would actually resolve if a /24 or larger was delegated
|
---|
| 6717 | # one way, and a sub-/24 in that >=/24 was delegated elsewhere...
|
---|
| 6718 | my $dblock = NetAddr::IP->new($val);
|
---|
| 6719 | if (!$dblock->{isv6} && $dblock->masklen > 24) {
|
---|
| 6720 | my @subs = $dblock->split;
|
---|
| 6721 | foreach (@subs) {
|
---|
| 6722 | next if $$recflags{"$_"};
|
---|
| 6723 | my ($oct) = ($_->addr =~ /(\d+)$/);
|
---|
| 6724 | print $datafile "C"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$oct.".
|
---|
| 6725 | _ZONE($dblock, 'ZONE.in-addr.arpa', 'r', '.').":$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6726 | $$recflags{"$_"}++;
|
---|
| 6727 | }
|
---|
| 6728 | }
|
---|
| 6729 | }
|
---|
[345] | 6730 |
|
---|
[750] | 6731 | } elsif ($type == 65300) { # ALIAS
|
---|
| 6732 | # Implemented as a unique record in parallel with many other
|
---|
| 6733 | # management tools, for clarity VS formal behviour around CNAME
|
---|
| 6734 | # Mainly for "root CNAME" or "apex alias"; limited value for any
|
---|
| 6735 | # other use case since CNAME can generally be used elsewhere.
|
---|
| 6736 |
|
---|
| 6737 | # .arpa zones don't need this hack. shouldn't be allowed into
|
---|
| 6738 | # the DB in the first place, but Just In Case...
|
---|
| 6739 | return if $revrec eq 'y';
|
---|
| 6740 |
|
---|
[752] | 6741 | my ($iplist) = $self->{dbh}->selectrow_array("SELECT auxdata FROM records WHERE record_id = ?", undef, $recid);
|
---|
[750] | 6742 | my $res = Net::DNS::Resolver->new;
|
---|
[752] | 6743 | my $reply = $res->query($val);
|
---|
[750] | 6744 |
|
---|
[752] | 6745 | if ($reply) {
|
---|
[750] | 6746 | my $liveips;
|
---|
| 6747 | my @newlist;
|
---|
| 6748 | foreach my $rr ($reply->answer) { #@alist) {
|
---|
| 6749 | next unless $rr->type eq "A";
|
---|
| 6750 | push @newlist, $rr->address;
|
---|
| 6751 | }
|
---|
| 6752 | # we don't need this to be perfectly correct IP address order, just consistent.
|
---|
| 6753 | $liveips = join(':', sort(@newlist));
|
---|
| 6754 | if ($iplist ne $liveips) {
|
---|
| 6755 | # update the cache of IPs from the target
|
---|
[752] | 6756 | $self->{dbh}->do("UPDATE records SET auxdata = ? WHERE record_id = ?", undef, $liveips, $recid);
|
---|
[750] | 6757 | $iplist = $liveips;
|
---|
| 6758 | }
|
---|
| 6759 | } else {
|
---|
[752] | 6760 | warn "Failure retrieving IP list for cache validation/update on ALIAS '$host -> $val': ", $res->errorstring, "\n";
|
---|
[750] | 6761 | }
|
---|
| 6762 |
|
---|
| 6763 | # output a plain old A record for each IP the target name really points to.
|
---|
| 6764 | foreach my $subip (split ':', $iplist) {
|
---|
[752] | 6765 | print "+$host:$subip:$ttl:$stamp:$loc\n" or die $!;
|
---|
[750] | 6766 | }
|
---|
| 6767 |
|
---|
[364] | 6768 | ##
|
---|
| 6769 | ## Uncommon types. These will need better UI support Any Day Sometime Maybe(TM).
|
---|
| 6770 | ##
|
---|
| 6771 |
|
---|
[636] | 6772 | } elsif ($type == 44) { # SSHFP
|
---|
[637] | 6773 |
|
---|
| 6774 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
| 6775 |
|
---|
[636] | 6776 | my ($algo,$fpt,$fp) = split /\s+/, $val;
|
---|
[364] | 6777 |
|
---|
[636] | 6778 | my $rec = sprintf ":$host:44:\\%0.3o\\%0.3o", $algo, $fpt;
|
---|
| 6779 | while (my ($byte) = ($fp =~ /^(..)/) ) {
|
---|
| 6780 | $rec .= sprintf "\\%0.3o", hex($byte);
|
---|
| 6781 | $fp =~ s/^..//;
|
---|
| 6782 | }
|
---|
| 6783 | print $datafile "$rec:$ttl:$stamp:$loc\n" or die $!;
|
---|
[364] | 6784 |
|
---|
[636] | 6785 | } else {
|
---|
| 6786 | # raw record. we don't know what's in here, so we ASS-U-ME the user has
|
---|
| 6787 | # put it in correctly, since either the user is messing directly with the
|
---|
| 6788 | # database, or the record was imported via AXFR
|
---|
| 6789 | # <split by char>
|
---|
| 6790 | # convert anything not a-zA-Z0-9.- to octal coding
|
---|
[108] | 6791 |
|
---|
| 6792 | ##fixme: add flag to export "unknown" record types - note we'll probably end up
|
---|
| 6793 | # mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
|
---|
[636] | 6794 | #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
|
---|
[108] | 6795 |
|
---|
[636] | 6796 | } # record type if-else
|
---|
[103] | 6797 |
|
---|
[329] | 6798 | } # end _printrec_tiny()
|
---|
[103] | 6799 |
|
---|
| 6800 |
|
---|
[197] | 6801 | ## DNSDB::mailNotify()
|
---|
[283] | 6802 | # Sends notification mail to recipients regarding a DNSDB operation
|
---|
[197] | 6803 | sub mailNotify {
|
---|
[483] | 6804 | my $self = shift;
|
---|
| 6805 | my $dbh = $self->{dbh};
|
---|
[197] | 6806 | my ($subj,$message) = @_;
|
---|
| 6807 |
|
---|
[517] | 6808 | return if $self->{mailhost} eq 'smtp.example.com'; # do nothing if still using default SMTP host.
|
---|
[197] | 6809 |
|
---|
[517] | 6810 | my $mailer = Net::SMTP->new($self->{mailhost}, Hello => "dnsadmin.$self->{domain}");
|
---|
[197] | 6811 |
|
---|
[517] | 6812 | my $mailsender = ($self->{mailsender} ? $self->{mailsender} : $self->{mailnotify});
|
---|
[197] | 6813 |
|
---|
| 6814 | $mailer->mail($mailsender);
|
---|
[517] | 6815 | $mailer->to($self->{mailnotify});
|
---|
| 6816 | $mailer->data("From: \"$self->{mailname}\" <$mailsender>\n",
|
---|
| 6817 | "To: <$self->{mailnotify}>\n",
|
---|
[197] | 6818 | "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
|
---|
| 6819 | "Subject: $subj\n",
|
---|
[529] | 6820 | "X-Mailer: DNSAdmin v".$DNSDB::VERSION." Notify\n",
|
---|
[517] | 6821 | "Organization: $self->{orgname}\n",
|
---|
[197] | 6822 | "\n$message\n");
|
---|
| 6823 | $mailer->quit;
|
---|
| 6824 | }
|
---|
| 6825 |
|
---|
[2] | 6826 | # shut Perl up
|
---|
| 6827 | 1;
|
---|