[2] | 1 | # dns/trunk/DNSDB.pm
|
---|
| 2 | # Abstraction functions for DNS administration
|
---|
[262] | 3 | ##
|
---|
| 4 | # $Id: DNSDB.pm 733 2016-06-23 20:52:59Z kdeugau $
|
---|
[496] | 5 | # Copyright 2008-2013 Kris Deugau <kdeugau@deepnet.cx>
|
---|
[262] | 6 | #
|
---|
| 7 | # This program is free software: you can redistribute it and/or modify
|
---|
| 8 | # it under the terms of the GNU General Public License as published by
|
---|
| 9 | # the Free Software Foundation, either version 3 of the License, or
|
---|
| 10 | # (at your option) any later version.
|
---|
| 11 | #
|
---|
| 12 | # This program is distributed in the hope that it will be useful,
|
---|
| 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
|
---|
| 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
---|
| 15 | # GNU General Public License for more details.
|
---|
| 16 | #
|
---|
| 17 | # You should have received a copy of the GNU General Public License
|
---|
| 18 | # along with this program. If not, see <http://www.gnu.org/licenses/>.
|
---|
| 19 | ##
|
---|
[2] | 20 |
|
---|
| 21 | package DNSDB;
|
---|
| 22 |
|
---|
| 23 | use strict;
|
---|
| 24 | use warnings;
|
---|
| 25 | use Exporter;
|
---|
| 26 | use DBI;
|
---|
[33] | 27 | use Net::DNS;
|
---|
[65] | 28 | use Crypt::PasswdMD5;
|
---|
[559] | 29 | use Digest::MD5 qw(md5_hex);
|
---|
[198] | 30 | use Net::SMTP;
|
---|
[539] | 31 | use NetAddr::IP 4.027 qw(:lower);
|
---|
[198] | 32 | use POSIX;
|
---|
[368] | 33 | use Fcntl qw(:flock);
|
---|
[543] | 34 | use Time::TAI64 qw(:tai64);
|
---|
[368] | 35 |
|
---|
[2] | 36 | use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
|
---|
| 37 |
|
---|
[561] | 38 | $VERSION = 1.3; ##VERSION##
|
---|
[2] | 39 | @ISA = qw(Exporter);
|
---|
| 40 | @EXPORT_OK = qw(
|
---|
[279] | 41 | &initGlobals &login &initActionLog
|
---|
[489] | 42 | &getPermissions &changePermissions &comparePermissions
|
---|
[112] | 43 | &changeGroup
|
---|
[517] | 44 | &connectDB &finish
|
---|
[276] | 45 | &addDomain &delZone &domainName &revName &domainID &revID &addRDNS
|
---|
[383] | 46 | &getZoneCount &getZoneList &getZoneLocation
|
---|
[22] | 47 | &addGroup &delGroup &getChildren &groupName
|
---|
[314] | 48 | &getGroupCount &getGroupList
|
---|
[83] | 49 | &addUser &updateUser &delUser &userFullName &userStatus &getUserData
|
---|
[326] | 50 | &getUserCount &getUserList &getUserDropdown
|
---|
[375] | 51 | &addLoc &updateLoc &delLoc &getLoc
|
---|
[370] | 52 | &getLocCount &getLocList &getLocDropdown
|
---|
[495] | 53 | &getSOA &updateSOA &getRecLine &getRecList &getRecCount
|
---|
[22] | 54 | &addRec &updateRec &delRec
|
---|
[323] | 55 | &getLogCount &getLogEntries
|
---|
[452] | 56 | &getRevPattern
|
---|
[225] | 57 | &getTypelist
|
---|
[254] | 58 | &parentID
|
---|
[117] | 59 | &isParent
|
---|
[452] | 60 | &zoneStatus &getZonesByCIDR &importAXFR
|
---|
[103] | 61 | &export
|
---|
[197] | 62 | &mailNotify
|
---|
[517] | 63 | %typemap %reverse_typemap
|
---|
[489] | 64 | @permtypes $permlist %permchains
|
---|
[2] | 65 | );
|
---|
| 66 |
|
---|
[489] | 67 | @EXPORT = qw(%typemap %reverse_typemap @permtypes $permlist %permchains);
|
---|
[2] | 68 | %EXPORT_TAGS = ( ALL => [qw(
|
---|
[279] | 69 | &initGlobals &login &initActionLog
|
---|
[489] | 70 | &getPermissions &changePermissions &comparePermissions
|
---|
[112] | 71 | &changeGroup
|
---|
[517] | 72 | &connectDB &finish
|
---|
[276] | 73 | &addDomain &delZone &domainName &revName &domainID &revID &addRDNS
|
---|
[383] | 74 | &getZoneCount &getZoneList &getZoneLocation
|
---|
[22] | 75 | &addGroup &delGroup &getChildren &groupName
|
---|
[314] | 76 | &getGroupCount &getGroupList
|
---|
[83] | 77 | &addUser &updateUser &delUser &userFullName &userStatus &getUserData
|
---|
[326] | 78 | &getUserCount &getUserList &getUserDropdown
|
---|
[375] | 79 | &addLoc &updateLoc &delLoc &getLoc
|
---|
[370] | 80 | &getLocCount &getLocList &getLocDropdown
|
---|
[495] | 81 | &getSOA &updateSOA &getRecLine &getRecList &getRecCount
|
---|
[22] | 82 | &addRec &updateRec &delRec
|
---|
[323] | 83 | &getLogCount &getLogEntries
|
---|
[452] | 84 | &getRevPattern
|
---|
[225] | 85 | &getTypelist
|
---|
[254] | 86 | &parentID
|
---|
[117] | 87 | &isParent
|
---|
[452] | 88 | &zoneStatus &getZonesByCIDR &importAXFR
|
---|
[103] | 89 | &export
|
---|
[197] | 90 | &mailNotify
|
---|
[517] | 91 | %typemap %reverse_typemap
|
---|
[489] | 92 | @permtypes $permlist %permchains
|
---|
[2] | 93 | )]
|
---|
| 94 | );
|
---|
| 95 |
|
---|
| 96 | our $errstr = '';
|
---|
[283] | 97 | our $resultstr = '';
|
---|
[2] | 98 |
|
---|
[66] | 99 | # Arguably defined wholly in the db, but little reason to change without supporting code changes
|
---|
[370] | 100 | # group_view, user_view permissions? separate rDNS permission(s)?
|
---|
[66] | 101 | our @permtypes = qw (
|
---|
| 102 | group_edit group_create group_delete
|
---|
| 103 | user_edit user_create user_delete
|
---|
| 104 | domain_edit domain_create domain_delete
|
---|
[387] | 105 | record_edit record_create record_delete record_locchg
|
---|
[370] | 106 | location_edit location_create location_delete location_view
|
---|
[66] | 107 | self_edit admin
|
---|
| 108 | );
|
---|
| 109 | our $permlist = join(',',@permtypes);
|
---|
| 110 |
|
---|
[390] | 111 | # Some permissions more or less require certain others.
|
---|
| 112 | our %permchains = (
|
---|
| 113 | user_edit => 'self_edit',
|
---|
| 114 | location_edit => 'location_view',
|
---|
| 115 | location_create => 'location_view',
|
---|
| 116 | location_delete => 'location_view',
|
---|
| 117 | record_locchg => 'location_view',
|
---|
| 118 | );
|
---|
| 119 |
|
---|
[2] | 120 | # DNS record type map and reverse map.
|
---|
| 121 | # loaded from the database, from http://www.iana.org/assignments/dns-parameters
|
---|
| 122 | our %typemap;
|
---|
| 123 | our %reverse_typemap;
|
---|
| 124 |
|
---|
[228] | 125 | ## (Semi)private variables
|
---|
[278] | 126 |
|
---|
[228] | 127 | # Hash of functions for validating record types. Filled in initGlobals() since
|
---|
| 128 | # it relies on visibility flags from the rectypes table in the DB
|
---|
| 129 | my %validators;
|
---|
[128] | 130 |
|
---|
[295] | 131 | # Entity-relationship reference hashes.
|
---|
| 132 | my %par_tbl = (
|
---|
| 133 | group => 'groups',
|
---|
| 134 | user => 'users',
|
---|
| 135 | defrec => 'default_records',
|
---|
| 136 | defrevrec => 'default_rev_records',
|
---|
| 137 | domain => 'domains',
|
---|
| 138 | revzone => 'revzones',
|
---|
| 139 | record => 'records'
|
---|
| 140 | );
|
---|
| 141 | my %id_col = (
|
---|
| 142 | group => 'group_id',
|
---|
| 143 | user => 'user_id',
|
---|
| 144 | defrec => 'record_id',
|
---|
| 145 | defrevrec => 'record_id',
|
---|
| 146 | domain => 'domain_id',
|
---|
| 147 | revzone => 'rdns_id',
|
---|
| 148 | record => 'record_id'
|
---|
| 149 | );
|
---|
| 150 | my %par_col = (
|
---|
| 151 | group => 'parent_group_id',
|
---|
| 152 | user => 'group_id',
|
---|
| 153 | defrec => 'group_id',
|
---|
| 154 | defrevrec => 'group_id',
|
---|
| 155 | domain => 'group_id',
|
---|
| 156 | revzone => 'group_id',
|
---|
| 157 | record => 'domain_id'
|
---|
| 158 | );
|
---|
| 159 | my %par_type = (
|
---|
| 160 | group => 'group',
|
---|
| 161 | user => 'group',
|
---|
| 162 | defrec => 'group',
|
---|
| 163 | defrevrec => 'group',
|
---|
| 164 | domain => 'group',
|
---|
| 165 | revzone => 'group',
|
---|
| 166 | record => 'domain'
|
---|
| 167 | );
|
---|
[278] | 168 |
|
---|
[2] | 169 | ##
|
---|
[465] | 170 | ## Constructor and destructor
|
---|
| 171 | ##
|
---|
| 172 |
|
---|
| 173 | sub new {
|
---|
| 174 | my $this = shift;
|
---|
| 175 | my $class = ref($this) || $this;
|
---|
| 176 | my %args = @_;
|
---|
[517] | 177 |
|
---|
| 178 | # Prepopulate a basic config. Note some of these *will* cause errors if left unset.
|
---|
| 179 | # note: add appropriate stanzas in __cfgload() to parse these
|
---|
| 180 | my %defconfig = (
|
---|
[529] | 181 | # The only configuration options not loadable from a config file.
|
---|
| 182 | configfile => "/etc/dnsdb/dnsdb.conf", ##CFG_LEAF##
|
---|
[517] | 183 |
|
---|
| 184 | # Database connection info
|
---|
| 185 | dbname => 'dnsdb',
|
---|
| 186 | dbuser => 'dnsdb',
|
---|
| 187 | dbpass => 'secret',
|
---|
| 188 | dbhost => '',
|
---|
| 189 |
|
---|
| 190 | # Email notice settings
|
---|
| 191 | mailhost => 'smtp.example.com',
|
---|
| 192 | mailnotify => 'dnsdb@example.com', # to
|
---|
| 193 | mailsender => 'dnsdb@example.com', # from
|
---|
| 194 | mailname => 'DNS Administration',
|
---|
| 195 | orgname => 'Example Corp',
|
---|
| 196 | domain => 'example.com',
|
---|
| 197 |
|
---|
| 198 | # Template directory
|
---|
| 199 | templatedir => 'templates/',
|
---|
| 200 | # fmeh. this is a real web path, not a logical internal one. hm..
|
---|
| 201 | # cssdir => 'templates/',
|
---|
| 202 | sessiondir => 'session/',
|
---|
| 203 | exportcache => 'cache/',
|
---|
[559] | 204 | usecache => 1, # do we bother using the cache above?
|
---|
[517] | 205 |
|
---|
| 206 | # Session params
|
---|
| 207 | timeout => '1h', # passed as-is to CGI::Session
|
---|
| 208 |
|
---|
| 209 | # Other miscellanea
|
---|
| 210 | log_failures => 1, # log all evarthing by default
|
---|
| 211 | perpage => 15,
|
---|
[559] | 212 | maxfcgi => 10, # reasonable default?
|
---|
[524] | 213 | force_refresh => 1,
|
---|
[542] | 214 | lowercase => 0, # mangle as little as possible by default
|
---|
[583] | 215 | # show IPs and CIDR blocks as-is for reverse zones. valid values are
|
---|
| 216 | # 'none' (default, show natural IP or CIDR)
|
---|
| 217 | # 'zone' (zone name, wherever used)
|
---|
| 218 | # 'record' (IP or CIDR values in reverse record lists)
|
---|
| 219 | # 'all' (all IP values in any reverse zone view)
|
---|
| 220 | showrev_arpa => 'none',
|
---|
[644] | 221 | # Two options for template record expansion:
|
---|
| 222 | template_skip_0 => 0, # publish .0 by default
|
---|
| 223 | template_skip_255 => 0, # publish .255 by default
|
---|
[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:
|
---|
| 458 | # domain_id, rdns_id
|
---|
[282] | 459 | # The %userdata hash provides the user ID, username, and fullname
|
---|
[281] | 460 | sub _log {
|
---|
[466] | 461 | my $self = shift;
|
---|
| 462 | my $dbh = $self->{dbh};
|
---|
[281] | 463 |
|
---|
| 464 | my %args = @_;
|
---|
| 465 |
|
---|
| 466 | $args{rdns_id} = 0 if !$args{rdns_id};
|
---|
| 467 | $args{domain_id} = 0 if !$args{domain_id};
|
---|
| 468 |
|
---|
| 469 | ##fixme: farm out the actual logging to different subs for file, syslog, internal, etc based on config
|
---|
[517] | 470 | # if ($self->{log_channel} eq 'sql') {
|
---|
[281] | 471 | $dbh->do("INSERT INTO log (domain_id,rdns_id,group_id,entry,user_id,email,name) VALUES (?,?,?,?,?,?,?)",
|
---|
| 472 | undef,
|
---|
| 473 | ($args{domain_id}, $args{rdns_id}, $args{group_id}, $args{entry},
|
---|
[488] | 474 | $self->{loguserid}, $self->{logusername}, $self->{logfullname}) );
|
---|
[517] | 475 | # } elsif ($self->{log_channel} eq 'file') {
|
---|
| 476 | # } elsif ($self->{log_channel} eq 'syslog') {
|
---|
[281] | 477 | # }
|
---|
| 478 | } # end _log
|
---|
| 479 |
|
---|
| 480 |
|
---|
[224] | 481 | ##
|
---|
[228] | 482 | ## Record validation subs.
|
---|
| 483 | ##
|
---|
| 484 |
|
---|
[281] | 485 | ## All of these subs take substantially the same arguments:
|
---|
| 486 | # a hash containing at least the following keys:
|
---|
| 487 | # - defrec (default/live flag)
|
---|
| 488 | # - revrec (forward/reverse flag)
|
---|
| 489 | # - id (parent entity ID)
|
---|
| 490 | # - host (hostname)
|
---|
| 491 | # - rectype
|
---|
| 492 | # - val (IP, hostname [CNAME/MX/SRV] or text)
|
---|
| 493 | # - addr (NetAddr::IP object from val. May be undef.)
|
---|
| 494 | # MX and SRV record validation also expect distance, and SRV records expect weight and port as well.
|
---|
| 495 | # host, rectype, and addr should be references as these may be modified in validation
|
---|
| 496 |
|
---|
[228] | 497 | # A record
|
---|
| 498 | sub _validate_1 {
|
---|
[467] | 499 | my $self = shift;
|
---|
| 500 | my $dbh = $self->{dbh};
|
---|
[229] | 501 |
|
---|
[230] | 502 | my %args = @_;
|
---|
[229] | 503 |
|
---|
[606] | 504 | # only for strict type restrictions
|
---|
| 505 | # return ('FAIL', 'Reverse zones cannot contain A records') if $args{revrec} eq 'y';
|
---|
[229] | 506 |
|
---|
[606] | 507 | if ($args{revrec} eq 'y') {
|
---|
| 508 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 509 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
[229] | 510 |
|
---|
[610] | 511 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
[606] | 512 |
|
---|
[611] | 513 | # ${$args{val}} is either a valid IP or a string ending with the .arpa zone name;
|
---|
| 514 | # now check if it's a well-formed FQDN
|
---|
[613] | 515 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
[612] | 516 | ${$args{val}} =~ /\.arpa$/;
|
---|
[611] | 517 |
|
---|
[606] | 518 | # Check IP is well-formed, and that it's a v4 address
|
---|
| 519 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
|
---|
| 520 | return ('FAIL',"A record must be a valid IPv4 address")
|
---|
[660] | 521 | unless ${$args{host}} =~ m{^\d+\.\d+\.\d+\.\d+(/\d+)?$};
|
---|
[606] | 522 | $args{addr} = new NetAddr::IP ${$args{host}};
|
---|
| 523 | return ('FAIL',"A record must be a valid IPv4 address")
|
---|
| 524 | unless $args{addr} && !$args{addr}->{isv6};
|
---|
| 525 | # coerce IP/value to normalized form for storage
|
---|
| 526 | ${$args{host}} = $args{addr}->addr;
|
---|
| 527 |
|
---|
| 528 | # I'm just going to ignore the utterly barmy idea of an A record in the *default*
|
---|
| 529 | # records for a reverse zone; it's bad enough to find one in funky legacy data.
|
---|
| 530 |
|
---|
| 531 | } else {
|
---|
| 532 | # revrec ne 'y'
|
---|
| 533 |
|
---|
| 534 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 535 | # or the intended parent domain for live records.
|
---|
| 536 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[657] | 537 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i);
|
---|
[606] | 538 |
|
---|
[620] | 539 | # Check if it's a proper formal .arpa name for an IP, and renormalize it to the IP
|
---|
| 540 | # value if so. Done mainly for symmetry with PTR/A+PTR, and saves a conversion on export.
|
---|
| 541 | if (${$args{val}} =~ /\.arpa$/) {
|
---|
| 542 | my ($code,$tmp) = _zone2cidr(${$args{val}});
|
---|
| 543 | if ($code ne 'FAIL') {
|
---|
| 544 | ${$args{val}} = $tmp->addr;
|
---|
| 545 | $args{addr} = $tmp;
|
---|
| 546 | }
|
---|
| 547 | }
|
---|
[606] | 548 | # Check IP is well-formed, and that it's a v4 address
|
---|
| 549 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
|
---|
| 550 | return ('FAIL',"A record must be a valid IPv4 address")
|
---|
[234] | 551 | unless ${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/;
|
---|
[629] | 552 | $args{addr} = new NetAddr::IP ${$args{val}};
|
---|
[606] | 553 | return ('FAIL',"A record must be a valid IPv4 address")
|
---|
[230] | 554 | unless $args{addr} && !$args{addr}->{isv6};
|
---|
[606] | 555 | # coerce IP/value to normalized form for storage
|
---|
| 556 | ${$args{val}} = $args{addr}->addr;
|
---|
| 557 | }
|
---|
[229] | 558 |
|
---|
[228] | 559 | return ('OK','OK');
|
---|
| 560 | } # done A record
|
---|
| 561 |
|
---|
| 562 | # NS record
|
---|
| 563 | sub _validate_2 {
|
---|
[467] | 564 | my $self = shift;
|
---|
| 565 | my $dbh = $self->{dbh};
|
---|
[230] | 566 |
|
---|
| 567 | my %args = @_;
|
---|
| 568 |
|
---|
[616] | 569 | # NS target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 570 | if ($args{revrec} eq 'y') {
|
---|
| 571 | return ('FAIL', "NS records cannot point directly to an IP address")
|
---|
| 572 | if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
| 573 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
| 574 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 575 | } else {
|
---|
| 576 | return ('FAIL', "NS records cannot point directly to an IP address")
|
---|
| 577 | if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
| 578 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
| 579 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 580 | }
|
---|
| 581 |
|
---|
[328] | 582 | # Check that the target of the record is within the parent.
|
---|
| 583 | if ($args{defrec} eq 'n') {
|
---|
| 584 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
| 585 | if ($args{revrec} eq 'y') {
|
---|
[616] | 586 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 587 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
| 588 |
|
---|
| 589 | # Note the NS record may or may not be for the zone itself, it may be a pointer for a subzone
|
---|
| 590 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
| 591 |
|
---|
| 592 | # ${$args{val}} is either a valid IP or a string ending with the .arpa zone name;
|
---|
| 593 | # now check if it's a well-formed FQDN
|
---|
| 594 | ##enhance or ##fixme
|
---|
| 595 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design
|
---|
| 596 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
| 597 | ${$args{val}} =~ /\.arpa$/;
|
---|
[328] | 598 | } else {
|
---|
[616] | 599 | # Forcibly append the domain name if the hostname being added does not end with the current domain name
|
---|
[467] | 600 | my $pname = $self->domainName($args{id});
|
---|
[657] | 601 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i);
|
---|
[328] | 602 | }
|
---|
[230] | 603 | } else {
|
---|
[616] | 604 | # Default reverse NS records should always refer to the implied parent.
|
---|
| 605 | if ($args{revrec} eq 'y') {
|
---|
| 606 | ${$args{val}} = 'ZONE';
|
---|
| 607 | } else {
|
---|
| 608 | ${$args{host}} = 'DOMAIN';
|
---|
| 609 | }
|
---|
[230] | 610 | }
|
---|
| 611 |
|
---|
[228] | 612 | return ('OK','OK');
|
---|
| 613 | } # done NS record
|
---|
| 614 |
|
---|
| 615 | # CNAME record
|
---|
| 616 | sub _validate_5 {
|
---|
[467] | 617 | my $self = shift;
|
---|
| 618 | my $dbh = $self->{dbh};
|
---|
[230] | 619 |
|
---|
| 620 | my %args = @_;
|
---|
| 621 |
|
---|
[618] | 622 | # CNAMEs in reverse zones shouldn't be handled manually, they should be generated on
|
---|
| 623 | # export by use of the "delegation" type. For the masochistic, and those importing
|
---|
| 624 | # legacy data from $deity-knows-where, we'll support them.
|
---|
[230] | 625 |
|
---|
[618] | 626 | if ($args{revrec} eq 'y') {
|
---|
| 627 | # CNAME target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 628 | return ('FAIL', "CNAME records cannot point directly to an IP address")
|
---|
| 629 | if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
[230] | 630 |
|
---|
[618] | 631 | if ($args{defrec} eq 'n') {
|
---|
| 632 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 633 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
| 634 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
[632] | 635 | # CNAMEs can not be used for parent nodes; just leaf nodes with no other record types
|
---|
| 636 | # note that this WILL probably miss some edge cases.
|
---|
| 637 | if (${$args{val}} =~ /^[\d.\/]+$/) {
|
---|
| 638 | # convert IP "hostname" to .arpa
|
---|
| 639 | my $tmphn = _ZONE(NetAddr::IP->new(${$args{val}}), 'ZONE', 'r', '.');
|
---|
| 640 | my $tmpz = _ZONE($revzone, 'ZONE', 'r', '.');
|
---|
| 641 | return ('FAIL', "The bare zone may not be a CNAME") if $tmphn eq $tmpz;
|
---|
[656] | 642 | ##enhance: look up the target name and publish that instead on export
|
---|
[632] | 643 | }
|
---|
[618] | 644 | }
|
---|
| 645 |
|
---|
| 646 | ##enhance or ##fixme
|
---|
| 647 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design
|
---|
| 648 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
| 649 | ${$args{val}} =~ /\.arpa$/;
|
---|
| 650 |
|
---|
| 651 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
| 652 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 653 | } else {
|
---|
| 654 | # CNAME target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 655 | return ('FAIL', "CNAME records cannot point directly to an IP address")
|
---|
| 656 | if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
| 657 |
|
---|
[669] | 658 | # Make sure target is a well-formed hostname
|
---|
| 659 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 660 |
|
---|
[618] | 661 | # Forcibly append the domain name if the hostname being added does not end with the current domain name
|
---|
| 662 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[657] | 663 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/i;
|
---|
[618] | 664 |
|
---|
[632] | 665 | # CNAMEs can not be used for parent nodes; just leaf nodes with no other record types
|
---|
| 666 | # Enforce this for the zone name
|
---|
[653] | 667 | return ('FAIL', "The bare zone name may not be a CNAME") if ${$args{host}} eq $pname || ${$args{host}} =~ /^\@/;
|
---|
[632] | 668 |
|
---|
[618] | 669 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
| 670 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 671 | }
|
---|
| 672 |
|
---|
[228] | 673 | return ('OK','OK');
|
---|
| 674 | } # done CNAME record
|
---|
| 675 |
|
---|
| 676 | # SOA record
|
---|
| 677 | sub _validate_6 {
|
---|
[230] | 678 | # Smart monkeys won't stick their fingers in here; we have
|
---|
| 679 | # separate dedicated routines to deal with SOA records.
|
---|
[228] | 680 | return ('OK','OK');
|
---|
| 681 | } # done SOA record
|
---|
| 682 |
|
---|
| 683 | # PTR record
|
---|
| 684 | sub _validate_12 {
|
---|
[467] | 685 | my $self = shift;
|
---|
| 686 | my $dbh = $self->{dbh};
|
---|
[232] | 687 |
|
---|
| 688 | my %args = @_;
|
---|
[620] | 689 | my $warnflag = '';
|
---|
[232] | 690 |
|
---|
[620] | 691 | if ($args{defrec} eq 'y') {
|
---|
| 692 | if ($args{revrec} eq 'y') {
|
---|
| 693 | if (${$args{val}} =~ /^[\d.]+$/) {
|
---|
| 694 | # v4 or bare number
|
---|
| 695 | if (${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/) {
|
---|
| 696 | # probable full IP. pointless but harmless. validate/normalize.
|
---|
| 697 | my $tmp = NetAddr::IP->new(${$args{val}})->addr
|
---|
| 698 | or return ('FAIL', "${$args{val}} is not a valid IP address");
|
---|
| 699 | ${$args{val}} = $tmp;
|
---|
| 700 | $warnflag = "${$args{val}} will only be added to a small number of zones\n";
|
---|
| 701 | } elsif (${$args{val}} =~ /^\d+$/) {
|
---|
| 702 | # bare number. This can be expanded to either a v4 or v6 zone
|
---|
| 703 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
| 704 | } else {
|
---|
| 705 | # $deity-only-knows what kind of gibberish we've been given. Only usable as a formal .arpa name.
|
---|
| 706 | # Append ARPAZONE to be replaced with the formal .arpa zone name when converted to a live record.
|
---|
| 707 | ${$args{val}} =~ s/\.*$/.ARPAZONE/ unless ${$args{val}} =~ /ARPAZONE$/;
|
---|
| 708 | }
|
---|
| 709 | } elsif (${$args{val}} =~ /^[a-fA-F0-9:]+$/) {
|
---|
| 710 | # v6 or fragment; pray it's not complete gibberish
|
---|
| 711 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
[234] | 712 | } else {
|
---|
[620] | 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}} .= ".ARPAZONE" unless ${$args{val}} =~ /ARPAZONE$/;
|
---|
[234] | 716 | }
|
---|
[620] | 717 | } else {
|
---|
| 718 | return ('FAIL', "PTR records are not supported in default record sets for forward zones (domains)");
|
---|
[232] | 719 | }
|
---|
[620] | 720 | } else {
|
---|
| 721 | if ($args{revrec} eq 'y') {
|
---|
| 722 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 723 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
[232] | 724 |
|
---|
[620] | 725 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
[249] | 726 |
|
---|
[620] | 727 | if (${$args{val}} =~ /\.arpa$/) {
|
---|
| 728 | # Check that it's well-formed
|
---|
| 729 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 730 |
|
---|
| 731 | # Check if it's a proper formal .arpa name for an IP, and renormalize it to the IP
|
---|
| 732 | # value if so. I can't see why someone would voluntarily work with those instead of
|
---|
| 733 | # the natural IP values but what the hey.
|
---|
| 734 | my ($code,$tmp) = _zone2cidr(${$args{val}});
|
---|
| 735 | ${$args{val}} = $tmp->addr if $code ne 'FAIL';
|
---|
[272] | 736 | } else {
|
---|
[620] | 737 | # not a formal .arpa name, so it should be an IP value. Validate...
|
---|
| 738 | return ('FAIL', "${$args{val}} is not a valid IP value")
|
---|
| 739 | unless ${$args{val}} =~ /^(?:\d+\.\d+\.\d+\.\d+|[a-fA-F0-9:]+)$/;
|
---|
| 740 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
| 741 | or return ('FAIL', "IP/value looks like an IP address but isn't valid");
|
---|
| 742 | # ... and normalize.
|
---|
| 743 | ${$args{val}} = $args{addr}->addr;
|
---|
[272] | 744 | }
|
---|
[620] | 745 | # Validate PTR target for form.
|
---|
[677] | 746 | # %blank% skips the IP when expanding a template record
|
---|
| 747 | return ('FAIL', $errstr)
|
---|
| 748 | unless _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) ||
|
---|
| 749 | lc(${$args{host}}) eq '%blank%';
|
---|
[620] | 750 | } else { # revrec ne 'y'
|
---|
| 751 | # Fetch the domain and append if the passed hostname isn't within it.
|
---|
| 752 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[657] | 753 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i);
|
---|
[620] | 754 | # Validate hostname and target for form
|
---|
| 755 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 756 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
[249] | 757 | }
|
---|
[620] | 758 | }
|
---|
[272] | 759 |
|
---|
[620] | 760 | # Multiple PTR records do NOT generally do what most people believe they do,
|
---|
| 761 | # and tend to fail in the most awkward way possible. Check and warn.
|
---|
| 762 |
|
---|
| 763 | my $chkbase = ${$args{val}};;
|
---|
| 764 | my $hostcol = 'val'; # Reverse zone hostnames are stored "backwards"
|
---|
| 765 | if ($args{revrec} eq 'n') { # PTRs in forward zones should be rare.
|
---|
| 766 | $chkbase = ${$args{host}};
|
---|
| 767 | $hostcol = 'host';
|
---|
[232] | 768 | }
|
---|
[620] | 769 | my @checkvals = ($chkbase);
|
---|
| 770 | if ($chkbase =~ /,/) {
|
---|
| 771 | # push . and :: variants into checkvals if $chkbase has ,
|
---|
| 772 | my $tmp;
|
---|
| 773 | ($tmp = $chkbase) =~ s/,/./;
|
---|
| 774 | push @checkvals, $tmp;
|
---|
| 775 | ($tmp = $chkbase) =~ s/,/::/;
|
---|
| 776 | push @checkvals, $tmp;
|
---|
| 777 | }
|
---|
[232] | 778 |
|
---|
[620] | 779 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE $hostcol = ?");
|
---|
| 780 | foreach my $checkme (@checkvals) {
|
---|
| 781 | if ($args{update}) {
|
---|
| 782 | # $args{update} contains the ID of the record being updated. If the list of records that matches
|
---|
| 783 | # the new hostname specification doesn't include this, the change effectively adds a new PTR that's
|
---|
| 784 | # the same as one or more existing ones.
|
---|
| 785 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 786 | " WHERE val = ?", undef, ($checkme)) };
|
---|
| 787 | $warnflag .= "PTR record for $checkme already exists; adding another will probably not do what you want"
|
---|
| 788 | if @ptrs && (!grep /^$args{update}$/, @ptrs);
|
---|
| 789 | } else {
|
---|
| 790 | # New record. Always warn if a PTR exists
|
---|
[661] | 791 | # Don't warn when a matching A record exists tho
|
---|
[620] | 792 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
[661] | 793 | " WHERE $hostcol = ? AND (type=12 OR type=65280 OR type=65281)", undef, ($checkme));
|
---|
[620] | 794 | $warnflag .= "PTR record for $checkme already exists; adding another will probably not do what you want"
|
---|
| 795 | if $ptrcount;
|
---|
| 796 | }
|
---|
| 797 | }
|
---|
| 798 |
|
---|
| 799 | return ('WARN',$warnflag) if $warnflag;
|
---|
| 800 |
|
---|
[228] | 801 | return ('OK','OK');
|
---|
| 802 | } # done PTR record
|
---|
| 803 |
|
---|
| 804 | # MX record
|
---|
| 805 | sub _validate_15 {
|
---|
[467] | 806 | my $self = shift;
|
---|
| 807 | my $dbh = $self->{dbh};
|
---|
[230] | 808 |
|
---|
| 809 | my %args = @_;
|
---|
| 810 |
|
---|
[622] | 811 | # only for strict type restrictions
|
---|
| 812 | # return ('FAIL', 'Reverse zones cannot contain MX records') if $args{revrec} eq 'y';
|
---|
[230] | 813 |
|
---|
| 814 | return ('FAIL', "Distance is required for MX records") unless defined(${$args{dist}});
|
---|
| 815 | ${$args{dist}} =~ s/\s*//g;
|
---|
| 816 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
|
---|
| 817 |
|
---|
| 818 | ${$args{fields}} = "distance,";
|
---|
| 819 | push @{$args{vallist}}, ${$args{dist}};
|
---|
| 820 |
|
---|
[622] | 821 | if ($args{revrec} eq 'n') {
|
---|
| 822 | # MX target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 823 | return ('FAIL', "MX records cannot point directly to an IP address")
|
---|
| 824 | if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
[230] | 825 |
|
---|
[622] | 826 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 827 | # or the intended parent domain for live records.
|
---|
| 828 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[657] | 829 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i);
|
---|
[653] | 830 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
[622] | 831 | } else {
|
---|
| 832 | # MX target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 833 | return ('FAIL', "MX records cannot point directly to an IP address")
|
---|
[627] | 834 | if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
[273] | 835 |
|
---|
[622] | 836 | # MX records in reverse zones get stricter treatment. The UI bars adding them in
|
---|
| 837 | # reverse record sets, but we "need" to allow editing existing ones. And we'll allow
|
---|
| 838 | # editing them if some loon manually munges one into a default reverse record set.
|
---|
| 839 | if ($args{defrec} eq 'n') {
|
---|
| 840 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 841 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
| 842 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
| 843 | }
|
---|
| 844 |
|
---|
| 845 | ##enhance or ##fixme
|
---|
| 846 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design
|
---|
| 847 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
| 848 | ${$args{val}} =~ /\.arpa$/;
|
---|
| 849 |
|
---|
| 850 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
| 851 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 852 |
|
---|
| 853 | }
|
---|
| 854 |
|
---|
[228] | 855 | return ('OK','OK');
|
---|
| 856 | } # done MX record
|
---|
| 857 |
|
---|
| 858 | # TXT record
|
---|
| 859 | sub _validate_16 {
|
---|
[586] | 860 | my $self = shift;
|
---|
| 861 |
|
---|
| 862 | my %args = @_;
|
---|
| 863 |
|
---|
[623] | 864 | if ($args{revrec} eq 'n') {
|
---|
[586] | 865 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 866 | # or the intended parent domain for live records.
|
---|
| 867 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[657] | 868 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i);
|
---|
[623] | 869 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 870 | } else {
|
---|
| 871 | # We don't coerce reverse "hostnames" into the zone, mainly because we store most sane
|
---|
| 872 | # records as IP values, not .arpa names.
|
---|
| 873 | if ($args{defrec} eq 'n') {
|
---|
| 874 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 875 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
| 876 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
| 877 | }
|
---|
| 878 |
|
---|
| 879 | ##enhance or ##fixme
|
---|
| 880 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design
|
---|
| 881 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
| 882 | ${$args{val}} =~ /\.arpa$/;
|
---|
[586] | 883 | }
|
---|
| 884 |
|
---|
[231] | 885 | # Could arguably put a WARN return here on very long (>512) records
|
---|
[228] | 886 | return ('OK','OK');
|
---|
| 887 | } # done TXT record
|
---|
| 888 |
|
---|
| 889 | # RP record
|
---|
| 890 | sub _validate_17 {
|
---|
[623] | 891 | # Probably have to validate these separately some day. Call _validate_16() above since
|
---|
| 892 | # they're otherwise very similar
|
---|
| 893 | return _validate_16(@_);
|
---|
[228] | 894 | } # done RP record
|
---|
| 895 |
|
---|
| 896 | # AAAA record
|
---|
[626] | 897 | # Almost but not quite an exact duplicate of A record
|
---|
[228] | 898 | sub _validate_28 {
|
---|
[467] | 899 | my $self = shift;
|
---|
| 900 | my $dbh = $self->{dbh};
|
---|
[229] | 901 |
|
---|
[230] | 902 | my %args = @_;
|
---|
[229] | 903 |
|
---|
[626] | 904 | # only for strict type restrictions
|
---|
| 905 | # return ('FAIL', 'Reverse zones cannot contain AAAA records') if $args{revrec} eq 'y';
|
---|
[229] | 906 |
|
---|
[626] | 907 | if ($args{revrec} eq 'y') {
|
---|
| 908 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 909 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
[229] | 910 |
|
---|
[626] | 911 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
| 912 |
|
---|
| 913 | # ${$args{val}} is either a valid IP or a string ending with the .arpa zone name;
|
---|
| 914 | # now check if it's a well-formed FQDN
|
---|
| 915 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
| 916 | ${$args{val}} =~ /\.arpa$/;
|
---|
| 917 |
|
---|
| 918 | # Check IP is well-formed, and that it's a v4 address
|
---|
| 919 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
|
---|
| 920 | return ('FAIL',"AAAA record must be a valid IPv6 address")
|
---|
| 921 | unless ${$args{host}} =~ /^[a-fA-F0-9:]+$/;
|
---|
| 922 | $args{addr} = new NetAddr::IP ${$args{host}};
|
---|
| 923 | return ('FAIL',"AAAA record must be a valid IPv6 address")
|
---|
[230] | 924 | unless $args{addr} && $args{addr}->{isv6};
|
---|
[626] | 925 | # coerce IP/value to normalized form for storage
|
---|
| 926 | ${$args{host}} = $args{addr}->addr;
|
---|
[229] | 927 |
|
---|
[626] | 928 | # I'm just going to ignore the utterly barmy idea of an AAAA record in the *default*
|
---|
| 929 | # records for a reverse zone; it's bad enough to find one in funky legacy data.
|
---|
| 930 |
|
---|
| 931 | } else {
|
---|
| 932 | # revrec ne 'y'
|
---|
| 933 |
|
---|
| 934 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 935 | # or the intended parent domain for live records.
|
---|
| 936 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[657] | 937 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i);
|
---|
[626] | 938 |
|
---|
| 939 | # Check if it's a proper formal .arpa name for an IP, and renormalize it to the IP
|
---|
| 940 | # value if so. Done mainly for symmetry with PTR/AAAA+PTR, and saves a conversion on export.
|
---|
| 941 | if (${$args{val}} =~ /\.arpa$/) {
|
---|
| 942 | my ($code,$tmp) = _zone2cidr(${$args{val}});
|
---|
| 943 | if ($code ne 'FAIL') {
|
---|
| 944 | ${$args{val}} = $tmp->addr;
|
---|
| 945 | $args{addr} = $tmp;
|
---|
| 946 | }
|
---|
| 947 | }
|
---|
| 948 | # Check IP is well-formed, and that it's a v6 address
|
---|
| 949 | return ('FAIL',"AAAA record must be a valid IPv6 address")
|
---|
| 950 | unless ${$args{val}} =~ /^[a-fA-F0-9:]+$/;
|
---|
| 951 | $args{addr} = new NetAddr::IP ${$args{val}};
|
---|
| 952 | return ('FAIL',"AAAA record must be a valid IPv6 address")
|
---|
| 953 | unless $args{addr} && $args{addr}->{isv6};
|
---|
| 954 | # coerce IP/value to normalized form for storage
|
---|
| 955 | ${$args{val}} = $args{addr}->addr;
|
---|
| 956 | }
|
---|
| 957 |
|
---|
[228] | 958 | return ('OK','OK');
|
---|
| 959 | } # done AAAA record
|
---|
| 960 |
|
---|
| 961 | # SRV record
|
---|
| 962 | sub _validate_33 {
|
---|
[467] | 963 | my $self = shift;
|
---|
| 964 | my $dbh = $self->{dbh};
|
---|
[231] | 965 |
|
---|
| 966 | my %args = @_;
|
---|
| 967 |
|
---|
| 968 | # Not absolutely true but WTF use is an SRV record for a reverse zone?
|
---|
[656] | 969 | # return ('FAIL', 'Reverse zones cannot contain SRV records') if $args{revrec} eq 'y';
|
---|
[231] | 970 |
|
---|
[627] | 971 | # Key additional record parts. Always required.
|
---|
| 972 | return ('FAIL',"Distance, port and weight are required for SRV records")
|
---|
| 973 | unless defined(${$args{weight}}) && defined(${$args{port}}) && defined(${$args{dist}});
|
---|
[231] | 974 | ${$args{dist}} =~ s/\s*//g;
|
---|
| 975 | ${$args{weight}} =~ s/\s*//g;
|
---|
| 976 | ${$args{port}} =~ s/\s*//g;
|
---|
[627] | 977 | return ('FAIL',"Distance, port and weight are required, and must be numeric")
|
---|
[231] | 978 | unless ${$args{weight}} =~ /^\d+$/ && ${$args{port}} =~ /^\d+$/;
|
---|
| 979 |
|
---|
| 980 | ${$args{fields}} = "distance,weight,port,";
|
---|
| 981 | push @{$args{vallist}}, (${$args{dist}}, ${$args{weight}}, ${$args{port}});
|
---|
| 982 |
|
---|
[627] | 983 | if ($args{revrec} eq 'n') {
|
---|
| 984 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 985 | # or the intended parent domain for live records.
|
---|
| 986 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[657] | 987 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/i;
|
---|
[627] | 988 |
|
---|
[631] | 989 | ##enhance: Rejig so that we can pass back a WARN red flag, instead of
|
---|
| 990 | # hard-failing, since it seems that purely from the DNS record perspective,
|
---|
| 991 | # SRV records without underscores are syntactically valid
|
---|
[627] | 992 | # Not strictly true, but SRV records not following this convention won't be found.
|
---|
| 993 | return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]")
|
---|
[698] | 994 | unless ${$args{host}} =~ /^_[A-Za-z-]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/;
|
---|
[627] | 995 |
|
---|
| 996 | # SRV target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 997 | return ('FAIL', "SRV records cannot point directly to an IP address")
|
---|
| 998 | if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
| 999 | } else {
|
---|
| 1000 | # hm. we can't do anything sane with IP values here; part of the record data is in
|
---|
| 1001 | # fact encoded in the "hostname". enforce .arpa names? OTOH, SRV records in a reverse
|
---|
| 1002 | # zone are pretty silly.
|
---|
| 1003 |
|
---|
[631] | 1004 | ##enhance: Rejig so that we can pass back a WARN red flag, instead of
|
---|
| 1005 | # hard-failing, since it seems that purely from the DNS record perspective,
|
---|
| 1006 | # SRV records without underscores are syntactically valid
|
---|
[627] | 1007 | # Not strictly true, but SRV records not following this convention won't be found.
|
---|
| 1008 | return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]")
|
---|
| 1009 | unless ${$args{val}} =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/;
|
---|
| 1010 |
|
---|
| 1011 | # SRV target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 1012 | return ('FAIL', "SRV records cannot point directly to an IP address")
|
---|
| 1013 | if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
| 1014 |
|
---|
| 1015 | # SRV records in reverse zones get stricter treatment. The UI bars adding them in
|
---|
| 1016 | # reverse record sets, but we "need" to allow editing existing ones. And we'll allow
|
---|
| 1017 | # editing them if some loon manually munges one into a default reverse record set.
|
---|
| 1018 | if ($args{defrec} eq 'n') {
|
---|
| 1019 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 1020 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
| 1021 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
| 1022 | }
|
---|
| 1023 |
|
---|
| 1024 | ##enhance or ##fixme
|
---|
| 1025 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design
|
---|
| 1026 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
| 1027 | ${$args{val}} =~ /\.arpa$/;
|
---|
| 1028 |
|
---|
| 1029 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
| 1030 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 1031 |
|
---|
| 1032 | }
|
---|
| 1033 |
|
---|
[228] | 1034 | return ('OK','OK');
|
---|
| 1035 | } # done SRV record
|
---|
| 1036 |
|
---|
| 1037 | # Now the custom types
|
---|
| 1038 |
|
---|
[232] | 1039 | # A+PTR record. With a very little bit of magic we can also use this sub to validate AAAA+PTR. Whee!
|
---|
[228] | 1040 | sub _validate_65280 {
|
---|
[467] | 1041 | my $self = shift;
|
---|
| 1042 | my $dbh = $self->{dbh};
|
---|
[232] | 1043 |
|
---|
| 1044 | my %args = @_;
|
---|
| 1045 |
|
---|
| 1046 | my $code = 'OK';
|
---|
| 1047 | my $msg = 'OK';
|
---|
| 1048 |
|
---|
| 1049 | if ($args{defrec} eq 'n') {
|
---|
| 1050 | # live record; revrec determines whether we validate the PTR or A component first.
|
---|
[233] | 1051 |
|
---|
[630] | 1052 | # Fail early on non-IP gibberish in ${$args{val}}. Arguably .arpa names might be acceptable
|
---|
| 1053 | # but that gets stupid in forward zones, since these records are shared.
|
---|
| 1054 | return ('FAIL', "$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
[660] | 1055 | if ${$args{rectype}} == 65280 && ${$args{val}} !~ m{^\d+\.\d+\.\d+\.\d+(?:/\d+)?$};
|
---|
[630] | 1056 | return ('FAIL', "$typemap{${$args{rectype}}} record must be a valid IPv6 address")
|
---|
[660] | 1057 | if ${$args{rectype}} == 65281 && ${$args{val}} !~ m{^[a-fA-F0-9:]+(?:/\d+)?$};
|
---|
[630] | 1058 | # If things are not OK, this should prevent Stupid in the error log.
|
---|
| 1059 | $args{addr} = new NetAddr::IP ${$args{val}}
|
---|
| 1060 | or return ('FAIL', "$typemap{${$args{rectype}}} record must be a valid IPv".
|
---|
| 1061 | (${$args{rectype}} == 65280 ? '4' : '6')." address");
|
---|
| 1062 | ${$args{val}} = $args{addr}->addr;
|
---|
| 1063 |
|
---|
[232] | 1064 | if ($args{revrec} eq 'y') {
|
---|
[467] | 1065 | ($code,$msg) = $self->_validate_12(%args);
|
---|
[232] | 1066 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 1067 |
|
---|
[467] | 1068 | # check A+PTR is really v4
|
---|
| 1069 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
| 1070 | if ${$args{rectype}} == 65280 && $args{addr}->{isv6};
|
---|
| 1071 | # check AAAA+PTR is really v6
|
---|
| 1072 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
|
---|
| 1073 | if ${$args{rectype}} == 65281 && !$args{addr}->{isv6};
|
---|
| 1074 |
|
---|
[232] | 1075 | # Check if the reqested domain exists. If not, coerce the type down to PTR and warn.
|
---|
[467] | 1076 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) {
|
---|
[272] | 1077 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
| 1078 | " as PTR instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
[232] | 1079 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
| 1080 | $msg = $addmsg if $code eq 'OK';
|
---|
| 1081 | ${$args{rectype}} = $reverse_typemap{PTR};
|
---|
| 1082 | return ('WARN', $msg);
|
---|
| 1083 | }
|
---|
| 1084 |
|
---|
[242] | 1085 | # Add domain ID to field list and values
|
---|
| 1086 | ${$args{fields}} .= "domain_id,";
|
---|
| 1087 | push @{$args{vallist}}, ${$args{domid}};
|
---|
| 1088 |
|
---|
[232] | 1089 | } else {
|
---|
[467] | 1090 | ($code,$msg) = $self->_validate_1(%args) if ${$args{rectype}} == 65280;
|
---|
| 1091 | ($code,$msg) = $self->_validate_28(%args) if ${$args{rectype}} == 65281;
|
---|
[232] | 1092 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 1093 |
|
---|
| 1094 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
| 1095 | # work here since we don't *know* which parent to put it in.
|
---|
[233] | 1096 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
[232] | 1097 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
| 1098 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
| 1099 | if (!$revid) {
|
---|
[272] | 1100 | $msg = "Record ".($args{update} ? 'updated' : 'added')." as ".(${$args{rectype}} == 65280 ? 'A' : 'AAAA').
|
---|
[232] | 1101 | " instead of $typemap{${$args{rectype}}}; reverse zone not found for ${$args{val}}";
|
---|
| 1102 | ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
| 1103 | return ('WARN', $msg);
|
---|
| 1104 | }
|
---|
| 1105 |
|
---|
| 1106 | # Check for duplicate PTRs. Note we don't have to play games with $code and $msg, because
|
---|
| 1107 | # by definition there can't be duplicate PTRs if the reverse zone isn't managed here.
|
---|
[272] | 1108 | if ($args{update}) {
|
---|
| 1109 | # Record update. There should usually be an existing PTR (the record being updated)
|
---|
| 1110 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 1111 | " WHERE val = ?", undef, (${$args{val}})) };
|
---|
[273] | 1112 | if (@ptrs && (!grep /^$args{update}$/, @ptrs)) {
|
---|
[272] | 1113 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
|
---|
| 1114 | $code = 'WARN';
|
---|
| 1115 | }
|
---|
| 1116 | } else {
|
---|
| 1117 | # New record. Always warn if a PTR exists
|
---|
| 1118 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 1119 | " WHERE val = ?", undef, (${$args{val}}));
|
---|
| 1120 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want"
|
---|
| 1121 | if $ptrcount;
|
---|
| 1122 | $code = 'WARN' if $ptrcount;
|
---|
[232] | 1123 | }
|
---|
| 1124 |
|
---|
[630] | 1125 | # Add the reverse zone ID to the fieldlist
|
---|
[232] | 1126 | ${$args{fields}} .= "rdns_id,";
|
---|
| 1127 | push @{$args{vallist}}, $revid;
|
---|
| 1128 |
|
---|
[653] | 1129 | # Coerce the hostname back to the domain; this is so it displays and manipulates
|
---|
| 1130 | # sanely in the reverse zone.
|
---|
| 1131 | if (${$args{host}} eq '@') {
|
---|
| 1132 | ${$args{host}} = $self->domainName($args{id}); # errors? What errors?
|
---|
| 1133 | }
|
---|
| 1134 | } # revrec ne 'y'
|
---|
| 1135 |
|
---|
[233] | 1136 | } else { # defrec eq 'y'
|
---|
[630] | 1137 |
|
---|
[233] | 1138 | if ($args{revrec} eq 'y') {
|
---|
[467] | 1139 | ($code,$msg) = $self->_validate_12(%args);
|
---|
[233] | 1140 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 1141 | if (${$args{rectype}} == 65280) {
|
---|
| 1142 | return ('FAIL',"A+PTR record must be a valid IPv4 address or fragment")
|
---|
| 1143 | if ${$args{val}} =~ /:/;
|
---|
[234] | 1144 | ${$args{val}} =~ s/^ZONE,/ZONE./; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
[233] | 1145 | } elsif (${$args{rectype}} == 65281) {
|
---|
| 1146 | return ('FAIL',"AAAA+PTR record must be a valid IPv6 address or fragment")
|
---|
| 1147 | if ${$args{val}} =~ /\./;
|
---|
[234] | 1148 | ${$args{val}} =~ s/^ZONE,/ZONE::/; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
[233] | 1149 | }
|
---|
| 1150 | } else {
|
---|
| 1151 | # This is easy. I also can't see a real use-case for A/AAAA+PTR in *all* forward
|
---|
| 1152 | # domains, since you wouldn't be able to substitute both domain and reverse zone
|
---|
| 1153 | # sanely, and you'd end up with guaranteed over-replicated PTR records that would
|
---|
| 1154 | # confuse the hell out of pretty much anything that uses them.
|
---|
[234] | 1155 | ##fixme: make this a config flag?
|
---|
[233] | 1156 | return ('FAIL', "$typemap{${$args{rectype}}} records not allowed in default domains");
|
---|
| 1157 | }
|
---|
[232] | 1158 | }
|
---|
| 1159 |
|
---|
| 1160 | return ($code, $msg);
|
---|
[228] | 1161 | } # done A+PTR record
|
---|
| 1162 |
|
---|
| 1163 | # AAAA+PTR record
|
---|
[232] | 1164 | # A+PTR above has been magicked to handle AAAA+PTR as well.
|
---|
[228] | 1165 | sub _validate_65281 {
|
---|
[232] | 1166 | return _validate_65280(@_);
|
---|
[228] | 1167 | } # done AAAA+PTR record
|
---|
| 1168 |
|
---|
| 1169 | # PTR template record
|
---|
| 1170 | sub _validate_65282 {
|
---|
[467] | 1171 | my $self = shift;
|
---|
| 1172 | my $dbh = $self->{dbh};
|
---|
[340] | 1173 |
|
---|
| 1174 | my %args = @_;
|
---|
| 1175 |
|
---|
| 1176 | # we're *this* >.< close to being able to just call _validate_12... unfortunately we can't, quite.
|
---|
| 1177 | if ($args{revrec} eq 'y') {
|
---|
| 1178 | if ($args{defrec} eq 'n') {
|
---|
[467] | 1179 | return ('FAIL', "Template block ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
| 1180 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
[340] | 1181 | ##fixme: warn if $args{val} is not /31 or larger block?
|
---|
| 1182 | ${$args{val}} = "$args{addr}";
|
---|
| 1183 | } else {
|
---|
| 1184 | if (${$args{val}} =~ /\./) {
|
---|
| 1185 | # looks like a v4 or fragment
|
---|
| 1186 | if (${$args{val}} =~ m|^\d+\.\d+\.\d+\.\d+(?:/\d+)?$|) {
|
---|
| 1187 | # woo! a complete IP! validate it and normalize, or fail.
|
---|
| 1188 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
| 1189 | or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
|
---|
| 1190 | ${$args{val}} = "$args{addr}";
|
---|
| 1191 | } else {
|
---|
| 1192 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
| 1193 | }
|
---|
| 1194 | } elsif (${$args{val}} =~ /[a-f:]/) {
|
---|
| 1195 | # looks like a v6 or fragment
|
---|
| 1196 | ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
|
---|
| 1197 | if ($args{addr}) {
|
---|
| 1198 | if ($args{addr}->addr =~ /^0/) {
|
---|
| 1199 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
| 1200 | } else {
|
---|
| 1201 | ${$args{val}} = "$args{addr}";
|
---|
| 1202 | }
|
---|
| 1203 | }
|
---|
| 1204 | } else {
|
---|
| 1205 | # bare number (probably). These could be v4 or v6, so we'll
|
---|
| 1206 | # expand on these on creation of a reverse zone.
|
---|
| 1207 | ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
|
---|
| 1208 | }
|
---|
| 1209 | }
|
---|
| 1210 | ##fixme: validate %-patterns?
|
---|
| 1211 |
|
---|
| 1212 | # Unlike single PTR records, there is absolutely no way to sanely support multiple
|
---|
| 1213 | # PTR templates for the same block, since they expect to expand to all the individual
|
---|
| 1214 | # IPs on export. Nested templates should be supported though.
|
---|
| 1215 |
|
---|
| 1216 | my @checkvals = (${$args{val}});
|
---|
| 1217 | if (${$args{val}} =~ /,/) {
|
---|
| 1218 | # push . and :: variants into checkvals if val has ,
|
---|
| 1219 | my $tmp;
|
---|
| 1220 | ($tmp = ${$args{val}}) =~ s/,/./;
|
---|
| 1221 | push @checkvals, $tmp;
|
---|
| 1222 | ($tmp = ${$args{val}}) =~ s/,/::/;
|
---|
| 1223 | push @checkvals, $tmp;
|
---|
| 1224 | }
|
---|
| 1225 | ##fixme: this feels wrong still - need to restrict template pseudorecords to One Of Each
|
---|
| 1226 | # Per Netblock such that they don't conflict on export
|
---|
| 1227 | my $typeck;
|
---|
| 1228 | # type 65282 -> ptr template -> look for any of 65282, 65283, 65284
|
---|
| 1229 | $typeck = 'type=65283 OR type=65284' if ${$args{rectype}} == 65282;
|
---|
| 1230 | # type 65283 -> a+ptr template -> v4 -> look for 65282 or 65283
|
---|
| 1231 | $typeck = 'type=65283' if ${$args{rectype}} == 65282;
|
---|
| 1232 | # type 65284 -> aaaa+ptr template -> v6 -> look for 65282 or 65284
|
---|
| 1233 | $typeck = 'type=65284' if ${$args{rectype}} == 65282;
|
---|
| 1234 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ? ".
|
---|
| 1235 | "AND (type=65282 OR $typeck)");
|
---|
| 1236 | foreach my $checkme (@checkvals) {
|
---|
| 1237 | $pcsth->execute($checkme);
|
---|
| 1238 | my ($rc) = $pcsth->fetchrow_array;
|
---|
[442] | 1239 | return ('FAIL', "Only one template pseudorecord may exist for a given IP block") if $rc > 1;
|
---|
[340] | 1240 | }
|
---|
| 1241 |
|
---|
| 1242 | } else {
|
---|
| 1243 | return ('FAIL', "Forward zones cannot contain PTR records");
|
---|
| 1244 | }
|
---|
| 1245 |
|
---|
[228] | 1246 | return ('OK','OK');
|
---|
| 1247 | } # done PTR template record
|
---|
| 1248 |
|
---|
| 1249 | # A+PTR template record
|
---|
| 1250 | sub _validate_65283 {
|
---|
[467] | 1251 | my $self = shift;
|
---|
| 1252 | my $dbh = $self->{dbh};
|
---|
[340] | 1253 |
|
---|
| 1254 | my %args = @_;
|
---|
| 1255 |
|
---|
| 1256 | my ($code,$msg) = ('OK','OK');
|
---|
| 1257 |
|
---|
| 1258 | ##fixme: need to fiddle things since A+PTR templates are acceptable in live
|
---|
| 1259 | # forward zones but not default records
|
---|
| 1260 | if ($args{defrec} eq 'n') {
|
---|
| 1261 | if ($args{revrec} eq 'n') {
|
---|
| 1262 |
|
---|
[653] | 1263 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 1264 | # or the intended parent domain for live records.
|
---|
| 1265 | my $pname = $self->domainName($args{id});
|
---|
[657] | 1266 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/i;
|
---|
[653] | 1267 |
|
---|
| 1268 | # check for form; note this checks both normal and "other" hostnames.
|
---|
| 1269 | return ('FAIL', $errstr)
|
---|
| 1270 | if !_check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 1271 |
|
---|
[340] | 1272 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
| 1273 | # work here since we don't *know* which parent to put it in.
|
---|
| 1274 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
| 1275 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
| 1276 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
| 1277 | # Fail if no match; we can't coerce a PTR-template type down to not include the PTR bit currently.
|
---|
| 1278 | if (!$revid) {
|
---|
| 1279 | $msg = "Can't ".($args{update} ? 'update' : 'add')." ${$args{host}}/${$args{val}} as ".
|
---|
| 1280 | "$typemap{${$args{rectype}}}: reverse zone not found for ${$args{val}}";
|
---|
| 1281 | ##fixme: add A template, AAAA template types?
|
---|
| 1282 | # ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
| 1283 | return ('FAIL', $msg);
|
---|
| 1284 | }
|
---|
| 1285 |
|
---|
| 1286 | # Add reverse zone ID to field list and values
|
---|
| 1287 | ${$args{fields}} .= "rdns_id,";
|
---|
| 1288 | push @{$args{vallist}}, $revid;
|
---|
| 1289 |
|
---|
| 1290 | } else {
|
---|
[467] | 1291 | return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
| 1292 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
[340] | 1293 | ${$args{val}} = "$args{addr}";
|
---|
| 1294 |
|
---|
[467] | 1295 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) {
|
---|
[340] | 1296 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
| 1297 | " as PTR template instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
| 1298 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
| 1299 | $msg = $addmsg if $code eq 'OK';
|
---|
| 1300 | ${$args{rectype}} = 65282;
|
---|
| 1301 | return ('WARN', $msg);
|
---|
| 1302 | }
|
---|
| 1303 |
|
---|
| 1304 | # Add domain ID to field list and values
|
---|
| 1305 | ${$args{fields}} .= "domain_id,";
|
---|
| 1306 | push @{$args{vallist}}, ${$args{domid}};
|
---|
| 1307 | }
|
---|
| 1308 |
|
---|
| 1309 | } else {
|
---|
[467] | 1310 | my ($code,$msg) = $self->_validate_65282(%args);
|
---|
[340] | 1311 | return ($code, $msg) if $code eq 'FAIL';
|
---|
| 1312 | # get domain, check against ${$args{name}}
|
---|
| 1313 | }
|
---|
| 1314 |
|
---|
[228] | 1315 | return ('OK','OK');
|
---|
[624] | 1316 | } # done A+PTR template record
|
---|
[228] | 1317 |
|
---|
| 1318 | # AAAA+PTR template record
|
---|
[624] | 1319 | # Not sure this can be handled sanely due to the size of IPv6 address space
|
---|
[674] | 1320 | # _validate_65283 above should handle v6 template records fine. It's on export we've got trouble.
|
---|
[228] | 1321 | sub _validate_65284 {
|
---|
[674] | 1322 | my $self = shift;
|
---|
| 1323 | my %args = @_;
|
---|
| 1324 |
|
---|
| 1325 | # do a quick check on the form of the hostname part; this is effectively a
|
---|
| 1326 | # "*.0.0.f.ip6.arpa" hostname, not an actual expandable IP template pattern
|
---|
| 1327 | # like with 65283.
|
---|
| 1328 | return ('FAIL', $errstr)
|
---|
| 1329 | if !_check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 1330 | return $self->_validate_65283(%args);
|
---|
[228] | 1331 | } # done AAAA+PTR template record
|
---|
| 1332 |
|
---|
[342] | 1333 | # Delegation record
|
---|
[345] | 1334 | # This is essentially a specialized clone of the NS record, primarily useful
|
---|
| 1335 | # for delegating IPv4 sub-/24 reverse blocks
|
---|
[342] | 1336 | sub _validate_65285 {
|
---|
[467] | 1337 | my $self = shift;
|
---|
| 1338 | my $dbh = $self->{dbh};
|
---|
[345] | 1339 |
|
---|
| 1340 | my %args = @_;
|
---|
| 1341 |
|
---|
| 1342 | # Almost, but not quite, identical to NS record validation.
|
---|
| 1343 |
|
---|
| 1344 | # Check that the target of the record is within the parent.
|
---|
| 1345 | # Yes, host<->val are mixed up here; can't see a way to avoid it. :(
|
---|
| 1346 | if ($args{defrec} eq 'n') {
|
---|
| 1347 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
| 1348 | if ($args{revrec} eq 'y') {
|
---|
| 1349 | my $tmpip = NetAddr::IP->new(${$args{val}});
|
---|
[467] | 1350 | my $pname = $self->revName($args{id});
|
---|
[345] | 1351 | return ('FAIL',"${$args{val}} not within $pname")
|
---|
[467] | 1352 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$tmpip);
|
---|
[345] | 1353 | # Normalize
|
---|
| 1354 | ${$args{val}} = "$tmpip";
|
---|
| 1355 | } else {
|
---|
[467] | 1356 | my $pname = $self->domainName($args{id});
|
---|
[657] | 1357 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/i;
|
---|
[345] | 1358 | }
|
---|
| 1359 | } else {
|
---|
| 1360 | return ('FAIL',"Delegation records are not permitted in default record sets");
|
---|
| 1361 | }
|
---|
[342] | 1362 | return ('OK','OK');
|
---|
| 1363 | }
|
---|
[228] | 1364 |
|
---|
[617] | 1365 | # Subs not specific to a particular record type
|
---|
[342] | 1366 |
|
---|
[617] | 1367 | # Convert $$host and/or $$val to lowercase as appropriate.
|
---|
| 1368 | # Should only be called if $self->{lowercase} is true.
|
---|
| 1369 | # $rectype is also a reference for caller convenience
|
---|
| 1370 | sub _caseclean {
|
---|
| 1371 | my ($rectype, $host, $val, $defrec, $revrec) = @_;
|
---|
| 1372 |
|
---|
| 1373 | # Can't case-squash default records, due to DOMAIN, ZONE, and ADMINDOMAIN templating
|
---|
| 1374 | return if $defrec eq 'y';
|
---|
| 1375 |
|
---|
| 1376 | if ($typemap{$$rectype} eq 'TXT' || $typemap{$$rectype} eq 'SPF') {
|
---|
| 1377 | # TXT records should preserve user entry in the string.
|
---|
| 1378 | # SPF records are a duplicate of TXT with a new record type value (99)
|
---|
| 1379 | $$host = lc($$host) if $revrec eq 'n'; # only lowercase $$host on live forward TXT; preserve TXT content
|
---|
| 1380 | $$val = lc($$val) if $revrec eq 'y'; # only lowercase $$val on live reverse TXT; preserve TXT content
|
---|
| 1381 | } else {
|
---|
| 1382 | # Non-TXT, live records, are fully case-insensitive
|
---|
| 1383 | $$host = lc($$host);
|
---|
| 1384 | $$val = lc($$val);
|
---|
| 1385 | } # $typemap{$$rectype} else
|
---|
| 1386 |
|
---|
| 1387 | } # _caseclean()
|
---|
| 1388 |
|
---|
| 1389 |
|
---|
[265] | 1390 | ##
|
---|
| 1391 | ## Record data substitution subs
|
---|
| 1392 | ##
|
---|
[228] | 1393 |
|
---|
[298] | 1394 | # Replace ZONE in hostname, or create (most of) the actual proper zone name
|
---|
[265] | 1395 | sub _ZONE {
|
---|
| 1396 | my $zone = shift;
|
---|
| 1397 | my $string = shift;
|
---|
| 1398 | my $fr = shift || 'f'; # flag for forward/reverse order? nb: ignored for IP
|
---|
[298] | 1399 | my $sep = shift || '-'; # Separator character - unlikely we'll ever need more than . or -
|
---|
[265] | 1400 |
|
---|
[298] | 1401 | my $prefix;
|
---|
[265] | 1402 |
|
---|
| 1403 | $string =~ s/,/./ if !$zone->{isv6};
|
---|
| 1404 | $string =~ s/,/::/ if $zone->{isv6};
|
---|
| 1405 |
|
---|
[298] | 1406 | # Subbing ZONE in the host. We need to properly ID the netblock range
|
---|
| 1407 | # The subbed text should have "network IP with trailing zeros stripped" for
|
---|
| 1408 | # blocks lined up on octet (for v4) or hex-quad (for v6) boundaries
|
---|
| 1409 | # For blocks that do NOT line up on these boundaries, we take the most
|
---|
| 1410 | # significant octet or 16-bit chunk of the "broadcast" IP and append it
|
---|
| 1411 | # after a double-dash
|
---|
| 1412 | # ie:
|
---|
| 1413 | # 8.0.0.0/6 -> 8.0.0.0 -> 11.255.255.255; sub should be 8--11
|
---|
| 1414 | # 10.0.0.0/12 -> 10.0.0.0 -> 10.0.0.0 -> 10.15.255.255; sub should be 10-0--15
|
---|
| 1415 | # 192.168.4.0/22 -> 192.168.4.0 -> 192.168.7.255; sub should be 192-168-4--7
|
---|
| 1416 | # 192.168.0.8/29 -> 192.168.0.8 -> 192.168.0.15; sub should be 192-168-0-8--15
|
---|
| 1417 | # Similar for v6
|
---|
[265] | 1418 |
|
---|
[298] | 1419 | if (!$zone->{isv6}) { # IPv4
|
---|
| 1420 |
|
---|
| 1421 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
| 1422 | # a funky subnet that had host bits set.
|
---|
| 1423 | my $bc = $zone->broadcast->addr;
|
---|
| 1424 |
|
---|
| 1425 | if ($zone->masklen > 24) {
|
---|
| 1426 | $bc =~ s/^\d+\.\d+\.\d+\.//;
|
---|
| 1427 | } elsif ($zone->masklen > 16) {
|
---|
| 1428 | $prefix =~ s/\.0$//;
|
---|
| 1429 | $bc =~ s/^\d+\.\d+\.//;
|
---|
| 1430 | } elsif ($zone->masklen > 8) {
|
---|
| 1431 | $bc =~ s/^\d+\.//;
|
---|
| 1432 | $prefix =~ s/\.0\.0$//;
|
---|
| 1433 | } else {
|
---|
| 1434 | $prefix =~ s/\.0\.0\.0$//;
|
---|
| 1435 | }
|
---|
| 1436 | if ($zone->masklen % 8) {
|
---|
| 1437 | $bc =~ s/(\.255)+$//;
|
---|
| 1438 | $prefix .= "--$bc"; #"--".zone->masklen; # use range or mask length?
|
---|
| 1439 | }
|
---|
| 1440 | if ($fr eq 'f') {
|
---|
| 1441 | $prefix =~ s/\.+/$sep/g;
|
---|
| 1442 | } else {
|
---|
| 1443 | $prefix = join($sep, reverse(split(/\./, $prefix)));
|
---|
| 1444 | }
|
---|
| 1445 |
|
---|
| 1446 | } else { # IPv6
|
---|
| 1447 |
|
---|
| 1448 | if ($fr eq 'f') {
|
---|
| 1449 |
|
---|
| 1450 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
| 1451 | # a funky subnet that had host bits set.
|
---|
[265] | 1452 | my $bc = $zone->broadcast->addr;
|
---|
| 1453 | if (($zone->masklen % 16) != 0) {
|
---|
[298] | 1454 | # Strip trailing :0 off $prefix, and :ffff off the broadcast IP
|
---|
| 1455 | for (my $i=0; $i<(7-int($zone->masklen / 16)); $i++) {
|
---|
| 1456 | $prefix =~ s/:0$//;
|
---|
| 1457 | $bc =~ s/:ffff$//;
|
---|
| 1458 | }
|
---|
| 1459 | # Strip the leading 16-bit chunks off the front of the broadcast IP
|
---|
| 1460 | $bc =~ s/^([a-f0-9]+:)+//;
|
---|
| 1461 | # Append the remaining 16-bit chunk to the prefix after "--"
|
---|
| 1462 | $prefix .= "--$bc";
|
---|
[265] | 1463 | } else {
|
---|
[298] | 1464 | # Strip off :0 from the end until we reach the netblock length.
|
---|
| 1465 | for (my $i=0; $i<(8-$zone->masklen / 16); $i++) {
|
---|
[265] | 1466 | $prefix =~ s/:0$//;
|
---|
[298] | 1467 | }
|
---|
[265] | 1468 | }
|
---|
[298] | 1469 | # Actually deal with the separator
|
---|
| 1470 | $prefix =~ s/:/$sep/g;
|
---|
| 1471 |
|
---|
| 1472 | } else { # $fr eq 'f'
|
---|
| 1473 |
|
---|
| 1474 | $prefix = $zone->network->full; # Just In Case someone managed to slip in
|
---|
| 1475 | # a funky subnet that had host bits set.
|
---|
| 1476 | my $bc = $zone->broadcast->full;
|
---|
| 1477 | $prefix =~ s/://g; # clean these out since they're not spaced right for this case
|
---|
| 1478 | $bc =~ s/://g;
|
---|
| 1479 | # Strip trailing 0 off $prefix, and f off the broadcast IP, to match the mask length
|
---|
| 1480 | for (my $i=0; $i<(31-int($zone->masklen / 4)); $i++) {
|
---|
| 1481 | $prefix =~ s/0$//;
|
---|
| 1482 | $bc =~ s/f$//;
|
---|
| 1483 | }
|
---|
| 1484 | # Split and reverse the order of the nibbles in the network/broadcast IPs
|
---|
[332] | 1485 | # trim another 0 for nibble-aligned blocks first, but only if we really have a block, not an IP
|
---|
| 1486 | $prefix =~ s/0$// if $zone->masklen % 4 == 0 && $zone->masklen != 128;
|
---|
[298] | 1487 | my @nbits = reverse split //, $prefix;
|
---|
| 1488 | my @bbits = reverse split //, $bc;
|
---|
| 1489 | # Handle the sub-nibble case. Eww. I feel dirty supporting this...
|
---|
| 1490 | $nbits[0] = "$nbits[0]-$bbits[0]" if ($zone->masklen % 4) != 0;
|
---|
| 1491 | # Glue it back together
|
---|
| 1492 | $prefix = join($sep, @nbits);
|
---|
| 1493 |
|
---|
| 1494 | } # $fr ne 'f'
|
---|
| 1495 |
|
---|
| 1496 | } # $zone->{isv6}
|
---|
| 1497 |
|
---|
| 1498 | # Do the substitution, finally
|
---|
| 1499 | $string =~ s/ZONE/$prefix/;
|
---|
| 1500 | $string =~ s/--/-/ if $sep ne '-'; # - as separator needs extra help for sub-octet v4 netblocks
|
---|
| 1501 | return $string;
|
---|
| 1502 | } # done _ZONE()
|
---|
| 1503 |
|
---|
| 1504 | # Not quite a substitution sub, but placed here as it's basically the inverse of above;
|
---|
| 1505 | # given the .arpa zone name, return the CIDR netblock the zone is for.
|
---|
[304] | 1506 | # Supports v4 non-octet/non-classful netblocks as per the method outlined in the Grasshopper Book (2nd Ed p217-218)
|
---|
[298] | 1507 | # Does NOT support non-quad v6 netblocks via the same scheme; it shouldn't ever be necessary.
|
---|
| 1508 | # Takes a nominal .arpa zone name, returns a success code and NetAddr::IP, or a fail code and message
|
---|
| 1509 | sub _zone2cidr {
|
---|
| 1510 | my $zone = shift;
|
---|
| 1511 |
|
---|
| 1512 | my $cidr;
|
---|
[301] | 1513 | my $tmpcidr;
|
---|
| 1514 | my $warnmsg = '';
|
---|
[298] | 1515 |
|
---|
| 1516 | if ($zone =~ /\.in-addr\.arpa\.?$/) {
|
---|
| 1517 | # v4 revzone, formal zone name type
|
---|
| 1518 | my $tmpzone = $zone;
|
---|
[583] | 1519 | return ('FAIL', "Non-numerics in apparent IPv4 reverse zone name [$tmpzone]")
|
---|
| 1520 | if $tmpzone !~ m{^(?:\d+[/-])?[\d\.]+\.in-addr\.arpa\.?$};
|
---|
[298] | 1521 | $tmpzone =~ s/\.in-addr\.arpa\.?//;
|
---|
| 1522 |
|
---|
| 1523 | # Snag the octet pieces
|
---|
| 1524 | my @octs = split /\./, $tmpzone;
|
---|
| 1525 |
|
---|
| 1526 | # Map result of a range manipulation to a mask length change. Cheaper than finding the 2-root of $octets[0]+1.
|
---|
[304] | 1527 | # Note we will not support /31 blocks, mostly due to issues telling "24-31" -> .24/29 apart from
|
---|
| 1528 | # "24-31" -> .24/31", with a litte bit of "/31 is icky".
|
---|
| 1529 | my %maskmap = ( 3 => 2, 7 => 3, 15 => 4, 31 => 5, 63 => 6, 127 => 7,
|
---|
| 1530 | 30 => 2, 29 => 3, 28 => 4, 27 => 5, 26 => 6, 25 => 7
|
---|
| 1531 | );
|
---|
[298] | 1532 |
|
---|
| 1533 | # Handle "range" blocks, eg, 80-83.168.192.in-addr.arpa (192.168.80.0/22)
|
---|
| 1534 | # Need to take the size of the range to offset the basic octet-based mask length,
|
---|
| 1535 | # and make sure the first number in the range gets used as the network address for the block
|
---|
[304] | 1536 | # Alternate form: The second number is actually the real netmask, not the end of the range.
|
---|
[298] | 1537 | my $masklen = 0;
|
---|
[571] | 1538 | if ($octs[0] =~ m{^((\d+)[/-](\d+))$}) { # take the range...
|
---|
[307] | 1539 | if (24 < $3 && $3 < 31) {
|
---|
[304] | 1540 | # we have a real netmask
|
---|
[307] | 1541 | $masklen = -$maskmap{$3};
|
---|
[304] | 1542 | } else {
|
---|
| 1543 | # we have a range. NB: only real CIDR ranges are supported
|
---|
[307] | 1544 | $masklen -= $maskmap{-(eval $1)}; # find the mask base...
|
---|
[304] | 1545 | }
|
---|
[307] | 1546 | $octs[0] = $2; # set the base octet of the range...
|
---|
[265] | 1547 | }
|
---|
[298] | 1548 | @octs = reverse @octs; # We can reverse the octet pieces now that we've extracted and munged any ranges
|
---|
[265] | 1549 |
|
---|
[304] | 1550 | # arguably we should only allow sub-octet range/mask in-addr.arpa
|
---|
| 1551 | # specifications in the least significant octet, but the code is
|
---|
| 1552 | # simpler if we deal with sub-octet delegations at any level.
|
---|
| 1553 |
|
---|
[298] | 1554 | # Now we find the "true" mask with the aid of the "base" calculated above
|
---|
| 1555 | if ($#octs == 0) {
|
---|
| 1556 | $masklen += 8;
|
---|
| 1557 | $tmpcidr = "$octs[0].0.0.0/$masklen"; # really hope we don't see one of these very often.
|
---|
| 1558 | } elsif ($#octs == 1) {
|
---|
| 1559 | $masklen += 16;
|
---|
| 1560 | $tmpcidr = "$octs[0].$octs[1].0.0/$masklen";
|
---|
| 1561 | } elsif ($#octs == 2) {
|
---|
| 1562 | $masklen += 24;
|
---|
| 1563 | $tmpcidr = "$octs[0].$octs[1].$octs[2].0/$masklen";
|
---|
[265] | 1564 | } else {
|
---|
[298] | 1565 | $masklen += 32;
|
---|
| 1566 | $tmpcidr = "$octs[0].$octs[1].$octs[2].$octs[3]/$masklen";
|
---|
[265] | 1567 | }
|
---|
| 1568 |
|
---|
[583] | 1569 | } elsif ($zone =~ /\.ip6\.arpa\.?$/) {
|
---|
[298] | 1570 | # v6 revzone, formal zone name type
|
---|
| 1571 | my $tmpzone = $zone;
|
---|
[583] | 1572 | ##fixme: if-n-when we decide we can support sub-nibble v6 zone names, we'll need to change this segment
|
---|
| 1573 | return ('FAIL', "Non-hexadecimals in apparent IPv6 reverse zone name [$tmpzone]")
|
---|
| 1574 | if $tmpzone !~ /^[a-fA-F\d\.]+\.ip6\.arpa\.?$/;
|
---|
[298] | 1575 | $tmpzone =~ s/\.ip6\.arpa\.?//;
|
---|
| 1576 | my @quads = reverse(split(/\./, $tmpzone));
|
---|
| 1577 | $warnmsg .= "Apparent sub-/64 IPv6 reverse zone\n" if $#quads > 15;
|
---|
| 1578 | my $nc;
|
---|
| 1579 | foreach (@quads) {
|
---|
[301] | 1580 | $tmpcidr .= $_;
|
---|
[583] | 1581 | $tmpcidr .= ":" if ++$nc % 4 == 0 && $nc < $#quads;
|
---|
[298] | 1582 | }
|
---|
| 1583 | my $nq = 1 if $nc % 4 != 0;
|
---|
| 1584 | my $mask = $nc * 4; # need to do this here because we probably increment it below
|
---|
| 1585 | while ($nc++ % 4 != 0) {
|
---|
[301] | 1586 | $tmpcidr .= "0";
|
---|
[298] | 1587 | }
|
---|
[583] | 1588 | # polish it off with trailing ::/mask if this is a CIDR block instead of an IP
|
---|
| 1589 | $tmpcidr .= "::/$mask" if $mask != 128;
|
---|
[298] | 1590 | }
|
---|
[301] | 1591 |
|
---|
| 1592 | # Just to be sure, use NetAddr::IP to validate. Saves a lot of nasty regex watching for valid octet values.
|
---|
| 1593 | return ('FAIL', "Invalid zone $zone (apparent netblock $tmpcidr)")
|
---|
| 1594 | unless $cidr = NetAddr::IP->new($tmpcidr);
|
---|
| 1595 |
|
---|
| 1596 | if ($warnmsg) {
|
---|
| 1597 | $errstr = $warnmsg;
|
---|
| 1598 | return ('WARN', $cidr);
|
---|
| 1599 | }
|
---|
| 1600 | return ('OK', $cidr);
|
---|
[583] | 1601 | ##fixme: use wantarray() to decide what to return?
|
---|
[298] | 1602 | } # done _zone2cidr()
|
---|
[265] | 1603 |
|
---|
[337] | 1604 | # Record template %-parameter expansion, IPv4. Note that IPv6 doesn't
|
---|
| 1605 | # really have a sane way to handle this type of expansion at the moment
|
---|
| 1606 | # due to the size of the address space.
|
---|
[685] | 1607 | # Takes a reference to a template string to be expanded, an IP to use in the replacement,
|
---|
| 1608 | # an optional netblock for the %ngb (net, gw, bcast) expansion, and an optional index
|
---|
| 1609 | # number for %c "n'th usable IP in block/range" patterns.
|
---|
| 1610 | # Alters the template string referred.
|
---|
[337] | 1611 | sub _template4_expand {
|
---|
[685] | 1612 | # ugh pthui
|
---|
| 1613 | my $self;
|
---|
| 1614 | $self = shift if ref($_[0]) eq 'DNSDB';
|
---|
| 1615 |
|
---|
[337] | 1616 | my $tmpl = shift;
|
---|
| 1617 | my $ip = shift;
|
---|
[685] | 1618 | my $subnet = shift; # for %ngb and %c
|
---|
| 1619 | my $ipindex = shift; # for %c
|
---|
[298] | 1620 |
|
---|
[685] | 1621 | # blank $tmpl on config template_skip_0 or template_skip_255, unless we have a %ngb
|
---|
| 1622 | if ($$tmpl !~ /\%-?n-?g-?b\%/) {
|
---|
| 1623 | if ( ($ip =~ /\.0$/ && $self->{template_skip_0}) ||
|
---|
| 1624 | ($ip =~ /\.255$/ && $self->{template_skip_255}) ) {
|
---|
| 1625 | $$tmpl = '';
|
---|
| 1626 | return;
|
---|
| 1627 | }
|
---|
| 1628 | }
|
---|
| 1629 |
|
---|
[337] | 1630 | my @ipparts = split /\./, $ip;
|
---|
| 1631 | my @iphex;
|
---|
| 1632 | my @ippad;
|
---|
| 1633 | for (@ipparts) {
|
---|
| 1634 | push @iphex, sprintf("%x", $_);
|
---|
[443] | 1635 | push @ippad, sprintf("%0.3u", $_);
|
---|
[337] | 1636 | }
|
---|
| 1637 |
|
---|
[685] | 1638 | # Two or three consecutive separator characters (_ or -) should be rare - users that use them
|
---|
| 1639 | # anywhere other than punycoded internationalized domains get to keep the pieces when it breaks.
|
---|
| 1640 | # We clean up the ones that we may inadvertently generate after replacing %c and %ngb%
|
---|
| 1641 | my ($thrsep) = ($$tmpl =~ /[_-]{3}/);
|
---|
| 1642 | my ($twosep) = ($$tmpl =~ /[_-]{2}/);
|
---|
| 1643 |
|
---|
| 1644 | # Take the simplest path to pattern substitution; replace only exactly the %c or %ngb%
|
---|
| 1645 | # patterns as-is. Then check after to see if we've caused doubled separator characters (- or _)
|
---|
| 1646 | # and eliminate them, but only if the original template didn't have them already. Also
|
---|
| 1647 | # unconditionally drop separator characters immediately before a dot; these do not always
|
---|
| 1648 | # strictly make the label invalid but almost always, and any exceptions should never show up
|
---|
| 1649 | # in a template record that expands to "many" real records anyway.
|
---|
| 1650 |
|
---|
| 1651 | # %ngb and %c require a netblock
|
---|
| 1652 | if ($subnet) {
|
---|
| 1653 | # extract the fragments
|
---|
| 1654 | my ($ngb,$n,$g,$b) = ($$tmpl =~ /(\%(-?n)(-?g)(-?b)\%)/);
|
---|
| 1655 | my ($c) = ($$tmpl =~ /(\%-?c)/); my $nld = ''; my $cld = '';
|
---|
| 1656 | $c = '' if !$c;
|
---|
| 1657 | my $skipgw = ($c =~ /\%-c/ ? 0 : 1);
|
---|
| 1658 | my $ipkill = 0;
|
---|
| 1659 |
|
---|
| 1660 | ##fixme: still have one edge case not handled well:
|
---|
| 1661 | # %c%n-gb%
|
---|
| 1662 | # do we drop the record as per -g, or publish the record with an index of 1 as per %c?
|
---|
| 1663 | # arguably this is a "that's a STUPID question!" case
|
---|
| 1664 |
|
---|
| 1665 | if ($c) {
|
---|
| 1666 | # "n'th usable IP in the block" pattern. We need the caller to provide an index
|
---|
| 1667 | # number otherwise we see exponential time growth because we have to iterate over
|
---|
| 1668 | # the whole block to map the IP back to an index. :/
|
---|
| 1669 | # NetAddr::IP does not have a method for asking "what index is IP <foo> at?"
|
---|
| 1670 |
|
---|
| 1671 | # no index, or index == 0, (AKA network address), or IP == broadcast, blank the index fragment
|
---|
| 1672 | if (!$ipindex || ($$subnet->broadcast->addr eq $ip)) {
|
---|
| 1673 | $$tmpl =~ s/$c//;
|
---|
| 1674 | } else {
|
---|
| 1675 | # if we have %c, AKA "skip the gateway", and we're on the nominal gateway IP, blank the index fragment
|
---|
| 1676 | if ($skipgw && $$subnet->first->addr eq $ip) {
|
---|
| 1677 | $$tmpl =~ s/$c//;
|
---|
| 1678 | }
|
---|
| 1679 | # else replace the index fragment with the passed index minus $skipgw, so that we can start the
|
---|
| 1680 | # resulting index at 1 on net+2
|
---|
| 1681 | else {
|
---|
| 1682 | $$tmpl =~ s/$c/($ipindex-$skipgw)/e;
|
---|
| 1683 | }
|
---|
| 1684 | }
|
---|
| 1685 | } # if ($c)
|
---|
| 1686 |
|
---|
| 1687 | if ($ngb) {
|
---|
| 1688 | # individually check the network, standard gateway (net+1) IP, and broadcast IP
|
---|
| 1689 | # blank $$tmpl if n, g, or b was prefixed with - (this allows "hiding" net/gw/bcast entries)
|
---|
| 1690 |
|
---|
| 1691 | if ($$subnet->network->addr eq $ip) {
|
---|
| 1692 | if ($n eq '-n') {
|
---|
| 1693 | $$tmpl = '';
|
---|
| 1694 | } else {
|
---|
| 1695 | $$tmpl =~ s/$ngb/net/;
|
---|
| 1696 | $ipkill = 1;
|
---|
| 1697 | }
|
---|
| 1698 | } elsif ($$subnet->first->addr eq $ip) {
|
---|
| 1699 | if ($g eq '-g') {
|
---|
| 1700 | $$tmpl = '';
|
---|
| 1701 | } else {
|
---|
| 1702 | $$tmpl =~ s/$ngb/gw/;
|
---|
| 1703 | $ipkill = 1;
|
---|
| 1704 | }
|
---|
| 1705 | } elsif ($$subnet->broadcast->addr eq $ip) {
|
---|
| 1706 | if ($b eq '-b') {
|
---|
| 1707 | $$tmpl = '';
|
---|
| 1708 | } else {
|
---|
| 1709 | $$tmpl =~ s/$ngb/bcast/;
|
---|
| 1710 | $ipkill = 1;
|
---|
| 1711 | }
|
---|
| 1712 | } else {
|
---|
| 1713 | $$tmpl =~ s/$ngb//;
|
---|
| 1714 | }
|
---|
| 1715 | }
|
---|
| 1716 |
|
---|
| 1717 | # We don't (usually) want to expand the IP-related patterns on the -net, -gw, or -bcast IPs.
|
---|
| 1718 | # Arguably this is another place for another config knob, or possibly further extension of
|
---|
| 1719 | # the template pattern to control it on a per-subnet basis.
|
---|
| 1720 | if ($ipkill) {
|
---|
| 1721 | # kill common IP patterns
|
---|
| 1722 | $$tmpl =~ s/\%[_.-]?[irdh]//;
|
---|
| 1723 | # kill IP octet patterns
|
---|
| 1724 | $$tmpl =~ s/\%[1234][dh0](?:[_.-]\%[1234][dh0]){0,3}//;
|
---|
| 1725 | }
|
---|
| 1726 |
|
---|
| 1727 | # and now clean up to make sure we leave a valid DNS label... mostly. Should arguably
|
---|
| 1728 | # split on /\./ and process each label separately.
|
---|
| 1729 | $$tmpl =~ s/([_-]){3}/$1/ if !$thrsep;
|
---|
| 1730 | $$tmpl =~ s/([_-]){2}/$1/ if !$twosep;
|
---|
| 1731 | $$tmpl =~ s/[_-]\././;
|
---|
| 1732 |
|
---|
| 1733 | } # if ($subnet)
|
---|
| 1734 |
|
---|
[337] | 1735 | # IP substitutions in template records:
|
---|
| 1736 | #major patterns:
|
---|
| 1737 | #dashed IP, forward and reverse
|
---|
[532] | 1738 | #underscoreed IP, forward and reverse
|
---|
[337] | 1739 | #dotted IP, forward and reverse (even if forward is... dumb)
|
---|
[532] | 1740 | # -> %r for reverse, %i for forward, leading -, _, or . to indicate separator, defaults to -
|
---|
[337] | 1741 | # %r or %-r => %4d-%3d-%2d-%1d
|
---|
[532] | 1742 | # %_r => %4d_%3d_%2d_%1d
|
---|
[337] | 1743 | # %.r => %4d.%3d.%2d.%1d
|
---|
| 1744 | # %i or %-i => %1d-%2d-%3d-%4d
|
---|
[532] | 1745 | # %_i => %1d_%2d_%3d_%4d
|
---|
[337] | 1746 | # %.i => %1d.%2d.%3d.%4d
|
---|
| 1747 | $$tmpl =~ s/\%r/\%4d-\%3d-\%2d-\%1d/g;
|
---|
[532] | 1748 | $$tmpl =~ s/\%([-._])r/\%4d$1\%3d$1\%2d$1\%1d/g;
|
---|
[337] | 1749 | $$tmpl =~ s/\%i/\%1d-\%2d-\%3d-\%4d/g;
|
---|
[532] | 1750 | $$tmpl =~ s/\%([-._])i/\%1d$1\%2d$1\%3d$1\%4d/g;
|
---|
[337] | 1751 |
|
---|
| 1752 | #hex-coded IP
|
---|
| 1753 | # %h
|
---|
| 1754 | $$tmpl =~ s/\%h/$iphex[0]$iphex[1]$iphex[2]$iphex[3]/g;
|
---|
| 1755 |
|
---|
| 1756 | #IP as decimal-coded 32-bit value
|
---|
| 1757 | # %d
|
---|
| 1758 | my $iptmp = $ipparts[0]*256*256*256 + $ipparts[1]*256*256 + $ipparts[2]*256 + $ipparts[3];
|
---|
| 1759 | $$tmpl =~ s/\%d/$iptmp/g;
|
---|
| 1760 |
|
---|
| 1761 | #minor patterns (per-octet)
|
---|
| 1762 | # %[1234][dh0]
|
---|
| 1763 | #octet
|
---|
| 1764 | #hex-coded octet
|
---|
| 1765 | #0-padded octet
|
---|
| 1766 | $$tmpl =~ s/\%([1234])d/$ipparts[$1-1]/g;
|
---|
| 1767 | $$tmpl =~ s/\%([1234])h/$iphex[$1-1]/g;
|
---|
[443] | 1768 | $$tmpl =~ s/\%([1234])0/$ippad[$1-1]/g;
|
---|
[685] | 1769 |
|
---|
[337] | 1770 | } # _template4_expand()
|
---|
| 1771 |
|
---|
[532] | 1772 | # Broad syntactic check on the hostname. Checks for valid characters, correctly-expandable template patterns.
|
---|
| 1773 | # Takes the hostname, type, and live/default and forward/reverse flags
|
---|
| 1774 | # Returns true/false, sets errstr on failures
|
---|
| 1775 | sub _check_hostname_form {
|
---|
| 1776 | my ($hname,$rectype,$defrec,$revrec) = @_;
|
---|
[337] | 1777 |
|
---|
[532] | 1778 | if ($hname =~ /\%/ && ($rectype == 65282 || $rectype == 65283) ) {
|
---|
| 1779 | my $tmphost = $hname;
|
---|
| 1780 | # we don't actually need to test with the real IP passed; that saves a bit of fiddling.
|
---|
[685] | 1781 | DNSDB::_template4_expand(\$tmphost, '10.10.10.10');
|
---|
[653] | 1782 | if ($tmphost =~ /\%/ || lc($tmphost) !~ /^(?:\*\.)?(?:[0-9a-z_.-]+)$/) {
|
---|
[532] | 1783 | $errstr = "Invalid template $hname";
|
---|
| 1784 | return;
|
---|
| 1785 | }
|
---|
[668] | 1786 | } elsif ($rectype == $reverse_typemap{CNAME} && $revrec eq 'y') {
|
---|
[625] | 1787 | # Allow / in reverse CNAME hostnames for sub-/24 delegation
|
---|
| 1788 | if (lc($hname) !~ m|^[0-9a-z_./-]+$|) {
|
---|
| 1789 | # error message is deliberately restrictive; special cases are SPECIAL and not for general use
|
---|
| 1790 | $errstr = "Hostnames may not contain anything other than (0-9 a-z . _)";
|
---|
| 1791 | return;
|
---|
| 1792 | }
|
---|
[532] | 1793 | } elsif ($revrec eq 'y') {
|
---|
| 1794 | # Reverse zones don't support @ in hostnames
|
---|
[625] | 1795 | if (lc($hname) !~ /^(?:\*\.)?[0-9a-z_.-]+$/) {
|
---|
| 1796 | # error message is deliberately restrictive; special cases are SPECIAL and not for general use
|
---|
[532] | 1797 | $errstr = "Hostnames may not contain anything other than (0-9 a-z . _)";
|
---|
| 1798 | return;
|
---|
| 1799 | }
|
---|
| 1800 | } else {
|
---|
[600] | 1801 | if (lc($hname) !~ /^(?:\*\.)?(?:[0-9a-z_.-]+|@)$/) {
|
---|
[532] | 1802 | # Don't mention @, because it would be far too wordy to explain the nuance of @
|
---|
| 1803 | $errstr = "Hostnames may not contain anything other than (0-9 a-z . _)";
|
---|
| 1804 | return;
|
---|
| 1805 | }
|
---|
| 1806 | }
|
---|
| 1807 | return 1;
|
---|
| 1808 | } # _check_hostname_form()
|
---|
| 1809 |
|
---|
| 1810 |
|
---|
[228] | 1811 | ##
|
---|
[2] | 1812 | ## Initialization and cleanup subs
|
---|
| 1813 | ##
|
---|
| 1814 |
|
---|
[128] | 1815 | ## DNSDB::__cfgload()
|
---|
| 1816 | # Private sub to parse a config file and load it into %config
|
---|
[517] | 1817 | # Takes a filename and a hashref to put the parsed entries in
|
---|
[128] | 1818 | sub __cfgload {
|
---|
| 1819 | $errstr = '';
|
---|
| 1820 | my $cfgfile = shift;
|
---|
[517] | 1821 | my $cfg = shift;
|
---|
[131] | 1822 |
|
---|
[128] | 1823 | if (open CFG, "<$cfgfile") {
|
---|
| 1824 | while (<CFG>) {
|
---|
| 1825 | chomp;
|
---|
| 1826 | s/^\s*//;
|
---|
| 1827 | next if /^#/;
|
---|
| 1828 | next if /^$/;
|
---|
| 1829 | # hmm. more complex bits in this file might require [heading] headers, maybe?
|
---|
| 1830 | # $mode = $1 if /^\[(a-z)+]/;
|
---|
| 1831 | # DB connect info
|
---|
[517] | 1832 | $cfg->{dbname} = $1 if /^dbname\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1833 | $cfg->{dbuser} = $1 if /^dbuser\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1834 | $cfg->{dbpass} = $1 if /^dbpass\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1835 | $cfg->{dbhost} = $1 if /^dbhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
[128] | 1836 | # Mail settings
|
---|
[517] | 1837 | $cfg->{mailhost} = $1 if /^mailhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1838 | $cfg->{mailnotify} = $1 if /^mailnotify\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
| 1839 | $cfg->{mailsender} = $1 if /^mailsender\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
| 1840 | $cfg->{mailname} = $1 if /^mailname\s*=\s*([a-z0-9\s_.-]+)/i;
|
---|
| 1841 | $cfg->{orgname} = $1 if /^orgname\s*=\s*([a-z0-9\s_.,'-]+)/i;
|
---|
| 1842 | $cfg->{domain} = $1 if /^domain\s*=\s*([a-z0-9_.-]+)/i;
|
---|
[163] | 1843 | # session - note this is fed directly to CGI::Session
|
---|
[517] | 1844 | $cfg->{timeout} = $1 if /^[tT][iI][mM][eE][oO][uU][tT]\s*=\s*(\d+[smhdwMy]?)/;
|
---|
| 1845 | $cfg->{sessiondir} = $1 if m{^sessiondir\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
[201] | 1846 | # misc
|
---|
[517] | 1847 | $cfg->{log_failures} = $1 if /^log_failures\s*=\s*([a-z01]+)/i;
|
---|
| 1848 | $cfg->{perpage} = $1 if /^perpage\s*=\s*(\d+)/i;
|
---|
| 1849 | $cfg->{exportcache} = $1 if m{^exportcache\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
[559] | 1850 | $cfg->{usecache} = $1 if m{^usecache\s*=\s*([a-z01]+)}i;
|
---|
| 1851 | $cfg->{force_refresh} = $1 if /^force_refresh\s*=\s*([a-z01]+)/i;
|
---|
[542] | 1852 | $cfg->{lowercase} = $1 if /^lowercase\s*=\s*([a-z01]+)/i;
|
---|
[583] | 1853 | $cfg->{showrev_arpa} = $1 if /^showrev_arpa\s*=\s*([a-z]+)/i;
|
---|
[644] | 1854 | $cfg->{template_skip_0} = $1 if /^template_skip_0\s*=\s*([a-z01]+)/i;
|
---|
| 1855 | $cfg->{template_skip_255} = $1 if /^template_skip_255\s*=\s*([a-z01]+)/i;
|
---|
[714] | 1856 | $cfg->{autotxt} = $1 if /^autotxt\s*=\s*([a-z01]+)/i;
|
---|
[517] | 1857 | # not supported in dns.cgi yet
|
---|
| 1858 | # $cfg->{templatedir} = $1 if m{^templatedir\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
| 1859 | # $cfg->{templateoverride} = $1 if m{^templateoverride\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
[400] | 1860 | # RPC options
|
---|
[517] | 1861 | $cfg->{rpcmode} = $1 if /^rpc_mode\s*=\s*(socket|HTTP|XMLRPC)\s*$/i;
|
---|
| 1862 | $cfg->{maxfcgi} = $1 if /^max_fcgi_requests\s*=\s*(\d+)\s*$/i;
|
---|
[465] | 1863 | if (my ($tmp) = /^rpc_iplist\s*=\s*(.+)/i) {
|
---|
| 1864 | my @ips = split /[,\s]+/, $tmp;
|
---|
| 1865 | my $rpcsys = shift @ips;
|
---|
[517] | 1866 | push @{$cfg->{rpcacl}{$rpcsys}}, @ips;
|
---|
[400] | 1867 | }
|
---|
[128] | 1868 | }
|
---|
| 1869 | close CFG;
|
---|
| 1870 | } else {
|
---|
[517] | 1871 | $errstr = "Couldn't load configuration file $cfgfile: $!";
|
---|
[128] | 1872 | return;
|
---|
| 1873 | }
|
---|
| 1874 | return 1;
|
---|
| 1875 | } # end __cfgload()
|
---|
| 1876 |
|
---|
| 1877 |
|
---|
[2] | 1878 | ## DNSDB::connectDB()
|
---|
| 1879 | # Creates connection to DNS database.
|
---|
| 1880 | # Requires the database name, username, and password.
|
---|
[465] | 1881 | # Returns a handle to the db or undef on failure.
|
---|
[2] | 1882 | # Set up for a PostgreSQL db; could be any transactional DBMS with the
|
---|
| 1883 | # right changes.
|
---|
[465] | 1884 | # Called by new(); not intended to be called publicly.
|
---|
[2] | 1885 | sub connectDB {
|
---|
| 1886 | $errstr = '';
|
---|
[15] | 1887 | my $dbname = shift;
|
---|
| 1888 | my $user = shift;
|
---|
| 1889 | my $pass = shift;
|
---|
[2] | 1890 | my $dbh;
|
---|
| 1891 | my $DSN = "DBI:Pg:dbname=$dbname";
|
---|
| 1892 |
|
---|
| 1893 | my $host = shift;
|
---|
| 1894 | $DSN .= ";host=$host" if $host;
|
---|
| 1895 |
|
---|
| 1896 | # Note that we want to autocommit by default, and we will turn it off locally as necessary.
|
---|
| 1897 | # We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
|
---|
| 1898 | $dbh = DBI->connect($DSN, $user, $pass, {
|
---|
| 1899 | AutoCommit => 1,
|
---|
| 1900 | PrintError => 0
|
---|
[465] | 1901 | });
|
---|
| 1902 | if (!$dbh) {
|
---|
| 1903 | $errstr = $DBI::errstr;
|
---|
| 1904 | return;
|
---|
| 1905 | }
|
---|
| 1906 | #) if(!$dbh);
|
---|
[2] | 1907 |
|
---|
[465] | 1908 | local $dbh->{RaiseError} = 1;
|
---|
| 1909 |
|
---|
| 1910 | eval {
|
---|
[212] | 1911 | ##fixme: initialize the DB if we can't find the table (since, by definition, there's
|
---|
| 1912 | # nothing there if we can't select from it...)
|
---|
[465] | 1913 | my $tblsth = $dbh->prepare("SELECT count(*) FROM pg_catalog.pg_class WHERE relkind='r' AND relname=?");
|
---|
| 1914 | my ($tblcount) = $dbh->selectrow_array($tblsth, undef, ('misc'));
|
---|
| 1915 | # return (undef,$DBI::errstr) if $dbh->err;
|
---|
[212] | 1916 |
|
---|
| 1917 | #if ($tblcount == 0) {
|
---|
| 1918 | # # create tables one at a time, checking for each.
|
---|
| 1919 | # return (undef, "check table misc missing");
|
---|
| 1920 | #}
|
---|
| 1921 |
|
---|
| 1922 | # Return here if we can't select.
|
---|
| 1923 | # This should retrieve the dbversion key.
|
---|
[465] | 1924 | my $sth = $dbh->prepare("SELECT key,value FROM misc WHERE misc_id=1");
|
---|
| 1925 | $sth->execute();
|
---|
| 1926 | # return (undef,$DBI::errstr) if ($sth->err);
|
---|
[2] | 1927 |
|
---|
[212] | 1928 | ##fixme: do stuff to the DB on version mismatch
|
---|
| 1929 | # x.y series should upgrade on $DNSDB::VERSION > misc(key=>version)
|
---|
| 1930 | # DB should be downward-compatible; column defaults should give sane (if possibly
|
---|
| 1931 | # useless-and-needs-help) values in columns an older software stack doesn't know about.
|
---|
| 1932 |
|
---|
[2] | 1933 | # See if the select returned anything (or null data). This should
|
---|
| 1934 | # succeed if the select executed, but...
|
---|
[465] | 1935 | $sth->fetchrow();
|
---|
| 1936 | # return (undef,$DBI::errstr) if ($sth->err);
|
---|
[2] | 1937 |
|
---|
[465] | 1938 | $sth->finish;
|
---|
[2] | 1939 |
|
---|
[465] | 1940 | }; # wrapped DB checks
|
---|
| 1941 | if ($@) {
|
---|
| 1942 | $errstr = $@;
|
---|
| 1943 | return;
|
---|
| 1944 | }
|
---|
| 1945 |
|
---|
[2] | 1946 | # If we get here, we should be OK.
|
---|
[465] | 1947 | return $dbh;
|
---|
[2] | 1948 | } # end connectDB
|
---|
| 1949 |
|
---|
| 1950 |
|
---|
| 1951 | ## DNSDB::finish()
|
---|
| 1952 | # Cleans up after database handles and so on.
|
---|
| 1953 | # Requires a database handle
|
---|
| 1954 | sub finish {
|
---|
[465] | 1955 | my $self = shift;
|
---|
| 1956 | $self->{dbh}->disconnect;
|
---|
[2] | 1957 | } # end finish
|
---|
| 1958 |
|
---|
| 1959 |
|
---|
| 1960 | ## DNSDB::initGlobals()
|
---|
| 1961 | # Initialize global variables
|
---|
| 1962 | # NB: this does NOT include web-specific session variables!
|
---|
| 1963 | sub initGlobals {
|
---|
[465] | 1964 | my $self = shift;
|
---|
| 1965 | my $dbh = $self->{dbh};
|
---|
[2] | 1966 |
|
---|
[208] | 1967 | # load record types from database
|
---|
[228] | 1968 | my $sth = $dbh->prepare("SELECT val,name,stdflag FROM rectypes");
|
---|
[2] | 1969 | $sth->execute;
|
---|
[228] | 1970 | while (my ($recval,$recname,$stdflag) = $sth->fetchrow_array()) {
|
---|
[2] | 1971 | $typemap{$recval} = $recname;
|
---|
| 1972 | $reverse_typemap{$recname} = $recval;
|
---|
[228] | 1973 | # now we fill the record validation function hash
|
---|
| 1974 | if ($stdflag < 5) {
|
---|
| 1975 | my $fn = "_validate_$recval";
|
---|
| 1976 | $validators{$recval} = \&$fn;
|
---|
| 1977 | } else {
|
---|
| 1978 | my $fn = "sub { return ('FAIL','Type $recval ($recname) not supported'); }";
|
---|
| 1979 | $validators{$recval} = eval $fn;
|
---|
| 1980 | }
|
---|
[2] | 1981 | }
|
---|
| 1982 | } # end initGlobals
|
---|
| 1983 |
|
---|
| 1984 |
|
---|
[401] | 1985 | ## DNSDB::initRPC()
|
---|
[469] | 1986 | # Takes a remote username and remote fullname.
|
---|
[401] | 1987 | # Sets up the RPC logging-pseudouser if needed.
|
---|
| 1988 | # Sets the %userdata hash for logging.
|
---|
| 1989 | # Returns undef on failure
|
---|
| 1990 | sub initRPC {
|
---|
[469] | 1991 | my $self = shift;
|
---|
| 1992 | my $dbh = $self->{dbh};
|
---|
[401] | 1993 | my %args = @_;
|
---|
| 1994 |
|
---|
| 1995 | return if !$args{username};
|
---|
| 1996 | return if !$args{fullname};
|
---|
| 1997 |
|
---|
[406] | 1998 | $args{username} = "$args{username}/$args{rpcsys}";
|
---|
| 1999 |
|
---|
| 2000 | my $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
|
---|
[404] | 2001 | " FROM users WHERE username=?", undef, ($args{username}) );
|
---|
[406] | 2002 | if (!$tmpuser) {
|
---|
[401] | 2003 | $dbh->do("INSERT INTO users (username,password,firstname,type) VALUES (?,'RPC',?,'R')", undef,
|
---|
| 2004 | ($args{username}, $args{fullname}) );
|
---|
[406] | 2005 | $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
|
---|
[404] | 2006 | " FROM users WHERE username=?", undef, ($args{username}) );
|
---|
[401] | 2007 | }
|
---|
[488] | 2008 | $tmpuser->{lastname} = '' if !$tmpuser->{lastname};
|
---|
| 2009 | $self->{loguserid} = $tmpuser->{userid};
|
---|
| 2010 | $self->{logusername} = $tmpuser->{username};
|
---|
| 2011 | $self->{logfullname} = "$tmpuser->{firstname} $tmpuser->{lastname} ($args{rpcsys})";
|
---|
[406] | 2012 | return 1 if $tmpuser;
|
---|
[401] | 2013 | } # end initRPC()
|
---|
| 2014 |
|
---|
| 2015 |
|
---|
[278] | 2016 | ## DNSDB::login()
|
---|
| 2017 | # Takes a database handle, username and password
|
---|
[316] | 2018 | # Returns a userdata hash (UID, GID, username, fullname parts) if username exists,
|
---|
| 2019 | # password matches the one on file, and account is not disabled
|
---|
[278] | 2020 | # Returns undef otherwise
|
---|
| 2021 | sub login {
|
---|
[469] | 2022 | my $self = shift;
|
---|
| 2023 | my $dbh = $self->{dbh};
|
---|
[278] | 2024 | my $user = shift;
|
---|
| 2025 | my $pass = shift;
|
---|
| 2026 |
|
---|
[316] | 2027 | my $userinfo = $dbh->selectrow_hashref("SELECT user_id,group_id,password,firstname,lastname,status".
|
---|
| 2028 | " FROM users WHERE username=?",
|
---|
[279] | 2029 | undef, ($user) );
|
---|
| 2030 | return if !$userinfo;
|
---|
[316] | 2031 | return if !$userinfo->{status};
|
---|
[278] | 2032 |
|
---|
[279] | 2033 | if ($userinfo->{password} =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
|
---|
[278] | 2034 | # native passwords (crypt-md5)
|
---|
[279] | 2035 | return if $userinfo->{password} ne unix_md5_crypt($pass,$1);
|
---|
| 2036 | } elsif ($userinfo->{password} =~ /^[0-9a-f]{32}$/) {
|
---|
[278] | 2037 | # VegaDNS import (hex-coded MD5)
|
---|
[279] | 2038 | return if $userinfo->{password} ne md5_hex($pass);
|
---|
[278] | 2039 | } else {
|
---|
| 2040 | # plaintext (convenient now and then)
|
---|
[279] | 2041 | return if $userinfo->{password} ne $pass;
|
---|
[278] | 2042 | }
|
---|
| 2043 |
|
---|
[279] | 2044 | return $userinfo;
|
---|
[278] | 2045 | } # end login()
|
---|
| 2046 |
|
---|
| 2047 |
|
---|
[279] | 2048 | ## DNSDB::initActionLog()
|
---|
| 2049 | # Set up action logging. Takes a database handle and user ID
|
---|
| 2050 | # Sets some internal globals and Does The Right Thing to set up a logging channel.
|
---|
| 2051 | # This sets up _log() to spew out log entries to the defined channel without worrying
|
---|
| 2052 | # about having to open a file or a syslog channel
|
---|
| 2053 | ##fixme Need to call _initActionLog_blah() for various logging channels, configured
|
---|
[517] | 2054 | # via dnsdb.conf, in $self->{log_channel} or something
|
---|
[279] | 2055 | # See https://secure.deepnet.cx/trac/dnsadmin/ticket/21
|
---|
| 2056 | sub initActionLog {
|
---|
[469] | 2057 | my $self = shift;
|
---|
| 2058 | my $dbh = $self->{dbh};
|
---|
[279] | 2059 | my $uid = shift;
|
---|
| 2060 |
|
---|
| 2061 | return if !$uid;
|
---|
| 2062 |
|
---|
| 2063 | # snag user info for logging. there's got to be a way to not have to pass this back
|
---|
| 2064 | # and forth from a caller, but web usage means no persistence we can rely on from
|
---|
| 2065 | # the server side.
|
---|
| 2066 | my ($username,$fullname) = $dbh->selectrow_array("SELECT username, firstname || ' ' || lastname".
|
---|
| 2067 | " FROM users WHERE user_id=?", undef, ($uid));
|
---|
| 2068 | ##fixme: errors are unpossible!
|
---|
| 2069 |
|
---|
[488] | 2070 | $self->{logusername} = $username;
|
---|
| 2071 | $self->{loguserid} = $uid;
|
---|
| 2072 | $self->{logfullname} = $fullname;
|
---|
[279] | 2073 |
|
---|
| 2074 | # convert to real check once we have other logging channels
|
---|
[517] | 2075 | # if ($self->{log_channel} eq 'sql') {
|
---|
[279] | 2076 | # Open Log, Sez Me!
|
---|
| 2077 | # }
|
---|
| 2078 |
|
---|
| 2079 | } # end initActionLog
|
---|
| 2080 |
|
---|
| 2081 |
|
---|
[65] | 2082 | ## DNSDB::getPermissions()
|
---|
| 2083 | # Get permissions from DB
|
---|
| 2084 | # Requires DB handle, group or user flag, ID, and hashref.
|
---|
| 2085 | sub getPermissions {
|
---|
[469] | 2086 | my $self = shift;
|
---|
| 2087 | my $dbh = $self->{dbh};
|
---|
| 2088 |
|
---|
[65] | 2089 | my $type = shift;
|
---|
| 2090 | my $id = shift;
|
---|
| 2091 | my $hash = shift;
|
---|
| 2092 |
|
---|
| 2093 | my $sql = qq(
|
---|
| 2094 | SELECT
|
---|
| 2095 | p.admin,p.self_edit,
|
---|
| 2096 | p.group_create,p.group_edit,p.group_delete,
|
---|
| 2097 | p.user_create,p.user_edit,p.user_delete,
|
---|
| 2098 | p.domain_create,p.domain_edit,p.domain_delete,
|
---|
[387] | 2099 | p.record_create,p.record_edit,p.record_delete,p.record_locchg,
|
---|
[382] | 2100 | p.location_create,p.location_edit,p.location_delete,p.location_view
|
---|
[65] | 2101 | FROM permissions p
|
---|
| 2102 | );
|
---|
| 2103 | if ($type eq 'group') {
|
---|
| 2104 | $sql .= qq(
|
---|
| 2105 | JOIN groups g ON g.permission_id=p.permission_id
|
---|
| 2106 | WHERE g.group_id=?
|
---|
| 2107 | );
|
---|
| 2108 | } else {
|
---|
| 2109 | $sql .= qq(
|
---|
| 2110 | JOIN users u ON u.permission_id=p.permission_id
|
---|
| 2111 | WHERE u.user_id=?
|
---|
| 2112 | );
|
---|
| 2113 | }
|
---|
| 2114 |
|
---|
| 2115 | my $sth = $dbh->prepare($sql);
|
---|
| 2116 |
|
---|
[514] | 2117 | ##fixme? we don't trap other plain SELECT errors
|
---|
| 2118 | $sth->execute($id);
|
---|
[65] | 2119 |
|
---|
| 2120 | # my $permref = $sth->fetchrow_hashref;
|
---|
| 2121 | # return $permref;
|
---|
| 2122 | # $hash = $permref;
|
---|
| 2123 | # Eww. Need to learn how to forcibly drop a hashref onto an existing hash.
|
---|
| 2124 | ($hash->{admin},$hash->{self_edit},
|
---|
| 2125 | $hash->{group_create},$hash->{group_edit},$hash->{group_delete},
|
---|
| 2126 | $hash->{user_create},$hash->{user_edit},$hash->{user_delete},
|
---|
| 2127 | $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete},
|
---|
[387] | 2128 | $hash->{record_create},$hash->{record_edit},$hash->{record_delete},$hash->{record_locchg},
|
---|
[382] | 2129 | $hash->{location_create},$hash->{location_edit},$hash->{location_delete},$hash->{location_view}
|
---|
| 2130 | ) = $sth->fetchrow_array;
|
---|
[65] | 2131 |
|
---|
| 2132 | } # end getPermissions()
|
---|
| 2133 |
|
---|
| 2134 |
|
---|
| 2135 | ## DNSDB::changePermissions()
|
---|
| 2136 | # Update an ACL entry
|
---|
| 2137 | # Takes a db handle, type, owner-id, and hashref for the changed permissions.
|
---|
| 2138 | sub changePermissions {
|
---|
[474] | 2139 | my $self = shift;
|
---|
| 2140 | my $dbh = $self->{dbh};
|
---|
[65] | 2141 | my $type = shift;
|
---|
| 2142 | my $id = shift;
|
---|
| 2143 | my $newperms = shift;
|
---|
[87] | 2144 | my $inherit = shift || 0;
|
---|
[65] | 2145 |
|
---|
[294] | 2146 | my $resultmsg = '';
|
---|
[66] | 2147 |
|
---|
[87] | 2148 | # see if we're switching from inherited to custom. for bonus points,
|
---|
| 2149 | # snag the permid and parent permid anyway, since we'll need the permid
|
---|
| 2150 | # to set/alter custom perms, and both if we're switching from custom to
|
---|
| 2151 | # inherited.
|
---|
[294] | 2152 | my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id,".
|
---|
| 2153 | ($type eq 'user' ? 'u.group_id,u.username' : 'u.parent_group_id,u.group_name').
|
---|
[65] | 2154 | " FROM ".($type eq 'user' ? 'users' : 'groups')." u ".
|
---|
[66] | 2155 | " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ".
|
---|
[65] | 2156 | " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?");
|
---|
| 2157 | $sth->execute($id);
|
---|
| 2158 |
|
---|
[294] | 2159 | my ($wasinherited,$permid,$parpermid,$parid,$name) = $sth->fetchrow_array;
|
---|
[66] | 2160 |
|
---|
[78] | 2161 | # hack phtoui
|
---|
| 2162 | # group id 1 is "special" in that it's it's own parent (err... possibly.)
|
---|
| 2163 | # may make its parent id 0 which doesn't exist, and as a bonus is Perl-false.
|
---|
| 2164 | $wasinherited = 0 if ($type eq 'group' && $id == 1);
|
---|
| 2165 |
|
---|
[66] | 2166 | local $dbh->{AutoCommit} = 0;
|
---|
| 2167 | local $dbh->{RaiseError} = 1;
|
---|
| 2168 |
|
---|
| 2169 | # Wrap all the SQL in a transaction
|
---|
| 2170 | eval {
|
---|
[87] | 2171 | if ($inherit) {
|
---|
| 2172 |
|
---|
| 2173 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ".
|
---|
| 2174 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) );
|
---|
| 2175 | $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) );
|
---|
| 2176 |
|
---|
| 2177 | } else {
|
---|
| 2178 |
|
---|
| 2179 | if ($wasinherited) { # munge new permission entry in if we're switching from inherited perms
|
---|
[66] | 2180 | ##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users
|
---|
[87] | 2181 | # ... if'n'when we have groups with fully inherited permissions.
|
---|
| 2182 | # SQL is coo
|
---|
| 2183 | $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ".
|
---|
| 2184 | "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) );
|
---|
| 2185 | ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ".
|
---|
| 2186 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) );
|
---|
| 2187 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ".
|
---|
| 2188 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) );
|
---|
[66] | 2189 | }
|
---|
[78] | 2190 |
|
---|
[87] | 2191 | # and now set the permissions we were passed
|
---|
| 2192 | foreach (@permtypes) {
|
---|
| 2193 | if (defined ($newperms->{$_})) {
|
---|
| 2194 | $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) );
|
---|
| 2195 | }
|
---|
| 2196 | }
|
---|
| 2197 |
|
---|
| 2198 | } # (inherited->)? custom
|
---|
| 2199 |
|
---|
[294] | 2200 | if ($type eq 'user') {
|
---|
| 2201 | $resultmsg = "Updated permissions for user $name";
|
---|
| 2202 | } else {
|
---|
| 2203 | $resultmsg = "Updated default permissions for group $name";
|
---|
| 2204 | }
|
---|
[487] | 2205 | $self->_log(group_id => ($type eq 'user' ? $parid : $id), entry => $resultmsg);
|
---|
[66] | 2206 | $dbh->commit;
|
---|
| 2207 | }; # end eval
|
---|
| 2208 | if ($@) {
|
---|
| 2209 | my $msg = $@;
|
---|
| 2210 | eval { $dbh->rollback; };
|
---|
[294] | 2211 | return ('FAIL',"Error changing permissions: $msg");
|
---|
[66] | 2212 | }
|
---|
| 2213 |
|
---|
[294] | 2214 | return ('OK',$resultmsg);
|
---|
[65] | 2215 | } # end changePermissions()
|
---|
| 2216 |
|
---|
| 2217 |
|
---|
[67] | 2218 | ## DNSDB::comparePermissions()
|
---|
| 2219 | # Compare two permission hashes
|
---|
| 2220 | # Returns '>', '<', '=', '!'
|
---|
| 2221 | sub comparePermissions {
|
---|
[592] | 2222 | my $self = shift;
|
---|
[67] | 2223 | my $p1 = shift;
|
---|
| 2224 | my $p2 = shift;
|
---|
| 2225 |
|
---|
| 2226 | my $retval = '='; # assume equality until proven otherwise
|
---|
| 2227 |
|
---|
| 2228 | no warnings "uninitialized";
|
---|
| 2229 |
|
---|
| 2230 | foreach (@permtypes) {
|
---|
| 2231 | next if $p1->{$_} == $p2->{$_}; # equal is good
|
---|
| 2232 | if ($p1->{$_} && !$p2->{$_}) {
|
---|
| 2233 | if ($retval eq '<') { # if we've already found an unequal pair where
|
---|
| 2234 | $retval = '!'; # $p2 has more access, and we now find a pair
|
---|
| 2235 | last; # where $p1 has more access, the overall access
|
---|
| 2236 | } # is neither greater or lesser, it's unequal.
|
---|
| 2237 | $retval = '>';
|
---|
| 2238 | }
|
---|
| 2239 | if (!$p1->{$_} && $p2->{$_}) {
|
---|
| 2240 | if ($retval eq '>') { # if we've already found an unequal pair where
|
---|
| 2241 | $retval = '!'; # $p1 has more access, and we now find a pair
|
---|
| 2242 | last; # where $p2 has more access, the overall access
|
---|
| 2243 | } # is neither greater or lesser, it's unequal.
|
---|
| 2244 | $retval = '<';
|
---|
| 2245 | }
|
---|
| 2246 | }
|
---|
| 2247 | return $retval;
|
---|
| 2248 | } # end comparePermissions()
|
---|
| 2249 |
|
---|
| 2250 |
|
---|
[112] | 2251 | ## DNSDB::changeGroup()
|
---|
| 2252 | # Change group ID of an entity
|
---|
| 2253 | # Takes a database handle, entity type, entity ID, and new group ID
|
---|
| 2254 | sub changeGroup {
|
---|
[476] | 2255 | my $self = shift;
|
---|
| 2256 | my $dbh = $self->{dbh};
|
---|
[112] | 2257 | my $type = shift;
|
---|
| 2258 | my $id = shift;
|
---|
| 2259 | my $newgrp = shift;
|
---|
| 2260 |
|
---|
| 2261 | ##fixme: fail on not enough args
|
---|
| 2262 | #return ('FAIL', "Missing
|
---|
| 2263 |
|
---|
[295] | 2264 | return ('FAIL', "Can't change the group of a $type")
|
---|
| 2265 | unless grep /^$type$/, ('domain','revzone','user','group'); # could be extended for defrecs?
|
---|
| 2266 |
|
---|
| 2267 | # Collect some names for logging and messages
|
---|
| 2268 | my $entname;
|
---|
[112] | 2269 | if ($type eq 'domain') {
|
---|
[473] | 2270 | $entname = $self->domainName($id);
|
---|
[295] | 2271 | } elsif ($type eq 'revzone') {
|
---|
[473] | 2272 | $entname = $self->revName($id);
|
---|
[112] | 2273 | } elsif ($type eq 'user') {
|
---|
[473] | 2274 | $entname = $self->userFullName($id, '%u');
|
---|
[112] | 2275 | } elsif ($type eq 'group') {
|
---|
[473] | 2276 | $entname = $self->groupName($id);
|
---|
[112] | 2277 | }
|
---|
[295] | 2278 |
|
---|
| 2279 | my ($oldgid) = $dbh->selectrow_array("SELECT group_id FROM $par_tbl{$type} WHERE $id_col{$type}=?",
|
---|
| 2280 | undef, ($id));
|
---|
[473] | 2281 | my $oldgname = $self->groupName($oldgid);
|
---|
| 2282 | my $newgname = $self->groupName($newgrp);
|
---|
[295] | 2283 |
|
---|
| 2284 | return ('FAIL', "Can't move things into a group that doesn't exist") if !$newgname;
|
---|
| 2285 |
|
---|
| 2286 | return ('WARN', "Nothing to do, new group is the same as the old group") if $oldgid == $newgrp;
|
---|
| 2287 |
|
---|
| 2288 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2289 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2290 | local $dbh->{AutoCommit} = 0;
|
---|
| 2291 | local $dbh->{RaiseError} = 1;
|
---|
| 2292 |
|
---|
| 2293 | eval {
|
---|
| 2294 | $dbh->do("UPDATE $par_tbl{$type} SET group_id=? WHERE $id_col{$type}=?", undef, ($newgrp, $id));
|
---|
| 2295 | # Log the change in both the old and new groups
|
---|
[487] | 2296 | $self->_log(group_id => $oldgid, entry => "Moved $type $entname from $oldgname to $newgname");
|
---|
| 2297 | $self->_log(group_id => $newgrp, entry => "Moved $type $entname from $oldgname to $newgname");
|
---|
[295] | 2298 | $dbh->commit;
|
---|
| 2299 | };
|
---|
| 2300 | if ($@) {
|
---|
| 2301 | my $msg = $@;
|
---|
| 2302 | eval { $dbh->rollback; };
|
---|
[517] | 2303 | if ($self->{log_failures}) {
|
---|
[487] | 2304 | $self->_log(group_id => $oldgid, entry => "Error moving $type $entname to $newgname: $msg");
|
---|
[295] | 2305 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2306 | }
|
---|
| 2307 | return ('FAIL',"Error moving $type $entname to $newgname: $msg");
|
---|
| 2308 | }
|
---|
| 2309 |
|
---|
| 2310 | return ('OK',"Moved $type $entname from $oldgname to $newgname");
|
---|
[112] | 2311 | } # end changeGroup()
|
---|
| 2312 |
|
---|
| 2313 |
|
---|
[2] | 2314 | ##
|
---|
| 2315 | ## Processing subs
|
---|
| 2316 | ##
|
---|
| 2317 |
|
---|
| 2318 | ## DNSDB::addDomain()
|
---|
| 2319 | # Add a domain
|
---|
[190] | 2320 | # Takes a database handle, domain name, numeric group, boolean(ish) state (active/inactive),
|
---|
[704] | 2321 | # and a default location indicator
|
---|
[2] | 2322 | # Returns a status code and message
|
---|
| 2323 | sub addDomain {
|
---|
| 2324 | $errstr = '';
|
---|
[477] | 2325 | my $self = shift;
|
---|
| 2326 | my $dbh = $self->{dbh};
|
---|
[2] | 2327 | my $domain = shift;
|
---|
[497] | 2328 | return ('FAIL',"Domain must not be blank\n") if !$domain;
|
---|
[2] | 2329 | my $group = shift;
|
---|
[497] | 2330 | return ('FAIL',"Group must be specified\n") if !defined($group);
|
---|
[2] | 2331 | my $state = shift;
|
---|
[497] | 2332 | return ('FAIL',"Domain status must be specified\n") if !defined($state);
|
---|
[516] | 2333 | my $defloc = shift || '';
|
---|
[2] | 2334 |
|
---|
[116] | 2335 | $state = 1 if $state =~ /^active$/;
|
---|
| 2336 | $state = 1 if $state =~ /^on$/;
|
---|
| 2337 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 2338 | $state = 0 if $state =~ /^off$/;
|
---|
| 2339 |
|
---|
| 2340 | return ('FAIL',"Invalid domain status") if $state !~ /^\d+$/;
|
---|
| 2341 |
|
---|
[542] | 2342 | $domain = lc($domain) if $self->{lowercase};
|
---|
| 2343 |
|
---|
[190] | 2344 | return ('FAIL', "Invalid characters in domain") if $domain !~ /^[a-zA-Z0-9_.-]+$/;
|
---|
| 2345 |
|
---|
[707] | 2346 | my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE lower(domain) = lower(?) AND default_location = ?");
|
---|
[3] | 2347 | my $dom_id;
|
---|
| 2348 |
|
---|
[38] | 2349 | # quick check to start to see if we've already got one
|
---|
[704] | 2350 | $sth->execute($domain, $defloc);
|
---|
[38] | 2351 | ($dom_id) = $sth->fetchrow_array;
|
---|
| 2352 |
|
---|
| 2353 | return ('FAIL', "Domain already exists") if $dom_id;
|
---|
| 2354 |
|
---|
[2] | 2355 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2356 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2357 | local $dbh->{AutoCommit} = 0;
|
---|
| 2358 | local $dbh->{RaiseError} = 1;
|
---|
| 2359 |
|
---|
| 2360 | # Wrap all the SQL in a transaction
|
---|
| 2361 | eval {
|
---|
| 2362 | # insert the domain...
|
---|
[516] | 2363 | $dbh->do("INSERT INTO domains (domain,group_id,status,default_location) VALUES (?,?,?,?)", undef,
|
---|
| 2364 | ($domain, $group, $state, $defloc));
|
---|
[2] | 2365 |
|
---|
| 2366 | # get the ID...
|
---|
[707] | 2367 | ($dom_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?) AND default_location = ?",
|
---|
[704] | 2368 | undef, ($domain, $defloc));
|
---|
[2] | 2369 |
|
---|
[487] | 2370 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
| 2371 | entry => "Added ".($state ? 'active' : 'inactive')." domain $domain");
|
---|
[190] | 2372 |
|
---|
[2] | 2373 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
[190] | 2374 | my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
[516] | 2375 | my $sth_in = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,distance,weight,port,ttl,location)".
|
---|
| 2376 | " VALUES ($dom_id,?,?,?,?,?,?,?,?)");
|
---|
[190] | 2377 | $sth->execute($group);
|
---|
[516] | 2378 | while (my ($host, $type, $val, $dist, $weight, $port, $ttl) = $sth->fetchrow_array()) {
|
---|
[2] | 2379 | $host =~ s/DOMAIN/$domain/g;
|
---|
[37] | 2380 | $val =~ s/DOMAIN/$domain/g;
|
---|
[617] | 2381 | _caseclean(\$type, \$host, \$val, 'n', 'n') if $self->{lowercase};
|
---|
[516] | 2382 | $sth_in->execute($host, $type, $val, $dist, $weight, $port, $ttl, $defloc);
|
---|
[190] | 2383 | if ($typemap{$type} eq 'SOA') {
|
---|
| 2384 | my @tmp1 = split /:/, $host;
|
---|
| 2385 | my @tmp2 = split /:/, $val;
|
---|
[487] | 2386 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
[284] | 2387 | entry => "[new $domain] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
[487] | 2388 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl");
|
---|
[190] | 2389 | } else {
|
---|
| 2390 | my $logentry = "[new $domain] Added record '$host $typemap{$type}";
|
---|
| 2391 | $logentry .= " [distance $dist]" if $typemap{$type} eq 'MX';
|
---|
| 2392 | $logentry .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$type} eq 'SRV';
|
---|
[487] | 2393 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
| 2394 | entry => $logentry." $val', TTL $ttl");
|
---|
[190] | 2395 | }
|
---|
[2] | 2396 | }
|
---|
| 2397 |
|
---|
| 2398 | # once we get here, we should have suceeded.
|
---|
| 2399 | $dbh->commit;
|
---|
| 2400 | }; # end eval
|
---|
| 2401 |
|
---|
| 2402 | if ($@) {
|
---|
| 2403 | my $msg = $@;
|
---|
| 2404 | eval { $dbh->rollback; };
|
---|
[487] | 2405 | $self->_log(group_id => $group, entry => "Failed adding domain $domain ($msg)")
|
---|
[517] | 2406 | if $self->{log_failures};
|
---|
[284] | 2407 | $dbh->commit; # since we enabled transactions earlier
|
---|
[193] | 2408 | return ('FAIL',$msg);
|
---|
[2] | 2409 | } else {
|
---|
[3] | 2410 | return ('OK',$dom_id);
|
---|
[2] | 2411 | }
|
---|
| 2412 | } # end addDomain
|
---|
| 2413 |
|
---|
| 2414 |
|
---|
[274] | 2415 | ## DNSDB::delZone()
|
---|
| 2416 | # Delete a forward or reverse zone.
|
---|
| 2417 | # Takes a database handle, zone ID, and forward/reverse flag.
|
---|
[3] | 2418 | # for now, just delete the records, then the domain.
|
---|
| 2419 | # later we may want to archive it in some way instead (status code 2, for example?)
|
---|
[274] | 2420 | sub delZone {
|
---|
[477] | 2421 | my $self = shift;
|
---|
| 2422 | my $dbh = $self->{dbh};
|
---|
[274] | 2423 | my $zoneid = shift;
|
---|
| 2424 | my $revrec = shift;
|
---|
[3] | 2425 |
|
---|
| 2426 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2427 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2428 | local $dbh->{AutoCommit} = 0;
|
---|
| 2429 | local $dbh->{RaiseError} = 1;
|
---|
| 2430 |
|
---|
[687] | 2431 | return ('FAIL', 'Need a zone identifier to look up') if !$zoneid;
|
---|
| 2432 |
|
---|
[285] | 2433 | my $msg = '';
|
---|
[23] | 2434 | my $failmsg = '';
|
---|
[473] | 2435 | my $zone = ($revrec eq 'n' ? $self->domainName($zoneid) : $self->revName($zoneid));
|
---|
[23] | 2436 |
|
---|
[343] | 2437 | return ('FAIL', ($revrec eq 'n' ? 'Domain' : 'Reverse zone')." ID $zoneid doesn't exist") if !$zone;
|
---|
| 2438 |
|
---|
[517] | 2439 | # Set this up here since we may use if if $self->{log_failures} is enabled
|
---|
[285] | 2440 | my %loghash;
|
---|
| 2441 | $loghash{domain_id} = $zoneid if $revrec eq 'n';
|
---|
| 2442 | $loghash{rdns_id} = $zoneid if $revrec eq 'y';
|
---|
[473] | 2443 | $loghash{group_id} = $self->parentID(
|
---|
| 2444 | id => $zoneid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec);
|
---|
[285] | 2445 |
|
---|
[3] | 2446 | # Wrap all the SQL in a transaction
|
---|
| 2447 | eval {
|
---|
[274] | 2448 | # Disentangle custom record types before removing the
|
---|
| 2449 | # ones that are only in the zone to be deleted
|
---|
| 2450 | if ($revrec eq 'n') {
|
---|
| 2451 | my $sth = $dbh->prepare("UPDATE records SET type=?,domain_id=0 WHERE domain_id=? AND type=?");
|
---|
| 2452 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
| 2453 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65280);
|
---|
| 2454 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65281);
|
---|
| 2455 | $sth->execute(65282, $zoneid, 65283);
|
---|
| 2456 | $sth->execute(65282, $zoneid, 65284);
|
---|
| 2457 | $failmsg = "Failure removing domain records";
|
---|
| 2458 | $dbh->do("DELETE FROM records WHERE domain_id=?", undef, ($zoneid));
|
---|
| 2459 | $failmsg = "Failure removing domain";
|
---|
| 2460 | $dbh->do("DELETE FROM domains WHERE domain_id=?", undef, ($zoneid));
|
---|
| 2461 | } else {
|
---|
| 2462 | my $sth = $dbh->prepare("UPDATE records SET type=?,rdns_id=0 WHERE rdns_id=? AND type=?");
|
---|
| 2463 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
| 2464 | $sth->execute($reverse_typemap{A}, $zoneid, 65280);
|
---|
| 2465 | $sth->execute($reverse_typemap{AAAA}, $zoneid, 65281);
|
---|
| 2466 | # We don't have an "A template" or "AAAA template" type, although it might be useful for symmetry.
|
---|
[345] | 2467 | # $sth->execute(65286?, $zoneid, 65283);
|
---|
| 2468 | # $sth->execute(65286?, $zoneid, 65284);
|
---|
[274] | 2469 | $failmsg = "Failure removing reverse records";
|
---|
| 2470 | $dbh->do("DELETE FROM records WHERE rdns_id=?", undef, ($zoneid));
|
---|
| 2471 | $failmsg = "Failure removing reverse zone";
|
---|
| 2472 | $dbh->do("DELETE FROM revzones WHERE rdns_id=?", undef, ($zoneid));
|
---|
| 2473 | }
|
---|
[3] | 2474 |
|
---|
[285] | 2475 | $msg = "Deleted ".($revrec eq 'n' ? 'domain' : 'reverse zone')." $zone";
|
---|
| 2476 | $loghash{entry} = $msg;
|
---|
[487] | 2477 | $self->_log(%loghash);
|
---|
[285] | 2478 |
|
---|
[3] | 2479 | # once we get here, we should have suceeded.
|
---|
[23] | 2480 | $dbh->commit;
|
---|
[3] | 2481 | }; # end eval
|
---|
| 2482 |
|
---|
| 2483 | if ($@) {
|
---|
[285] | 2484 | $msg = $@;
|
---|
[3] | 2485 | eval { $dbh->rollback; };
|
---|
[295] | 2486 | $loghash{entry} = "Error deleting $zone: $msg ($failmsg)";
|
---|
[517] | 2487 | if ($self->{log_failures}) {
|
---|
[487] | 2488 | $self->_log(%loghash);
|
---|
[295] | 2489 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2490 | }
|
---|
| 2491 | return ('FAIL', $loghash{entry});
|
---|
[3] | 2492 | } else {
|
---|
[295] | 2493 | return ('OK', $msg);
|
---|
[3] | 2494 | }
|
---|
| 2495 |
|
---|
[274] | 2496 | } # end delZone()
|
---|
[3] | 2497 |
|
---|
| 2498 |
|
---|
[2] | 2499 | ## DNSDB::domainName()
|
---|
| 2500 | # Return the domain name based on a domain ID
|
---|
| 2501 | # Takes a database handle and the domain ID
|
---|
| 2502 | # Returns the domain name or undef on failure
|
---|
| 2503 | sub domainName {
|
---|
| 2504 | $errstr = '';
|
---|
[473] | 2505 | my $self = shift;
|
---|
| 2506 | my $dbh = $self->{dbh};
|
---|
[2] | 2507 | my $domid = shift;
|
---|
[91] | 2508 | my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
|
---|
[2] | 2509 | $errstr = $DBI::errstr if !$domname;
|
---|
| 2510 | return $domname if $domname;
|
---|
[91] | 2511 | } # end domainName()
|
---|
[2] | 2512 |
|
---|
| 2513 |
|
---|
[224] | 2514 | ## DNSDB::revName()
|
---|
| 2515 | # Return the reverse zone name based on an rDNS ID
|
---|
[583] | 2516 | # Takes a database handle and the rDNS ID, and an optional flag to force return of the CIDR zone
|
---|
| 2517 | # instead of the formal .arpa zone name
|
---|
[224] | 2518 | # Returns the reverse zone name or undef on failure
|
---|
| 2519 | sub revName {
|
---|
| 2520 | $errstr = '';
|
---|
[473] | 2521 | my $self = shift;
|
---|
| 2522 | my $dbh = $self->{dbh};
|
---|
[224] | 2523 | my $revid = shift;
|
---|
[583] | 2524 | my $cidrflag = shift || 'n';
|
---|
[224] | 2525 | my ($revname) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id=?", undef, ($revid) );
|
---|
| 2526 | $errstr = $DBI::errstr if !$revname;
|
---|
[583] | 2527 | my $tmp = new NetAddr::IP $revname;
|
---|
| 2528 | $revname = _ZONE($tmp, 'ZONE', 'r', '.').($tmp->{isv6} ? '.ip6.arpa' : '.in-addr.arpa')
|
---|
| 2529 | if ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all') && $cidrflag eq 'n';
|
---|
[224] | 2530 | return $revname if $revname;
|
---|
| 2531 | } # end revName()
|
---|
| 2532 |
|
---|
| 2533 |
|
---|
[91] | 2534 | ## DNSDB::domainID()
|
---|
| 2535 | # Takes a database handle and domain name
|
---|
| 2536 | # Returns the domain ID number
|
---|
| 2537 | sub domainID {
|
---|
| 2538 | $errstr = '';
|
---|
[473] | 2539 | my $self = shift;
|
---|
| 2540 | my $dbh = $self->{dbh};
|
---|
[91] | 2541 | my $domain = shift;
|
---|
[719] | 2542 | my $location = shift;
|
---|
| 2543 |
|
---|
| 2544 | # Note that location may be *empty*, but it may not be *undefined*
|
---|
| 2545 | if (!defined($location)) {
|
---|
| 2546 | $errstr = "Missing location";
|
---|
| 2547 | return;
|
---|
| 2548 | }
|
---|
| 2549 |
|
---|
| 2550 | my ($domid) = $dbh->selectrow_array(
|
---|
| 2551 | "SELECT domain_id FROM domains WHERE lower(domain) = lower(?) AND default_location = ?",
|
---|
| 2552 | undef, ($domain, $location) );
|
---|
[501] | 2553 | if (!$domid) {
|
---|
| 2554 | if ($dbh->err) {
|
---|
| 2555 | $errstr = $DBI::errstr;
|
---|
| 2556 | } else {
|
---|
| 2557 | $errstr = "Domain $domain not present";
|
---|
| 2558 | }
|
---|
| 2559 | }
|
---|
[91] | 2560 | return $domid if $domid;
|
---|
| 2561 | } # end domainID()
|
---|
| 2562 |
|
---|
| 2563 |
|
---|
[276] | 2564 | ## DNSDB::revID()
|
---|
| 2565 | # Takes a database handle and reverse zone name
|
---|
| 2566 | # Returns the rDNS ID number
|
---|
| 2567 | sub revID {
|
---|
| 2568 | $errstr = '';
|
---|
[473] | 2569 | my $self = shift;
|
---|
| 2570 | my $dbh = $self->{dbh};
|
---|
[276] | 2571 | my $revzone = shift;
|
---|
[719] | 2572 | my $location = shift;
|
---|
| 2573 |
|
---|
| 2574 | # Note that location may be *empty*, but it may not be *undefined*
|
---|
| 2575 | if (!defined($location)) {
|
---|
| 2576 | $errstr = "Missing location";
|
---|
| 2577 | return;
|
---|
| 2578 | }
|
---|
| 2579 |
|
---|
| 2580 | my ($revid) = $dbh->selectrow_array(
|
---|
| 2581 | "SELECT rdns_id FROM revzones WHERE revnet = ? AND default_location = ?",
|
---|
| 2582 | undef, ($revzone, $location) );
|
---|
[501] | 2583 | if (!$revid) {
|
---|
| 2584 | if ($dbh->err) {
|
---|
| 2585 | $errstr = $DBI::errstr;
|
---|
| 2586 | } else {
|
---|
| 2587 | $errstr = "Reverse zone $revzone not present";
|
---|
| 2588 | }
|
---|
| 2589 | }
|
---|
[276] | 2590 | return $revid if $revid;
|
---|
| 2591 | } # end revID()
|
---|
| 2592 |
|
---|
| 2593 |
|
---|
[260] | 2594 | ## DNSDB::addRDNS
|
---|
| 2595 | # Adds a reverse DNS zone
|
---|
[286] | 2596 | # Takes a database handle, CIDR block, reverse DNS pattern, numeric group,
|
---|
| 2597 | # and boolean(ish) state (active/inactive)
|
---|
[260] | 2598 | # Returns a status code and message
|
---|
| 2599 | sub addRDNS {
|
---|
[477] | 2600 | my $self = shift;
|
---|
| 2601 | my $dbh = $self->{dbh};
|
---|
[583] | 2602 | my $zone = shift;
|
---|
[446] | 2603 |
|
---|
[583] | 2604 | # Autodetect formal .arpa zones
|
---|
| 2605 | if ($zone =~ /\.arpa\.?$/) {
|
---|
| 2606 | my $code;
|
---|
| 2607 | ($code,$zone) = _zone2cidr($zone);
|
---|
| 2608 | return ('FAIL', $zone) if $code eq 'FAIL';
|
---|
| 2609 | }
|
---|
| 2610 | $zone = NetAddr::IP->new($zone);
|
---|
| 2611 |
|
---|
[260] | 2612 | return ('FAIL',"Zone name must be a valid CIDR netblock") unless ($zone && $zone->addr !~ /^0/);
|
---|
[270] | 2613 | my $revpatt = shift; # construct a custom (A/AAAA+)? PTR template record
|
---|
[260] | 2614 | my $group = shift;
|
---|
| 2615 | my $state = shift;
|
---|
[446] | 2616 | my $defloc = shift || '';
|
---|
[260] | 2617 |
|
---|
| 2618 | $state = 1 if $state =~ /^active$/;
|
---|
| 2619 | $state = 1 if $state =~ /^on$/;
|
---|
| 2620 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 2621 | $state = 0 if $state =~ /^off$/;
|
---|
| 2622 |
|
---|
| 2623 | return ('FAIL',"Invalid zone status") if $state !~ /^\d+$/;
|
---|
| 2624 |
|
---|
| 2625 | # quick check to start to see if we've already got one
|
---|
[704] | 2626 | my ($rdns_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet = ? AND default_location = ?",
|
---|
| 2627 | undef, ("$zone", $defloc));
|
---|
[260] | 2628 |
|
---|
| 2629 | return ('FAIL', "Zone already exists") if $rdns_id;
|
---|
| 2630 |
|
---|
| 2631 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2632 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2633 | local $dbh->{AutoCommit} = 0;
|
---|
| 2634 | local $dbh->{RaiseError} = 1;
|
---|
| 2635 |
|
---|
[264] | 2636 | my $warnstr = '';
|
---|
[270] | 2637 | my $defttl = 3600; # 1 hour should be reasonable. And unless things have gone horribly
|
---|
| 2638 | # wrong, we should have a value to override this anyway.
|
---|
[264] | 2639 |
|
---|
[260] | 2640 | # Wrap all the SQL in a transaction
|
---|
| 2641 | eval {
|
---|
[446] | 2642 | # insert the zone...
|
---|
| 2643 | $dbh->do("INSERT INTO revzones (revnet,group_id,status,default_location) VALUES (?,?,?,?)", undef,
|
---|
| 2644 | ($zone, $group, $state, $defloc) );
|
---|
[260] | 2645 |
|
---|
| 2646 | # get the ID...
|
---|
| 2647 | ($rdns_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
| 2648 |
|
---|
[487] | 2649 | $self->_log(rdns_id => $rdns_id, group_id => $group,
|
---|
| 2650 | entry => "Added ".($state ? 'active' : 'inactive')." reverse zone $zone");
|
---|
[260] | 2651 |
|
---|
| 2652 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
| 2653 | my $sth = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
[446] | 2654 | my $sth_in = $dbh->prepare("INSERT INTO records (rdns_id,domain_id,host,type,val,ttl,location)".
|
---|
| 2655 | " VALUES ($rdns_id,?,?,?,?,?,?)");
|
---|
[260] | 2656 | $sth->execute($group);
|
---|
| 2657 | while (my ($host,$type,$val,$ttl) = $sth->fetchrow_array()) {
|
---|
[264] | 2658 | # Silently skip v4/v6 mismatches. This is not an error, this is expected.
|
---|
| 2659 | if ($zone->{isv6}) {
|
---|
| 2660 | next if ($type == 65280 || $type == 65283);
|
---|
| 2661 | } else {
|
---|
| 2662 | next if ($type == 65281 || $type == 65284);
|
---|
| 2663 | }
|
---|
[269] | 2664 |
|
---|
[517] | 2665 | $host =~ s/ADMINDOMAIN/$self->{domain}/g;
|
---|
[264] | 2666 |
|
---|
[265] | 2667 | # Check to make sure the IP stubs will fit in the zone. Under most usage failures here should be rare.
|
---|
| 2668 | # On failure, tack a note on to a warning string and continue without adding this record.
|
---|
| 2669 | # While we're at it, we substitute $zone for ZONE in the value.
|
---|
| 2670 | if ($val eq 'ZONE') {
|
---|
[444] | 2671 | # If we've got a pattern, we skip the default record version on (A+)PTR-template types
|
---|
| 2672 | next if $revpatt && ($type == 65282 || $type == 65283);
|
---|
[269] | 2673 | ##fixme? do we care if we have multiple whole-zone templates?
|
---|
[265] | 2674 | $val = $zone->network;
|
---|
| 2675 | } elsif ($val =~ /ZONE/) {
|
---|
| 2676 | my $tmpval = $val;
|
---|
| 2677 | $tmpval =~ s/ZONE//;
|
---|
[269] | 2678 | # Bend the rules and allow single-trailing-number PTR or PTR template records to be inserted
|
---|
| 2679 | # as either v4 or v6. May make this an off-by-default config flag
|
---|
| 2680 | # Note that the origin records that may trigger this **SHOULD** already have ZONE,\d
|
---|
| 2681 | if ($type == 12 || $type == 65282) {
|
---|
| 2682 | $tmpval =~ s/[,.]/::/ if ($tmpval =~ /^[,.]\d+$/ && $zone->{isv6});
|
---|
| 2683 | $tmpval =~ s/[,:]+/./ if ($tmpval =~ /^(?:,|::)\d+$/ && !$zone->{isv6});
|
---|
| 2684 | }
|
---|
[265] | 2685 | my $addr;
|
---|
[471] | 2686 | if ($self->_ipparent('n', 'y', \$tmpval, $rdns_id, \$addr)) {
|
---|
[265] | 2687 | $val = $addr->addr;
|
---|
| 2688 | } else {
|
---|
[269] | 2689 | $warnstr .= "\nDefault record '$val $typemap{$type} $host' doesn't fit in $zone, skipping";
|
---|
[264] | 2690 | next;
|
---|
| 2691 | }
|
---|
| 2692 | }
|
---|
| 2693 |
|
---|
[328] | 2694 | # Substitute $zone for ZONE in the hostname, but only for non-NS records.
|
---|
| 2695 | # NS records get this substitution on the value instead.
|
---|
| 2696 | $host = _ZONE($zone, $host) if $type != 2;
|
---|
[265] | 2697 |
|
---|
[269] | 2698 | # Fill in the forward domain ID if we can find it, otherwise:
|
---|
| 2699 | # Coerce type down to PTR or PTR template if we can't
|
---|
| 2700 | my $domid = 0;
|
---|
| 2701 | if ($type >= 65280) {
|
---|
[471] | 2702 | if (!($domid = $self->_hostparent($host))) {
|
---|
[269] | 2703 | $warnstr .= "\nRecord added as PTR instead of $typemap{$type}; domain not found for $host";
|
---|
| 2704 | $type = $reverse_typemap{PTR};
|
---|
| 2705 | $domid = 0; # just to be explicit.
|
---|
| 2706 | }
|
---|
| 2707 | }
|
---|
| 2708 |
|
---|
[617] | 2709 | _caseclean(\$type, \$host, \$val, 'n', 'y') if $self->{lowercase};
|
---|
| 2710 |
|
---|
[446] | 2711 | $sth_in->execute($domid,$host,$type,$val,$ttl,$defloc);
|
---|
[269] | 2712 |
|
---|
[260] | 2713 | if ($typemap{$type} eq 'SOA') {
|
---|
| 2714 | my @tmp1 = split /:/, $host;
|
---|
| 2715 | my @tmp2 = split /:/, $val;
|
---|
[487] | 2716 | $self->_log(rdns_id => $rdns_id, group_id => $group,
|
---|
[286] | 2717 | entry => "[new $zone] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
[487] | 2718 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl");
|
---|
[270] | 2719 | $defttl = $tmp2[3];
|
---|
[260] | 2720 | } else {
|
---|
[446] | 2721 | my $logentry = "[new $zone] Added record '$host $typemap{$type} $val', TTL $ttl";
|
---|
[480] | 2722 | $logentry .= ", default location ".$self->getLoc($defloc)->{description} if $defloc;
|
---|
[487] | 2723 | $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group, entry => $logentry);
|
---|
[260] | 2724 | }
|
---|
| 2725 | }
|
---|
| 2726 |
|
---|
[270] | 2727 | # Generate record based on provided pattern.
|
---|
| 2728 | if ($revpatt) {
|
---|
| 2729 | my $host;
|
---|
| 2730 | my $type = ($zone->{isv6} ? 65284 : 65283);
|
---|
| 2731 | my $val = $zone->network;
|
---|
[269] | 2732 |
|
---|
[270] | 2733 | # Substitute $zone for ZONE in the hostname.
|
---|
| 2734 | $host = _ZONE($zone, $revpatt);
|
---|
| 2735 |
|
---|
| 2736 | my $domid = 0;
|
---|
[471] | 2737 | if (!($domid = $self->_hostparent($host))) {
|
---|
[270] | 2738 | $warnstr .= "\nDefault pattern added as PTR template instead of $typemap{$type}; domain not found for $host";
|
---|
| 2739 | $type = 65282;
|
---|
| 2740 | $domid = 0; # just to be explicit.
|
---|
| 2741 | }
|
---|
| 2742 |
|
---|
[446] | 2743 | $sth_in->execute($domid,$host,$type,$val,$defttl,$defloc);
|
---|
[286] | 2744 | my $logentry = "[new $zone] Added record '$host $typemap{$type}";
|
---|
[487] | 2745 | $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group,
|
---|
| 2746 | entry => $logentry." $val', TTL $defttl from pattern");
|
---|
[270] | 2747 | }
|
---|
| 2748 |
|
---|
[264] | 2749 | # If there are warnings (presumably about default records skipped for cause) log them
|
---|
[487] | 2750 | $self->_log(rdns_id => $rdns_id, group_id => $group, entry => "Warning(s) adding $zone:$warnstr")
|
---|
[264] | 2751 | if $warnstr;
|
---|
[269] | 2752 |
|
---|
[260] | 2753 | # once we get here, we should have suceeded.
|
---|
| 2754 | $dbh->commit;
|
---|
| 2755 | }; # end eval
|
---|
| 2756 |
|
---|
| 2757 | if ($@) {
|
---|
| 2758 | my $msg = $@;
|
---|
| 2759 | eval { $dbh->rollback; };
|
---|
[487] | 2760 | $self->_log(group_id => $group, entry => "Failed adding reverse zone $zone ($msg)")
|
---|
[517] | 2761 | if $self->{log_failures};
|
---|
[286] | 2762 | $dbh->commit; # since we enabled transactions earlier
|
---|
[260] | 2763 | return ('FAIL',$msg);
|
---|
| 2764 | } else {
|
---|
[286] | 2765 | my $retcode = 'OK';
|
---|
| 2766 | if ($warnstr) {
|
---|
| 2767 | $resultstr = $warnstr;
|
---|
| 2768 | $retcode = 'WARN';
|
---|
| 2769 | }
|
---|
| 2770 | return ($retcode, $rdns_id);
|
---|
[260] | 2771 | }
|
---|
| 2772 |
|
---|
| 2773 | } # end addRDNS()
|
---|
| 2774 |
|
---|
| 2775 |
|
---|
[237] | 2776 | ## DNSDB::getZoneCount
|
---|
| 2777 | # Get count of zones in group or groups
|
---|
| 2778 | # Takes a database handle and hash containing:
|
---|
| 2779 | # - the "current" group
|
---|
| 2780 | # - an array of "acceptable" groups
|
---|
| 2781 | # - a flag for forward/reverse zones
|
---|
| 2782 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
| 2783 | # Returns an integer count of the resulting zone list.
|
---|
| 2784 | sub getZoneCount {
|
---|
[477] | 2785 | my $self = shift;
|
---|
| 2786 | my $dbh = $self->{dbh};
|
---|
[237] | 2787 |
|
---|
| 2788 | my %args = @_;
|
---|
| 2789 |
|
---|
[509] | 2790 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 2791 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 2792 | $errstr = "Bad or missing curgroup argument";
|
---|
| 2793 | return;
|
---|
| 2794 | }
|
---|
| 2795 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 2796 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 2797 | $errstr = "Bad childlist argument";
|
---|
| 2798 | return;
|
---|
| 2799 | }
|
---|
| 2800 |
|
---|
[237] | 2801 | my @filterargs;
|
---|
[239] | 2802 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2803 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2804 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
[237] | 2805 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2806 |
|
---|
| 2807 | my $sql;
|
---|
| 2808 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
| 2809 | if ($args{revrec} eq 'n') {
|
---|
| 2810 | $sql = "SELECT count(*) FROM domains".
|
---|
| 2811 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2812 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
| 2813 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
| 2814 | } else {
|
---|
| 2815 | $sql = "SELECT count(*) FROM revzones".
|
---|
| 2816 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
[583] | 2817 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2818 | # if ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all') {
|
---|
| 2819 | # Just In Case the UI is using formal .arpa notation, and someone enters something reversed,
|
---|
| 2820 | # we want to match both the formal and natural zone name
|
---|
| 2821 | $sql .= ($args{filter} ? " AND (CAST(revnet AS VARCHAR) ~* ? OR CAST(revnet AS VARCHAR) ~* ?)" : '');
|
---|
| 2822 | push @filterargs, join('[.]',reverse(split(/\[\.\]/,$args{filter}))) if $args{filter};
|
---|
| 2823 | # } else {
|
---|
| 2824 | # $sql .= ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2825 | # }
|
---|
[237] | 2826 | }
|
---|
| 2827 | my ($count) = $dbh->selectrow_array($sql, undef, @filterargs);
|
---|
| 2828 | return $count;
|
---|
| 2829 | } # end getZoneCount()
|
---|
| 2830 |
|
---|
| 2831 |
|
---|
| 2832 | ## DNSDB::getZoneList()
|
---|
| 2833 | # Get a list of zones in the specified group(s)
|
---|
| 2834 | # Takes the same arguments as getZoneCount() above
|
---|
| 2835 | # Returns a reference to an array of hashrefs suitable for feeding to HTML::Template
|
---|
| 2836 | sub getZoneList {
|
---|
[477] | 2837 | my $self = shift;
|
---|
| 2838 | my $dbh = $self->{dbh};
|
---|
[237] | 2839 |
|
---|
| 2840 | my %args = @_;
|
---|
| 2841 |
|
---|
| 2842 | my @zonelist;
|
---|
| 2843 |
|
---|
[475] | 2844 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
[239] | 2845 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[237] | 2846 |
|
---|
[509] | 2847 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 2848 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 2849 | $errstr = "Bad or missing curgroup argument";
|
---|
| 2850 | return;
|
---|
| 2851 | }
|
---|
| 2852 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 2853 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 2854 | $errstr = "Bad childlist argument";
|
---|
| 2855 | return;
|
---|
| 2856 | }
|
---|
| 2857 |
|
---|
[237] | 2858 | my @filterargs;
|
---|
[239] | 2859 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2860 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2861 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
[237] | 2862 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2863 |
|
---|
| 2864 | my $sql;
|
---|
| 2865 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
| 2866 | if ($args{revrec} eq 'n') {
|
---|
[475] | 2867 | $args{sortby} = 'domain' if !$args{sortby} || !grep /^$args{sortby}$/, ('domain','group','status');
|
---|
[704] | 2868 | $sql = q(SELECT
|
---|
| 2869 | domain_id AS zoneid,
|
---|
| 2870 | domain AS zone,
|
---|
| 2871 | status,
|
---|
| 2872 | groups.group_name AS group,
|
---|
| 2873 | l.description AS location
|
---|
| 2874 | FROM domains
|
---|
| 2875 | LEFT JOIN locations l ON domains.default_location=l.location
|
---|
| 2876 | INNER JOIN groups ON domains.group_id=groups.group_id ).
|
---|
| 2877 | "WHERE domains.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
[237] | 2878 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
| 2879 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
| 2880 | } else {
|
---|
[239] | 2881 | ##fixme: arguably startwith here is irrelevant. depends on the UI though.
|
---|
[475] | 2882 | $args{sortby} = 'revnet' if !$args{sortby} || !grep /^$args{sortby}$/, ('revnet','group','status');
|
---|
[704] | 2883 | $sql = q(SELECT
|
---|
| 2884 | rdns_id AS zoneid,
|
---|
| 2885 | revnet AS zone,
|
---|
| 2886 | status,
|
---|
| 2887 | groups.group_name AS group,
|
---|
| 2888 | l.description AS location
|
---|
| 2889 | FROM revzones
|
---|
| 2890 | LEFT JOIN locations l ON revzones.default_location=l.location
|
---|
| 2891 | INNER JOIN groups ON revzones.group_id=groups.group_id ).
|
---|
[237] | 2892 | " WHERE revzones.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
[583] | 2893 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2894 | # if ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all') {
|
---|
| 2895 | # Just In Case the UI is using formal .arpa notation, and someone enters something reversed,
|
---|
| 2896 | # we want to match both the formal and natural zone name
|
---|
| 2897 | $sql .= ($args{filter} ? " AND (CAST(revnet AS VARCHAR) ~* ? OR CAST(revnet AS VARCHAR) ~* ?)" : '');
|
---|
| 2898 | push @filterargs, join('[.]',reverse(split(/\[\.\]/,$args{filter}))) if $args{filter};
|
---|
| 2899 | # } else {
|
---|
| 2900 | # $sql .= ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2901 | # }
|
---|
[237] | 2902 | }
|
---|
| 2903 | # A common tail.
|
---|
[239] | 2904 | $sql .= " ORDER BY ".($args{sortby} eq 'group' ? 'groups.group_name' : $args{sortby})." $args{sortorder} ".
|
---|
[517] | 2905 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage}".
|
---|
| 2906 | " OFFSET ".$args{offset}*$self->{perpage});
|
---|
[237] | 2907 |
|
---|
[583] | 2908 | my @working;
|
---|
| 2909 | my $zsth = $dbh->prepare($sql);
|
---|
| 2910 | $zsth->execute(@filterargs);
|
---|
| 2911 | while (my $zone = $zsth->fetchrow_hashref) {
|
---|
| 2912 | if ($args{revrec} eq 'y' && ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all')) {
|
---|
| 2913 | my $tmp = new NetAddr::IP $zone->{zone};
|
---|
| 2914 | $zone->{zone} = DNSDB::_ZONE($tmp, 'ZONE', 'r', '.').($tmp->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 2915 | }
|
---|
| 2916 | push @working, $zone;
|
---|
| 2917 | }
|
---|
| 2918 | return \@working;
|
---|
[237] | 2919 | } # end getZoneList()
|
---|
| 2920 |
|
---|
| 2921 |
|
---|
[383] | 2922 | ## DNSDB::getZoneLocation()
|
---|
[387] | 2923 | # Retrieve the default location for a zone.
|
---|
[383] | 2924 | # Takes a database handle, forward/reverse flag, and zone ID
|
---|
| 2925 | sub getZoneLocation {
|
---|
[477] | 2926 | my $self = shift;
|
---|
| 2927 | my $dbh = $self->{dbh};
|
---|
[383] | 2928 | my $revrec = shift;
|
---|
| 2929 | my $zoneid = shift;
|
---|
| 2930 |
|
---|
| 2931 | my ($loc) = $dbh->selectrow_array("SELECT default_location FROM ".
|
---|
| 2932 | ($revrec eq 'n' ? 'domains WHERE domain_id = ?' : 'revzones WHERE rdns_id = ?'),
|
---|
| 2933 | undef, ($zoneid));
|
---|
| 2934 | return $loc;
|
---|
| 2935 | } # end getZoneLocation()
|
---|
| 2936 |
|
---|
| 2937 |
|
---|
[18] | 2938 | ## DNSDB::addGroup()
|
---|
| 2939 | # Add a group
|
---|
[66] | 2940 | # Takes a database handle, group name, parent group, hashref for permissions,
|
---|
[292] | 2941 | # and optional template-vs-cloneme flag for the default records
|
---|
[18] | 2942 | # Returns a status code and message
|
---|
| 2943 | sub addGroup {
|
---|
| 2944 | $errstr = '';
|
---|
[476] | 2945 | my $self = shift;
|
---|
| 2946 | my $dbh = $self->{dbh};
|
---|
[20] | 2947 | my $groupname = shift;
|
---|
| 2948 | my $pargroup = shift;
|
---|
[66] | 2949 | my $permissions = shift;
|
---|
[18] | 2950 |
|
---|
[66] | 2951 | # 0 indicates "custom", hardcoded.
|
---|
[18] | 2952 | # Any other value clones that group's default records, if it exists.
|
---|
[66] | 2953 | my $inherit = shift || 0;
|
---|
| 2954 | ##fixme: need a flag to indicate clone records or <?> ?
|
---|
[18] | 2955 |
|
---|
| 2956 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2957 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2958 | local $dbh->{AutoCommit} = 0;
|
---|
| 2959 | local $dbh->{RaiseError} = 1;
|
---|
| 2960 |
|
---|
[292] | 2961 | my ($group_id) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($groupname));
|
---|
[38] | 2962 |
|
---|
| 2963 | return ('FAIL', "Group already exists") if $group_id;
|
---|
| 2964 |
|
---|
[18] | 2965 | # Wrap all the SQL in a transaction
|
---|
| 2966 | eval {
|
---|
[292] | 2967 | $dbh->do("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)", undef, ($pargroup, $groupname) );
|
---|
[18] | 2968 |
|
---|
[292] | 2969 | my ($groupid) = $dbh->selectrow_array("SELECT currval('groups_group_id_seq')");
|
---|
[18] | 2970 |
|
---|
[292] | 2971 | # We work through the whole set of permissions instead of specifying them so
|
---|
| 2972 | # that when we add a new permission, we don't have to change the code anywhere
|
---|
| 2973 | # that doesn't explicitly deal with that specific permission.
|
---|
| 2974 | my @permvals;
|
---|
| 2975 | foreach (@permtypes) {
|
---|
| 2976 | if (!defined ($permissions->{$_})) {
|
---|
| 2977 | push @permvals, 0;
|
---|
| 2978 | } else {
|
---|
| 2979 | push @permvals, $permissions->{$_};
|
---|
[66] | 2980 | }
|
---|
[292] | 2981 | }
|
---|
| 2982 | $dbh->do("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")",
|
---|
| 2983 | undef, ($groupid, @permvals) );
|
---|
| 2984 | my ($permid) = $dbh->selectrow_array("SELECT currval('permissions_permission_id_seq')");
|
---|
| 2985 | $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
|
---|
[66] | 2986 |
|
---|
[292] | 2987 | # Default records
|
---|
[255] | 2988 | my $sthf = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
|
---|
[20] | 2989 | "VALUES ($groupid,?,?,?,?,?,?,?)");
|
---|
[255] | 2990 | my $sthr = $dbh->prepare("INSERT INTO default_rev_records (group_id,host,type,val,ttl) ".
|
---|
| 2991 | "VALUES ($groupid,?,?,?,?)");
|
---|
[66] | 2992 | if ($inherit) {
|
---|
[87] | 2993 | # Duplicate records from parent. Actually relying on inherited records feels
|
---|
| 2994 | # very fragile, and it would be problematic to roll over at a later time.
|
---|
[18] | 2995 | my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
[87] | 2996 | $sth2->execute($pargroup);
|
---|
[18] | 2997 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
[255] | 2998 | $sthf->execute(@clonedata);
|
---|
[18] | 2999 | }
|
---|
[255] | 3000 | # And now the reverse records
|
---|
[292] | 3001 | $sth2 = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
[255] | 3002 | $sth2->execute($pargroup);
|
---|
| 3003 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
| 3004 | $sthr->execute(@clonedata);
|
---|
| 3005 | }
|
---|
[18] | 3006 | } else {
|
---|
[66] | 3007 | ##fixme: Hardcoding is Bad, mmmmkaaaay?
|
---|
[18] | 3008 | # reasonable basic defaults for SOA, MX, NS, and minimal hosting
|
---|
| 3009 | # could load from a config file, but somewhere along the line we need hardcoded bits.
|
---|
[255] | 3010 | $sthf->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
|
---|
| 3011 | $sthf->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
|
---|
| 3012 | $sthf->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
|
---|
| 3013 | $sthf->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
|
---|
| 3014 | $sthf->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
|
---|
| 3015 | $sthf->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
|
---|
| 3016 | # reasonable basic defaults for generic reverse zone. Same as initial SQL tabledef.
|
---|
| 3017 | $sthr->execute('hostmaster.ADMINDOMAIN:ns1.ADMINDOMAIN', 6, '10800:3600:604800:10800', 86400);
|
---|
| 3018 | $sthr->execute('unused-%r.ADMINDOMAIN', 65283, 'ZONE', 3600);
|
---|
[18] | 3019 | }
|
---|
| 3020 |
|
---|
[487] | 3021 | $self->_log(group_id => $pargroup, entry => "Added group $groupname");
|
---|
[292] | 3022 |
|
---|
[18] | 3023 | # once we get here, we should have suceeded.
|
---|
| 3024 | $dbh->commit;
|
---|
| 3025 | }; # end eval
|
---|
| 3026 |
|
---|
| 3027 | if ($@) {
|
---|
| 3028 | my $msg = $@;
|
---|
| 3029 | eval { $dbh->rollback; };
|
---|
[517] | 3030 | if ($self->{log_failures}) {
|
---|
[487] | 3031 | $self->_log(group_id => $pargroup, entry => "Failed to add group $groupname: $msg");
|
---|
[292] | 3032 | $dbh->commit;
|
---|
| 3033 | }
|
---|
[18] | 3034 | return ('FAIL',$msg);
|
---|
| 3035 | }
|
---|
| 3036 |
|
---|
[292] | 3037 | return ('OK','OK');
|
---|
[18] | 3038 | } # end addGroup()
|
---|
| 3039 |
|
---|
| 3040 |
|
---|
[22] | 3041 | ## DNSDB::delGroup()
|
---|
| 3042 | # Delete a group.
|
---|
| 3043 | # Takes a group ID
|
---|
| 3044 | # Returns a status code and message
|
---|
| 3045 | sub delGroup {
|
---|
[476] | 3046 | my $self = shift;
|
---|
| 3047 | my $dbh = $self->{dbh};
|
---|
[22] | 3048 | my $groupid = shift;
|
---|
| 3049 |
|
---|
| 3050 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3051 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3052 | local $dbh->{AutoCommit} = 0;
|
---|
| 3053 | local $dbh->{RaiseError} = 1;
|
---|
| 3054 |
|
---|
| 3055 | ##fixme: locate "knowable" error conditions and deal with them before the eval
|
---|
[23] | 3056 | # ... or inside, whatever.
|
---|
[22] | 3057 | # -> domains still exist in group
|
---|
| 3058 | # -> ...
|
---|
[23] | 3059 | my $failmsg = '';
|
---|
[293] | 3060 | my $resultmsg = '';
|
---|
[22] | 3061 |
|
---|
[293] | 3062 | # collect some pieces for logging and error messages
|
---|
[473] | 3063 | my $groupname = $self->groupName($groupid);
|
---|
| 3064 | my $parid = $self->parentID(id => $groupid, type => 'group');
|
---|
[293] | 3065 |
|
---|
[22] | 3066 | # Wrap all the SQL in a transaction
|
---|
| 3067 | eval {
|
---|
[293] | 3068 | # Check for Things in the group
|
---|
| 3069 | $failmsg = "Can't remove group $groupname";
|
---|
| 3070 | my ($grpcnt) = $dbh->selectrow_array("SELECT count(*) FROM groups WHERE parent_group_id=?", undef, ($groupid));
|
---|
| 3071 | die "$grpcnt groups still in group\n" if $grpcnt;
|
---|
| 3072 | my ($domcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($groupid));
|
---|
[23] | 3073 | die "$domcnt domains still in group\n" if $domcnt;
|
---|
[512] | 3074 | my ($revcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($groupid));
|
---|
| 3075 | die "$revcnt reverse zones still in group\n" if $revcnt;
|
---|
[293] | 3076 | my ($usercnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($groupid));
|
---|
| 3077 | die "$usercnt users still in group\n" if $usercnt;
|
---|
[23] | 3078 |
|
---|
[293] | 3079 | $failmsg = "Failed to delete default records for $groupname";
|
---|
| 3080 | $dbh->do("DELETE from default_records WHERE group_id=?", undef, ($groupid));
|
---|
| 3081 | $failmsg = "Failed to delete default reverse records for $groupname";
|
---|
| 3082 | $dbh->do("DELETE from default_rev_records WHERE group_id=?", undef, ($groupid));
|
---|
| 3083 | $failmsg = "Failed to remove group $groupname";
|
---|
| 3084 | $dbh->do("DELETE from groups WHERE group_id=?", undef, ($groupid));
|
---|
[22] | 3085 |
|
---|
[487] | 3086 | $self->_log(group_id => $parid, entry => "Deleted group $groupname");
|
---|
[293] | 3087 | $resultmsg = "Deleted group $groupname";
|
---|
| 3088 |
|
---|
[22] | 3089 | # once we get here, we should have suceeded.
|
---|
| 3090 | $dbh->commit;
|
---|
| 3091 | }; # end eval
|
---|
| 3092 |
|
---|
| 3093 | if ($@) {
|
---|
| 3094 | my $msg = $@;
|
---|
| 3095 | eval { $dbh->rollback; };
|
---|
[517] | 3096 | if ($self->{log_failures}) {
|
---|
[487] | 3097 | $self->_log(group_id => $parid, entry => "$failmsg: $msg");
|
---|
[293] | 3098 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 3099 | }
|
---|
[23] | 3100 | return ('FAIL',"$failmsg: $msg");
|
---|
[22] | 3101 | }
|
---|
[293] | 3102 |
|
---|
| 3103 | return ('OK',$resultmsg);
|
---|
[22] | 3104 | } # end delGroup()
|
---|
| 3105 |
|
---|
| 3106 |
|
---|
[19] | 3107 | ## DNSDB::getChildren()
|
---|
| 3108 | # Get a list of all groups whose parent^n is group <n>
|
---|
[24] | 3109 | # Takes a database handle, group ID, reference to an array to put the group IDs in,
|
---|
| 3110 | # and an optional flag to return only immediate children or all children-of-children
|
---|
| 3111 | # default to returning all children
|
---|
[19] | 3112 | # Calls itself
|
---|
| 3113 | sub getChildren {
|
---|
| 3114 | $errstr = '';
|
---|
[476] | 3115 | my $self = shift;
|
---|
| 3116 | my $dbh = $self->{dbh};
|
---|
[20] | 3117 | my $rootgroup = shift;
|
---|
| 3118 | my $groupdest = shift;
|
---|
[24] | 3119 | my $immed = shift || 'all';
|
---|
[19] | 3120 |
|
---|
| 3121 | # special break for default group; otherwise we get stuck.
|
---|
[20] | 3122 | if ($rootgroup == 1) {
|
---|
[19] | 3123 | # by definition, group 1 is the Root Of All Groups
|
---|
[24] | 3124 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
|
---|
[331] | 3125 | ($immed ne 'all' ? " AND parent_group_id=1" : '')." ORDER BY group_name");
|
---|
[19] | 3126 | $sth->execute;
|
---|
| 3127 | while (my @this = $sth->fetchrow_array) {
|
---|
[20] | 3128 | push @$groupdest, @this;
|
---|
[19] | 3129 | }
|
---|
| 3130 | } else {
|
---|
[331] | 3131 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=? ORDER BY group_name");
|
---|
[20] | 3132 | $sth->execute($rootgroup);
|
---|
[19] | 3133 | return if $sth->rows == 0;
|
---|
[20] | 3134 | my @grouplist;
|
---|
| 3135 | while (my ($group) = $sth->fetchrow_array) {
|
---|
| 3136 | push @$groupdest, $group;
|
---|
[476] | 3137 | $self->getChildren($group, $groupdest) if $immed eq 'all';
|
---|
[19] | 3138 | }
|
---|
| 3139 | }
|
---|
| 3140 | } # end getChildren()
|
---|
| 3141 |
|
---|
| 3142 |
|
---|
[20] | 3143 | ## DNSDB::groupName()
|
---|
[17] | 3144 | # Return the group name based on a group ID
|
---|
| 3145 | # Takes a database handle and the group ID
|
---|
| 3146 | # Returns the group name or undef on failure
|
---|
[20] | 3147 | sub groupName {
|
---|
[13] | 3148 | $errstr = '';
|
---|
[473] | 3149 | my $self = shift;
|
---|
| 3150 | my $dbh = $self->{dbh};
|
---|
[20] | 3151 | my $groupid = shift;
|
---|
| 3152 | my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
|
---|
| 3153 | $sth->execute($groupid);
|
---|
| 3154 | my ($groupname) = $sth->fetchrow_array();
|
---|
| 3155 | $errstr = $DBI::errstr if !$groupname;
|
---|
| 3156 | return $groupname if $groupname;
|
---|
| 3157 | } # end groupName
|
---|
[13] | 3158 |
|
---|
| 3159 |
|
---|
[314] | 3160 | ## DNSDB::getGroupCount()
|
---|
| 3161 | # Get count of subgroups in group or groups
|
---|
| 3162 | # Takes a database handle and hash containing:
|
---|
| 3163 | # - the "current" group
|
---|
| 3164 | # - an array of "acceptable" groups
|
---|
| 3165 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
| 3166 | # Returns an integer count of the resulting group list.
|
---|
| 3167 | sub getGroupCount {
|
---|
[476] | 3168 | my $self = shift;
|
---|
| 3169 | my $dbh = $self->{dbh};
|
---|
[314] | 3170 |
|
---|
| 3171 | my %args = @_;
|
---|
| 3172 |
|
---|
[509] | 3173 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 3174 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 3175 | $errstr = "Bad or missing curgroup argument";
|
---|
| 3176 | return;
|
---|
| 3177 | }
|
---|
| 3178 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 3179 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 3180 | $errstr = "Bad childlist argument";
|
---|
| 3181 | return;
|
---|
| 3182 | }
|
---|
| 3183 |
|
---|
[314] | 3184 | my @filterargs;
|
---|
| 3185 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3186 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3187 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3188 |
|
---|
| 3189 | my $sql = "SELECT count(*) FROM groups ".
|
---|
| 3190 | "WHERE parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3191 | ($args{startwith} ? " AND group_name ~* ?" : '').
|
---|
| 3192 | ($args{filter} ? " AND group_name ~* ?" : '');
|
---|
| 3193 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 3194 | $errstr = $dbh->errstr if !$count;
|
---|
| 3195 | return $count;
|
---|
| 3196 | } # end getGroupCount
|
---|
| 3197 |
|
---|
| 3198 |
|
---|
| 3199 | ## DNSDB::getGroupList()
|
---|
| 3200 | # Get a list of sub^n-groups in the specified group(s)
|
---|
| 3201 | # Takes the same arguments as getGroupCount() above
|
---|
| 3202 | # Returns an arrayref containing hashrefs suitable for feeding straight to HTML::Template
|
---|
| 3203 | sub getGroupList {
|
---|
[476] | 3204 | my $self = shift;
|
---|
| 3205 | my $dbh = $self->{dbh};
|
---|
[314] | 3206 |
|
---|
| 3207 | my %args = @_;
|
---|
| 3208 |
|
---|
[509] | 3209 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 3210 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 3211 | $errstr = "Bad or missing curgroup argument";
|
---|
| 3212 | return;
|
---|
| 3213 | }
|
---|
| 3214 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 3215 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 3216 | $errstr = "Bad childlist argument";
|
---|
| 3217 | return;
|
---|
| 3218 | }
|
---|
| 3219 |
|
---|
[314] | 3220 | my @filterargs;
|
---|
| 3221 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3222 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3223 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3224 |
|
---|
| 3225 | # protection against bad or missing arguments
|
---|
[508] | 3226 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
| 3227 | $args{sortby} = 'group' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
[397] | 3228 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[314] | 3229 |
|
---|
| 3230 | # munge sortby for columns in database
|
---|
| 3231 | $args{sortby} = 'g.group_name' if $args{sortby} eq 'group';
|
---|
| 3232 | $args{sortby} = 'g2.group_name' if $args{sortby} eq 'parent';
|
---|
| 3233 |
|
---|
[385] | 3234 | my $sql = q(SELECT g.group_id AS groupid, g.group_name AS groupname, g2.group_name AS pgroup
|
---|
[314] | 3235 | FROM groups g
|
---|
| 3236 | INNER JOIN groups g2 ON g2.group_id=g.parent_group_id
|
---|
| 3237 | ).
|
---|
[385] | 3238 | " WHERE g.parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
[314] | 3239 | ($args{startwith} ? " AND g.group_name ~* ?" : '').
|
---|
| 3240 | ($args{filter} ? " AND g.group_name ~* ?" : '').
|
---|
| 3241 | " GROUP BY g.group_id, g.group_name, g2.group_name ".
|
---|
| 3242 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
[517] | 3243 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
[314] | 3244 | my $glist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 3245 | $errstr = $dbh->errstr if !$glist;
|
---|
[385] | 3246 |
|
---|
| 3247 | # LEFT JOINs make the result set balloon beyond sanity just to include counts;
|
---|
| 3248 | # this means there's lots of crunching needed to trim the result set back down.
|
---|
| 3249 | # So instead we track the order of the groups, and push the counts into the
|
---|
| 3250 | # arrayref result separately.
|
---|
| 3251 | ##fixme: put this whole sub in a transaction? might be
|
---|
| 3252 | # needed for accurate results on very busy systems.
|
---|
[386] | 3253 | ##fixme: large group lists need prepared statements?
|
---|
| 3254 | #my $ucsth = $dbh->prepare("SELECT count(*) FROM users WHERE group_id=?");
|
---|
| 3255 | #my $dcsth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
|
---|
| 3256 | #my $rcsth = $dbh->prepare("SELECT count(*) FROM revzones WHERE group_id=?");
|
---|
[385] | 3257 | foreach (@{$glist}) {
|
---|
[386] | 3258 | my ($ucnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 3259 | $$_{nusers} = $ucnt;
|
---|
| 3260 | my ($dcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 3261 | $$_{ndomains} = $dcnt;
|
---|
| 3262 | my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 3263 | $$_{nrevzones} = $rcnt;
|
---|
[385] | 3264 | }
|
---|
| 3265 |
|
---|
[314] | 3266 | return $glist;
|
---|
| 3267 | } # end getGroupList
|
---|
| 3268 |
|
---|
| 3269 |
|
---|
[118] | 3270 | ## DNSDB::groupID()
|
---|
| 3271 | # Return the group ID based on the group name
|
---|
| 3272 | # Takes a database handle and the group name
|
---|
| 3273 | # Returns the group ID or undef on failure
|
---|
| 3274 | sub groupID {
|
---|
| 3275 | $errstr = '';
|
---|
[473] | 3276 | my $self = shift;
|
---|
| 3277 | my $dbh = $self->{dbh};
|
---|
[118] | 3278 | my $group = shift;
|
---|
[406] | 3279 | my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($group) );
|
---|
[118] | 3280 | $errstr = $DBI::errstr if !$grpid;
|
---|
| 3281 | return $grpid if $grpid;
|
---|
| 3282 | } # end groupID()
|
---|
| 3283 |
|
---|
| 3284 |
|
---|
[24] | 3285 | ## DNSDB::addUser()
|
---|
[87] | 3286 | # Add a user.
|
---|
| 3287 | # Takes a DB handle, username, group ID, password, state (active/inactive).
|
---|
| 3288 | # Optionally accepts:
|
---|
| 3289 | # user type (user/admin) - defaults to user
|
---|
| 3290 | # permissions string - defaults to inherit from group
|
---|
| 3291 | # three valid forms:
|
---|
| 3292 | # i - Inherit permissions
|
---|
| 3293 | # c:<user_id> - Clone permissions from <user_id>
|
---|
| 3294 | # C:<permission list> - Set these specific permissions
|
---|
| 3295 | # first name - defaults to username
|
---|
| 3296 | # last name - defaults to blank
|
---|
| 3297 | # phone - defaults to blank (could put other data within column def)
|
---|
[90] | 3298 | # Returns (OK,<uid>) on success, (FAIL,<message>) on failure
|
---|
[24] | 3299 | sub addUser {
|
---|
| 3300 | $errstr = '';
|
---|
[479] | 3301 | my $self = shift;
|
---|
| 3302 | my $dbh = $self->{dbh};
|
---|
[24] | 3303 | my $username = shift;
|
---|
| 3304 | my $group = shift;
|
---|
| 3305 | my $pass = shift;
|
---|
| 3306 | my $state = shift;
|
---|
[25] | 3307 |
|
---|
[90] | 3308 | return ('FAIL', "Missing one or more required entries") if !defined($state);
|
---|
| 3309 | return ('FAIL', "Username must not be blank") if !$username;
|
---|
[87] | 3310 |
|
---|
[408] | 3311 | # Munge in some alternate state values
|
---|
| 3312 | $state = 1 if $state =~ /^active$/;
|
---|
| 3313 | $state = 1 if $state =~ /^on$/;
|
---|
| 3314 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 3315 | $state = 0 if $state =~ /^off$/;
|
---|
| 3316 |
|
---|
[25] | 3317 | my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
|
---|
| 3318 |
|
---|
[67] | 3319 | my $permstring = shift || 'i'; # default is to inhert permissions from group
|
---|
| 3320 |
|
---|
[25] | 3321 | my $fname = shift || $username;
|
---|
[24] | 3322 | my $lname = shift || '';
|
---|
[25] | 3323 | my $phone = shift || ''; # not going format-check
|
---|
[24] | 3324 |
|
---|
[38] | 3325 | my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
|
---|
[24] | 3326 | my $user_id;
|
---|
| 3327 |
|
---|
[38] | 3328 | # quick check to start to see if we've already got one
|
---|
| 3329 | $sth->execute($username);
|
---|
| 3330 | ($user_id) = $sth->fetchrow_array;
|
---|
| 3331 |
|
---|
| 3332 | return ('FAIL', "User already exists") if $user_id;
|
---|
| 3333 |
|
---|
[24] | 3334 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3335 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3336 | local $dbh->{AutoCommit} = 0;
|
---|
| 3337 | local $dbh->{RaiseError} = 1;
|
---|
| 3338 |
|
---|
| 3339 | # Wrap all the SQL in a transaction
|
---|
| 3340 | eval {
|
---|
[87] | 3341 | # insert the user... note we set inherited perms by default since
|
---|
| 3342 | # it's simple and cleans up some other bits of state
|
---|
[592] | 3343 | ##fixme: need better handling of case of inherited or missing (!!) permissions entries
|
---|
[87] | 3344 | my $sth = $dbh->prepare("INSERT INTO users ".
|
---|
| 3345 | "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
|
---|
| 3346 | "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
|
---|
| 3347 | $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);
|
---|
[24] | 3348 |
|
---|
| 3349 | # get the ID...
|
---|
[94] | 3350 | ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");
|
---|
[24] | 3351 |
|
---|
[87] | 3352 | # Permissions! Gotta set'em all!
|
---|
[401] | 3353 | die "Invalid permission string $permstring\n"
|
---|
[87] | 3354 | if $permstring !~ /^(?:
|
---|
| 3355 | i # inherit
|
---|
| 3356 | |c:\d+ # clone
|
---|
| 3357 | # custom. no, the leading , is not a typo
|
---|
[391] | 3358 | |C:(?:,(?:group|user|domain|record|location|self)_(?:edit|create|delete|locchg|view))*
|
---|
[87] | 3359 | )$/x;
|
---|
| 3360 | # bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
|
---|
| 3361 | if ($permstring ne 'i') {
|
---|
| 3362 | # for cloned or custom permissions, we have to create a new permissions entry.
|
---|
| 3363 | my $clonesrc = $group;
|
---|
| 3364 | if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
|
---|
| 3365 | $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
|
---|
| 3366 | "SELECT $permlist,? FROM permissions WHERE permission_id=".
|
---|
| 3367 | "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
|
---|
| 3368 | undef, ($user_id,$clonesrc) );
|
---|
| 3369 | $dbh->do("UPDATE users SET permission_id=".
|
---|
| 3370 | "(SELECT permission_id FROM permissions WHERE user_id=?) ".
|
---|
| 3371 | "WHERE user_id=?", undef, ($user_id, $user_id) );
|
---|
| 3372 | }
|
---|
| 3373 | if ($permstring =~ /^C:/) {
|
---|
| 3374 | # finally for custom permissions, we set the passed-in permissions (and unset
|
---|
| 3375 | # any that might have been brought in by the clone operation above)
|
---|
| 3376 | my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
|
---|
| 3377 | undef, ($user_id) );
|
---|
| 3378 | foreach (@permtypes) {
|
---|
| 3379 | if ($permstring =~ /,$_/) {
|
---|
| 3380 | $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
|
---|
| 3381 | } else {
|
---|
| 3382 | $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
|
---|
| 3383 | }
|
---|
| 3384 | }
|
---|
| 3385 | }
|
---|
| 3386 |
|
---|
| 3387 | $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
|
---|
| 3388 |
|
---|
[25] | 3389 | ##fixme: add another table to hold name/email for log table?
|
---|
| 3390 |
|
---|
[487] | 3391 | $self->_log(group_id => $group, entry => "Added user $username ($fname $lname)");
|
---|
[24] | 3392 | # once we get here, we should have suceeded.
|
---|
| 3393 | $dbh->commit;
|
---|
| 3394 | }; # end eval
|
---|
| 3395 |
|
---|
| 3396 | if ($@) {
|
---|
| 3397 | my $msg = $@;
|
---|
| 3398 | eval { $dbh->rollback; };
|
---|
[517] | 3399 | if ($self->{log_failures}) {
|
---|
[487] | 3400 | $self->_log(group_id => $group, entry => "Error adding user $username: $msg");
|
---|
[294] | 3401 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 3402 | }
|
---|
| 3403 | return ('FAIL',"Error adding user $username: $msg");
|
---|
[24] | 3404 | }
|
---|
[294] | 3405 |
|
---|
| 3406 | return ('OK',"User $username ($fname $lname) added");
|
---|
[24] | 3407 | } # end addUser
|
---|
| 3408 |
|
---|
| 3409 |
|
---|
[325] | 3410 | ## DNSDB::getUserCount()
|
---|
| 3411 | # Get count of users in group
|
---|
| 3412 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
| 3413 | # - a reference list of secondary groups
|
---|
| 3414 | # - a filter string
|
---|
| 3415 | # - a "Starts with" string
|
---|
| 3416 | sub getUserCount {
|
---|
[479] | 3417 | my $self = shift;
|
---|
| 3418 | my $dbh = $self->{dbh};
|
---|
[325] | 3419 |
|
---|
| 3420 | my %args = @_;
|
---|
| 3421 |
|
---|
[509] | 3422 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 3423 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 3424 | $errstr = "Bad or missing curgroup argument";
|
---|
| 3425 | return;
|
---|
| 3426 | }
|
---|
| 3427 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 3428 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 3429 | $errstr = "Bad childlist argument";
|
---|
| 3430 | return;
|
---|
| 3431 | }
|
---|
| 3432 |
|
---|
[325] | 3433 | my @filterargs;
|
---|
| 3434 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3435 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3436 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3437 |
|
---|
| 3438 | my $sql = "SELECT count(*) FROM users ".
|
---|
| 3439 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3440 | ($args{startwith} ? " AND username ~* ?" : '').
|
---|
[730] | 3441 | ($args{filter} ? " AND username ~* ?" : '').
|
---|
| 3442 | " AND NOT type = 'R' ";
|
---|
[325] | 3443 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 3444 | $errstr = $dbh->errstr if !$count;
|
---|
| 3445 | return $count;
|
---|
| 3446 | } # end getUserCount()
|
---|
| 3447 |
|
---|
| 3448 |
|
---|
| 3449 | ## DNSDB::getUserList()
|
---|
| 3450 | # Get list of users
|
---|
| 3451 | # Takes the same arguments as getUserCount() above, plus optional:
|
---|
| 3452 | # - sort field
|
---|
| 3453 | # - sort order
|
---|
| 3454 | # - offset/return-all-everything flag (defaults to $perpage records)
|
---|
| 3455 | sub getUserList {
|
---|
[479] | 3456 | my $self = shift;
|
---|
| 3457 | my $dbh = $self->{dbh};
|
---|
[325] | 3458 |
|
---|
| 3459 | my %args = @_;
|
---|
| 3460 |
|
---|
[509] | 3461 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 3462 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 3463 | $errstr = "Bad or missing curgroup argument";
|
---|
| 3464 | return;
|
---|
| 3465 | }
|
---|
| 3466 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 3467 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 3468 | $errstr = "Bad childlist argument";
|
---|
| 3469 | return;
|
---|
| 3470 | }
|
---|
| 3471 |
|
---|
[325] | 3472 | my @filterargs;
|
---|
| 3473 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3474 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3475 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3476 |
|
---|
| 3477 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
| 3478 | my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
| 3479 | fname => 'fname');
|
---|
| 3480 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 3481 |
|
---|
| 3482 | # protection against bad or missing arguments
|
---|
[508] | 3483 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
| 3484 | $args{sortby} = 'u.username' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
[397] | 3485 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[325] | 3486 |
|
---|
| 3487 | my $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ".
|
---|
| 3488 | "FROM users u ".
|
---|
| 3489 | "INNER JOIN groups g ON u.group_id=g.group_id ".
|
---|
| 3490 | "WHERE u.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3491 | ($args{startwith} ? " AND u.username ~* ?" : '').
|
---|
| 3492 | ($args{filter} ? " AND u.username ~* ?" : '').
|
---|
[401] | 3493 | " AND NOT u.type = 'R' ".
|
---|
[325] | 3494 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
[517] | 3495 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
[325] | 3496 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 3497 | $errstr = $dbh->errstr if !$ulist;
|
---|
| 3498 | return $ulist;
|
---|
| 3499 | } # end getUserList()
|
---|
| 3500 |
|
---|
| 3501 |
|
---|
[326] | 3502 | ## DNSDB::getUserDropdown()
|
---|
| 3503 | # Get a list of usernames for use in a dropdown menu.
|
---|
| 3504 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
| 3505 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
| 3506 | sub getUserDropdown {
|
---|
[479] | 3507 | my $self = shift;
|
---|
| 3508 | my $dbh = $self->{dbh};
|
---|
[326] | 3509 | my $grp = shift;
|
---|
| 3510 | my $sel = shift || 0;
|
---|
| 3511 |
|
---|
[720] | 3512 | my $sth = $dbh->prepare("SELECT username,user_id FROM users WHERE group_id=? AND password <> 'RPC'");
|
---|
[326] | 3513 | $sth->execute($grp);
|
---|
| 3514 |
|
---|
| 3515 | my @userlist;
|
---|
| 3516 | while (my ($username,$uid) = $sth->fetchrow_array) {
|
---|
| 3517 | my %row = (
|
---|
| 3518 | username => $username,
|
---|
| 3519 | uid => $uid,
|
---|
| 3520 | selected => ($sel == $uid ? 1 : 0)
|
---|
| 3521 | );
|
---|
| 3522 | push @userlist, \%row;
|
---|
| 3523 | }
|
---|
| 3524 | return \@userlist;
|
---|
| 3525 | } # end getUserDropdown()
|
---|
| 3526 |
|
---|
| 3527 |
|
---|
[83] | 3528 | ## DNSDB:: updateUser()
|
---|
[90] | 3529 | # Update general data about user
|
---|
[83] | 3530 | sub updateUser {
|
---|
[479] | 3531 | my $self = shift;
|
---|
| 3532 | my $dbh = $self->{dbh};
|
---|
[118] | 3533 |
|
---|
| 3534 | ##fixme: tweak calling convention so that we can update any given bit of data
|
---|
[83] | 3535 | my $uid = shift;
|
---|
| 3536 | my $username = shift;
|
---|
| 3537 | my $group = shift;
|
---|
| 3538 | my $pass = shift;
|
---|
| 3539 | my $state = shift;
|
---|
[87] | 3540 | my $type = shift || 'u';
|
---|
[83] | 3541 | my $fname = shift || $username;
|
---|
| 3542 | my $lname = shift || '';
|
---|
| 3543 | my $phone = shift || ''; # not going format-check
|
---|
| 3544 |
|
---|
[294] | 3545 | my $resultmsg = '';
|
---|
[83] | 3546 |
|
---|
[411] | 3547 | # Munge in some alternate state values
|
---|
| 3548 | $state = 1 if $state =~ /^active$/;
|
---|
| 3549 | $state = 1 if $state =~ /^on$/;
|
---|
| 3550 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 3551 | $state = 0 if $state =~ /^off$/;
|
---|
| 3552 |
|
---|
[83] | 3553 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3554 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3555 | local $dbh->{AutoCommit} = 0;
|
---|
| 3556 | local $dbh->{RaiseError} = 1;
|
---|
| 3557 |
|
---|
| 3558 | my $sth;
|
---|
| 3559 |
|
---|
| 3560 | # Password can be left blank; if so we assume there's one on file.
|
---|
| 3561 | # Actual blank passwords are bad, mm'kay?
|
---|
| 3562 | if (!$pass) {
|
---|
[294] | 3563 | ($pass) = $dbh->selectrow_array("SELECT password FROM users WHERE user_id=?", undef, ($uid));
|
---|
[83] | 3564 | } else {
|
---|
| 3565 | $pass = unix_md5_crypt($pass);
|
---|
| 3566 | }
|
---|
| 3567 |
|
---|
| 3568 | eval {
|
---|
[294] | 3569 | $dbh->do("UPDATE users SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?".
|
---|
| 3570 | " WHERE user_id=?", undef, ($username, $pass, $fname, $lname, $phone, $type, $state, $uid));
|
---|
| 3571 | $resultmsg = "Updated user info for $username ($fname $lname)";
|
---|
[487] | 3572 | $self->_log(group_id => $group, entry => $resultmsg);
|
---|
[83] | 3573 | $dbh->commit;
|
---|
| 3574 | };
|
---|
| 3575 | if ($@) {
|
---|
| 3576 | my $msg = $@;
|
---|
| 3577 | eval { $dbh->rollback; };
|
---|
[517] | 3578 | if ($self->{log_failures}) {
|
---|
[487] | 3579 | $self->_log(group_id => $group, entry => "Error updating user $username: $msg");
|
---|
[294] | 3580 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 3581 | }
|
---|
| 3582 | return ('FAIL',"Error updating user $username: $msg");
|
---|
[83] | 3583 | }
|
---|
[294] | 3584 |
|
---|
| 3585 | return ('OK',$resultmsg);
|
---|
[83] | 3586 | } # end updateUser()
|
---|
| 3587 |
|
---|
| 3588 |
|
---|
[24] | 3589 | ## DNSDB::delUser()
|
---|
[297] | 3590 | # Delete a user.
|
---|
| 3591 | # Takes a database handle and user ID
|
---|
| 3592 | # Returns a success/failure code and matching message
|
---|
[24] | 3593 | sub delUser {
|
---|
[479] | 3594 | my $self = shift;
|
---|
| 3595 | my $dbh = $self->{dbh};
|
---|
[25] | 3596 | my $userid = shift;
|
---|
| 3597 |
|
---|
[297] | 3598 | return ('FAIL',"Bad userid") if !defined($userid);
|
---|
[25] | 3599 |
|
---|
[479] | 3600 | my $userdata = $self->getUserData($userid);
|
---|
[25] | 3601 |
|
---|
[297] | 3602 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3603 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3604 | local $dbh->{AutoCommit} = 0;
|
---|
| 3605 | local $dbh->{RaiseError} = 1;
|
---|
[25] | 3606 |
|
---|
[297] | 3607 | eval {
|
---|
| 3608 | $dbh->do("DELETE FROM users WHERE user_id=?", undef, ($userid));
|
---|
[487] | 3609 | $self->_log(group_id => $userdata->{group_id},
|
---|
[297] | 3610 | entry => "Deleted user ID $userid/".$userdata->{username}.
|
---|
[487] | 3611 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")");
|
---|
[297] | 3612 | $dbh->commit;
|
---|
| 3613 | };
|
---|
| 3614 | if ($@) {
|
---|
| 3615 | my $msg = $@;
|
---|
| 3616 | eval { $dbh->rollback; };
|
---|
[517] | 3617 | if ($self->{log_failures}) {
|
---|
[487] | 3618 | $self->_log(group_id => $userdata->{group_id}, entry => "Error deleting user ID ".
|
---|
| 3619 | "$userid/".$userdata->{username}.": $msg");
|
---|
[297] | 3620 | $dbh->commit;
|
---|
| 3621 | }
|
---|
| 3622 | return ('FAIL',"Error deleting user $userid/".$userdata->{username}.": $msg");
|
---|
| 3623 | }
|
---|
| 3624 |
|
---|
| 3625 | return ('OK',"Deleted user ".$userdata->{username}." (".$userdata->{firstname}." ".$userdata->{lastname}.")");
|
---|
[24] | 3626 | } # end delUser
|
---|
| 3627 |
|
---|
| 3628 |
|
---|
[25] | 3629 | ## DNSDB::userFullName()
|
---|
| 3630 | # Return a pretty string!
|
---|
| 3631 | # Takes a user_id and optional printf-ish string to indicate which pieces where:
|
---|
| 3632 | # %u for the username
|
---|
| 3633 | # %f for the first name
|
---|
| 3634 | # %l for the last name
|
---|
| 3635 | # All other text in the passed string will be left as-is.
|
---|
| 3636 | ##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
|
---|
| 3637 | sub userFullName {
|
---|
| 3638 | $errstr = '';
|
---|
[473] | 3639 | my $self = shift;
|
---|
| 3640 | my $dbh = $self->{dbh};
|
---|
[25] | 3641 | my $userid = shift;
|
---|
| 3642 | my $fullformat = shift || '%f %l (%u)';
|
---|
| 3643 | my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
|
---|
| 3644 | $sth->execute($userid);
|
---|
| 3645 | my ($uname,$fname,$lname) = $sth->fetchrow_array();
|
---|
| 3646 | $errstr = $DBI::errstr if !$uname;
|
---|
| 3647 |
|
---|
[732] | 3648 | no warnings qw (uninitialized);
|
---|
[25] | 3649 | $fullformat =~ s/\%u/$uname/g;
|
---|
| 3650 | $fullformat =~ s/\%f/$fname/g;
|
---|
| 3651 | $fullformat =~ s/\%l/$lname/g;
|
---|
| 3652 |
|
---|
| 3653 | return $fullformat;
|
---|
| 3654 | } # end userFullName
|
---|
| 3655 |
|
---|
| 3656 |
|
---|
[51] | 3657 | ## DNSDB::userStatus()
|
---|
| 3658 | # Sets and/or returns a user's status
|
---|
| 3659 | # Takes a database handle, user ID and optionally a status argument
|
---|
| 3660 | # Returns undef on errors.
|
---|
| 3661 | sub userStatus {
|
---|
[479] | 3662 | my $self = shift;
|
---|
| 3663 | my $dbh = $self->{dbh};
|
---|
[51] | 3664 | my $id = shift;
|
---|
[296] | 3665 | my $newstatus = shift || 'mu';
|
---|
[51] | 3666 |
|
---|
| 3667 | return undef if $id !~ /^\d+$/;
|
---|
| 3668 |
|
---|
[479] | 3669 | my $userdata = $self->getUserData($id);
|
---|
[51] | 3670 |
|
---|
[296] | 3671 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3672 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3673 | local $dbh->{AutoCommit} = 0;
|
---|
| 3674 | local $dbh->{RaiseError} = 1;
|
---|
| 3675 |
|
---|
| 3676 | if ($newstatus ne 'mu') {
|
---|
| 3677 | # ooo, fun! let's see what we were passed for status
|
---|
| 3678 | eval {
|
---|
| 3679 | $newstatus = 0 if $newstatus eq 'useroff';
|
---|
| 3680 | $newstatus = 1 if $newstatus eq 'useron';
|
---|
| 3681 | $dbh->do("UPDATE users SET status=? WHERE user_id=?", undef, ($newstatus, $id));
|
---|
| 3682 |
|
---|
[297] | 3683 | $resultstr = ($newstatus ? 'Enabled' : 'Disabled')." user ".$userdata->{username}.
|
---|
| 3684 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")";
|
---|
[296] | 3685 |
|
---|
| 3686 | my %loghash;
|
---|
[473] | 3687 | $loghash{group_id} = $self->parentID(id => $id, type => 'user');
|
---|
[296] | 3688 | $loghash{entry} = $resultstr;
|
---|
[487] | 3689 | $self->_log(%loghash);
|
---|
[296] | 3690 |
|
---|
| 3691 | $dbh->commit;
|
---|
| 3692 | };
|
---|
| 3693 | if ($@) {
|
---|
| 3694 | my $msg = $@;
|
---|
| 3695 | eval { $dbh->rollback; };
|
---|
| 3696 | $resultstr = '';
|
---|
| 3697 | $errstr = $msg;
|
---|
| 3698 | ##fixme: failure logging?
|
---|
| 3699 | return;
|
---|
[51] | 3700 | }
|
---|
| 3701 | }
|
---|
| 3702 |
|
---|
[296] | 3703 | my ($status) = $dbh->selectrow_array("SELECT status FROM users WHERE user_id=?", undef, ($id));
|
---|
[51] | 3704 | return $status;
|
---|
| 3705 | } # end userStatus()
|
---|
| 3706 |
|
---|
| 3707 |
|
---|
[83] | 3708 | ## DNSDB::getUserData()
|
---|
| 3709 | # Get misc user data for display
|
---|
| 3710 | sub getUserData {
|
---|
[479] | 3711 | my $self = shift;
|
---|
| 3712 | my $dbh = $self->{dbh};
|
---|
[83] | 3713 | my $uid = shift;
|
---|
| 3714 |
|
---|
| 3715 | my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
|
---|
| 3716 | "FROM users WHERE user_id=?");
|
---|
| 3717 | $sth->execute($uid);
|
---|
| 3718 | return $sth->fetchrow_hashref();
|
---|
| 3719 | } # end getUserData()
|
---|
| 3720 |
|
---|
| 3721 |
|
---|
[370] | 3722 | ## DNSDB::addLoc()
|
---|
[375] | 3723 | # Add a new location.
|
---|
| 3724 | # Takes a database handle, group ID, short and long description, and a comma-separated
|
---|
| 3725 | # list of IP addresses.
|
---|
| 3726 | # Returns ('OK',<location>) on success, ('FAIL',<failmsg>) on failure
|
---|
| 3727 | sub addLoc {
|
---|
[480] | 3728 | my $self = shift;
|
---|
| 3729 | my $dbh = $self->{dbh};
|
---|
[709] | 3730 | my %args = @_;
|
---|
[370] | 3731 |
|
---|
[709] | 3732 | my $grp = $args{group};
|
---|
| 3733 | my $shdesc = $args{desc};
|
---|
| 3734 | my $comments = $args{comments};
|
---|
| 3735 | my $iplist = $args{iplist};
|
---|
| 3736 |
|
---|
[375] | 3737 | # $shdesc gets set to the generated location ID if possible, but these can be de-undefined here.
|
---|
| 3738 | $comments = '' if !$comments;
|
---|
| 3739 | $iplist = '' if !$iplist;
|
---|
| 3740 |
|
---|
[709] | 3741 | # allow requesting a specific location entry.
|
---|
| 3742 | my $loc = $args{loc};
|
---|
[375] | 3743 |
|
---|
| 3744 | # Generate a location ID. This is, by spec, a two-character widget. We'll use [a-z][a-z]
|
---|
| 3745 | # for now; 676 locations should satisfy all but the largest of the huge networks.
|
---|
| 3746 |
|
---|
[709] | 3747 | # just to be as clear as possible; as per http://cr.yp.to/djbdns/tinydns-data.html:
|
---|
[699] | 3748 |
|
---|
| 3749 | #For versions 1.04 and above: You may include a client location on each line. The line is ignored for clients
|
---|
| 3750 | #outside that location. Client locations are specified by % lines:
|
---|
| 3751 | #
|
---|
| 3752 | # %lo:ipprefix
|
---|
| 3753 | #
|
---|
| 3754 | #means that IP addresses starting with ipprefix are in location lo. lo is a sequence of one or two ASCII letters.
|
---|
| 3755 |
|
---|
[709] | 3756 | # this has been confirmed by experiment; locations "lo", "Lo", and "lO" are all distinct.
|
---|
[699] | 3757 |
|
---|
[375] | 3758 | # add just after "my $origloc = $loc;":
|
---|
| 3759 | # # These expand the possible space from 26^2 to 52^2 [* note in testing only 2052 were achieved],
|
---|
| 3760 | # # and wrap it around.
|
---|
| 3761 | # # Yes, they skip a couple of possibles. No, I don't care.
|
---|
| 3762 | # $loc = 'aA' if $loc eq 'zz';
|
---|
| 3763 | # $loc = 'Aa' if $loc eq 'zZ';
|
---|
| 3764 | # $loc = 'ZA' if $loc eq 'Zz';
|
---|
| 3765 | # $loc = 'aa' if $loc eq 'ZZ';
|
---|
| 3766 |
|
---|
| 3767 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3768 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3769 | local $dbh->{AutoCommit} = 0;
|
---|
| 3770 | local $dbh->{RaiseError} = 1;
|
---|
| 3771 |
|
---|
| 3772 | ##fixme: There is probably a far better way to do this. Sequential increments
|
---|
| 3773 | # are marginally less stupid that pure random generation though, and the existence
|
---|
| 3774 | # check makes sure we don't stomp on an imported one.
|
---|
| 3775 |
|
---|
| 3776 | eval {
|
---|
| 3777 | # Get the "last" location. Note this is the only use for loc_id, because selecting on location Does Funky Things
|
---|
[709] | 3778 | my ($newloc) = $dbh->selectrow_array("SELECT location FROM locations ORDER BY loc_id DESC LIMIT 1");
|
---|
| 3779 |
|
---|
| 3780 | no warnings qw(uninitialized);
|
---|
| 3781 |
|
---|
| 3782 | my $ecnt = $dbh->prepare("SELECT count(*) FROM locations WHERE location LIKE ?");
|
---|
| 3783 |
|
---|
| 3784 | if ($loc) {
|
---|
| 3785 | $ecnt->execute($loc);
|
---|
| 3786 | if (($ecnt->fetchrow_array())[0]) {
|
---|
| 3787 | # too bad, so sad, requested location is unavailable.
|
---|
| 3788 | ##fixme: known failure case: caller requests a location ID that is not two characters.
|
---|
| 3789 | die "Requested location is already defined\n" if $args{reqonly};
|
---|
| 3790 | # fall back to autoincrement
|
---|
| 3791 | }
|
---|
| 3792 | $newloc = $loc;
|
---|
| 3793 | }
|
---|
| 3794 |
|
---|
| 3795 | # Either the requested location ID is unavailable and the caller isn't too attached
|
---|
| 3796 | # to it, OR, the caller hasn't specified a location ID. (The second case should be
|
---|
| 3797 | # far more common.) Find the "next available" location identifier.
|
---|
| 3798 |
|
---|
| 3799 | ($newloc) = ($newloc =~ /^(..)/) if $newloc;
|
---|
| 3800 | my $origloc = $newloc;
|
---|
| 3801 | $newloc = 'aa' if !$newloc;
|
---|
[375] | 3802 | # Make a change...
|
---|
| 3803 | # ... and keep changing if it exists
|
---|
[709] | 3804 | while ($dbh->selectrow_array("SELECT count(*) FROM locations WHERE location LIKE ?", undef, ($newloc.'%'))) {
|
---|
| 3805 | $newloc++;
|
---|
| 3806 | ($newloc) = ($newloc =~ /^(..)/);
|
---|
| 3807 | die "too many locations in use, can't add another one\n" if $newloc eq $origloc;
|
---|
[375] | 3808 | ##fixme: really need to handle this case faster somehow
|
---|
| 3809 | #if $loc eq $origloc die "<thwap> bad admin: all locations used, your network is too fragmented";
|
---|
| 3810 | }
|
---|
[709] | 3811 | # And now we should have a unique location.
|
---|
| 3812 | $shdesc = $newloc if !$shdesc;
|
---|
[375] | 3813 | $dbh->do("INSERT INTO locations (location, group_id, iplist, description, comments) VALUES (?,?,?,?,?)",
|
---|
[709] | 3814 | undef, ($newloc, $grp, $iplist, $shdesc, $comments) );
|
---|
[487] | 3815 | $self->_log(entry => "Added location ($shdesc, '$iplist')");
|
---|
[709] | 3816 | $loc = $newloc;
|
---|
[377] | 3817 | $dbh->commit;
|
---|
[375] | 3818 | };
|
---|
| 3819 | if ($@) {
|
---|
| 3820 | my $msg = $@;
|
---|
| 3821 | eval { $dbh->rollback; };
|
---|
[517] | 3822 | if ($self->{log_failures}) {
|
---|
[375] | 3823 | $shdesc = $loc if !$shdesc;
|
---|
[487] | 3824 | $self->_log(entry => "Failed adding location ($shdesc, '$iplist'): $msg");
|
---|
[375] | 3825 | $dbh->commit;
|
---|
| 3826 | }
|
---|
| 3827 | return ('FAIL',$msg);
|
---|
| 3828 | }
|
---|
| 3829 |
|
---|
| 3830 | return ('OK',$loc);
|
---|
[377] | 3831 | } # end addLoc()
|
---|
[375] | 3832 |
|
---|
| 3833 |
|
---|
[370] | 3834 | ## DNSDB::updateLoc()
|
---|
[428] | 3835 | # Update details of a location.
|
---|
| 3836 | # Takes a database handle, location ID, group ID, short description,
|
---|
| 3837 | # long comments/notes, and comma/space-separated IP list
|
---|
| 3838 | # Returns a result code and message
|
---|
[377] | 3839 | sub updateLoc {
|
---|
[480] | 3840 | my $self = shift;
|
---|
| 3841 | my $dbh = $self->{dbh};
|
---|
[377] | 3842 | my $loc = shift;
|
---|
| 3843 | my $grp = shift;
|
---|
| 3844 | my $shdesc = shift;
|
---|
| 3845 | my $comments = shift;
|
---|
| 3846 | my $iplist = shift;
|
---|
[370] | 3847 |
|
---|
[377] | 3848 | $shdesc = '' if !$shdesc;
|
---|
| 3849 | $comments = '' if !$comments;
|
---|
| 3850 | $iplist = '' if !$iplist;
|
---|
| 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 |
|
---|
[480] | 3857 | my $oldloc = $self->getLoc($loc);
|
---|
[377] | 3858 | my $okmsg = "Updated location (".$oldloc->{description}.", '".$oldloc->{iplist}."') to ($shdesc, '$iplist')";
|
---|
| 3859 |
|
---|
| 3860 | eval {
|
---|
| 3861 | $dbh->do("UPDATE locations SET group_id=?,iplist=?,description=?,comments=? WHERE location=?",
|
---|
| 3862 | undef, ($grp, $iplist, $shdesc, $comments, $loc) );
|
---|
[487] | 3863 | $self->_log(entry => $okmsg);
|
---|
[377] | 3864 | $dbh->commit;
|
---|
| 3865 | };
|
---|
| 3866 | if ($@) {
|
---|
| 3867 | my $msg = $@;
|
---|
| 3868 | eval { $dbh->rollback; };
|
---|
[517] | 3869 | if ($self->{log_failures}) {
|
---|
[377] | 3870 | $shdesc = $loc if !$shdesc;
|
---|
[487] | 3871 | $self->_log(entry => "Failed updating location ($shdesc, '$iplist'): $msg");
|
---|
[377] | 3872 | $dbh->commit;
|
---|
| 3873 | }
|
---|
| 3874 | return ('FAIL',$msg);
|
---|
| 3875 | }
|
---|
| 3876 |
|
---|
| 3877 | return ('OK',$okmsg);
|
---|
| 3878 | } # end updateLoc()
|
---|
| 3879 |
|
---|
| 3880 |
|
---|
[370] | 3881 | ## DNSDB::delLoc()
|
---|
[428] | 3882 | sub delLoc {
|
---|
[480] | 3883 | my $self = shift;
|
---|
| 3884 | my $dbh = $self->{dbh};
|
---|
[428] | 3885 | my $loc = shift;
|
---|
[370] | 3886 |
|
---|
[428] | 3887 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3888 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3889 | local $dbh->{AutoCommit} = 0;
|
---|
| 3890 | local $dbh->{RaiseError} = 1;
|
---|
[370] | 3891 |
|
---|
[480] | 3892 | my $oldloc = $self->getLoc($loc);
|
---|
[428] | 3893 | my $olddesc = ($oldloc->{description} ? $oldloc->{description} : $loc);
|
---|
| 3894 | my $okmsg = "Deleted location ($olddesc, '".$oldloc->{iplist}."')";
|
---|
| 3895 |
|
---|
| 3896 | eval {
|
---|
| 3897 | # Check for records with this location first. Deleting a location without deleting records
|
---|
| 3898 | # tagged for that location will render them unpublished without other warning.
|
---|
| 3899 | my ($r) = $dbh->selectrow_array("SELECT record_id FROM records WHERE location=? LIMIT 1", undef, ($loc) );
|
---|
| 3900 | die "Records still exist in location $olddesc\n" if $r;
|
---|
| 3901 | $dbh->do("DELETE FROM locations WHERE location=?", undef, ($loc) );
|
---|
[487] | 3902 | $self->_log(entry => $okmsg);
|
---|
[428] | 3903 | $dbh->commit;
|
---|
| 3904 | };
|
---|
| 3905 | if ($@) {
|
---|
| 3906 | my $msg = $@;
|
---|
| 3907 | eval { $dbh->rollback; };
|
---|
[517] | 3908 | if ($self->{log_failures}) {
|
---|
[487] | 3909 | $self->_log(entry => "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
|
---|
[428] | 3910 | $dbh->commit;
|
---|
| 3911 | }
|
---|
| 3912 | return ('FAIL', "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
|
---|
| 3913 | }
|
---|
| 3914 |
|
---|
| 3915 | return ('OK',$okmsg);
|
---|
| 3916 | } # end delLoc()
|
---|
| 3917 |
|
---|
| 3918 |
|
---|
[375] | 3919 | ## DNSDB::getLoc()
|
---|
[428] | 3920 | # Get details about a location/view
|
---|
| 3921 | # Takes a database handle and location ID.
|
---|
| 3922 | # Returns a reference to a hash containing the group ID, IP list, description, and comments/notes
|
---|
[375] | 3923 | sub getLoc {
|
---|
[480] | 3924 | my $self = shift;
|
---|
| 3925 | my $dbh = $self->{dbh};
|
---|
[375] | 3926 | my $loc = shift;
|
---|
| 3927 |
|
---|
| 3928 | my $sth = $dbh->prepare("SELECT group_id,iplist,description,comments FROM locations WHERE location=?");
|
---|
| 3929 | $sth->execute($loc);
|
---|
| 3930 | return $sth->fetchrow_hashref();
|
---|
| 3931 | } # end getLoc()
|
---|
| 3932 |
|
---|
| 3933 |
|
---|
[370] | 3934 | ## DNSDB::getLocCount()
|
---|
| 3935 | # Get count of locations/views
|
---|
| 3936 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
| 3937 | # - a reference list of secondary groups
|
---|
| 3938 | # - a filter string
|
---|
| 3939 | # - a "Starts with" string
|
---|
| 3940 | sub getLocCount {
|
---|
[480] | 3941 | my $self = shift;
|
---|
| 3942 | my $dbh = $self->{dbh};
|
---|
[370] | 3943 |
|
---|
| 3944 | my %args = @_;
|
---|
| 3945 |
|
---|
[509] | 3946 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 3947 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 3948 | $errstr = "Bad or missing curgroup argument";
|
---|
| 3949 | return;
|
---|
| 3950 | }
|
---|
| 3951 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 3952 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 3953 | $errstr = "Bad childlist argument";
|
---|
| 3954 | return;
|
---|
| 3955 | }
|
---|
| 3956 |
|
---|
[370] | 3957 | my @filterargs;
|
---|
| 3958 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3959 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3960 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3961 |
|
---|
| 3962 | my $sql = "SELECT count(*) FROM locations ".
|
---|
| 3963 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3964 | ($args{startwith} ? " AND description ~* ?" : '').
|
---|
| 3965 | ($args{filter} ? " AND description ~* ?" : '');
|
---|
| 3966 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 3967 | $errstr = $dbh->errstr if !$count;
|
---|
| 3968 | return $count;
|
---|
| 3969 | } # end getLocCount()
|
---|
| 3970 |
|
---|
| 3971 |
|
---|
| 3972 | ## DNSDB::getLocList()
|
---|
| 3973 | sub getLocList {
|
---|
[480] | 3974 | my $self = shift;
|
---|
| 3975 | my $dbh = $self->{dbh};
|
---|
[370] | 3976 |
|
---|
| 3977 | my %args = @_;
|
---|
| 3978 |
|
---|
[509] | 3979 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 3980 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 3981 | $errstr = "Bad or missing curgroup argument";
|
---|
| 3982 | return;
|
---|
| 3983 | }
|
---|
| 3984 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 3985 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 3986 | $errstr = "Bad childlist argument";
|
---|
| 3987 | return;
|
---|
| 3988 | }
|
---|
| 3989 |
|
---|
[370] | 3990 | my @filterargs;
|
---|
| 3991 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3992 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3993 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3994 |
|
---|
| 3995 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
| 3996 | # my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
| 3997 | # fname => 'fname');
|
---|
| 3998 | # $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 3999 |
|
---|
| 4000 | # protection against bad or missing arguments
|
---|
[508] | 4001 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
| 4002 | $args{sortby} = 'l.description' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
[397] | 4003 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[370] | 4004 |
|
---|
| 4005 | my $sql = "SELECT l.location, l.description, l.iplist, g.group_name ".
|
---|
| 4006 | "FROM locations l ".
|
---|
| 4007 | "INNER JOIN groups g ON l.group_id=g.group_id ".
|
---|
| 4008 | "WHERE l.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 4009 | ($args{startwith} ? " AND l.description ~* ?" : '').
|
---|
| 4010 | ($args{filter} ? " AND l.description ~* ?" : '').
|
---|
| 4011 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
[517] | 4012 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
[370] | 4013 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 4014 | $errstr = $dbh->errstr if !$ulist;
|
---|
| 4015 | return $ulist;
|
---|
| 4016 | } # end getLocList()
|
---|
| 4017 |
|
---|
| 4018 |
|
---|
| 4019 | ## DNSDB::getLocDropdown()
|
---|
[383] | 4020 | # Get a list of location names for use in a dropdown menu.
|
---|
| 4021 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
| 4022 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
| 4023 | sub getLocDropdown {
|
---|
[480] | 4024 | my $self = shift;
|
---|
| 4025 | my $dbh = $self->{dbh};
|
---|
[383] | 4026 | my $grp = shift;
|
---|
| 4027 | my $sel = shift || '';
|
---|
[370] | 4028 |
|
---|
[383] | 4029 | my $sth = $dbh->prepare(qq(
|
---|
| 4030 | SELECT description,location FROM locations
|
---|
| 4031 | WHERE group_id=?
|
---|
| 4032 | ORDER BY description
|
---|
| 4033 | ) );
|
---|
| 4034 | $sth->execute($grp);
|
---|
[370] | 4035 |
|
---|
[383] | 4036 | my @loclist;
|
---|
[446] | 4037 | push @loclist, { locname => "(Default/All)", loc => '', selected => ($sel ? 0 : ($sel eq '' ? 1 : 0)) };
|
---|
[383] | 4038 | while (my ($locname, $loc) = $sth->fetchrow_array) {
|
---|
| 4039 | my %row = (
|
---|
| 4040 | locname => $locname,
|
---|
| 4041 | loc => $loc,
|
---|
| 4042 | selected => ($sel eq $loc ? 1 : 0)
|
---|
| 4043 | );
|
---|
| 4044 | push @loclist, \%row;
|
---|
| 4045 | }
|
---|
| 4046 | return \@loclist;
|
---|
| 4047 | } # end getLocDropdown()
|
---|
| 4048 |
|
---|
| 4049 |
|
---|
[2] | 4050 | ## DNSDB::getSOA()
|
---|
| 4051 | # Return all suitable fields from an SOA record in separate elements of a hash
|
---|
[224] | 4052 | # Takes a database handle, default/live flag, domain/reverse flag, and parent ID
|
---|
[2] | 4053 | sub getSOA {
|
---|
| 4054 | $errstr = '';
|
---|
[481] | 4055 | my $self = shift;
|
---|
| 4056 | my $dbh = $self->{dbh};
|
---|
[2] | 4057 | my $def = shift;
|
---|
[224] | 4058 | my $rev = shift;
|
---|
[2] | 4059 | my $id = shift;
|
---|
| 4060 |
|
---|
[224] | 4061 | # (ab)use distance and weight columns to store SOA data? can't for default_rev_records...
|
---|
| 4062 | # - should really attach serial to the zone parent somewhere
|
---|
[101] | 4063 |
|
---|
[224] | 4064 | my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev).
|
---|
| 4065 | " WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}";
|
---|
[311] | 4066 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
| 4067 | return if !$ret;
|
---|
[246] | 4068 | ##fixme: stick a flag somewhere if the record doesn't exist. by the API, this is an impossible case, but...
|
---|
[2] | 4069 |
|
---|
[311] | 4070 | ($ret->{contact},$ret->{prins}) = split /:/, $ret->{host};
|
---|
| 4071 | delete $ret->{host};
|
---|
| 4072 | ($ret->{refresh},$ret->{retry},$ret->{expire},$ret->{minttl}) = split /:/, $ret->{val};
|
---|
| 4073 | delete $ret->{val};
|
---|
[2] | 4074 |
|
---|
[311] | 4075 | return $ret;
|
---|
[2] | 4076 | } # end getSOA()
|
---|
| 4077 |
|
---|
| 4078 |
|
---|
[246] | 4079 | ## DNSDB::updateSOA()
|
---|
| 4080 | # Update the specified SOA record
|
---|
| 4081 | # Takes a database handle, default/live flag, forward/reverse flag, and SOA data hash
|
---|
[277] | 4082 | # Returns a two-element list with a result code and message
|
---|
[246] | 4083 | sub updateSOA {
|
---|
[473] | 4084 | my $self = shift;
|
---|
| 4085 | my $dbh = $self->{dbh};
|
---|
[246] | 4086 | my $defrec = shift;
|
---|
[248] | 4087 | my $revrec = shift;
|
---|
[246] | 4088 |
|
---|
| 4089 | my %soa = @_;
|
---|
| 4090 |
|
---|
[473] | 4091 | my $oldsoa = $self->getSOA($defrec, $revrec, $soa{id});
|
---|
[277] | 4092 |
|
---|
[311] | 4093 | my $msg;
|
---|
| 4094 | my %logdata;
|
---|
| 4095 | if ($defrec eq 'n') {
|
---|
| 4096 | $logdata{domain_id} = $soa{id} if $revrec eq 'n';
|
---|
| 4097 | $logdata{rdns_id} = $soa{id} if $revrec eq 'y';
|
---|
[473] | 4098 | $logdata{group_id} = $self->parentID(id => $soa{id}, revrec => $revrec,
|
---|
| 4099 | type => ($revrec eq 'n' ? 'domain' : 'revzone') );
|
---|
[311] | 4100 | } else {
|
---|
| 4101 | $logdata{group_id} = $soa{id};
|
---|
| 4102 | }
|
---|
[473] | 4103 | my $parname = ($defrec eq 'y' ? $self->groupName($soa{id}) :
|
---|
| 4104 | ($revrec eq 'n' ? $self->domainName($soa{id}) : $self->revName($soa{id})) );
|
---|
[311] | 4105 |
|
---|
[277] | 4106 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4107 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4108 | local $dbh->{AutoCommit} = 0;
|
---|
| 4109 | local $dbh->{RaiseError} = 1;
|
---|
| 4110 |
|
---|
| 4111 | eval {
|
---|
[565] | 4112 | if (!$oldsoa) {
|
---|
| 4113 | # old SOA record is missing for some reason. create a new one.
|
---|
[583] | 4114 | my $sql = "INSERT INTO "._rectable($defrec, $revrec)." ("._recparent($defrec, $revrec).
|
---|
| 4115 | ", host, type, val, ttl) VALUES (?,?,6,?,?)";
|
---|
[565] | 4116 | $dbh->do($sql, undef, ($soa{id}, "$soa{contact}:$soa{prins}",
|
---|
| 4117 | "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}", $soa{ttl}) );
|
---|
| 4118 | $msg = ($defrec eq 'y' ? ($revrec eq 'y' ? 'Default reverse ' : 'Default ') : '').
|
---|
| 4119 | "SOA missing for $parname; added (ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
|
---|
| 4120 | " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})";
|
---|
| 4121 | } else {
|
---|
| 4122 | my $sql = "UPDATE "._rectable($defrec, $revrec)." SET host=?, val=?, ttl=? WHERE record_id=? AND type=6";
|
---|
| 4123 | $dbh->do($sql, undef, ("$soa{contact}:$soa{prins}", "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}",
|
---|
[311] | 4124 | $soa{ttl}, $oldsoa->{record_id}) );
|
---|
[565] | 4125 | $msg = "Updated ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse ' : 'default ') : '').
|
---|
[311] | 4126 | "SOA for $parname: ".
|
---|
| 4127 | "(ns $oldsoa->{prins}, contact $oldsoa->{contact}, refresh $oldsoa->{refresh},".
|
---|
| 4128 | " retry $oldsoa->{retry}, expire $oldsoa->{expire}, minTTL $oldsoa->{minttl}, TTL $oldsoa->{ttl}) to ".
|
---|
[277] | 4129 | "(ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
|
---|
| 4130 | " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})";
|
---|
[565] | 4131 | }
|
---|
[311] | 4132 | $logdata{entry} = $msg;
|
---|
[487] | 4133 | $self->_log(%logdata);
|
---|
[277] | 4134 |
|
---|
| 4135 | $dbh->commit;
|
---|
| 4136 | };
|
---|
| 4137 | if ($@) {
|
---|
| 4138 | $msg = $@;
|
---|
| 4139 | eval { $dbh->rollback; };
|
---|
[311] | 4140 | $logdata{entry} = "Error updating ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse zone ' : 'default ') : '').
|
---|
| 4141 | "SOA record for $parname: $msg";
|
---|
[517] | 4142 | if ($self->{log_failures}) {
|
---|
[487] | 4143 | $self->_log(%logdata);
|
---|
[311] | 4144 | $dbh->commit;
|
---|
| 4145 | }
|
---|
| 4146 | return ('FAIL', $logdata{entry});
|
---|
[277] | 4147 | } else {
|
---|
| 4148 | return ('OK', $msg);
|
---|
| 4149 | }
|
---|
[246] | 4150 | } # end updateSOA()
|
---|
| 4151 |
|
---|
| 4152 |
|
---|
[2] | 4153 | ## DNSDB::getRecLine()
|
---|
| 4154 | # Return all data fields for a zone record in separate elements of a hash
|
---|
[243] | 4155 | # Takes a database handle, default/live flag, forward/reverse flag, and record ID
|
---|
[2] | 4156 | sub getRecLine {
|
---|
| 4157 | $errstr = '';
|
---|
[481] | 4158 | my $self = shift;
|
---|
| 4159 | my $dbh = $self->{dbh};
|
---|
[243] | 4160 | my $defrec = shift;
|
---|
| 4161 | my $revrec = shift;
|
---|
[2] | 4162 | my $id = shift;
|
---|
| 4163 |
|
---|
[543] | 4164 | ##fixme: do we need a knob to twist to switch between unix epoch and postgres time string?
|
---|
[429] | 4165 | my $sql = "SELECT record_id,host,type,val,ttl".
|
---|
| 4166 | ($defrec eq 'n' ? ',location' : '').
|
---|
| 4167 | ($revrec eq 'n' ? ',distance,weight,port' : '').
|
---|
[543] | 4168 | (($defrec eq 'y') ? ',group_id FROM ' : ',domain_id,rdns_id,stamp,stamp < now() AS ispast,expires,stampactive FROM ').
|
---|
[243] | 4169 | _rectable($defrec,$revrec)." WHERE record_id=?";
|
---|
[123] | 4170 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
[2] | 4171 |
|
---|
[90] | 4172 | if ($dbh->err) {
|
---|
[2] | 4173 | $errstr = $DBI::errstr;
|
---|
| 4174 | return undef;
|
---|
| 4175 | }
|
---|
| 4176 |
|
---|
[123] | 4177 | if (!$ret) {
|
---|
| 4178 | $errstr = "No such record";
|
---|
| 4179 | return undef;
|
---|
| 4180 | }
|
---|
| 4181 |
|
---|
[243] | 4182 | # explicitly set a parent id
|
---|
| 4183 | if ($defrec eq 'y') {
|
---|
| 4184 | $ret->{parid} = $ret->{group_id};
|
---|
| 4185 | } else {
|
---|
| 4186 | $ret->{parid} = (($revrec eq 'n') ? $ret->{domain_id} : $ret->{rdns_id});
|
---|
| 4187 | # and a secondary if we have a custom type that lives in both a forward and reverse zone
|
---|
| 4188 | $ret->{secid} = (($revrec eq 'y') ? $ret->{domain_id} : $ret->{rdns_id}) if $ret->{type} > 65279;
|
---|
| 4189 | }
|
---|
[451] | 4190 | $ret->{address} = $ret->{val}; # because.
|
---|
[90] | 4191 |
|
---|
| 4192 | return $ret;
|
---|
[2] | 4193 | }
|
---|
| 4194 |
|
---|
| 4195 |
|
---|
| 4196 | ##fixme: should use above (getRecLine()) to get lines for below?
|
---|
[495] | 4197 | ## DNSDB::getRecList()
|
---|
| 4198 | # Return records for a group or zone
|
---|
| 4199 | # Takes a default/live flag, group or zone ID, start,
|
---|
[2] | 4200 | # number of records, sort field, and sort order
|
---|
| 4201 | # Returns a reference to an array of hashes
|
---|
[495] | 4202 | sub getRecList {
|
---|
[2] | 4203 | $errstr = '';
|
---|
[481] | 4204 | my $self = shift;
|
---|
| 4205 | my $dbh = $self->{dbh};
|
---|
[2] | 4206 |
|
---|
[397] | 4207 | my %args = @_;
|
---|
[4] | 4208 |
|
---|
[666] | 4209 | $args{revrec} = 'n' if !$args{revrec};
|
---|
| 4210 | $args{defrec} = 'n' if !$args{defrec};
|
---|
| 4211 |
|
---|
[716] | 4212 | # RPC callers generally want the "true" IP. Flag argument for those to bypass showrev_arpa
|
---|
| 4213 | ##fixme: this will still blow up if some idiot has actually stored .arpa names in the DB.
|
---|
| 4214 | # ... do we care?
|
---|
| 4215 | $args{rpc} = 0 if !$args{rpc};
|
---|
| 4216 |
|
---|
[397] | 4217 | # protection against bad or missing arguments
|
---|
[508] | 4218 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
[510] | 4219 | my $defsort;
|
---|
| 4220 | $defsort = 'host' if $args{revrec} eq 'n'; # default sort by host on domain record list
|
---|
| 4221 | $defsort = 'val' if $args{revrec} eq 'y'; # default sort by IP on revzone record list
|
---|
[513] | 4222 | $args{sortby} = '' if !$args{sortby};
|
---|
[508] | 4223 | $args{sortby} = $defsort if !$args{revrec};
|
---|
[512] | 4224 | $args{sortby} = $defsort if $args{sortby} !~ /^[\w_,.]+$/;
|
---|
[397] | 4225 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[517] | 4226 | my $perpage = ($args{nrecs} ? $args{nrecs} : $self->{perpage});
|
---|
[397] | 4227 |
|
---|
[543] | 4228 | ##fixme: do we need a knob to twist to switch from unix epoch to postgres time string?
|
---|
[666] | 4229 | my @bindvars;
|
---|
| 4230 | my $sql = "SELECT r.record_id,";
|
---|
| 4231 | # only include the parent info if we don't already know which parent we're in
|
---|
| 4232 | $sql .= "r.domain_id,r.rdns_id," unless $args{id};
|
---|
| 4233 | $sql .= "r.host,r.type,r.val,r.ttl";
|
---|
[543] | 4234 | $sql .= ",l.description AS locname,stamp,r.stamp < now() AS ispast,r.expires,r.stampactive"
|
---|
| 4235 | if $args{defrec} eq 'n';
|
---|
[397] | 4236 | $sql .= ",r.distance,r.weight,r.port" if $args{revrec} eq 'n';
|
---|
| 4237 | $sql .= " FROM "._rectable($args{defrec},$args{revrec})." r ";
|
---|
[104] | 4238 | $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
|
---|
[397] | 4239 | $sql .= "LEFT JOIN locations l ON r.location=l.location " if $args{defrec} eq 'n';
|
---|
[666] | 4240 | $sql .= "WHERE NOT r.type=$reverse_typemap{SOA}";
|
---|
| 4241 |
|
---|
| 4242 | # "normal" record list
|
---|
| 4243 | if ($args{id}) {
|
---|
| 4244 | $sql .= " AND "._recparent($args{defrec},$args{revrec})." = ?";
|
---|
| 4245 | push @bindvars, $args{id};
|
---|
| 4246 | }
|
---|
| 4247 |
|
---|
| 4248 | # Filtering on host/val (mainly normal record list)
|
---|
[614] | 4249 | if ($args{filter}) {
|
---|
| 4250 | $sql .= " AND (r.host ~* ? OR r.val ~* ? OR r.host ~* ? OR r.val ~* ?)";
|
---|
| 4251 | my $tmp = join('.',reverse(split(/\./,$args{filter})));
|
---|
[666] | 4252 | push @bindvars, ($args{filter},$args{filter});
|
---|
[614] | 4253 | push @bindvars, ($tmp, $tmp);
|
---|
| 4254 | }
|
---|
[666] | 4255 |
|
---|
| 4256 | # Filtering on other fields
|
---|
[715] | 4257 | foreach (qw(type distance weight port ttl description location)) {
|
---|
[666] | 4258 | if ($args{$_}) {
|
---|
[716] | 4259 | $sql .= " AND r.$_ ~* ?";
|
---|
[666] | 4260 | push @bindvars, $args{$_};
|
---|
| 4261 | }
|
---|
| 4262 | }
|
---|
| 4263 |
|
---|
| 4264 | # whee! multisort means just passing comma-separated fields in sortby!
|
---|
| 4265 | my $newsort = '';
|
---|
| 4266 | foreach my $sf (split /,/, $args{sortby}) {
|
---|
| 4267 | $sf = "r.$sf";
|
---|
| 4268 | # sort on IP, correctly
|
---|
| 4269 | $sf =~ s/r\.val/inetlazy(r.val)/;
|
---|
| 4270 | # hmm. do we really need to limit this?
|
---|
| 4271 | # if $args{revrec} eq 'y' && $args{defrec} eq 'n';
|
---|
| 4272 | $sf =~ s/r\.type/t.alphaorder/; # subtly different from sorting on rectypes.name
|
---|
| 4273 | $newsort .= ",$sf";
|
---|
| 4274 | }
|
---|
| 4275 | $newsort =~ s/^,//;
|
---|
| 4276 | ##enhance: pass in ascending/descending sort per-field
|
---|
[420] | 4277 | $sql .= " ORDER BY $newsort $args{sortorder}";
|
---|
[324] | 4278 | # ensure consistent ordering by sorting on record_id too
|
---|
[397] | 4279 | $sql .= ", record_id $args{sortorder}";
|
---|
[666] | 4280 |
|
---|
| 4281 | # Offset/pagination
|
---|
[501] | 4282 | $sql .= ($args{offset} eq 'all' ? '' : " LIMIT $perpage OFFSET ".$args{offset}*$perpage);
|
---|
[4] | 4283 |
|
---|
[583] | 4284 | my @working;
|
---|
| 4285 | my $recsth = $dbh->prepare($sql);
|
---|
| 4286 | $recsth->execute(@bindvars);
|
---|
| 4287 | while (my $rec = $recsth->fetchrow_hashref) {
|
---|
[716] | 4288 | if (!$args{rpc} && $args{revrec} eq 'y' && $args{defrec} eq 'n' &&
|
---|
[607] | 4289 | ($self->{showrev_arpa} eq 'record' || $self->{showrev_arpa} eq 'all') &&
|
---|
| 4290 | $rec->{val} !~ /\.arpa$/ ) {
|
---|
[608] | 4291 | # skip all reverse zone .arpa "hostnames" since they're already .arpa names.
|
---|
[583] | 4292 | ##enhance: extend {showrev_arpa} eq 'record' to specify record types
|
---|
[633] | 4293 | my $tmpip = new NetAddr::IP $rec->{val} if $rec->{val} =~ /^(?:[\d.\/]+|[a-fA-F0-9:\/]+)$/;
|
---|
[607] | 4294 | $rec->{val} = DNSDB::_ZONE($tmpip, 'ZONE', 'r', '.').($tmpip->{isv6} ? '.ip6.arpa' : '.in-addr.arpa') if $tmpip;
|
---|
[583] | 4295 | }
|
---|
| 4296 | push @working, $rec;
|
---|
| 4297 | }
|
---|
| 4298 | return \@working;
|
---|
[495] | 4299 | } # end getRecList()
|
---|
[2] | 4300 |
|
---|
| 4301 |
|
---|
[91] | 4302 | ## DNSDB::getRecCount()
|
---|
[224] | 4303 | # Return count of non-SOA records in zone (or default records in a group)
|
---|
| 4304 | # Takes a database handle, default/live flag, reverse/forward flag, group/domain ID,
|
---|
| 4305 | # and optional filtering modifier
|
---|
[91] | 4306 | # Returns the count
|
---|
| 4307 | sub getRecCount {
|
---|
[481] | 4308 | my $self = shift;
|
---|
| 4309 | my $dbh = $self->{dbh};
|
---|
[91] | 4310 |
|
---|
[666] | 4311 | my %args = @_;
|
---|
[135] | 4312 |
|
---|
[666] | 4313 | $args{defrec} = 'n' if !$args{defrec};
|
---|
| 4314 | $args{revrec} = 'n' if !$args{revrec};
|
---|
| 4315 |
|
---|
| 4316 | my @bindvars;
|
---|
[224] | 4317 | my $sql = "SELECT count(*) FROM ".
|
---|
[666] | 4318 | _rectable($args{defrec},$args{revrec}).
|
---|
[689] | 4319 | " r WHERE NOT type=$reverse_typemap{SOA}";
|
---|
[666] | 4320 | if ($args{id}) {
|
---|
| 4321 | $sql .= " AND "._recparent($args{defrec},$args{revrec})." = ?";
|
---|
| 4322 | push @bindvars, $args{id};
|
---|
| 4323 | }
|
---|
| 4324 |
|
---|
| 4325 | # Filtering on host/val (mainly normal record list)
|
---|
| 4326 | if ($args{filter}) {
|
---|
[614] | 4327 | $sql .= " AND (r.host ~* ? OR r.val ~* ? OR r.host ~* ? OR r.val ~* ?)";
|
---|
[666] | 4328 | my $tmp = join('.',reverse(split(/\./,$args{filter})));
|
---|
| 4329 | push @bindvars, ($args{filter},$args{filter});
|
---|
[614] | 4330 | push @bindvars, ($tmp, $tmp);
|
---|
| 4331 | }
|
---|
[584] | 4332 |
|
---|
[666] | 4333 | # Filtering on other fields
|
---|
| 4334 | foreach (qw(type distance weight port ttl description)) {
|
---|
| 4335 | if ($args{$_}) {
|
---|
| 4336 | $sql .= " AND $_ ~* ?";
|
---|
| 4337 | push @bindvars, $args{$_};
|
---|
| 4338 | }
|
---|
| 4339 | }
|
---|
| 4340 |
|
---|
[224] | 4341 | my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) );
|
---|
[91] | 4342 |
|
---|
| 4343 | return $count;
|
---|
| 4344 |
|
---|
| 4345 | } # end getRecCount()
|
---|
| 4346 |
|
---|
| 4347 |
|
---|
[3] | 4348 | ## DNSDB::addRec()
|
---|
[2] | 4349 | # Add a new record to a domain or a group's default records
|
---|
| 4350 | # Takes a database handle, default/live flag, group/domain ID,
|
---|
| 4351 | # host, type, value, and TTL
|
---|
| 4352 | # Some types require additional detail: "distance" for MX and SRV,
|
---|
| 4353 | # and weight/port for SRV
|
---|
| 4354 | # Returns a status code and detail message in case of error
|
---|
[234] | 4355 | ##fixme: pass a hash with the record data, not a series of separate values
|
---|
[2] | 4356 | sub addRec {
|
---|
| 4357 | $errstr = '';
|
---|
[481] | 4358 | my $self = shift;
|
---|
| 4359 | my $dbh = $self->{dbh};
|
---|
[2] | 4360 | my $defrec = shift;
|
---|
[226] | 4361 | my $revrec = shift;
|
---|
| 4362 | my $id = shift; # parent (group_id for defrecs, rdns_id for reverse records,
|
---|
| 4363 | # domain_id for domain records)
|
---|
[2] | 4364 |
|
---|
| 4365 | my $host = shift;
|
---|
[234] | 4366 | my $rectype = shift; # reference so we can coerce it if "+"-types can't find both zones
|
---|
[2] | 4367 | my $val = shift;
|
---|
| 4368 | my $ttl = shift;
|
---|
[389] | 4369 | my $location = shift;
|
---|
| 4370 | $location = '' if !$location;
|
---|
[2] | 4371 |
|
---|
[658] | 4372 | my $expires = shift || '';
|
---|
[543] | 4373 | $expires = 1 if $expires eq 'until'; # Turn some special values into the appropriate booleans.
|
---|
| 4374 | $expires = 0 if $expires eq 'after';
|
---|
| 4375 | my $stamp = shift;
|
---|
| 4376 | $stamp = '' if !$stamp; # Timestamp should be a string at this point.
|
---|
| 4377 |
|
---|
[674] | 4378 | # extra safety net - apparently RPC can squeak this by. O_o
|
---|
| 4379 | return ('FAIL', "host must contain a value") if !$$host;
|
---|
| 4380 | return ('FAIL', "val must contain a value") if !$$val;
|
---|
| 4381 |
|
---|
[417] | 4382 | # Spaces are evil.
|
---|
| 4383 | $$host =~ s/^\s+//;
|
---|
| 4384 | $$host =~ s/\s+$//;
|
---|
[418] | 4385 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
[417] | 4386 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 4387 | $$val =~ s/^\s+//;
|
---|
| 4388 | $$val =~ s/\s+$//;
|
---|
| 4389 | }
|
---|
| 4390 |
|
---|
[617] | 4391 | _caseclean($rectype, $host, $val, $defrec, $revrec) if $self->{lowercase};
|
---|
[542] | 4392 |
|
---|
[226] | 4393 | # prep for validation
|
---|
[609] | 4394 | my $addr = NetAddr::IP->new($$val) if _maybeip($val);
|
---|
[252] | 4395 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
[226] | 4396 |
|
---|
| 4397 | my $domid = 0;
|
---|
| 4398 | my $revid = 0;
|
---|
| 4399 |
|
---|
| 4400 | my $retcode = 'OK'; # assume everything will go OK
|
---|
| 4401 | my $retmsg = '';
|
---|
| 4402 |
|
---|
| 4403 | # do simple validation first
|
---|
[559] | 4404 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^-?\d+$/;
|
---|
[226] | 4405 |
|
---|
[234] | 4406 | # Collect these even if we're only doing a simple A record so we can call *any* validation sub
|
---|
| 4407 | my $dist = shift;
|
---|
[281] | 4408 | my $weight = shift;
|
---|
[234] | 4409 | my $port = shift;
|
---|
[226] | 4410 |
|
---|
[234] | 4411 | my $fields;
|
---|
| 4412 | my @vallist;
|
---|
[226] | 4413 |
|
---|
[234] | 4414 | # Call the validation sub for the type requested.
|
---|
[481] | 4415 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec, id => $id,
|
---|
[249] | 4416 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
[234] | 4417 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
[481] | 4418 | fields => \$fields, vallist => \@vallist);
|
---|
[129] | 4419 |
|
---|
[234] | 4420 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
[209] | 4421 |
|
---|
[234] | 4422 | # Set up database fields and bind parameters
|
---|
[481] | 4423 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
| 4424 | push @vallist, ($$host,$$rectype,$$val,$ttl,$id);
|
---|
| 4425 |
|
---|
| 4426 | if ($defrec eq 'n') {
|
---|
[543] | 4427 | # locations are not for default records, silly coder!
|
---|
[481] | 4428 | $fields .= ",location";
|
---|
| 4429 | push @vallist, $location;
|
---|
[543] | 4430 | # timestamps are rare.
|
---|
| 4431 | if ($stamp) {
|
---|
| 4432 | $fields .= ",stamp,expires,stampactive";
|
---|
| 4433 | push @vallist, $stamp, $expires, 'y';
|
---|
| 4434 | } else {
|
---|
| 4435 | $fields .= ",stampactive";
|
---|
| 4436 | push @vallist, 'n';
|
---|
| 4437 | }
|
---|
[481] | 4438 | }
|
---|
[543] | 4439 |
|
---|
| 4440 | # a little magic to get the right number of ? placeholders based on how many values we're providing
|
---|
[234] | 4441 | my $vallen = '?'.(',?'x$#vallist);
|
---|
[2] | 4442 |
|
---|
[287] | 4443 | # Put together the success log entry. We have to use this horrible kludge
|
---|
| 4444 | # because domain_id and rdns_id may or may not be present, and if they are,
|
---|
| 4445 | # they're not at a guaranteed consistent index in the array. wheee!
|
---|
| 4446 | my %logdata;
|
---|
| 4447 | my @ftmp = split /,/, $fields;
|
---|
| 4448 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
| 4449 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
| 4450 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
| 4451 | }
|
---|
| 4452 | $logdata{group_id} = $id if $defrec eq 'y';
|
---|
[473] | 4453 | $logdata{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec)
|
---|
[287] | 4454 | if $defrec eq 'n';
|
---|
[328] | 4455 | $logdata{entry} = "Added ".($defrec eq 'y' ? 'default record' : 'record');
|
---|
[621] | 4456 | # Log reverse records to match the formal .arpa tree
|
---|
| 4457 | if ($revrec eq 'y') {
|
---|
[328] | 4458 | $logdata{entry} .= " '$$val $typemap{$$rectype} $$host";
|
---|
| 4459 | } else {
|
---|
| 4460 | $logdata{entry} .= " '$$host $typemap{$$rectype} $$val";
|
---|
| 4461 | }
|
---|
| 4462 |
|
---|
[287] | 4463 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
| 4464 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]"
|
---|
| 4465 | if $typemap{$$rectype} eq 'SRV';
|
---|
[425] | 4466 | $logdata{entry} .= "', TTL $ttl";
|
---|
[480] | 4467 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location;
|
---|
[642] | 4468 | $logdata{entry} .= ($expires ? ', expires at ' : ', valid after ').$stamp if $stamp;
|
---|
[287] | 4469 |
|
---|
[90] | 4470 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4471 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4472 | local $dbh->{AutoCommit} = 0;
|
---|
| 4473 | local $dbh->{RaiseError} = 1;
|
---|
[2] | 4474 |
|
---|
[90] | 4475 | eval {
|
---|
[236] | 4476 | $dbh->do("INSERT INTO "._rectable($defrec, $revrec)." ($fields) VALUES ($vallen)",
|
---|
[90] | 4477 | undef, @vallist);
|
---|
[487] | 4478 | $self->_log(%logdata);
|
---|
[90] | 4479 | $dbh->commit;
|
---|
| 4480 | };
|
---|
| 4481 | if ($@) {
|
---|
| 4482 | my $msg = $@;
|
---|
| 4483 | eval { $dbh->rollback; };
|
---|
[517] | 4484 | if ($self->{log_failures}) {
|
---|
[289] | 4485 | $logdata{entry} = "Failed adding ".($defrec eq 'y' ? 'default ' : '').
|
---|
| 4486 | "record '$$host $typemap{$$rectype} $$val', TTL $ttl ($msg)";
|
---|
[487] | 4487 | $self->_log(%logdata);
|
---|
[289] | 4488 | $dbh->commit;
|
---|
| 4489 | }
|
---|
[90] | 4490 | return ('FAIL',$msg);
|
---|
| 4491 | }
|
---|
[2] | 4492 |
|
---|
[287] | 4493 | $resultstr = $logdata{entry};
|
---|
[226] | 4494 | return ($retcode, $retmsg);
|
---|
[90] | 4495 |
|
---|
[2] | 4496 | } # end addRec()
|
---|
| 4497 |
|
---|
| 4498 |
|
---|
[16] | 4499 | ## DNSDB::updateRec()
|
---|
| 4500 | # Update a record
|
---|
[273] | 4501 | # Takes a database handle, default and reverse flags, record ID, immediate parent ID, and new record data.
|
---|
| 4502 | # Returns a status code and message
|
---|
[16] | 4503 | sub updateRec {
|
---|
| 4504 | $errstr = '';
|
---|
[17] | 4505 |
|
---|
[481] | 4506 | my $self = shift;
|
---|
| 4507 | my $dbh = $self->{dbh};
|
---|
[679] | 4508 |
|
---|
[16] | 4509 | my $defrec = shift;
|
---|
[272] | 4510 | my $revrec = shift;
|
---|
[16] | 4511 | my $id = shift;
|
---|
[272] | 4512 | my $parid = shift; # immediate parent entity that we're descending from to update the record
|
---|
[16] | 4513 |
|
---|
[273] | 4514 | # all records have these
|
---|
[16] | 4515 | my $host = shift;
|
---|
[272] | 4516 | my $hostbk = $$host; # Keep a backup copy of the original, so we can WARN if the update mangles the domain
|
---|
| 4517 | my $rectype = shift;
|
---|
[16] | 4518 | my $val = shift;
|
---|
| 4519 | my $ttl = shift;
|
---|
[389] | 4520 | my $location = shift; # may be empty/null/undef depending on caller
|
---|
| 4521 | $location = '' if !$location;
|
---|
[16] | 4522 |
|
---|
[658] | 4523 | my $expires = shift || '';
|
---|
[543] | 4524 | $expires = 1 if $expires eq 'until'; # Turn some special values into the appropriate booleans.
|
---|
| 4525 | $expires = 0 if $expires eq 'after';
|
---|
| 4526 | my $stamp = shift;
|
---|
| 4527 | $stamp = '' if !$stamp; # Timestamp should be a string at this point.
|
---|
| 4528 |
|
---|
[510] | 4529 | # just set it to an empty string; failures will be caught later.
|
---|
| 4530 | $$host = '' if !$$host;
|
---|
| 4531 |
|
---|
[417] | 4532 | # Spaces are evil.
|
---|
| 4533 | $$host =~ s/^\s+//;
|
---|
| 4534 | $$host =~ s/\s+$//;
|
---|
[418] | 4535 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
[417] | 4536 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 4537 | $$val =~ s/^\s+//;
|
---|
| 4538 | $$val =~ s/\s+$//;
|
---|
| 4539 | }
|
---|
| 4540 |
|
---|
[617] | 4541 | _caseclean($rectype, $host, $val, $defrec, $revrec) if $self->{lowercase};
|
---|
[542] | 4542 |
|
---|
[272] | 4543 | # prep for validation
|
---|
[609] | 4544 | my $addr = NetAddr::IP->new($$val) if _maybeip($val);
|
---|
[272] | 4545 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
[16] | 4546 |
|
---|
[272] | 4547 | my $domid = 0;
|
---|
| 4548 | my $revid = 0;
|
---|
| 4549 |
|
---|
| 4550 | my $retcode = 'OK'; # assume everything will go OK
|
---|
| 4551 | my $retmsg = '';
|
---|
| 4552 |
|
---|
[273] | 4553 | # do simple validation first
|
---|
[559] | 4554 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^-?\d+$/;
|
---|
[272] | 4555 |
|
---|
[273] | 4556 | # only MX and SRV will use these
|
---|
[288] | 4557 | my $dist = shift || 0;
|
---|
| 4558 | my $weight = shift || 0;
|
---|
| 4559 | my $port = shift || 0;
|
---|
[16] | 4560 |
|
---|
[272] | 4561 | my $fields;
|
---|
| 4562 | my @vallist;
|
---|
[16] | 4563 |
|
---|
[273] | 4564 | # get old record data so we have the right parent ID
|
---|
| 4565 | # and for logging (eventually)
|
---|
[481] | 4566 | my $oldrec = $self->getRecLine($defrec, $revrec, $id);
|
---|
[223] | 4567 |
|
---|
[272] | 4568 | # Call the validation sub for the type requested.
|
---|
| 4569 | # Note the ID to pass here is the *parent*, not the record
|
---|
[481] | 4570 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec,
|
---|
[272] | 4571 | id => ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})),
|
---|
| 4572 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
| 4573 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
| 4574 | fields => \$fields, vallist => \@vallist,
|
---|
[481] | 4575 | update => $id);
|
---|
[272] | 4576 |
|
---|
| 4577 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
| 4578 |
|
---|
[273] | 4579 | # Set up database fields and bind parameters. Note only the optional fields
|
---|
| 4580 | # (distance, weight, port, secondary parent ID) are added in the validation call above
|
---|
[448] | 4581 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
| 4582 | push @vallist, ($$host,$$rectype,$$val,$ttl,
|
---|
[273] | 4583 | ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})) );
|
---|
[272] | 4584 |
|
---|
[448] | 4585 | if ($defrec eq 'n') {
|
---|
[543] | 4586 | # locations are not for default records, silly coder!
|
---|
[448] | 4587 | $fields .= ",location";
|
---|
| 4588 | push @vallist, $location;
|
---|
[543] | 4589 | # timestamps are rare.
|
---|
| 4590 | if ($stamp) {
|
---|
| 4591 | $fields .= ",stamp,expires,stampactive";
|
---|
| 4592 | push @vallist, $stamp, $expires, 'y';
|
---|
| 4593 | } else {
|
---|
| 4594 | $fields .= ",stampactive";
|
---|
| 4595 | push @vallist, 'n';
|
---|
| 4596 | }
|
---|
[448] | 4597 | }
|
---|
| 4598 |
|
---|
[273] | 4599 | # hack hack PTHUI
|
---|
| 4600 | # need to forcibly make sure we disassociate a record with a parent it's no longer related to.
|
---|
| 4601 | # eg, PTR records may not have a domain parent, or A/AAAA records may not have a revzone parent.
|
---|
[605] | 4602 | # needed for crossover types that got coerced down to "standard" types due to data changes
|
---|
| 4603 | # need to *avoid* funky records being updated like A/AAAA records in revzones, or PTRs in forward zones.
|
---|
| 4604 | if ($defrec eq 'n' && $oldrec->{type} > 65000) {
|
---|
[273] | 4605 | if ($$rectype == $reverse_typemap{PTR}) {
|
---|
| 4606 | $fields .= ",domain_id";
|
---|
| 4607 | push @vallist, 0;
|
---|
| 4608 | }
|
---|
| 4609 | if ($$rectype == $reverse_typemap{A} || $$rectype == $reverse_typemap{AAAA}) {
|
---|
| 4610 | $fields .= ",rdns_id";
|
---|
| 4611 | push @vallist, 0;
|
---|
| 4612 | }
|
---|
| 4613 | }
|
---|
[345] | 4614 | # fix fat-finger-originated record type changes
|
---|
[605] | 4615 | if ($$rectype == 65285) { # delegation
|
---|
[345] | 4616 | $fields .= ",rdns_id" if $revrec eq 'n';
|
---|
| 4617 | $fields .= ",domain_id" if $revrec eq 'y';
|
---|
| 4618 | push @vallist, 0;
|
---|
| 4619 | }
|
---|
[605] | 4620 | # ... and now make sure we *do* associate a record with the "calling" parent
|
---|
[341] | 4621 | if ($defrec eq 'n') {
|
---|
| 4622 | $domid = $parid if $revrec eq 'n';
|
---|
| 4623 | $revid = $parid if $revrec eq 'y';
|
---|
| 4624 | }
|
---|
[272] | 4625 |
|
---|
[288] | 4626 | # Put together the success log entry. Horrible kludge from addRec() copied as-is since
|
---|
| 4627 | # we don't know whether the passed arguments or retrieved values for domain_id and rdns_id
|
---|
| 4628 | # will be maintained (due to "not-in-zone" validation changes)
|
---|
| 4629 | my %logdata;
|
---|
[341] | 4630 | $logdata{domain_id} = $domid;
|
---|
| 4631 | $logdata{rdns_id} = $revid;
|
---|
[288] | 4632 | my @ftmp = split /,/, $fields;
|
---|
| 4633 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
| 4634 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
| 4635 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
| 4636 | }
|
---|
| 4637 | $logdata{group_id} = $parid if $defrec eq 'y';
|
---|
[473] | 4638 | $logdata{group_id} = $self->parentID(id => $parid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec)
|
---|
[288] | 4639 | if $defrec eq 'n';
|
---|
[328] | 4640 | $logdata{entry} = "Updated ".($defrec eq 'y' ? 'default record' : 'record')." from\n";
|
---|
[621] | 4641 | # Log reverse records "naturally", since they're stored, um, unnaturally.
|
---|
| 4642 | if ($revrec eq 'y') {
|
---|
[328] | 4643 | $logdata{entry} .= " '$oldrec->{val} $typemap{$oldrec->{type}} $oldrec->{host}";
|
---|
| 4644 | } else {
|
---|
| 4645 | $logdata{entry} .= " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
| 4646 | }
|
---|
[288] | 4647 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
| 4648 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
| 4649 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
[425] | 4650 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
[480] | 4651 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location};
|
---|
[543] | 4652 | $logdata{entry} .= ($oldrec->{expires} ? ', expires at ' : ', valid after ').$oldrec->{stamp}
|
---|
| 4653 | if $oldrec->{stampactive};
|
---|
[425] | 4654 | $logdata{entry} .= "\nto\n";
|
---|
[621] | 4655 | # Log reverse records "naturally", since they're stored, um, unnaturally.
|
---|
| 4656 | if ($revrec eq 'y') {
|
---|
[328] | 4657 | $logdata{entry} .= "'$$val $typemap{$$rectype} $$host";
|
---|
| 4658 | } else {
|
---|
| 4659 | $logdata{entry} .= "'$$host $typemap{$$rectype} $$val";
|
---|
| 4660 | }
|
---|
[288] | 4661 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
| 4662 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$$rectype} eq 'SRV';
|
---|
[425] | 4663 | $logdata{entry} .= "', TTL $ttl";
|
---|
[480] | 4664 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location;
|
---|
[642] | 4665 | $logdata{entry} .= ($expires ? ', expires at ' : ', valid after ').$stamp if $stamp;
|
---|
[288] | 4666 |
|
---|
[90] | 4667 | local $dbh->{AutoCommit} = 0;
|
---|
| 4668 | local $dbh->{RaiseError} = 1;
|
---|
| 4669 |
|
---|
[341] | 4670 | # Fiddle the field list into something suitable for updates
|
---|
| 4671 | $fields =~ s/,/=?,/g;
|
---|
| 4672 | $fields .= "=?";
|
---|
| 4673 |
|
---|
[90] | 4674 | eval {
|
---|
[273] | 4675 | $dbh->do("UPDATE "._rectable($defrec,$revrec)." SET $fields WHERE record_id=?", undef, (@vallist, $id) );
|
---|
[487] | 4676 | $self->_log(%logdata);
|
---|
[130] | 4677 | $dbh->commit;
|
---|
[90] | 4678 | };
|
---|
| 4679 | if ($@) {
|
---|
| 4680 | my $msg = $@;
|
---|
[288] | 4681 | eval { $dbh->rollback; };
|
---|
[517] | 4682 | if ($self->{log_failures}) {
|
---|
[289] | 4683 | $logdata{entry} = "Failed updating ".($defrec eq 'y' ? 'default ' : '').
|
---|
| 4684 | "record '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
[487] | 4685 | $self->_log(%logdata);
|
---|
[289] | 4686 | $dbh->commit;
|
---|
| 4687 | }
|
---|
[90] | 4688 | return ('FAIL', $msg);
|
---|
| 4689 | }
|
---|
| 4690 |
|
---|
[288] | 4691 | $resultstr = $logdata{entry};
|
---|
[272] | 4692 | return ($retcode, $retmsg);
|
---|
[16] | 4693 | } # end updateRec()
|
---|
| 4694 |
|
---|
| 4695 |
|
---|
[459] | 4696 | ## DNSDB::downconvert()
|
---|
| 4697 | # A mostly internal (not exported) semiutilty sub to downconvert from pseudotype <x>
|
---|
| 4698 | # to a compatible component type. Only a handful of operations are valid, anything
|
---|
| 4699 | # else is a null-op.
|
---|
| 4700 | # Takes the record ID and the new type. Returns boolean.
|
---|
| 4701 | sub downconvert {
|
---|
[481] | 4702 | my $self = shift;
|
---|
| 4703 | my $dbh = $self->{dbh};
|
---|
[459] | 4704 | my $recid = shift;
|
---|
| 4705 | my $newtype = shift;
|
---|
| 4706 |
|
---|
| 4707 | # also, only work on live records; little to no value trying to do this on default records.
|
---|
[481] | 4708 | my $rec = $self->getRecLine('n', 'y', $recid);
|
---|
[459] | 4709 |
|
---|
| 4710 | # hm?
|
---|
| 4711 | #return 1 if !$rec;
|
---|
| 4712 |
|
---|
| 4713 | return 1 if $rec->{type} < 65000; # Only the reverse-record pseudotypes can be downconverted
|
---|
| 4714 | return 1 if $rec->{type} == 65282; # Nowhere to go
|
---|
| 4715 |
|
---|
| 4716 | my $delpar;
|
---|
| 4717 | my @sqlargs;
|
---|
| 4718 | if ($rec->{type} == 65280) {
|
---|
| 4719 | return 1 if $newtype != 1 && $newtype != 12;
|
---|
| 4720 | $delpar = ($newtype == 1 ? 'rdns_id' : 'domain_id');
|
---|
| 4721 | push @sqlargs, 0, $newtype, $recid;
|
---|
| 4722 | } elsif ($rec->{type} == 65281) {
|
---|
| 4723 | return 1 if $newtype != 28 && $newtype != 12;
|
---|
| 4724 | $delpar = ($newtype == 28 ? 'rdns_id' : 'domain_id');
|
---|
| 4725 | push @sqlargs, 0, $newtype, $recid;
|
---|
| 4726 | } elsif ($rec->{type} == 65283) {
|
---|
| 4727 | return 1 if $newtype != 65282;
|
---|
| 4728 | $delpar = 'rdns_id';
|
---|
| 4729 | } elsif ($rec->{type} == 65284) {
|
---|
| 4730 | return 1 if $newtype != 65282;
|
---|
| 4731 | $delpar = 'rdns_id';
|
---|
| 4732 | } else {
|
---|
| 4733 | # Your llama is on fire.
|
---|
| 4734 | }
|
---|
| 4735 |
|
---|
| 4736 | local $dbh->{AutoCommit} = 0;
|
---|
| 4737 | local $dbh->{RaiseError} = 1;
|
---|
| 4738 |
|
---|
| 4739 | eval {
|
---|
| 4740 | $dbh->do("UPDATE records SET $delpar = ?, type = ? WHERE record_id = ?", undef, @sqlargs);
|
---|
[665] | 4741 | $self->_log(domain_id => $rec->{domain_id}, rdns_id => $rec->{rdns_id},
|
---|
| 4742 | group_id => $self->parentID(id => $rec->{rdns_id}, type => 'revzone', revrec => 'y'),
|
---|
| 4743 | entry => "'$rec->{host} $typemap{$rec->{type}} $rec->{val}' downconverted to ".
|
---|
| 4744 | "'$rec->{host} $typemap{$newtype} $rec->{val}'");
|
---|
[459] | 4745 | $dbh->commit;
|
---|
| 4746 | };
|
---|
| 4747 | if ($@) {
|
---|
| 4748 | $errstr = $@;
|
---|
| 4749 | eval { $dbh->rollback; };
|
---|
| 4750 | return 0;
|
---|
| 4751 | }
|
---|
| 4752 | return 1;
|
---|
| 4753 | } # end downconvert()
|
---|
| 4754 |
|
---|
| 4755 |
|
---|
[3] | 4756 | ## DNSDB::delRec()
|
---|
| 4757 | # Delete a record.
|
---|
[667] | 4758 | # Takes a default/live flag, forward/reverse flag, and the ID of the record to delete.
|
---|
[3] | 4759 | sub delRec {
|
---|
| 4760 | $errstr = '';
|
---|
[481] | 4761 | my $self = shift;
|
---|
| 4762 | my $dbh = $self->{dbh};
|
---|
[3] | 4763 | my $defrec = shift;
|
---|
[243] | 4764 | my $revrec = shift;
|
---|
[3] | 4765 | my $id = shift;
|
---|
| 4766 |
|
---|
[481] | 4767 | my $oldrec = $self->getRecLine($defrec, $revrec, $id);
|
---|
[3] | 4768 |
|
---|
[290] | 4769 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4770 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4771 | local $dbh->{AutoCommit} = 0;
|
---|
| 4772 | local $dbh->{RaiseError} = 1;
|
---|
[3] | 4773 |
|
---|
[290] | 4774 | # Put together the log entry
|
---|
| 4775 | my %logdata;
|
---|
| 4776 | $logdata{domain_id} = $oldrec->{domain_id};
|
---|
| 4777 | $logdata{rdns_id} = $oldrec->{rdns_id};
|
---|
| 4778 | $logdata{group_id} = $oldrec->{group_id} if $defrec eq 'y';
|
---|
[667] | 4779 | $logdata{group_id} = $self->parentID(id => ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id}),
|
---|
| 4780 | type => 'domain', revrec => $revrec)
|
---|
[290] | 4781 | if $defrec eq 'n';
|
---|
| 4782 | $logdata{entry} = "Deleted ".($defrec eq 'y' ? 'default record ' : 'record ').
|
---|
| 4783 | "'$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
| 4784 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
| 4785 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
| 4786 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
[425] | 4787 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
[480] | 4788 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location};
|
---|
[290] | 4789 |
|
---|
| 4790 | eval {
|
---|
| 4791 | my $sth = $dbh->do("DELETE FROM "._rectable($defrec,$revrec)." WHERE record_id=?", undef, ($id));
|
---|
[487] | 4792 | $self->_log(%logdata);
|
---|
[290] | 4793 | $dbh->commit;
|
---|
| 4794 | };
|
---|
| 4795 | if ($@) {
|
---|
| 4796 | my $msg = $@;
|
---|
| 4797 | eval { $dbh->rollback; };
|
---|
[517] | 4798 | if ($self->{log_failures}) {
|
---|
[290] | 4799 | $logdata{entry} = "Error deleting ".($defrec eq 'y' ? 'default record' : 'record').
|
---|
| 4800 | " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
[487] | 4801 | $self->_log(%logdata);
|
---|
[290] | 4802 | $dbh->commit;
|
---|
| 4803 | }
|
---|
| 4804 | return ('FAIL', $msg);
|
---|
| 4805 | }
|
---|
| 4806 |
|
---|
| 4807 | return ('OK',$logdata{entry});
|
---|
[3] | 4808 | } # end delRec()
|
---|
| 4809 |
|
---|
| 4810 |
|
---|
[323] | 4811 | ## DNSDB::getLogCount()
|
---|
| 4812 | # Get a count of log entries
|
---|
| 4813 | # Takes a database handle and a hash containing at least:
|
---|
[733] | 4814 | # - Entity identifier and entity type as the primary log "slice"
|
---|
[323] | 4815 | sub getLogCount {
|
---|
[483] | 4816 | my $self = shift;
|
---|
[733] | 4817 | return $self->getLogEntries(@_, count => 1);
|
---|
[323] | 4818 | } # end getLogCount()
|
---|
| 4819 |
|
---|
| 4820 |
|
---|
| 4821 | ## DNSDB::getLogEntries()
|
---|
| 4822 | # Get a list of log entries
|
---|
| 4823 | # Takes arguments as with getLogCount() above, plus optional:
|
---|
[733] | 4824 | # - "count" flag
|
---|
| 4825 | # OR
|
---|
[323] | 4826 | # - sort field
|
---|
| 4827 | # - sort order
|
---|
| 4828 | # - offset for pagination
|
---|
| 4829 | sub getLogEntries {
|
---|
[483] | 4830 | my $self = shift;
|
---|
| 4831 | my $dbh = $self->{dbh};
|
---|
[323] | 4832 |
|
---|
| 4833 | my %args = @_;
|
---|
| 4834 |
|
---|
| 4835 | my @filterargs;
|
---|
| 4836 |
|
---|
[733] | 4837 | # fail if the prime id type is missing or invalid
|
---|
| 4838 | $errstr = "Missing primary log slice type";
|
---|
[323] | 4839 | return if !$args{logtype};
|
---|
| 4840 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
| 4841 | $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
|
---|
[733] | 4842 | $errstr = "Invalid primary log slice type";
|
---|
[323] | 4843 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
|
---|
| 4844 |
|
---|
[733] | 4845 | # fail if we don't have a prime ID to look for log entries for
|
---|
| 4846 | $errstr = "Missing ID for primary log slice";
|
---|
| 4847 | return if !($args{id} || $args{fname});
|
---|
| 4848 |
|
---|
[323] | 4849 | # Sorting defaults
|
---|
[508] | 4850 | $args{sortorder} = 'DESC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
| 4851 | $args{sortby} = 'stamp' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
[397] | 4852 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[323] | 4853 |
|
---|
[733] | 4854 | my %sortmap = (fname => 'name', username => 'email', entry => 'entry', stamp => 'stamp',
|
---|
| 4855 | revzone => 'revnet', domain => 'domain');
|
---|
[323] | 4856 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 4857 |
|
---|
[733] | 4858 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 4859 | my $sql;
|
---|
| 4860 | if ($args{count}) {
|
---|
| 4861 | $sql = "SELECT count(*) FROM log l ";
|
---|
| 4862 | } else {
|
---|
| 4863 | $sql = "SELECT l.user_id AS userid, l.name AS userfname, d.domain, l.domain_id, r.revnet AS revzone, ".
|
---|
| 4864 | "l.rdns_id, l.entry AS logentry, date_trunc('second',l.stamp) AS logtime ".
|
---|
| 4865 | "FROM log l ".
|
---|
| 4866 | "LEFT JOIN domains d ON l.domain_id = d.domain_id ".
|
---|
| 4867 | "LEFT JOIN revzones r ON l.rdns_id = r.rdns_id ";
|
---|
| 4868 | }
|
---|
| 4869 |
|
---|
| 4870 | # decide which ID argument to use. Only use the "full name" if no normal ID is present
|
---|
| 4871 | my $idarg;
|
---|
| 4872 | if ($args{id}) {
|
---|
| 4873 | $sql .= "WHERE l.$id_col{$args{logtype}} = ? ";
|
---|
| 4874 | $idarg = $args{id};
|
---|
| 4875 | } else {
|
---|
| 4876 | $sql .= "WHERE l.name = ? ";
|
---|
| 4877 | $idarg = $args{fname};
|
---|
| 4878 | }
|
---|
| 4879 |
|
---|
| 4880 | # add the entry filter, if any
|
---|
| 4881 | $sql .= ($args{filter} ? " AND entry ~* ?" : '');
|
---|
| 4882 |
|
---|
| 4883 | # Limit scope based on group. Mainly useful for ltype==user, so subgroup
|
---|
| 4884 | # users can see what the deities in parent groups have done to their domains.
|
---|
| 4885 | if ($args{group} != 1) {
|
---|
| 4886 | my @grouplist;
|
---|
| 4887 | $self->getChildren($args{group}, \@grouplist);
|
---|
| 4888 | my $groupset = join(',', $args{group}, @grouplist);
|
---|
| 4889 | $sql .= " AND l.group_id IN ($groupset)";
|
---|
| 4890 | }
|
---|
| 4891 |
|
---|
| 4892 | if ($args{count}) {
|
---|
| 4893 | my ($count) = $dbh->selectrow_array($sql, undef, ($idarg, @filterargs) );
|
---|
| 4894 | $errstr = $dbh->errstr if !$count;
|
---|
| 4895 | return $count;
|
---|
| 4896 | } else {
|
---|
| 4897 | $sql .= " ORDER BY $args{sortby} $args{sortorder}, log_id $args{sortorder}".
|
---|
[517] | 4898 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
[733] | 4899 | my $loglist = $dbh->selectall_arrayref($sql, { Slice => {} }, ($idarg, @filterargs) );
|
---|
| 4900 | $errstr = $dbh->errstr if !$loglist;
|
---|
| 4901 | return $loglist;
|
---|
| 4902 | }
|
---|
| 4903 |
|
---|
| 4904 | # Your llama is on fire
|
---|
| 4905 |
|
---|
[323] | 4906 | } # end getLogEntries()
|
---|
| 4907 |
|
---|
| 4908 |
|
---|
[723] | 4909 | # a collection of joins for the record search
|
---|
| 4910 | our $recsearchsqlbase = q(
|
---|
[722] | 4911 | FROM records r
|
---|
| 4912 | LEFT JOIN domains d ON r.domain_id = d.domain_id
|
---|
| 4913 | LEFT JOIN groups g1 ON d.group_id = g1.group_id
|
---|
| 4914 | LEFT JOIN revzones z ON r.rdns_id = z.rdns_id
|
---|
| 4915 | LEFT JOIN groups g2 on z.group_id = g2.group_id
|
---|
| 4916 | JOIN rectypes t ON r.type = t.val
|
---|
| 4917 | LEFT JOIN locations l ON r.location = l.location
|
---|
| 4918 | WHERE r.type <> 6 AND (r.host ~* ? OR r.val ~* ?)
|
---|
| 4919 | );
|
---|
| 4920 |
|
---|
[723] | 4921 |
|
---|
| 4922 | ## DNSDB::recSearchCount()
|
---|
| 4923 | # Get a total count for a global record search
|
---|
| 4924 | # Takes a hash with the search string and the login group of the user
|
---|
| 4925 | sub recSearchCount {
|
---|
| 4926 | my $self = shift;
|
---|
| 4927 | my $dbh = $self->{dbh};
|
---|
| 4928 | my %args = @_;
|
---|
| 4929 |
|
---|
| 4930 | my $sql = "SELECT count(*)".$recsearchsqlbase;
|
---|
| 4931 |
|
---|
| 4932 | # Limit scope based on group
|
---|
| 4933 | if ($args{group} != 1) {
|
---|
| 4934 | my @grouplist;
|
---|
| 4935 | $self->getChildren($args{group}, \@grouplist);
|
---|
| 4936 | my $groupset = join(',', $args{group}, @grouplist);
|
---|
| 4937 | # oh my aching HEAD. there has to be a better way to do conditions on joined tables...
|
---|
| 4938 | $sql .= "AND (
|
---|
| 4939 | (g1.group_id IN ($groupset) AND g2.group_id IN ($groupset)) OR
|
---|
| 4940 | (g1.group_id IN ($groupset) AND g2.group_id IS NULL) OR
|
---|
| 4941 | (g1.group_id IS NULL AND g2.group_id IN ($groupset))
|
---|
| 4942 | )
|
---|
[722] | 4943 | ";
|
---|
[723] | 4944 | }
|
---|
[722] | 4945 |
|
---|
[723] | 4946 | my $count = $dbh->selectrow_array($sql, undef, $args{searchfor}, $args{searchfor});
|
---|
| 4947 | $errstr = $dbh->errstr if !$count;
|
---|
| 4948 | return $count;
|
---|
[722] | 4949 |
|
---|
[723] | 4950 | } # end recSearchCount()
|
---|
[722] | 4951 |
|
---|
| 4952 |
|
---|
[723] | 4953 | ## DNSDB::recSearch()
|
---|
| 4954 | # Find records matching the search string
|
---|
| 4955 | # Takes a hash with the search string, login group of the user, pagination offset, sort field,
|
---|
| 4956 | # and sort direction
|
---|
| 4957 | # Returns a reference to a list of hashrefs
|
---|
| 4958 | sub recSearch {
|
---|
| 4959 | my $self = shift;
|
---|
| 4960 | my $dbh = $self->{dbh};
|
---|
| 4961 | my %args = @_;
|
---|
| 4962 |
|
---|
| 4963 | my $sql = q(SELECT
|
---|
| 4964 | r.domain_id, d.domain, g1.group_name AS domgroup,
|
---|
| 4965 | r.rdns_id, z.revnet AS revzone, g2.group_name AS revgroup,
|
---|
| 4966 | r.host, t.name AS rectype, r.val, l.description AS location, r.record_id).
|
---|
| 4967 | $recsearchsqlbase;
|
---|
| 4968 |
|
---|
| 4969 | # Limit scope based on group
|
---|
| 4970 | if ($args{group} != 1) {
|
---|
| 4971 | my @grouplist;
|
---|
| 4972 | $self->getChildren($args{group}, \@grouplist);
|
---|
| 4973 | my $groupset = join(',', $args{group}, @grouplist);
|
---|
| 4974 | # oh my aching HEAD. there has to be a better way to do conditions on joined tables...
|
---|
| 4975 | $sql .= "AND (
|
---|
| 4976 | (g1.group_id IN ($groupset) AND g2.group_id IN ($groupset)) OR
|
---|
| 4977 | (g1.group_id IN ($groupset) AND g2.group_id IS NULL) OR
|
---|
| 4978 | (g1.group_id IS NULL AND g2.group_id IN ($groupset))
|
---|
| 4979 | )
|
---|
| 4980 | ";
|
---|
| 4981 | }
|
---|
| 4982 |
|
---|
| 4983 | # mixed tables means this isn't a simple prefix like the regular record list filter. :/
|
---|
| 4984 | my %sortmap = (
|
---|
| 4985 | domain => 'd.domain',
|
---|
| 4986 | revzone => 'z.revnet',
|
---|
| 4987 | host => 'r.host',
|
---|
| 4988 | type => 't.name',
|
---|
| 4989 | val => 'inetlazy(r.val)',
|
---|
| 4990 | location => 'r.location',
|
---|
| 4991 | );
|
---|
| 4992 |
|
---|
| 4993 | # Sorting defaults
|
---|
| 4994 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
| 4995 | $args{sortby} = 'r.host' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
| 4996 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
| 4997 |
|
---|
| 4998 | $args{sortby} = $sortmap{$args{sortby}} if $args{sortby} !~ /\./;
|
---|
| 4999 |
|
---|
| 5000 | # Add sort and offset to SQL
|
---|
| 5001 | $sql .= "ORDER BY $args{sortby} $args{sortorder},record_id ASC\n";
|
---|
| 5002 | $sql .= ($args{offset} eq 'all' ? '' : "LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
| 5003 |
|
---|
| 5004 | ##fixme: should probably sent the warning somewhere else
|
---|
| 5005 | return $dbh->selectall_arrayref($sql, { Slice => {} }, $args{searchfor}, $args{searchfor})
|
---|
| 5006 | or warn $dbh->errstr;
|
---|
| 5007 |
|
---|
[722] | 5008 | } # end recSearch()
|
---|
| 5009 |
|
---|
| 5010 |
|
---|
[673] | 5011 | ## DNSDB::getRevPattern()
|
---|
[452] | 5012 | # Get the narrowest template pattern applicable to a passed CIDR address (may be a netblock or an IP)
|
---|
| 5013 | sub getRevPattern {
|
---|
[483] | 5014 | my $self = shift;
|
---|
| 5015 | my $dbh = $self->{dbh};
|
---|
[452] | 5016 | my $cidr = shift;
|
---|
[701] | 5017 | my %args = @_;
|
---|
| 5018 | $args{group} = 1 if !$args{group}; # just in case
|
---|
| 5019 | $args{location} = '' if !$args{location};
|
---|
[452] | 5020 |
|
---|
[462] | 5021 | # for speed! Casting and comparing even ~7K records takes ~2.5s, so narrow it down to one revzone first.
|
---|
[664] | 5022 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >>= ?",
|
---|
| 5023 | undef, ($cidr) );
|
---|
[462] | 5024 |
|
---|
| 5025 | ##fixme? may need to narrow things down more by octet-chopping and doing text comparisons before casting.
|
---|
| 5026 | my ($revpatt) = $dbh->selectrow_array("SELECT host FROM records ".
|
---|
[701] | 5027 | "WHERE (type in (12,65280,65281,65282,65283,65284)) AND rdns_id = ? ".
|
---|
| 5028 | "AND location = ? AND inetlazy(val) >>= ? ".
|
---|
| 5029 | "ORDER BY inetlazy(val) DESC LIMIT 1",
|
---|
| 5030 | undef, ($revid, $args{location}, $cidr) );
|
---|
| 5031 |
|
---|
[452] | 5032 | return $revpatt;
|
---|
| 5033 | } # end getRevPattern()
|
---|
| 5034 |
|
---|
| 5035 |
|
---|
[673] | 5036 | ## DNSDB::getRevSet()
|
---|
| 5037 | # Return the unique per-IP reverse hostnames, if any, for the passed
|
---|
| 5038 | # CIDR address (may be a netblock or an IP)
|
---|
| 5039 | sub getRevSet {
|
---|
| 5040 | my $self = shift;
|
---|
| 5041 | my $dbh = $self->{dbh};
|
---|
| 5042 | my $cidr = shift;
|
---|
[701] | 5043 | my %args = @_;
|
---|
| 5044 | $args{group} = 1 if !$args{group}; # just in case
|
---|
| 5045 | $args{location} = '' if !$args{location};
|
---|
[673] | 5046 |
|
---|
| 5047 | # for speed! Casting and comparing even ~7K records takes ~2.5s, so narrow it down to one revzone first.
|
---|
| 5048 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >>= ?",
|
---|
| 5049 | undef, ($cidr) );
|
---|
| 5050 |
|
---|
| 5051 | $cidr = new NetAddr::IP $cidr;
|
---|
| 5052 | if ($cidr->num > 256) { # should also catch v6!
|
---|
| 5053 | # Even reverse entries for a v4 /24 of IPs is a bit much. I don't expect
|
---|
| 5054 | # there to be a sane reason to retrive more than a /27 at once, really.
|
---|
| 5055 | # v6 is going to be hairy no matter how you slice it.
|
---|
| 5056 | $errstr = "Reverse hostname detail range too large";
|
---|
| 5057 | return;
|
---|
| 5058 | }
|
---|
| 5059 |
|
---|
| 5060 | my $sth = $dbh->prepare("SELECT val, host FROM records ".
|
---|
[701] | 5061 | "WHERE (type in (12,65280,65281,65282,65283,65284)) AND rdns_id = ? AND location = ? AND inetlazy(val) = ?");
|
---|
[673] | 5062 |
|
---|
| 5063 | my @ret;
|
---|
| 5064 | foreach my $ip (@{$cidr->splitref()}) {
|
---|
[701] | 5065 | $sth->execute($revid, $args{location}, $ip);
|
---|
[673] | 5066 | my @data = $sth->fetchrow_array();
|
---|
| 5067 | my %row;
|
---|
| 5068 | if (@data) {
|
---|
| 5069 | $row{r_ip} = $data[0];
|
---|
| 5070 | $row{iphost} = $data[1];
|
---|
| 5071 | } else {
|
---|
| 5072 | $row{r_ip} = $ip->addr;
|
---|
| 5073 | $row{iphost} = '';
|
---|
| 5074 | }
|
---|
| 5075 | push @ret, \%row;
|
---|
| 5076 | }
|
---|
| 5077 |
|
---|
| 5078 | return \@ret;
|
---|
| 5079 | } # end getRevSet()
|
---|
| 5080 |
|
---|
| 5081 |
|
---|
[225] | 5082 | ## DNSDB::getTypelist()
|
---|
| 5083 | # Get a list of record types for various UI dropdowns
|
---|
| 5084 | # Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A)
|
---|
| 5085 | # Returns an arrayref to list of hashrefs perfect for HTML::Template
|
---|
| 5086 | sub getTypelist {
|
---|
[483] | 5087 | my $self = shift;
|
---|
| 5088 | my $dbh = $self->{dbh};
|
---|
[225] | 5089 | my $recgroup = shift;
|
---|
| 5090 | my $type = shift || $reverse_typemap{A};
|
---|
| 5091 |
|
---|
| 5092 | # also accepting $webvar{revrec}!
|
---|
| 5093 | $recgroup = 'f' if $recgroup eq 'n';
|
---|
| 5094 | $recgroup = 'r' if $recgroup eq 'y';
|
---|
| 5095 |
|
---|
| 5096 | my $sql = "SELECT val,name FROM rectypes WHERE ";
|
---|
| 5097 | if ($recgroup eq 'r') {
|
---|
| 5098 | # reverse zone types
|
---|
| 5099 | $sql .= "stdflag=2 OR stdflag=3";
|
---|
| 5100 | } elsif ($recgroup eq 'l') {
|
---|
| 5101 | # DNS lookup types. Note we avoid our custom types >= 65280, since those are entirely internal.
|
---|
| 5102 | $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280";
|
---|
| 5103 | } else {
|
---|
| 5104 | # default; forward zone types. technically $type eq 'f' but not worth the error message.
|
---|
| 5105 | $sql .= "stdflag=1 OR stdflag=2";
|
---|
[506] | 5106 | $sql .= " AND val < 65280" if $recgroup eq 'fo'; # An extra flag to trim off the pseudotypes as well.
|
---|
[225] | 5107 | }
|
---|
| 5108 | $sql .= " ORDER BY listorder";
|
---|
| 5109 |
|
---|
| 5110 | my $sth = $dbh->prepare($sql);
|
---|
| 5111 | $sth->execute;
|
---|
| 5112 | my @typelist;
|
---|
[603] | 5113 | # track whether the passed type is in the list at all. allows you to edit a record
|
---|
| 5114 | # that wouldn't otherwise be generally available in that zone (typically, reverse zones)
|
---|
| 5115 | # without changing its type (accidentally or otherwise)
|
---|
| 5116 | my $selflag = 0;
|
---|
[225] | 5117 | while (my ($rval,$rname) = $sth->fetchrow_array()) {
|
---|
| 5118 | my %row = ( recval => $rval, recname => $rname );
|
---|
[603] | 5119 | if ($rval == $type) {
|
---|
| 5120 | $row{tselect} = 1;
|
---|
| 5121 | $selflag = 1;
|
---|
| 5122 | }
|
---|
[225] | 5123 | push @typelist, \%row;
|
---|
| 5124 | }
|
---|
| 5125 |
|
---|
[603] | 5126 | # add the passed type if it wasn't in the list
|
---|
| 5127 | if (!$selflag) {
|
---|
| 5128 | my %row = ( recval => $type, recname => $typemap{$type}, tselect => 1 );
|
---|
| 5129 | push @typelist, \%row;
|
---|
| 5130 | }
|
---|
| 5131 |
|
---|
[225] | 5132 | # Add SOA on lookups since it's not listed in other dropdowns.
|
---|
| 5133 | if ($recgroup eq 'l') {
|
---|
| 5134 | my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
|
---|
| 5135 | $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
|
---|
| 5136 | push @typelist, \%row;
|
---|
| 5137 | }
|
---|
| 5138 |
|
---|
| 5139 | return \@typelist;
|
---|
| 5140 | } # end getTypelist()
|
---|
| 5141 |
|
---|
| 5142 |
|
---|
[254] | 5143 | ## DNSDB::parentID()
|
---|
| 5144 | # Get ID of entity that is nearest parent to requested id
|
---|
| 5145 | # Takes a database handle and a hash of entity ID, entity type, optional parent type flag
|
---|
| 5146 | # (domain/reverse zone or group), and optional default/live and forward/reverse flags
|
---|
| 5147 | # Returns the ID or undef on failure
|
---|
| 5148 | sub parentID {
|
---|
[473] | 5149 | my $self = shift;
|
---|
| 5150 | my $dbh = $self->{dbh};
|
---|
[116] | 5151 |
|
---|
[254] | 5152 | my %args = @_;
|
---|
[116] | 5153 |
|
---|
[254] | 5154 | # clean up defrec and revrec. default to live record, forward zone
|
---|
| 5155 | $args{defrec} = 'n' if !$args{defrec};
|
---|
| 5156 | $args{revrec} = 'n' if !$args{revrec};
|
---|
[116] | 5157 |
|
---|
[667] | 5158 | # clean up the parent-type. Set it to group if not set
|
---|
| 5159 | $args{partype} = 'group' if !$args{partype};
|
---|
| 5160 |
|
---|
| 5161 | # allow callers to be lazy with type
|
---|
| 5162 | $args{type} = 'revzone' if $args{type} eq 'domain' && $args{revrec} eq 'y';
|
---|
| 5163 |
|
---|
| 5164 | if ($par_type{$args{partype}} eq 'domain' || $par_type{$args{partype}} eq 'revzone') {
|
---|
[254] | 5165 | # only live records can have a domain/zone parent
|
---|
| 5166 | return unless ($args{type} eq 'record' && $args{defrec} eq 'n');
|
---|
| 5167 | my $result = $dbh->selectrow_hashref("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
| 5168 | " FROM records WHERE record_id = ?",
|
---|
| 5169 | undef, ($args{id}) ) or return;
|
---|
| 5170 | return $result;
|
---|
| 5171 | } else {
|
---|
| 5172 | # snag some arguments that will either fall through or be overwritten to save some code duplication
|
---|
| 5173 | my $tmpid = $args{id};
|
---|
| 5174 | my $type = $args{type};
|
---|
| 5175 | if ($type eq 'record' && $args{defrec} eq 'n') {
|
---|
| 5176 | # Live records go through the records table first.
|
---|
| 5177 | ($tmpid) = $dbh->selectrow_array("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
| 5178 | " FROM records WHERE record_id = ?",
|
---|
| 5179 | undef, ($args{id}) ) or return;
|
---|
| 5180 | $type = ($args{revrec} eq 'n' ? 'domain' : 'revzone');
|
---|
| 5181 | }
|
---|
| 5182 | my ($result) = $dbh->selectrow_array("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
|
---|
| 5183 | undef, ($tmpid) );
|
---|
| 5184 | return $result;
|
---|
| 5185 | }
|
---|
| 5186 | # should be impossible to get here with even remotely sane arguments
|
---|
| 5187 | return;
|
---|
| 5188 | } # end parentID()
|
---|
[116] | 5189 |
|
---|
| 5190 |
|
---|
[117] | 5191 | ## DNSDB::isParent()
|
---|
| 5192 | # Returns true if $id1 is a parent of $id2, false otherwise
|
---|
| 5193 | sub isParent {
|
---|
[470] | 5194 | my $self = shift;
|
---|
| 5195 | my $dbh = $self->{dbh};
|
---|
[117] | 5196 | my $id1 = shift;
|
---|
| 5197 | my $type1 = shift;
|
---|
| 5198 | my $id2 = shift;
|
---|
| 5199 | my $type2 = shift;
|
---|
| 5200 | ##todo: immediate, secondary, full (default)
|
---|
| 5201 |
|
---|
[157] | 5202 | # Return false on invalid types
|
---|
[244] | 5203 | return 0 if !grep /^$type1$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
| 5204 | return 0 if !grep /^$type2$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
[157] | 5205 |
|
---|
[117] | 5206 | # Return false on impossible relations
|
---|
| 5207 | return 0 if $type1 eq 'record'; # nothing may be a child of a record
|
---|
| 5208 | return 0 if $type1 eq 'defrec'; # nothing may be a child of a record
|
---|
[244] | 5209 | return 0 if $type1 eq 'defrevrec'; # nothing may be a child of a record
|
---|
[117] | 5210 | return 0 if $type1 eq 'user'; # nothing may be child of a user
|
---|
| 5211 | return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record
|
---|
[244] | 5212 | return 0 if $type1 eq 'revzone' && $type2 ne 'record';# reverse zone may not be a parent of anything other than a record
|
---|
[117] | 5213 |
|
---|
[186] | 5214 | # ennnhhhh.... if we're passed an id of 0, it will never be found. usual
|
---|
| 5215 | # case would be the UI creating a new <thing>, and so we don't have an ID for
|
---|
| 5216 | # <thing> to look up yet. in that case the UI should check the parent as well.
|
---|
| 5217 | return 0 if $id1 == 0; # nothing can have a parent id of 0
|
---|
| 5218 | return 1 if $id2 == 0; # anything could have a child id of 0 (or "unknown")
|
---|
| 5219 |
|
---|
[117] | 5220 | # group 1 is the ultimate root parent
|
---|
| 5221 | return 1 if $type1 eq 'group' && $id1 == 1;
|
---|
| 5222 |
|
---|
[155] | 5223 | # groups are always (a) parent of themselves
|
---|
| 5224 | return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2;
|
---|
| 5225 |
|
---|
[117] | 5226 | my $id = $id2;
|
---|
| 5227 | my $type = $type2;
|
---|
| 5228 | my $foundparent = 0;
|
---|
[155] | 5229 |
|
---|
[244] | 5230 | # Records are the only entity with two possible parents. We need to split the parent checks on
|
---|
| 5231 | # domain/rdns.
|
---|
| 5232 | if ($type eq 'record') {
|
---|
| 5233 | my ($dom,$rdns) = $dbh->selectrow_array("SELECT domain_id,rdns_id FROM records WHERE record_id=?",
|
---|
| 5234 | undef, ($id));
|
---|
| 5235 | # check immediate parent against request
|
---|
| 5236 | return 1 if $type1 eq 'domain' && $id1 == $dom;
|
---|
| 5237 | return 1 if $type1 eq 'revzone' && $id1 == $rdns;
|
---|
| 5238 | # if request is group, check *both* parents. Only check if the parent is nonzero though.
|
---|
[470] | 5239 | return 1 if $dom && $self->isParent($id1, $type1, $dom, 'domain');
|
---|
| 5240 | return 1 if $rdns && $self->isParent($id1, $type1, $rdns, 'revzone');
|
---|
[244] | 5241 | # exit here since we've executed the loop below by proxy in the above recursive calls.
|
---|
| 5242 | return 0;
|
---|
| 5243 | }
|
---|
| 5244 |
|
---|
| 5245 | # almost the same loop as getParents() above
|
---|
[186] | 5246 | my $limiter = 0;
|
---|
[117] | 5247 | while (1) {
|
---|
[155] | 5248 | my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
|
---|
[117] | 5249 | my $result = $dbh->selectrow_hashref($sql,
|
---|
[157] | 5250 | undef, ($id) );
|
---|
[186] | 5251 | if (!$result) {
|
---|
| 5252 | $limiter++;
|
---|
[244] | 5253 | ##fixme: how often will this happen on a live site? fail at max limiter <n>?
|
---|
[541] | 5254 | # 2013/10/22 only seems to happen when you request an entity that doesn't exist.
|
---|
[186] | 5255 | warn "no results looking for $sql with id $id (depth $limiter)\n";
|
---|
| 5256 | last;
|
---|
| 5257 | }
|
---|
[157] | 5258 | if ($result && $result->{$par_col{$type}} == $id1) {
|
---|
[117] | 5259 | $foundparent = 1;
|
---|
| 5260 | last;
|
---|
[157] | 5261 | } else {
|
---|
| 5262 | ##fixme: do we care about trying to return a "no such record/domain/user/group" error?
|
---|
[244] | 5263 | # should be impossible to create an inconsistent DB just with API calls.
|
---|
[157] | 5264 | warn $dbh->errstr." $sql, $id" if $dbh->errstr;
|
---|
[117] | 5265 | }
|
---|
| 5266 | # group 1 is its own parent. need this here more to break strange loops than for detecting a parent
|
---|
| 5267 | last if $result->{$par_col{$type}} == 1;
|
---|
[152] | 5268 | $id = $result->{$par_col{$type}};
|
---|
[117] | 5269 | $type = $par_type{$type};
|
---|
| 5270 | }
|
---|
| 5271 |
|
---|
| 5272 | return $foundparent;
|
---|
| 5273 | } # end isParent()
|
---|
| 5274 |
|
---|
| 5275 |
|
---|
[275] | 5276 | ## DNSDB::zoneStatus()
|
---|
| 5277 | # Returns and optionally sets a zone's status
|
---|
| 5278 | # Takes a database handle, domain/revzone ID, forward/reverse flag, and optionally a status argument
|
---|
| 5279 | # Returns status, or undef on errors.
|
---|
| 5280 | sub zoneStatus {
|
---|
[477] | 5281 | my $self = shift;
|
---|
| 5282 | my $dbh = $self->{dbh};
|
---|
[3] | 5283 | my $id = shift;
|
---|
[275] | 5284 | my $revrec = shift;
|
---|
| 5285 | my $newstatus = shift || 'mu';
|
---|
[3] | 5286 |
|
---|
| 5287 | return undef if $id !~ /^\d+$/;
|
---|
| 5288 |
|
---|
[283] | 5289 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 5290 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 5291 | local $dbh->{AutoCommit} = 0;
|
---|
| 5292 | local $dbh->{RaiseError} = 1;
|
---|
| 5293 |
|
---|
[275] | 5294 | if ($newstatus ne 'mu') {
|
---|
[283] | 5295 | # ooo, fun! let's see what we were passed for status
|
---|
| 5296 | eval {
|
---|
| 5297 | $newstatus = 0 if $newstatus eq 'domoff';
|
---|
| 5298 | $newstatus = 1 if $newstatus eq 'domon';
|
---|
| 5299 | $dbh->do("UPDATE ".($revrec eq 'n' ? 'domains' : 'revzones')." SET status=? WHERE ".
|
---|
[275] | 5300 | ($revrec eq 'n' ? 'domain_id' : 'rdns_id')."=?", undef, ($newstatus,$id) );
|
---|
[283] | 5301 |
|
---|
| 5302 | ##fixme switch to more consise "Enabled <domain"/"Disabled <domain>" as with users?
|
---|
[473] | 5303 | $resultstr = "Changed ".($revrec eq 'n' ? $self->domainName($id) : $self->revName($id)).
|
---|
[283] | 5304 | " state to ".($newstatus ? 'active' : 'inactive');
|
---|
| 5305 |
|
---|
| 5306 | my %loghash;
|
---|
| 5307 | $loghash{domain_id} = $id if $revrec eq 'n';
|
---|
| 5308 | $loghash{rdns_id} = $id if $revrec eq 'y';
|
---|
[473] | 5309 | $loghash{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec);
|
---|
[283] | 5310 | $loghash{entry} = $resultstr;
|
---|
[487] | 5311 | $self->_log(%loghash);
|
---|
[283] | 5312 |
|
---|
| 5313 | $dbh->commit;
|
---|
| 5314 | };
|
---|
| 5315 | if ($@) {
|
---|
| 5316 | my $msg = $@;
|
---|
| 5317 | eval { $dbh->rollback; };
|
---|
| 5318 | $resultstr = '';
|
---|
| 5319 | $errstr = $msg;
|
---|
| 5320 | return;
|
---|
| 5321 | }
|
---|
[3] | 5322 | }
|
---|
| 5323 |
|
---|
[275] | 5324 | my ($status) = $dbh->selectrow_array("SELECT status FROM ".
|
---|
| 5325 | ($revrec eq 'n' ? "domains WHERE domain_id=?" : "revzones WHERE rdns_id=?"),
|
---|
| 5326 | undef, ($id) );
|
---|
[3] | 5327 | return $status;
|
---|
[275] | 5328 | } # end zoneStatus()
|
---|
[3] | 5329 |
|
---|
| 5330 |
|
---|
[452] | 5331 | ## DNSDB::getZonesByCIDR()
|
---|
| 5332 | # Get a list of zone names and IDs that records for a passed CIDR block are within.
|
---|
[710] | 5333 | # Optionally restrict to a specific location/view
|
---|
[715] | 5334 | # Optionally leave off the default_location field
|
---|
[452] | 5335 | sub getZonesByCIDR {
|
---|
[477] | 5336 | my $self = shift;
|
---|
| 5337 | my $dbh = $self->{dbh};
|
---|
[452] | 5338 | my %args = @_;
|
---|
[715] | 5339 | $args{return_location} = 1 if !defined($args{return_location});
|
---|
[452] | 5340 |
|
---|
[715] | 5341 | my $sql = "SELECT rdns_id,revnet".($args{return_location} ? ',default_location' : '').
|
---|
| 5342 | " FROM revzones WHERE (revnet >>= ? OR revnet <<= ?)".
|
---|
| 5343 | (defined($args{location}) ? " AND default_location = ?" : '');
|
---|
[710] | 5344 | my @svals = ($args{cidr}, $args{cidr});
|
---|
[715] | 5345 | push @svals, $args{location} if defined $args{location};
|
---|
[710] | 5346 |
|
---|
| 5347 | my $result = $dbh->selectall_arrayref($sql, { Slice => {} }, @svals );
|
---|
[452] | 5348 | return $result;
|
---|
| 5349 | } # end getZonesByCIDR()
|
---|
| 5350 |
|
---|
| 5351 |
|
---|
[33] | 5352 | ## DNSDB::importAXFR
|
---|
| 5353 | # Import a domain via AXFR
|
---|
[37] | 5354 | # Takes AXFR host, domain to transfer, group to put the domain in,
|
---|
[484] | 5355 | # and an optional hash containing:
|
---|
| 5356 | # status - active/inactive state flag (defaults to active)
|
---|
| 5357 | # rwsoa - overwrite-SOA flag (defaults to off)
|
---|
| 5358 | # rwns - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
|
---|
| 5359 | # merge - flag to automerge A or AAAA records with matching PTR records
|
---|
[37] | 5360 | # Returns a status code (OK, WARN, or FAIL) and message - message should be blank
|
---|
| 5361 | # if status is OK, but WARN includes conditions that are not fatal but should
|
---|
| 5362 | # really be reported.
|
---|
[33] | 5363 | sub importAXFR {
|
---|
[484] | 5364 | my $self = shift;
|
---|
| 5365 | my $dbh = $self->{dbh};
|
---|
[35] | 5366 | my $ifrom_in = shift;
|
---|
[301] | 5367 | my $zone = shift;
|
---|
[33] | 5368 | my $group = shift;
|
---|
[484] | 5369 |
|
---|
| 5370 | my %args = @_;
|
---|
| 5371 |
|
---|
[33] | 5372 | ##fixme: add mode to delete&replace, merge+overwrite, merge new?
|
---|
| 5373 |
|
---|
[484] | 5374 | $args{status} = (defined($args{status}) ? $args{status} : 0);
|
---|
| 5375 | $args{status} = 1 if $args{status} eq 'on';
|
---|
| 5376 |
|
---|
[37] | 5377 | my $nrecs = 0;
|
---|
| 5378 | my $soaflag = 0;
|
---|
| 5379 | my $nsflag = 0;
|
---|
| 5380 | my $warnmsg = '';
|
---|
| 5381 | my $ifrom;
|
---|
[33] | 5382 |
|
---|
[301] | 5383 | my $rev = 'n';
|
---|
[302] | 5384 | my $code = 'OK';
|
---|
| 5385 | my $msg = 'foobar?';
|
---|
[301] | 5386 |
|
---|
[35] | 5387 | # choke on possible bad setting in ifrom
|
---|
[37] | 5388 | # IPv4 and v6, and valid hostnames!
|
---|
[35] | 5389 | ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
| 5390 | return ('FAIL', "Bad AXFR source host $ifrom")
|
---|
| 5391 | unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
| 5392 |
|
---|
[301] | 5393 | my $errmsg;
|
---|
| 5394 |
|
---|
| 5395 | my $zone_id;
|
---|
| 5396 | my $domain_id = 0;
|
---|
| 5397 | my $rdns_id = 0;
|
---|
| 5398 | my $cidr;
|
---|
| 5399 |
|
---|
| 5400 | # magic happens! detect if we're importing a domain or a reverse zone
|
---|
| 5401 | # while we're at it, figure out what the CIDR netblock is (if we got a .arpa)
|
---|
| 5402 | # or what the formal .arpa zone is (if we got a CIDR netblock)
|
---|
| 5403 | # Handles sub-octet v4 zones in the format specified in the Cricket Book, 2nd Ed, p217-218
|
---|
| 5404 |
|
---|
[601] | 5405 | if ($zone =~ m{(?:\.arpa\.?|/\d+|^[\d.]+|^[a-fA-F0-9:]+)$}) {
|
---|
[301] | 5406 | # we seem to have a reverse zone
|
---|
| 5407 | $rev = 'y';
|
---|
| 5408 |
|
---|
| 5409 | if ($zone =~ /\.arpa\.?$/) {
|
---|
| 5410 | # we have a formal reverse zone. call _zone2cidr and get the CIDR block.
|
---|
| 5411 | ($code,$msg) = _zone2cidr($zone);
|
---|
| 5412 | return ($code, $msg) if $code eq 'FAIL';
|
---|
| 5413 | $cidr = $msg;
|
---|
| 5414 | } elsif ($zone =~ m|^[\d.]+/\d+$|) {
|
---|
| 5415 | # v4 revzone, CIDR netblock
|
---|
| 5416 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 5417 | $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
[601] | 5418 | } elsif ($zone =~ /^[\d.]+$/) {
|
---|
| 5419 | # v4 revzone, leading-octet format
|
---|
| 5420 | my $mask = 32;
|
---|
| 5421 | while ($zone !~ /^\d+\.\d+\.\d+\.\d+$/) {
|
---|
| 5422 | $zone .= '.0';
|
---|
| 5423 | $mask -= 8;
|
---|
| 5424 | }
|
---|
| 5425 | $zone .= "/$mask";
|
---|
| 5426 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 5427 | $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
[301] | 5428 | } elsif ($zone =~ m|^[a-fA-F\d:]+/\d+$|) {
|
---|
| 5429 | # v6 revzone, CIDR netblock
|
---|
| 5430 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 5431 | return ('FAIL', "$zone is not a nibble-aligned block") if $cidr->masklen % 4 != 0;
|
---|
| 5432 | $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.');
|
---|
[601] | 5433 | } elsif ($zone =~ /^[a-fA-F\d:]+$/) {
|
---|
| 5434 | # v6 revzone, leading-group format
|
---|
| 5435 | $zone =~ s/::$//;
|
---|
| 5436 | my $mask = 128;
|
---|
| 5437 | while ($zone !~ /^(?:[a-fA-F\d]{1,4}:){7}[a-fA-F\d]$/) {
|
---|
| 5438 | $zone .= ":0";
|
---|
| 5439 | $mask -= 16;
|
---|
| 5440 | }
|
---|
| 5441 | $zone .= "/$mask";
|
---|
| 5442 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 5443 | $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.');
|
---|
[301] | 5444 | } else {
|
---|
| 5445 | # there is. no. else!
|
---|
[601] | 5446 | return ('FAIL', "Unknown zone name format '$zone'");
|
---|
[301] | 5447 | }
|
---|
| 5448 |
|
---|
[601] | 5449 | # several places this can be triggered from; better to do it once.
|
---|
| 5450 | $warnmsg .= "Apparent sub-/64 IPv6 reverse zone\n" if $cidr->masklen > 64;
|
---|
| 5451 |
|
---|
[301] | 5452 | # quick check to start to see if we've already got one
|
---|
| 5453 |
|
---|
| 5454 | ($zone_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?",
|
---|
| 5455 | undef, ("$cidr"));
|
---|
| 5456 | $rdns_id = $zone_id;
|
---|
| 5457 | } else {
|
---|
| 5458 | # default to domain
|
---|
[349] | 5459 | ($zone_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
[301] | 5460 | undef, ($zone));
|
---|
| 5461 | $domain_id = $zone_id;
|
---|
| 5462 | }
|
---|
| 5463 |
|
---|
| 5464 | return ('FAIL', ($rev eq 'n' ? 'Domain' : 'Reverse zone')." already exists") if $zone_id;
|
---|
| 5465 |
|
---|
[303] | 5466 | # little local utility sub to swap $val and $host for revzone records.
|
---|
| 5467 | sub _revswap {
|
---|
| 5468 | my $rechost = shift;
|
---|
| 5469 | my $recdata = shift;
|
---|
| 5470 |
|
---|
| 5471 | if ($rechost =~ /\.in-addr\.arpa\.?$/) {
|
---|
| 5472 | $rechost =~ s/\.in-addr\.arpa\.?$//;
|
---|
| 5473 | $rechost = join '.', reverse split /\./, $rechost;
|
---|
| 5474 | } else {
|
---|
| 5475 | $rechost =~ s/\.ip6\.arpa\.?$//;
|
---|
| 5476 | my @nibs = reverse split /\./, $rechost;
|
---|
| 5477 | $rechost = '';
|
---|
| 5478 | my $nc;
|
---|
| 5479 | foreach (@nibs) {
|
---|
[634] | 5480 | # # fail on multicharacter nibbles; it's syntactically valid but no standard lookup
|
---|
| 5481 | # # will ever reach it, because it doesn't directly represent a real IP address.
|
---|
| 5482 | # return ('FAIL', "Invalid reverse v6 entry") if $_ !~ /^.$/;
|
---|
[303] | 5483 | $rechost.= $_;
|
---|
| 5484 | $rechost .= ":" if ++$nc % 4 == 0 && $nc < 32;
|
---|
| 5485 | }
|
---|
[307] | 5486 | $rechost .= ":" if $nc < 32 && $rechost !~ /\*$/; # close netblock records?
|
---|
| 5487 | ##fixme: there's a case that ends up with a partial entry here:
|
---|
| 5488 | # ip:add:re:ss::
|
---|
| 5489 | # can't reproduce after letting it sit overnight after discovery. :(
|
---|
| 5490 | #print "$rechost\n";
|
---|
[303] | 5491 | # canonicalize with NetAddr::IP
|
---|
| 5492 | $rechost = NetAddr::IP->new($rechost)->addr unless $rechost =~ /\*$/;
|
---|
| 5493 | }
|
---|
| 5494 | return ($recdata,$rechost)
|
---|
| 5495 | }
|
---|
| 5496 |
|
---|
| 5497 |
|
---|
[33] | 5498 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 5499 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 5500 | local $dbh->{AutoCommit} = 0;
|
---|
| 5501 | local $dbh->{RaiseError} = 1;
|
---|
| 5502 |
|
---|
[301] | 5503 | my $sth;
|
---|
| 5504 | eval {
|
---|
[34] | 5505 |
|
---|
[301] | 5506 | if ($rev eq 'n') {
|
---|
[33] | 5507 | ##fixme: serial
|
---|
[484] | 5508 | $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef,
|
---|
[710] | 5509 | ($zone, $group, $args{status}) ) or die $dbh->errstr;
|
---|
[301] | 5510 | # get domain id so we can do the records
|
---|
| 5511 | ($zone_id) = $dbh->selectrow_array("SELECT currval('domains_domain_id_seq')");
|
---|
| 5512 | $domain_id = $zone_id;
|
---|
[487] | 5513 | $self->_log(group_id => $group, domain_id => $domain_id,
|
---|
| 5514 | entry => "[Added ".($args{status} ? 'active' : 'inactive')." domain $zone via AXFR]");
|
---|
[301] | 5515 | } else {
|
---|
| 5516 | ##fixme: serial
|
---|
[484] | 5517 | $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef,
|
---|
| 5518 | ($cidr,$group,$args{status}) );
|
---|
[301] | 5519 | # get revzone id so we can do the records
|
---|
| 5520 | ($zone_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
| 5521 | $rdns_id = $zone_id;
|
---|
[487] | 5522 | $self->_log(group_id => $group, rdns_id => $rdns_id,
|
---|
| 5523 | entry => "[Added ".($args{status} ? 'active' : 'inactive')." reverse zone $cidr via AXFR]");
|
---|
[301] | 5524 | }
|
---|
[33] | 5525 |
|
---|
[35] | 5526 | ## bizarre DBI<->Net::DNS interaction bug:
|
---|
| 5527 | ## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
|
---|
[37] | 5528 | ## fixed, apparently I was doing *something* odd, but not certain what it was that
|
---|
| 5529 | ## caused a commit instead of barfing
|
---|
[35] | 5530 |
|
---|
[34] | 5531 | my $res = Net::DNS::Resolver->new;
|
---|
[35] | 5532 | $res->nameservers($ifrom);
|
---|
[301] | 5533 | $res->axfr_start($zone)
|
---|
[35] | 5534 | or die "Couldn't begin AXFR\n";
|
---|
[34] | 5535 |
|
---|
[301] | 5536 | $sth = $dbh->prepare("INSERT INTO records (domain_id,rdns_id,host,type,val,distance,weight,port,ttl)".
|
---|
| 5537 | " VALUES (?,?,?,?,?,?,?,?,?)");
|
---|
| 5538 |
|
---|
[307] | 5539 | # Stash info about sub-octet v4 revzones here so we don't have
|
---|
| 5540 | # to store the CNAMEs used to delegate a suboctet zone
|
---|
| 5541 | # $suboct{zone}{ns}[] -> array of nameservers
|
---|
| 5542 | # $suboct{zone}{cname}[] -> array of extant CNAMEs (Just In Case someone did something bizarre)
|
---|
| 5543 | ## commented pending actual use of this data. for now, we'll just
|
---|
| 5544 | ## auto-(re)create the CNAMEs in revzones on export
|
---|
| 5545 | # my %suboct;
|
---|
| 5546 |
|
---|
[35] | 5547 | while (my $rr = $res->axfr_next()) {
|
---|
[301] | 5548 |
|
---|
[596] | 5549 | # Discard out-of-zone records. After trying for a while to replicate this with
|
---|
| 5550 | # *nix-based DNS servers, it appears that only MS DNS is prone to including these
|
---|
| 5551 | # in the AXFR data in the first place, and possibly only older versions at that...
|
---|
| 5552 | # so it can't be reasonably tested. Yay Microsoft.
|
---|
| 5553 | if ($rr->name !~ /$zone$/i) {
|
---|
| 5554 | $warnmsg .= "Discarding out-of-zone record ".$rr->string."\n";
|
---|
| 5555 | }
|
---|
| 5556 |
|
---|
[301] | 5557 | my $val;
|
---|
| 5558 | my $distance = 0;
|
---|
| 5559 | my $weight = 0;
|
---|
| 5560 | my $port = 0;
|
---|
[303] | 5561 | my $logfrag = '';
|
---|
[301] | 5562 |
|
---|
[602] | 5563 | # Collect some record parts
|
---|
[33] | 5564 | my $type = $rr->type;
|
---|
[301] | 5565 | my $host = $rr->name;
|
---|
[484] | 5566 | my $ttl = ($args{newttl} ? $args{newttl} : $rr->ttl); # allow force-override TTLs
|
---|
[35] | 5567 |
|
---|
[602] | 5568 | # Info flags for SOA and NS records
|
---|
[37] | 5569 | $soaflag = 1 if $type eq 'SOA';
|
---|
| 5570 | $nsflag = 1 if $type eq 'NS';
|
---|
[35] | 5571 |
|
---|
[34] | 5572 | # "Primary" types:
|
---|
| 5573 | # A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
|
---|
| 5574 | # maybe KEY
|
---|
| 5575 |
|
---|
[302] | 5576 | # BIND supports:
|
---|
| 5577 | # [standard]
|
---|
| 5578 | # A AAAA CNAME MX NS PTR SOA TXT
|
---|
| 5579 | # [variously experimental, obsolete, or obscure]
|
---|
| 5580 | # 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
|
---|
| 5581 | # ... if one can ever find the right magic to format them correctly
|
---|
| 5582 |
|
---|
| 5583 | # Net::DNS supports:
|
---|
| 5584 | # RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
|
---|
| 5585 | # EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
|
---|
| 5586 | # DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
|
---|
| 5587 |
|
---|
[35] | 5588 | # nasty big ugly case-like thing here, since we have to do *some* different
|
---|
| 5589 | # processing depending on the record. le sigh.
|
---|
| 5590 |
|
---|
[602] | 5591 | # do the initial processing as if the record was in a forward zone. If we're
|
---|
| 5592 | # doing a revzone, we can flip $host and $val as needed, once, after this
|
---|
| 5593 | # monster if-elsif-...-elsif-else. This actually simplifies things a lot.
|
---|
| 5594 |
|
---|
[105] | 5595 | ##fixme: what record types other than TXT can/will have >255-byte payloads?
|
---|
| 5596 |
|
---|
[34] | 5597 | if ($type eq 'A') {
|
---|
[301] | 5598 | $val = $rr->address;
|
---|
[34] | 5599 | } elsif ($type eq 'NS') {
|
---|
[635] | 5600 | # hmm. should we warn here if subdomain NS'es are left alone? OTOH, those should rarely be rewritten anyway.
|
---|
[602] | 5601 | next if ($args{rwns} && ($host eq $zone));
|
---|
| 5602 | $val = $rr->nsdname;
|
---|
[639] | 5603 | $warnmsg .= "Suspect record '".$rr->string."' may not be imported correctly: NS records may not be bare IP addresses\n"
|
---|
| 5604 | if $val =~ /^(?:(?:\d+\.){3}\d+|[a-fA-F0-9:]+)$/;
|
---|
[35] | 5605 | $nsflag = 1;
|
---|
[34] | 5606 | } elsif ($type eq 'CNAME') {
|
---|
[602] | 5607 | $val = $rr->cname;
|
---|
[639] | 5608 | $warnmsg .= "Suspect record '".$rr->string."' may not be imported correctly: CNAME records may not be bare IP addresses\n"
|
---|
| 5609 | if $val =~ /^(?:(?:\d+\.){3}\d+|[a-fA-F0-9:]+)$/;
|
---|
[34] | 5610 | } elsif ($type eq 'SOA') {
|
---|
[484] | 5611 | next if $args{rwsoa};
|
---|
[307] | 5612 | $host = $rr->rname.":".$rr->mname;
|
---|
[301] | 5613 | $val = $rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum;
|
---|
[35] | 5614 | $soaflag = 1;
|
---|
[34] | 5615 | } elsif ($type eq 'PTR') {
|
---|
[602] | 5616 | $val = $rr->ptrdname;
|
---|
[34] | 5617 | } elsif ($type eq 'MX') {
|
---|
[301] | 5618 | $val = $rr->exchange;
|
---|
| 5619 | $distance = $rr->preference;
|
---|
[34] | 5620 | } elsif ($type eq 'TXT') {
|
---|
| 5621 | ##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
|
---|
| 5622 | ## but don't really seem enthusiastic about it.
|
---|
[303] | 5623 | #print "should use rdatastr:\n\t".$rr->rdatastr."\n or char_str_list:\n\t".join(' ',$rr->char_str_list())."\n";
|
---|
| 5624 | # rdatastr returns a BIND-targetted logical string, including opening and closing quotes
|
---|
| 5625 | # char_str_list returns a list of the individual string fragments in the record
|
---|
[307] | 5626 | # txtdata returns the more useful all-in-one form (since we want to push such protocol
|
---|
| 5627 | # details as far down the stack as we can)
|
---|
[303] | 5628 | # NB: this may turn out to be more troublesome if we ever have need of >512-byte TXT records.
|
---|
[602] | 5629 | $val = $rr->txtdata;
|
---|
[34] | 5630 | } elsif ($type eq 'SPF') {
|
---|
| 5631 | ##fixme: and the same caveat here, since it is apparently a clone of ::TXT
|
---|
[301] | 5632 | $val = $rr->txtdata;
|
---|
[34] | 5633 | } elsif ($type eq 'AAAA') {
|
---|
[301] | 5634 | $val = $rr->address;
|
---|
[34] | 5635 | } elsif ($type eq 'SRV') {
|
---|
[301] | 5636 | $val = $rr->target;
|
---|
| 5637 | $distance = $rr->priority;
|
---|
| 5638 | $weight = $rr->weight;
|
---|
| 5639 | $port = $rr->port;
|
---|
[639] | 5640 | $warnmsg .= "Suspect record '".$rr->string."' may not be imported correctly: SRV records may not be bare IP addresses\n"
|
---|
| 5641 | if $val =~ /^(?:(?:\d+\.){3}\d+|[a-fA-F0-9:]+)$/;
|
---|
[34] | 5642 | } elsif ($type eq 'KEY') {
|
---|
[35] | 5643 | # we don't actually know what to do with these...
|
---|
[301] | 5644 | $val = $rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname;
|
---|
[35] | 5645 | } else {
|
---|
[301] | 5646 | $val = $rr->rdatastr;
|
---|
[35] | 5647 | # Finding a different record type is not fatal.... just problematic.
|
---|
[37] | 5648 | # We may not be able to export it correctly.
|
---|
[35] | 5649 | $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
|
---|
[33] | 5650 | }
|
---|
| 5651 |
|
---|
[602] | 5652 | if ($rev eq 'y' && $type ne 'SOA') {
|
---|
| 5653 | # up to this point we haven't meddled with the record's hostname part or rdata part.
|
---|
| 5654 | # for reverse records, (except SOA) we must swap the two.
|
---|
| 5655 | $host = $val;
|
---|
| 5656 | $val = $rr->name;
|
---|
| 5657 | my ($tmpcode,$tmpmsg) = _zone2cidr($val);
|
---|
| 5658 | if ($tmpcode eq 'FAIL') {
|
---|
| 5659 | # $val did not have a valid IP value. It's syntactically valid but WTF?
|
---|
| 5660 | $warnmsg .= "Suspect record '".$rr->string."' may not be imported correctly: $tmpmsg\n";
|
---|
| 5661 | } else {
|
---|
| 5662 | # $val has a valid IP value. See if we can store it as that IP value.
|
---|
| 5663 | # Note we're enumerating do-nothing cases for clarity.
|
---|
| 5664 | ##enhance: this is where we will implement the more subtle variations on #53
|
---|
| 5665 | if ($type ne 'PTR' && $type ne 'NS' && $type ne 'CNAME' && $type ne 'TXT') {
|
---|
| 5666 | # case: the record is "weird" - ie, not a PTR, NS, CNAME, or TXT
|
---|
| 5667 | # $warnmsg .= "Discarding suspect record '".$rr->string."'\n" if $self->{strict} eq 'full';
|
---|
| 5668 | } elsif ($type eq 'PTR' && $tmpmsg->masklen != 32 && $tmpmsg->masklen != 128) {
|
---|
| 5669 | # case: PTR with netblock value, not IP value
|
---|
| 5670 | # eg, "@ PTR foo" in zone f.e.e.b.d.a.e.d.ip6.arpa should not be
|
---|
| 5671 | # stored/displayed as dead:beef::/32 PTR foo
|
---|
| 5672 |
|
---|
| 5673 | ## hrm. WTF is this case for, anyway? Needs testing to check the logic.
|
---|
| 5674 | # } elsif ( ($type eq 'PTR' || $type eq 'NS' || $type eq 'CNAME' || $type eq 'TXT') &&
|
---|
| 5675 | # ($tmpmsg->masklen != $cidr->masklen)
|
---|
| 5676 | # ) {
|
---|
| 5677 | # # leave $val as-is if the record is "normal" (a PTR, NS, CNAME, or TXT),
|
---|
| 5678 | # # and the mask does not match the zone
|
---|
| 5679 | #$warnmsg .= "WTF case: $host $type $val\n";
|
---|
| 5680 | # # $warnmsg .= "Discarding suspect record '".$rr->string."'\n" if $self->{strict} eq 'full';
|
---|
| 5681 |
|
---|
| 5682 | } else {
|
---|
| 5683 | $val = $tmpmsg;
|
---|
| 5684 | $val =~ s/\/(?:32|128)$//; # automagically converts $val back to a string before s///
|
---|
| 5685 | #$val =~ s/:0$//g;
|
---|
| 5686 | }
|
---|
| 5687 | }
|
---|
| 5688 | # magic? convert * records to PTR template (not sure this actually makes sense)
|
---|
| 5689 | #if ($val =~ /^\*/) {
|
---|
| 5690 | # $val =~ s/\*\.//;
|
---|
| 5691 | # ($tmpcode,$tmpmsg) = _zone2cidr($val);
|
---|
| 5692 | # if ($tmpcode eq 'FAIL') {
|
---|
| 5693 | # $val = "*.$val";
|
---|
| 5694 | # $warnmsg .= "Suspect record '".$rr->string."' may not be converted to PTR template correctly: $tmpmsg\n";
|
---|
| 5695 | # } else {
|
---|
| 5696 | # $type = 'PTR template';
|
---|
| 5697 | # $val = $tmpmsg; if $tmp
|
---|
| 5698 | # $val =~ s/\/(?:32|128)$//; # automagically converts $val back to a string before s///
|
---|
| 5699 | # }
|
---|
| 5700 | #}
|
---|
| 5701 | } # non-SOA revrec $host/$val inversion and munging
|
---|
| 5702 |
|
---|
[303] | 5703 | my $logentry = "[AXFR ".($rev eq 'n' ? $zone : $cidr)."] ";
|
---|
[34] | 5704 |
|
---|
[484] | 5705 | if ($args{merge}) {
|
---|
[307] | 5706 | if ($rev eq 'n') {
|
---|
| 5707 | # importing a domain; we have A and AAAA records that could be merged with matching PTR records
|
---|
| 5708 | my $etype;
|
---|
| 5709 | my ($erdns,$erid,$ettl) = $dbh->selectrow_array("SELECT rdns_id,record_id,ttl FROM records ".
|
---|
| 5710 | "WHERE host=? AND val=? AND type=12",
|
---|
| 5711 | undef, ($host, $val) );
|
---|
| 5712 | if ($erid) {
|
---|
| 5713 | if ($type eq 'A') { # PTR -> A+PTR
|
---|
| 5714 | $etype = 65280;
|
---|
| 5715 | $logentry .= "Merged A record with existing PTR record '$host A+PTR $val', TTL $ettl";
|
---|
| 5716 | }
|
---|
| 5717 | if ($type eq 'AAAA') { # PTR -> AAAA+PTR
|
---|
| 5718 | $etype = 65281;
|
---|
| 5719 | $logentry .= "Merged AAAA record with existing PTR record '$host AAAA+PTR $val', TTL $ettl";
|
---|
| 5720 | }
|
---|
| 5721 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
| 5722 | $dbh->do("UPDATE records SET domain_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
| 5723 | ($domain_id, $ettl, $etype, $erid));
|
---|
| 5724 | $nrecs++;
|
---|
[487] | 5725 | $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $erdns, entry => $logentry);
|
---|
[307] | 5726 | next; # while axfr_next
|
---|
| 5727 | }
|
---|
| 5728 | } # $rev eq 'n'
|
---|
| 5729 | else {
|
---|
| 5730 | # importing a revzone, we have PTR records that could be merged with matching A/AAAA records
|
---|
| 5731 | my ($domid,$erid,$ettl,$etype) = $dbh->selectrow_array("SELECT domain_id,record_id,ttl,type FROM records ".
|
---|
| 5732 | "WHERE host=? AND val=? AND (type=1 OR type=28)",
|
---|
| 5733 | undef, ($host, $val) );
|
---|
| 5734 | if ($erid) {
|
---|
| 5735 | if ($etype == 1) { # A -> A+PTR
|
---|
| 5736 | $etype = 65280;
|
---|
| 5737 | $logentry .= "Merged PTR record with existing matching A record '$host A+PTR $val', TTL $ettl";
|
---|
| 5738 | }
|
---|
| 5739 | if ($etype == 28) { # AAAA -> AAAA+PTR
|
---|
| 5740 | $etype = 65281;
|
---|
| 5741 | $logentry .= "Merged PTR record with existing matching AAAA record '$host AAAA+PTR $val', TTL $ettl";
|
---|
| 5742 | }
|
---|
| 5743 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
| 5744 | $dbh->do("UPDATE records SET rdns_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
| 5745 | ($rdns_id, $ettl, $etype, $erid));
|
---|
| 5746 | $nrecs++;
|
---|
[487] | 5747 | $self->_log(group_id => $group, domain_id => $domid, rdns_id => $rdns_id, entry => $logentry);
|
---|
[307] | 5748 | next; # while axfr_next
|
---|
| 5749 | }
|
---|
| 5750 | } # $rev eq 'y'
|
---|
[484] | 5751 | } # if $args{merge}
|
---|
[34] | 5752 |
|
---|
[302] | 5753 | # Insert the new record
|
---|
[301] | 5754 | $sth->execute($domain_id, $rdns_id, $host, $reverse_typemap{$type}, $val,
|
---|
| 5755 | $distance, $weight, $port, $ttl);
|
---|
| 5756 |
|
---|
[37] | 5757 | $nrecs++;
|
---|
[34] | 5758 |
|
---|
[301] | 5759 | if ($type eq 'SOA') {
|
---|
[484] | 5760 | # also !$args{rwsoa}, but if that's set, it should be impossible to get here.
|
---|
[301] | 5761 | my @tmp1 = split /:/, $host;
|
---|
| 5762 | my @tmp2 = split /:/, $val;
|
---|
| 5763 | $logentry .= "Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
| 5764 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl";
|
---|
[303] | 5765 | } elsif ($logfrag) {
|
---|
| 5766 | # special case for log entries we need to meddle with a little.
|
---|
| 5767 | $logentry .= $logfrag;
|
---|
[301] | 5768 | } else {
|
---|
[602] | 5769 | $logentry .= "Added record '".($rev eq 'y' ? $val : $host)." $type";
|
---|
[301] | 5770 | $logentry .= " [distance $distance]" if $type eq 'MX';
|
---|
| 5771 | $logentry .= " [priority $distance] [weight $weight] [port $port]" if $type eq 'SRV';
|
---|
[602] | 5772 | $logentry .= " ".($rev eq 'y' ? $host : $val)."', TTL $ttl";
|
---|
[301] | 5773 | }
|
---|
[487] | 5774 | $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $rdns_id, entry => $logentry);
|
---|
[301] | 5775 |
|
---|
[37] | 5776 | } # while axfr_next
|
---|
| 5777 |
|
---|
[307] | 5778 | # Detect and handle delegated subzones
|
---|
| 5779 | # Placeholder for when we decide what to actually do with this, see previous comments in NS and CNAME handling.
|
---|
| 5780 | #foreach (keys %suboct) {
|
---|
| 5781 | # print "found ".($suboct{$_}{ns} ? @{$suboct{$_}{ns}} : '0')." NS records and ".
|
---|
| 5782 | # ($suboct{$_}{cname} ? @{$suboct{$_}{cname}} : '0')." CNAMEs for $_\n";
|
---|
| 5783 | #}
|
---|
| 5784 |
|
---|
[37] | 5785 | # Overwrite SOA record
|
---|
[484] | 5786 | if ($args{rwsoa}) {
|
---|
[37] | 5787 | $soaflag = 1;
|
---|
[573] | 5788 | my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM "._rectable('y', $rev)." WHERE group_id=? AND type=?");
|
---|
| 5789 | my $sthputsoa = $dbh->prepare("INSERT INTO records (".
|
---|
| 5790 | ($rev eq 'n' ? 'domain_id' : 'rdns_id').",host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
[37] | 5791 | $sthgetsoa->execute($group,$reverse_typemap{SOA});
|
---|
| 5792 | while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
|
---|
[573] | 5793 | if ($rev eq 'n') {
|
---|
| 5794 | $host =~ s/DOMAIN/$zone/g;
|
---|
| 5795 | $val =~ s/DOMAIN/$zone/g; # arguably useless
|
---|
| 5796 | } else {
|
---|
| 5797 | $host =~ s/ADMINDOMAIN/$self->{domain}/g;
|
---|
| 5798 | }
|
---|
[301] | 5799 | $sthputsoa->execute($zone_id,$host,$reverse_typemap{SOA},$val,$ttl);
|
---|
[34] | 5800 | }
|
---|
[37] | 5801 | }
|
---|
[34] | 5802 |
|
---|
[573] | 5803 | # Add standard NS records. The old one(s) should have been skipped by this point.
|
---|
[484] | 5804 | if ($args{rwns}) {
|
---|
[37] | 5805 | $nsflag = 1;
|
---|
[573] | 5806 | my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM "._rectable('y',$rev)." WHERE group_id=? AND type=?");
|
---|
| 5807 | my $sthputns = $dbh->prepare("INSERT INTO records (".
|
---|
| 5808 | ($rev eq 'n' ? 'domain_id' : 'rdns_id').",host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
[37] | 5809 | $sthgetns->execute($group,$reverse_typemap{NS});
|
---|
| 5810 | while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
|
---|
[573] | 5811 | if ($rev eq 'n') {
|
---|
| 5812 | $host =~ s/DOMAIN/$zone/g;
|
---|
| 5813 | $val =~ s/DOMAIN/$zone/g; #hmm.
|
---|
| 5814 | } else {
|
---|
| 5815 | $host =~ s/ADMINDOMAIN/$self->{domain}/g; #hmm.
|
---|
| 5816 | $val =~ s/ZONE/$cidr/g;
|
---|
| 5817 | }
|
---|
[301] | 5818 | $sthputns->execute($zone_id,$host,$reverse_typemap{NS},$val,$ttl);
|
---|
[37] | 5819 | }
|
---|
| 5820 | }
|
---|
[34] | 5821 |
|
---|
[35] | 5822 | die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
|
---|
| 5823 | die "Bad zone: No SOA record!\n" if !$soaflag;
|
---|
| 5824 | die "Bad zone: No NS records!\n" if !$nsflag;
|
---|
| 5825 |
|
---|
[37] | 5826 | $dbh->commit;
|
---|
[35] | 5827 |
|
---|
[33] | 5828 | };
|
---|
| 5829 |
|
---|
| 5830 | if ($@) {
|
---|
| 5831 | my $msg = $@;
|
---|
| 5832 | eval { $dbh->rollback; };
|
---|
[34] | 5833 | return ('FAIL',$msg." $warnmsg");
|
---|
[33] | 5834 | } else {
|
---|
[35] | 5835 | return ('WARN', $warnmsg) if $warnmsg;
|
---|
[91] | 5836 | return ('OK',"Imported OK");
|
---|
[33] | 5837 | }
|
---|
| 5838 |
|
---|
[37] | 5839 | # it should be impossible to get here.
|
---|
[34] | 5840 | return ('WARN',"OOOK!");
|
---|
[33] | 5841 | } # end importAXFR()
|
---|
| 5842 |
|
---|
| 5843 |
|
---|
[302] | 5844 | ## DNSDB::importBIND()
|
---|
| 5845 | sub importBIND {
|
---|
| 5846 | } # end importBIND()
|
---|
| 5847 |
|
---|
| 5848 |
|
---|
| 5849 | ## DNSDB::import_tinydns()
|
---|
| 5850 | sub import_tinydns {
|
---|
| 5851 | } # end import_tinydns()
|
---|
| 5852 |
|
---|
| 5853 |
|
---|
[103] | 5854 | ## DNSDB::export()
|
---|
| 5855 | # Export the DNS database, or a part of it
|
---|
[485] | 5856 | # Takes a string indicating the export type, plus optional arguments depending on type
|
---|
[103] | 5857 | # Writes zone data to targets as appropriate for type
|
---|
| 5858 | sub export {
|
---|
[485] | 5859 | my $self = shift;
|
---|
[103] | 5860 | my $target = shift;
|
---|
| 5861 |
|
---|
| 5862 | if ($target eq 'tiny') {
|
---|
[567] | 5863 | eval {
|
---|
| 5864 | $self->__export_tiny(@_);
|
---|
| 5865 | };
|
---|
| 5866 | if ($@) {
|
---|
| 5867 | $errstr = $@;
|
---|
| 5868 | return undef;
|
---|
| 5869 | }
|
---|
[103] | 5870 | }
|
---|
| 5871 | # elsif ($target eq 'foo') {
|
---|
[485] | 5872 | # __export_foo(@_);
|
---|
[103] | 5873 | #}
|
---|
| 5874 | # etc
|
---|
| 5875 |
|
---|
[567] | 5876 | return 1;
|
---|
[103] | 5877 | } # end export()
|
---|
| 5878 |
|
---|
| 5879 |
|
---|
| 5880 | ## DNSDB::__export_tiny
|
---|
| 5881 | # Internal sub to implement tinyDNS (compatible) export
|
---|
[485] | 5882 | # Takes filehandle to write export to, optional argument(s)
|
---|
[103] | 5883 | # to determine which data gets exported
|
---|
| 5884 | sub __export_tiny {
|
---|
[485] | 5885 | my $self = shift;
|
---|
| 5886 | my $dbh = $self->{dbh};
|
---|
[103] | 5887 | my $datafile = shift;
|
---|
[559] | 5888 | my $zonefilehandle = $datafile; # makes cache/no-cache a little simpler
|
---|
[103] | 5889 |
|
---|
| 5890 | ##fixme: slurp up further options to specify particular zone(s) to export
|
---|
| 5891 |
|
---|
| 5892 | ##fixme: fail if $datafile isn't an open, writable file
|
---|
| 5893 |
|
---|
[566] | 5894 | # Error check - does the cache dir exist, if we're using one?
|
---|
| 5895 | if ($self->{usecache}) {
|
---|
| 5896 | die "Cache directory does not exist\n" if !-e $self->{exportcache};
|
---|
| 5897 | die "$self->{exportcache} is not a directory\n" if !-d $self->{exportcache};
|
---|
| 5898 | die "$self->{exportcache} must be both readable and writable\n"
|
---|
| 5899 | if !-r $self->{exportcache} || !-w $self->{exportcache};
|
---|
| 5900 | }
|
---|
| 5901 |
|
---|
[103] | 5902 | # easy case - export all evarything
|
---|
| 5903 | # not-so-easy case - export item(s) specified
|
---|
| 5904 | # todo: figure out what kind of list we use to export items
|
---|
| 5905 |
|
---|
[329] | 5906 | # raw packet in unknown format: first byte indicates length
|
---|
| 5907 | # of remaining data, allows up to 255 raw bytes
|
---|
| 5908 |
|
---|
[566] | 5909 | # note: the only I/O failures we seem to be able to actually catch
|
---|
| 5910 | # here are "closed filehandle" errors. we're probably not writing
|
---|
| 5911 | # enough data at this point to properly trigger an "out of space"
|
---|
| 5912 | # error. :/
|
---|
| 5913 | eval {
|
---|
| 5914 | use warnings FATAL => ('io');
|
---|
| 5915 | # Locations/views - worth including in the caching setup?
|
---|
| 5916 | my $lochash = $dbh->selectall_hashref("SELECT location,iplist FROM locations", 'location');
|
---|
| 5917 | foreach my $location (keys %$lochash) {
|
---|
| 5918 | foreach my $ipprefix (split /[,\s]+/, $lochash->{$location}{iplist}) {
|
---|
| 5919 | $ipprefix =~ s/\s+//g;
|
---|
| 5920 | $ipprefix = new NetAddr::IP $ipprefix;
|
---|
[449] | 5921 | ##fixme: how to handle IPv6?
|
---|
| 5922 | next if $ipprefix->{isv6};
|
---|
[566] | 5923 | # have to account for /nn CIDR entries. tinydns only speaks octet-sliced prefix.
|
---|
| 5924 | if ($ipprefix->masklen <= 8) {
|
---|
| 5925 | foreach ($ipprefix->split(8)) {
|
---|
| 5926 | my $tmp = $_->addr;
|
---|
| 5927 | $tmp =~ s/\.\d+\.\d+\.\d+$//;
|
---|
| 5928 | print $datafile "%$location:$tmp\n";
|
---|
| 5929 | }
|
---|
| 5930 | } elsif ($ipprefix->masklen <= 16) {
|
---|
| 5931 | foreach ($ipprefix->split(16)) {
|
---|
| 5932 | my $tmp = $_->addr;
|
---|
| 5933 | $tmp =~ s/\.\d+\.\d+$//;
|
---|
| 5934 | print $datafile "%$location:$tmp\n";
|
---|
| 5935 | }
|
---|
| 5936 | } elsif ($ipprefix->masklen <= 24) {
|
---|
| 5937 | foreach ($ipprefix->split(24)) {
|
---|
| 5938 | my $tmp = $_->addr;
|
---|
| 5939 | $tmp =~ s/\.\d+$//;
|
---|
| 5940 | print $datafile "%$location:$tmp\n";
|
---|
| 5941 | }
|
---|
| 5942 | } else {
|
---|
| 5943 | foreach ($ipprefix->split(32)) {
|
---|
| 5944 | print $datafile "%$location:".$_->addr."\n";
|
---|
| 5945 | }
|
---|
[449] | 5946 | }
|
---|
| 5947 | }
|
---|
[566] | 5948 | print $datafile "%$location\n" if !$lochash->{$location}{iplist};
|
---|
[372] | 5949 | }
|
---|
[566] | 5950 | };
|
---|
| 5951 | if ($@) {
|
---|
| 5952 | die "Error writing locations to master file: $@, $!\n";
|
---|
[372] | 5953 | }
|
---|
| 5954 |
|
---|
[329] | 5955 | # tracking hash so we don't double-export A+PTR or AAAA+PTR records.
|
---|
| 5956 | my %recflags;
|
---|
| 5957 |
|
---|
[523] | 5958 | # For reasons unknown, we can't sanely UNION these statements. Feh.
|
---|
| 5959 | # Supposedly it should work though (note last 3 lines):
|
---|
| 5960 | ## PG manual
|
---|
| 5961 | #UNION Clause
|
---|
| 5962 | #
|
---|
| 5963 | #The UNION clause has this general form:
|
---|
| 5964 | #
|
---|
| 5965 | # select_statement UNION [ ALL ] select_statement
|
---|
| 5966 | #
|
---|
| 5967 | #select_statement is any SELECT statement without an ORDER BY, LIMIT, FOR UPDATE, or FOR SHARE clause. (ORDER BY
|
---|
| 5968 | #and LIMIT can be attached to a subexpression if it is enclosed in parentheses. Without parentheses, these
|
---|
| 5969 | #clauses will be taken to apply to the result of the UNION, not to its right-hand input expression.)
|
---|
| 5970 | my $soasth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
| 5971 | "FROM records WHERE rdns_id=? AND type=6");
|
---|
[543] | 5972 | my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location,extract(epoch from stamp),expires,stampactive ".
|
---|
[576] | 5973 | "FROM records WHERE rdns_id=? AND NOT type=6 ".
|
---|
[599] | 5974 | "ORDER BY masklen(inetlazy(val)) DESC, inetlazy(val)");
|
---|
[523] | 5975 | my $revsth = $dbh->prepare("SELECT rdns_id,revnet,status,changed FROM revzones WHERE status=1 ".
|
---|
[566] | 5976 | "ORDER BY masklen(revnet) DESC, rdns_id");
|
---|
[523] | 5977 | my $zonesth = $dbh->prepare("UPDATE revzones SET changed='n' WHERE rdns_id=?");
|
---|
| 5978 | $revsth->execute();
|
---|
| 5979 | while (my ($revid,$revzone,$revstat,$changed) = $revsth->fetchrow_array) {
|
---|
[368] | 5980 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
| 5981 | # O_NOFOLLOW
|
---|
| 5982 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
| 5983 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
| 5984 | # still be followed.
|
---|
| 5985 | # but that doesn't help other platforms. :/
|
---|
[523] | 5986 | my $tmpzone = NetAddr::IP->new($revzone);
|
---|
| 5987 | ##fixme: locations/views? subnet mask? need to avoid possible collisions with zone/superzone
|
---|
| 5988 | ## (eg /20 vs /24, starting on .0.0)
|
---|
| 5989 | my $cz = $tmpzone->network->addr."-".$tmpzone->masklen;
|
---|
| 5990 | my $cachefile = "$self->{exportcache}/$cz";
|
---|
| 5991 | my $tmpcache = "$self->{exportcache}/tmp.$cz.$$";
|
---|
[521] | 5992 | eval {
|
---|
[108] | 5993 |
|
---|
[559] | 5994 | # write fresh records if:
|
---|
| 5995 | # - we are not using the cache
|
---|
| 5996 | # - force_refresh is set
|
---|
| 5997 | # - the zone has changed
|
---|
| 5998 | # - the cache file does not exist
|
---|
| 5999 | # - the cache file is empty
|
---|
| 6000 | if (!$self->{usecache} || $self->{force_refresh} || $changed || !-e $cachefile || -z $cachefile) {
|
---|
| 6001 | if ($self->{usecache}) {
|
---|
| 6002 | open ZONECACHE, ">$tmpcache" or die "Error creating temporary file $tmpcache: $!\n";
|
---|
| 6003 | $zonefilehandle = *ZONECACHE;
|
---|
| 6004 | }
|
---|
[521] | 6005 |
|
---|
[523] | 6006 | # need to fetch this separately since the rest of the records all (should) have real IPs in val
|
---|
| 6007 | $soasth->execute($revid);
|
---|
| 6008 | my (@zsoa) = $soasth->fetchrow_array();
|
---|
[644] | 6009 | $self->_printrec_tiny($zonefilehandle, $zsoa[7], 'y',\%recflags,$revzone,
|
---|
[523] | 6010 | $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],'');
|
---|
| 6011 |
|
---|
| 6012 | $recsth->execute($revid);
|
---|
[596] | 6013 | my $fullzone = _ZONE($tmpzone, 'ZONE', 'r', '.').($tmpzone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 6014 |
|
---|
[573] | 6015 | while (my ($host, $type, $val, $dist, $weight, $port, $ttl, $recid, $loc, $stamp, $expires, $stampactive)
|
---|
| 6016 | = $recsth->fetchrow_array) {
|
---|
[523] | 6017 | next if $recflags{$recid};
|
---|
[521] | 6018 |
|
---|
[596] | 6019 | # Check for out-of-zone data
|
---|
| 6020 | if ($val =~ /\.arpa$/) {
|
---|
| 6021 | # val is non-IP
|
---|
| 6022 | if ($val !~ /$fullzone$/) {
|
---|
| 6023 | warn "Not exporting out-of-zone record $val $typemap{$type} $host, $ttl (zone $tmpzone)\n";
|
---|
| 6024 | next;
|
---|
| 6025 | }
|
---|
| 6026 | } else {
|
---|
| 6027 | my $ipval = new NetAddr::IP $val;
|
---|
| 6028 | if (!$tmpzone->contains($ipval)) {
|
---|
| 6029 | warn "Not exporting out-of-zone record $val $typemap{$type} $host, $ttl (zone $tmpzone)\n";
|
---|
| 6030 | next;
|
---|
| 6031 | }
|
---|
| 6032 | } # is $val a raw .arpa name?
|
---|
| 6033 |
|
---|
[597] | 6034 | # Spaces are evil.
|
---|
| 6035 | $val =~ s/^\s+//;
|
---|
| 6036 | $val =~ s/\s+$//;
|
---|
| 6037 | if ($typemap{$type} ne 'TXT') {
|
---|
| 6038 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 6039 | $host =~ s/^\s+//;
|
---|
| 6040 | $host =~ s/\s+$//;
|
---|
| 6041 | }
|
---|
[372] | 6042 |
|
---|
[644] | 6043 | $self->_printrec_tiny($zonefilehandle, $recid, 'y', \%recflags, $revzone,
|
---|
[559] | 6044 | $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp, $expires, $stampactive);
|
---|
[450] | 6045 |
|
---|
[523] | 6046 | $recflags{$recid} = 1;
|
---|
[368] | 6047 |
|
---|
[521] | 6048 | } # while ($recsth)
|
---|
| 6049 |
|
---|
[559] | 6050 | if ($self->{usecache}) {
|
---|
| 6051 | close ZONECACHE; # force the file to be written
|
---|
| 6052 | # catch obvious write errors that leave an empty temp file
|
---|
| 6053 | if (-s $tmpcache) {
|
---|
| 6054 | rename $tmpcache, $cachefile
|
---|
| 6055 | or die "Error overwriting cache file $cachefile with temporary file: $!\n";
|
---|
| 6056 | }
|
---|
[521] | 6057 | }
|
---|
| 6058 |
|
---|
| 6059 | } # if $changed or cache filesize is 0
|
---|
| 6060 |
|
---|
| 6061 | };
|
---|
| 6062 | if ($@) {
|
---|
[566] | 6063 | die "error writing ".($self->{usecache} ? 'new data for ' : '')."$revzone: $@\n";
|
---|
[521] | 6064 | # error! something borked, and we should be able to fall back on the old cache file
|
---|
| 6065 | # report the error, somehow.
|
---|
| 6066 | } else {
|
---|
[523] | 6067 | # mark zone as unmodified. Only do this if no errors, that way
|
---|
[521] | 6068 | # export failures should recover a little more automatically.
|
---|
[523] | 6069 | $zonesth->execute($revid);
|
---|
[368] | 6070 | }
|
---|
[521] | 6071 |
|
---|
[559] | 6072 | if ($self->{usecache}) {
|
---|
| 6073 | # We've already made as sure as we can that a cached zone file is "good",
|
---|
| 6074 | # although possibly stale/obsolete due to errors creating a new one.
|
---|
[566] | 6075 | eval {
|
---|
| 6076 | open CACHE, "<$cachefile" or die $!;
|
---|
| 6077 | print $datafile $_ or die "error copying cached $revzone to master file: $!" while <CACHE>;
|
---|
| 6078 | close CACHE;
|
---|
| 6079 | };
|
---|
| 6080 | die $@ if $@;
|
---|
[559] | 6081 | }
|
---|
| 6082 |
|
---|
[523] | 6083 | } # while ($revsth)
|
---|
[329] | 6084 |
|
---|
[576] | 6085 | $soasth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
[578] | 6086 | "FROM records WHERE domain_id=? AND type=6");
|
---|
[543] | 6087 | $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location,extract(epoch from stamp),expires,stampactive ".
|
---|
[576] | 6088 | "FROM records WHERE domain_id=? AND NOT type=6"); # Just exclude all types relating to rDNS
|
---|
[523] | 6089 | # "FROM records WHERE domain_id=? AND type < 65280"); # Just exclude all types relating to rDNS
|
---|
[576] | 6090 | my $domsth = $dbh->prepare("SELECT domain_id,domain,status,changed FROM domains WHERE status=1 ORDER BY domain_id");
|
---|
[523] | 6091 | $zonesth = $dbh->prepare("UPDATE domains SET changed='n' WHERE domain_id=?");
|
---|
| 6092 | $domsth->execute();
|
---|
| 6093 | while (my ($domid,$dom,$domstat,$changed) = $domsth->fetchrow_array) {
|
---|
[368] | 6094 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
| 6095 | # O_NOFOLLOW
|
---|
| 6096 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
| 6097 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
| 6098 | # still be followed.
|
---|
| 6099 | # but that doesn't help other platforms. :/
|
---|
[523] | 6100 | my $cachefile = "$self->{exportcache}/$dom";
|
---|
| 6101 | my $tmpcache = "$self->{exportcache}/tmp.$dom.$$";
|
---|
[521] | 6102 | eval {
|
---|
[344] | 6103 |
|
---|
[559] | 6104 | # write fresh records if:
|
---|
| 6105 | # - we are not using the cache
|
---|
| 6106 | # - force_refresh is set
|
---|
| 6107 | # - the zone has changed
|
---|
| 6108 | # - the cache file does not exist
|
---|
| 6109 | # - the cache file is empty
|
---|
| 6110 | if (!$self->{usecache} || $self->{force_refresh} || $changed || !-e $cachefile || -z $cachefile) {
|
---|
| 6111 | if ($self->{usecache}) {
|
---|
| 6112 | open ZONECACHE, ">$tmpcache" or die "Error creating temporary file $tmpcache: $!\n";
|
---|
| 6113 | $zonefilehandle = *ZONECACHE;
|
---|
| 6114 | }
|
---|
[329] | 6115 |
|
---|
[576] | 6116 | # need to fetch this separately so the SOA comes first in the flatfile....
|
---|
| 6117 | # Just In Case we need/want to reimport from the flatfile later on.
|
---|
| 6118 | $soasth->execute($domid);
|
---|
| 6119 | my (@zsoa) = $soasth->fetchrow_array();
|
---|
[644] | 6120 | $self->_printrec_tiny($zonefilehandle, $zsoa[7], 'n',\%recflags,$dom,
|
---|
[576] | 6121 | $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],'');
|
---|
| 6122 |
|
---|
[523] | 6123 | $recsth->execute($domid);
|
---|
[543] | 6124 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc,$stamp,$expires,$stampactive) = $recsth->fetchrow_array) {
|
---|
[523] | 6125 | next if $recflags{$recid};
|
---|
[521] | 6126 |
|
---|
[596] | 6127 | # Check for out-of-zone data
|
---|
[655] | 6128 | $host = $dom if $host eq '@';
|
---|
[663] | 6129 | if ($host !~ /$dom$/i) {
|
---|
[596] | 6130 | warn "Not exporting out-of-zone record $host $type $val, $ttl (zone $dom)\n";
|
---|
| 6131 | next;
|
---|
| 6132 | }
|
---|
| 6133 |
|
---|
[523] | 6134 | # Spaces are evil.
|
---|
| 6135 | $host =~ s/^\s+//;
|
---|
| 6136 | $host =~ s/\s+$//;
|
---|
| 6137 | if ($typemap{$type} ne 'TXT') {
|
---|
| 6138 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 6139 | $val =~ s/^\s+//;
|
---|
| 6140 | $val =~ s/\s+$//;
|
---|
| 6141 | }
|
---|
| 6142 |
|
---|
[644] | 6143 | $self->_printrec_tiny($zonefilehandle, $recid, 'n', \%recflags,
|
---|
[559] | 6144 | $dom, $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp, $expires, $stampactive);
|
---|
[329] | 6145 |
|
---|
[523] | 6146 | $recflags{$recid} = 1;
|
---|
[450] | 6147 |
|
---|
[521] | 6148 | } # while ($recsth)
|
---|
| 6149 |
|
---|
| 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 ' : '')."$dom: $@\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 domain as unmodified. Only do this if no errors, that way
|
---|
[521] | 6169 | # export failures should recover a little more automatically.
|
---|
[523] | 6170 | $zonesth->execute($domid);
|
---|
[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 $dom to master file: $!" while <CACHE>;
|
---|
| 6179 | close CACHE;
|
---|
| 6180 | };
|
---|
| 6181 | die $@ if $@;
|
---|
[559] | 6182 | }
|
---|
| 6183 |
|
---|
[329] | 6184 | } # while ($domsth)
|
---|
| 6185 |
|
---|
[566] | 6186 | return 1;
|
---|
[329] | 6187 | } # end __export_tiny()
|
---|
| 6188 |
|
---|
| 6189 |
|
---|
| 6190 | # Utility sub for __export_tiny above
|
---|
| 6191 | sub _printrec_tiny {
|
---|
[644] | 6192 | my $self = shift;
|
---|
[573] | 6193 | my ($datafile, $recid, $revrec, $recflags, $zone, $host, $type, $val, $dist, $weight, $port, $ttl,
|
---|
| 6194 | $loc, $stamp, $expires, $stampactive) = @_;
|
---|
[329] | 6195 |
|
---|
[543] | 6196 | $loc = '' if !$loc; # de-nullify - just in case
|
---|
| 6197 | ##fixme: handle case of record-with-location-that-doesn't-exist better.
|
---|
| 6198 | # note this currently fails safe (tested) - records with a location that
|
---|
| 6199 | # doesn't exist will not be sent to any client
|
---|
| 6200 | # $loc = '' if !$lochash->{$loc};
|
---|
| 6201 |
|
---|
| 6202 |
|
---|
| 6203 | ## Records that are valid only before or after a set time
|
---|
| 6204 |
|
---|
| 6205 | # record due to expire sometime is the complex case. we don't want to just
|
---|
| 6206 | # rely on tinydns' auto-adjusting TTLs, because the default TTL in that case
|
---|
| 6207 | # is one day instead of the SOA minttl as BIND might do.
|
---|
| 6208 |
|
---|
| 6209 | # consider the case where a record is set to expire a week ahead, but the next
|
---|
| 6210 | # day later you want to change it NOW (or as NOWish as you get with your DNS
|
---|
| 6211 | # management practice). but now you're stuck, because someone, somewhere,
|
---|
| 6212 | # has just done a lookup before your latest change was published, and they'll
|
---|
| 6213 | # be caching that old, broken record for 1 day instead of your zone default
|
---|
| 6214 | # TTL.
|
---|
| 6215 |
|
---|
| 6216 | # $stamp-$ttl is the *latest* we can publish the record with the defined TTL
|
---|
| 6217 | # to still have the expiry happen as scheduled, but we need to find some
|
---|
| 6218 | # *earlier* point. We can maybe guess, and 2x TTL is probably reasonable,
|
---|
| 6219 | # but we need info on the export frequency.
|
---|
| 6220 |
|
---|
| 6221 | # export the normal, non-expiring record up until $stamp-<guesstimate>, then
|
---|
| 6222 | # switch to exporting a record with the TAI64 stamp and a 0 TTL so tinydns
|
---|
| 6223 | # takes over TTL management.
|
---|
| 6224 |
|
---|
| 6225 | if ($stampactive) {
|
---|
| 6226 | if ($expires) {
|
---|
| 6227 | # record expires at $stamp; decide if we need to keep the TTL and ignore
|
---|
| 6228 | # the stamp for a time or if we need to change the TTL to 0 and convert
|
---|
| 6229 | # $stamp to TAI64 so tinydns can use $stamp to autoadjust the TTL on the fly.
|
---|
| 6230 | # extra hack, optimally needs more knowledge of data export frequency
|
---|
| 6231 | # smack the idiot customer who insists on 0 TTLs; they can suck up and
|
---|
| 6232 | # deal with a 10-minute TTL. especially on scheduled changes. note this
|
---|
| 6233 | # should be (export freq * 2), but we don't know the actual export frequency.
|
---|
| 6234 | $ttl = 300 if $ttl == 0; #hack phtui
|
---|
| 6235 | my $ahead = (86400 < $ttl*2 ? 86400 : $ttl*2);
|
---|
| 6236 | if ((time() + $ahead) < $stamp) {
|
---|
| 6237 | # more than 2x TTL OR more than one day (whichever is less) from expiry time; publish normal record
|
---|
| 6238 | $stamp = '';
|
---|
| 6239 | } else {
|
---|
| 6240 | # less than 2x TTL from expiry time, let tinydns take over TTL management and publish the TAI64 stamp.
|
---|
| 6241 | $ttl = 0;
|
---|
| 6242 | $stamp = unixtai64($stamp);
|
---|
| 6243 | $stamp =~ s/\@//;
|
---|
| 6244 | }
|
---|
| 6245 | } else {
|
---|
| 6246 | # record is "active after"; convert epoch from database to TAI64, publish, and collect $200.
|
---|
| 6247 | $stamp = unixtai64($stamp);
|
---|
| 6248 | $stamp =~ s/\@//;
|
---|
| 6249 | }
|
---|
| 6250 | } else {
|
---|
| 6251 | # flag for active timestamp is false; don't actually put a timestamp in the output
|
---|
| 6252 | $stamp = '';
|
---|
| 6253 | }
|
---|
| 6254 |
|
---|
| 6255 | # support tinydns' auto-TTL
|
---|
| 6256 | $ttl = '' if $ttl == -1;
|
---|
| 6257 | # these are WAY FREAKING HIGH - higher even than most TLD registry TTLs!
|
---|
| 6258 | # NS 259200 => 3d
|
---|
| 6259 | # all others 86400 => 1d
|
---|
| 6260 |
|
---|
[531] | 6261 | if ($revrec eq 'y') {
|
---|
| 6262 | $val = $zone if $val eq '@';
|
---|
| 6263 | } else {
|
---|
| 6264 | $host = $zone if $host eq '@';
|
---|
| 6265 | }
|
---|
| 6266 |
|
---|
[329] | 6267 | ## Convert a bare number into an octal-coded pair of octets.
|
---|
| 6268 | # Take optional arg to indicate a decimal or hex input. Defaults to hex.
|
---|
| 6269 | sub octalize {
|
---|
| 6270 | my $tmp = shift;
|
---|
| 6271 | my $srctype = shift || 'h'; # default assumes hex string
|
---|
| 6272 | $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
|
---|
| 6273 | $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
|
---|
| 6274 | my @o = ($tmp =~ /^(..)(..)$/); # split into octets
|
---|
[656] | 6275 | return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);
|
---|
[329] | 6276 | }
|
---|
| 6277 |
|
---|
[637] | 6278 | # Utility sub-sub for reverse records; with "any-record-in-any-zone"
|
---|
| 6279 | # we may need to do extra processing on $val to make it publishable.
|
---|
| 6280 | sub __revswap {
|
---|
| 6281 | my $host = shift;
|
---|
| 6282 | my $val = shift;
|
---|
| 6283 | return ($val, $host) if $val =~ /\.arpa/;
|
---|
| 6284 | $val = new NetAddr::IP $val;
|
---|
| 6285 | my $newval = _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 6286 | return ($newval, $host);
|
---|
| 6287 | }
|
---|
| 6288 |
|
---|
[339] | 6289 | ## WARNING: This works to export even the whole Internet's worth of IP space...
|
---|
| 6290 | ## if you have the disk/RAM to handle the dataset, and you call this sub based on /16-sized chunks
|
---|
| 6291 | ## A /16 took ~3 seconds with a handful of separate records; adding a /8 pushed export time out to ~13m:40s
|
---|
| 6292 | ## 0/0 is estimated to take ~54 hours and ~256G of disk
|
---|
| 6293 | ## RAM usage depends on how many non-template entries you have in the set.
|
---|
| 6294 | ## This should probably be done on record addition rather than export; large blocks may need to be done in a
|
---|
| 6295 | ## forked process
|
---|
| 6296 | sub __publish_subnet {
|
---|
[685] | 6297 | my $self = shift; # *sigh* need to pass in the DNSDB object so we can read a couple of options
|
---|
[339] | 6298 | my $sub = shift;
|
---|
| 6299 | my $recflags = shift;
|
---|
| 6300 | my $hpat = shift;
|
---|
| 6301 | my $fh = shift;
|
---|
| 6302 | my $ttl = shift;
|
---|
| 6303 | my $stamp = shift;
|
---|
| 6304 | my $loc = shift;
|
---|
[637] | 6305 | my $zone = new NetAddr::IP shift;
|
---|
[339] | 6306 | my $ptronly = shift || 0;
|
---|
| 6307 |
|
---|
[637] | 6308 | # do this conversion once, not (number-of-ips-in-subnet) times
|
---|
| 6309 | my $arpabase = _ZONE($zone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
| 6310 |
|
---|
[339] | 6311 | my $iplist = $sub->splitref(32);
|
---|
[685] | 6312 | my $ipindex = -1;
|
---|
[339] | 6313 | foreach (@$iplist) {
|
---|
| 6314 | my $ip = $_->addr;
|
---|
[685] | 6315 | $ipindex++;
|
---|
[339] | 6316 | # make as if we split the non-octet-aligned block into octet-aligned blocks as with SOA
|
---|
[637] | 6317 | my $lastoct = (split /\./, $ip)[3];
|
---|
[635] | 6318 | next if $$recflags{$ip}; # && $self->{skip_bcast_255}
|
---|
[339] | 6319 | $$recflags{$ip}++;
|
---|
[463] | 6320 | next if $hpat eq '%blank%'; # Allows blanking a subnet so no records are published.
|
---|
[339] | 6321 | my $rec = $hpat; # start fresh with the template for each IP
|
---|
[637] | 6322 | ##fixme: there really isn't a good way to handle sub-/24 zones here. This way at least
|
---|
[685] | 6323 | # seems less bad than some alternatives.
|
---|
| 6324 | $self->_template4_expand(\$rec, $ip, \$sub, $ipindex);
|
---|
| 6325 | # _template4_expand may blank $rec; if so, don't publish a record
|
---|
| 6326 | next if !$rec;
|
---|
[637] | 6327 | if ($ptronly || $zone->masklen > 24) {
|
---|
| 6328 | print $fh "^$lastoct.$arpabase:$rec:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6329 | if (!$ptronly) {
|
---|
| 6330 | # print a separate A record. Arguably we could use an = record here instead.
|
---|
| 6331 | print $fh "+$rec:$ip:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6332 | }
|
---|
| 6333 | } else {
|
---|
| 6334 | print $fh "=$rec:$ip:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6335 | }
|
---|
[339] | 6336 | }
|
---|
[679] | 6337 | } # __publish_subnet
|
---|
[339] | 6338 |
|
---|
[636] | 6339 | ## And now the meat.
|
---|
| 6340 |
|
---|
[103] | 6341 | ##fixme? append . to all host/val hostnames
|
---|
[637] | 6342 | #print "debug: rawdata: $host $typemap{$type} $val\n";
|
---|
[103] | 6343 |
|
---|
[636] | 6344 | if ($typemap{$type} eq 'SOA') {
|
---|
| 6345 | # host contains pri-ns:responsible
|
---|
| 6346 | # val is abused to contain refresh:retry:expire:minttl
|
---|
[103] | 6347 | ##fixme: "manual" serial vs tinydns-autoserial
|
---|
[636] | 6348 | # let's be explicit about abusing $host and $val
|
---|
| 6349 | my ($email, $primary) = (split /:/, $host)[0,1];
|
---|
| 6350 | my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
|
---|
| 6351 | if ($revrec eq 'y') {
|
---|
[337] | 6352 | ##fixme: have to publish SOA records for each v4 /24 in sub-/16, and each /16 in sub-/8
|
---|
| 6353 | # what about v6?
|
---|
| 6354 | # -> only need SOA for local chunks offset from reverse delegation boundaries, so v6 is fine
|
---|
[636] | 6355 | # anyone who says they need sub-nibble v6 delegations, at this time, needs their head examined.
|
---|
| 6356 | $zone = NetAddr::IP->new($zone);
|
---|
| 6357 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
| 6358 | if (!$zone->{isv6} && ($zone->masklen < 24) && ($zone->masklen % 8 != 0)) {
|
---|
| 6359 | foreach my $szone ($zone->split($zone->masklen + (8 - $zone->masklen % 8))) {
|
---|
| 6360 | $szone = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
| 6361 | print $datafile "Z$szone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n"
|
---|
| 6362 | or die $!;
|
---|
| 6363 | }
|
---|
| 6364 | return; # skips "default" bits just below
|
---|
| 6365 | }
|
---|
| 6366 | $zone = _ZONE($zone, 'ZONE', 'r', '.').($zone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 6367 | }
|
---|
| 6368 | print $datafile "Z$zone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n"
|
---|
| 6369 | or die $!;
|
---|
[103] | 6370 |
|
---|
[636] | 6371 | } elsif ($typemap{$type} eq 'A') {
|
---|
[103] | 6372 |
|
---|
[637] | 6373 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
[636] | 6374 | print $datafile "+$host:$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
[103] | 6375 |
|
---|
[636] | 6376 | } elsif ($typemap{$type} eq 'NS') {
|
---|
[103] | 6377 |
|
---|
[636] | 6378 | if ($revrec eq 'y') {
|
---|
| 6379 | $val = NetAddr::IP->new($val);
|
---|
| 6380 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
| 6381 | if (!$val->{isv6} && ($val->masklen < 24) && ($val->masklen % 8 != 0)) {
|
---|
| 6382 | foreach my $szone ($val->split($val->masklen + (8 - $val->masklen % 8))) {
|
---|
| 6383 | my $szone2 = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
| 6384 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
| 6385 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6386 | $$recflags{$szone2} = $val->masklen;
|
---|
| 6387 | }
|
---|
| 6388 | } elsif ($val->{isv6} && ($val->masklen < 64) && ($val->masklen % 4 !=0)) {
|
---|
| 6389 | foreach my $szone ($val->split($val->masklen + (4 - $val->masklen % 4))) {
|
---|
| 6390 | my $szone2 = _ZONE($szone, 'ZONE.ip6.arpa', 'r', '.');
|
---|
| 6391 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
| 6392 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6393 | $$recflags{$szone2} = $val->masklen;
|
---|
| 6394 | }
|
---|
| 6395 | } else {
|
---|
| 6396 | my $val2 = _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 6397 | print $datafile "\&$val2"."::$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6398 | $$recflags{$val2} = $val->masklen;
|
---|
| 6399 | }
|
---|
| 6400 | } else {
|
---|
| 6401 | print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6402 | }
|
---|
[103] | 6403 |
|
---|
[636] | 6404 | } elsif ($typemap{$type} eq 'AAAA') {
|
---|
[103] | 6405 |
|
---|
[637] | 6406 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
[636] | 6407 | my $altgrp = 0;
|
---|
| 6408 | my @altconv;
|
---|
| 6409 | # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
|
---|
| 6410 | foreach (split /:/, $val) {
|
---|
| 6411 | if (/^$/) {
|
---|
| 6412 | # flag blank entry; this is a series of 0's of (currently) unknown length
|
---|
| 6413 | $altconv[$altgrp++] = 's';
|
---|
| 6414 | } else {
|
---|
| 6415 | # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
|
---|
| 6416 | $altconv[$altgrp++] = octalize($_)
|
---|
| 6417 | }
|
---|
| 6418 | }
|
---|
| 6419 | my $prefix = ":$host:28:";
|
---|
| 6420 | foreach my $octet (@altconv) {
|
---|
| 6421 | # if not 's', output
|
---|
| 6422 | $prefix .= $octet unless $octet =~ /^s$/;
|
---|
| 6423 | # if 's', output (9-array length)x literal '\000\000'
|
---|
| 6424 | $prefix .= '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
|
---|
| 6425 | }
|
---|
| 6426 | print $datafile "$prefix:$ttl:$stamp:$loc\n" or die $!;
|
---|
[103] | 6427 |
|
---|
[636] | 6428 | } elsif ($typemap{$type} eq 'MX') {
|
---|
[103] | 6429 |
|
---|
[637] | 6430 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
[636] | 6431 | print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n" or die $!;
|
---|
[103] | 6432 |
|
---|
[636] | 6433 | } elsif ($typemap{$type} eq 'TXT') {
|
---|
[103] | 6434 |
|
---|
[637] | 6435 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
[703] | 6436 | # le sigh. Some idiot DNS implementations don't seem to like tinydns autosplitting
|
---|
| 6437 | # long TXT records at 127 characters instead of 255. Hand-crafting a record seems
|
---|
| 6438 | # to paper over the remote stupid. We will NOT try to split on whitespace; the
|
---|
| 6439 | # contents of a TXT record are opaque and clients who can't deal are even more broken
|
---|
| 6440 | # than the ones that don't like them split at 127 characters... because BIND tries
|
---|
| 6441 | # to "intelligently" split TXT data, and abso-by-damn-lutely generates chunks <255
|
---|
| 6442 | # characters, and anything that can't interpret BIND's DNS responses has no business
|
---|
| 6443 | # trying to interpret DNS data at all.
|
---|
[103] | 6444 |
|
---|
[708] | 6445 | if ($self->{autotxt}) {
|
---|
| 6446 | # let tinydns deal with splitting the record. note tinydns autosplits at 127
|
---|
| 6447 | # characters, not 255. Because Reasons.
|
---|
| 6448 | $val =~ s/:/\\072/g; # may need to replace other symbols
|
---|
| 6449 | print $datafile "'$host:$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6450 | } else {
|
---|
| 6451 | print $datafile ":$host:16:";
|
---|
| 6452 | my @txtsegs = $val =~ /.{1,255}/g;
|
---|
| 6453 | foreach (@txtsegs) {
|
---|
| 6454 | my $len = length($_);
|
---|
| 6455 | s/:/\\072/g;
|
---|
| 6456 | printf $datafile "\\%0.3o%s", $len, $_;
|
---|
| 6457 | }
|
---|
| 6458 | print $datafile ":$ttl:$stamp:$loc\n";
|
---|
[703] | 6459 | }
|
---|
| 6460 |
|
---|
[103] | 6461 | # by-hand TXT
|
---|
| 6462 | #:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
|
---|
| 6463 | #@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
|
---|
| 6464 | #'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
|
---|
| 6465 |
|
---|
| 6466 | #txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
|
---|
| 6467 | #: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
|
---|
| 6468 |
|
---|
| 6469 | # very long TXT record as brought in by axfr-get
|
---|
| 6470 | # note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
|
---|
| 6471 | # also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
|
---|
| 6472 | #:longtxt.deepnet.cx:16:
|
---|
| 6473 | #\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
|
---|
| 6474 | #\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.
|
---|
| 6475 | #\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.
|
---|
| 6476 | #:3600
|
---|
| 6477 |
|
---|
[636] | 6478 | } elsif ($typemap{$type} eq 'CNAME') {
|
---|
[103] | 6479 |
|
---|
[637] | 6480 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
| 6481 | print $datafile "C$host:$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
[103] | 6482 |
|
---|
[636] | 6483 | } elsif ($typemap{$type} eq 'SRV') {
|
---|
[103] | 6484 |
|
---|
[637] | 6485 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
| 6486 |
|
---|
[636] | 6487 | # data is two-byte values for priority, weight, port, in that order,
|
---|
| 6488 | # followed by length/string data
|
---|
[103] | 6489 |
|
---|
[637] | 6490 | my $prefix = ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
|
---|
[103] | 6491 |
|
---|
[636] | 6492 | $val .= '.' if $val !~ /\.$/;
|
---|
| 6493 | foreach (split /\./, $val) {
|
---|
[637] | 6494 | $prefix .= sprintf "\\%0.3o%s", length($_), $_ or die $!;
|
---|
[636] | 6495 | }
|
---|
[637] | 6496 | print $datafile "$prefix\\000:$ttl:$stamp:$loc\n" or die $!;
|
---|
[103] | 6497 |
|
---|
[636] | 6498 | } elsif ($typemap{$type} eq 'RP') {
|
---|
[103] | 6499 |
|
---|
[637] | 6500 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
[636] | 6501 | # RP consists of two mostly free-form strings.
|
---|
| 6502 | # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
|
---|
| 6503 | # The second is the "hostname" of a TXT record with more info.
|
---|
| 6504 | my $prefix = ":$host:17:";
|
---|
| 6505 | my ($who,$what) = split /\s/, $val;
|
---|
| 6506 | foreach (split /\./, $who) {
|
---|
| 6507 | $prefix .= sprintf "\\%0.3o%s", length($_), $_;
|
---|
| 6508 | }
|
---|
| 6509 | $prefix .= '\000';
|
---|
| 6510 | foreach (split /\./, $what) {
|
---|
| 6511 | $prefix .= sprintf "\\%0.3o%s", length($_), $_;
|
---|
| 6512 | }
|
---|
| 6513 | print $datafile "$prefix\\000:$ttl:$stamp:$loc\n" or die $!;
|
---|
[103] | 6514 |
|
---|
[636] | 6515 | } elsif ($typemap{$type} eq 'PTR') {
|
---|
[103] | 6516 |
|
---|
[636] | 6517 | $$recflags{$val}++;
|
---|
[637] | 6518 | if ($revrec eq 'y') {
|
---|
| 6519 |
|
---|
| 6520 | if ($val =~ /\.arpa$/) {
|
---|
| 6521 | # someone put in the formal .arpa name. humor them.
|
---|
| 6522 | print $datafile "^$val:$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6523 | } else {
|
---|
| 6524 | $zone = NetAddr::IP->new($zone);
|
---|
| 6525 | if (!$zone->{isv6} && $zone->masklen > 24) {
|
---|
| 6526 | # sub-octet v4 zone
|
---|
| 6527 | ($val) = ($val =~ /\.(\d+)$/);
|
---|
| 6528 | print $datafile "^$val."._ZONE($zone, 'ZONE', 'r', '.').'.in-addr.arpa'.
|
---|
| 6529 | ":$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6530 | } else {
|
---|
| 6531 | # not going to care about strange results if $val is not an IP value and is resolveable in DNS
|
---|
| 6532 | $val = NetAddr::IP->new($val);
|
---|
| 6533 | print $datafile "^".
|
---|
| 6534 | _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
| 6535 | ":$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6536 | }
|
---|
| 6537 | } # non-".arpa" $val
|
---|
| 6538 |
|
---|
[636] | 6539 | } else {
|
---|
[637] | 6540 | # PTRs in forward zones are less bizarre and insane than some other record types
|
---|
| 6541 | # in reverse zones... OTOH we can't validate them any which way, so we cross our
|
---|
| 6542 | # fingers and close our eyes and make it Someone Else's Problem.
|
---|
| 6543 | print $datafile "^$host:$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
[636] | 6544 | }
|
---|
[103] | 6545 |
|
---|
[636] | 6546 | } elsif ($type == 65280) { # A+PTR
|
---|
[334] | 6547 |
|
---|
[636] | 6548 | $$recflags{$val}++;
|
---|
| 6549 | print $datafile "=$host:$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
[334] | 6550 |
|
---|
[636] | 6551 | } elsif ($type == 65281) { # AAAA+PTR
|
---|
[333] | 6552 |
|
---|
[636] | 6553 | $$recflags{$val}++;
|
---|
| 6554 | # treat these as two separate records. since tinydns doesn't have
|
---|
| 6555 | # a native combined type, we have to create them separately anyway.
|
---|
| 6556 | # print both; a dangling record is harmless, and impossible via web
|
---|
| 6557 | # UI anyway
|
---|
[654] | 6558 | $self->_printrec_tiny($datafile,$recid,'n',$recflags, $self->domainName($self->_hostparent($host)),
|
---|
| 6559 | $host, 28, $val, $dist, $weight, $port, $ttl, $loc, $stamp);
|
---|
| 6560 | $self->_printrec_tiny($datafile, $recid, 'y', $recflags, $zone,
|
---|
| 6561 | $host, 12, $val, $dist, $weight, $port, $ttl, $loc, $stamp);
|
---|
| 6562 |
|
---|
[335] | 6563 | ##fixme: add a config flag to indicate use of the patch from http://www.fefe.de/dns/
|
---|
| 6564 | # type 6 is for AAAA+PTR, type 3 is for AAAA
|
---|
[333] | 6565 |
|
---|
[636] | 6566 | } elsif ($type == 65282) { # PTR template
|
---|
[335] | 6567 |
|
---|
[636] | 6568 | # only useful for v4 with standard DNS software, since this expands all
|
---|
| 6569 | # IPs in $zone (or possibly $val?) with autogenerated records
|
---|
| 6570 | $val = NetAddr::IP->new($val);
|
---|
| 6571 | return if $val->{isv6};
|
---|
[336] | 6572 |
|
---|
[636] | 6573 | if ($val->masklen <= 16) {
|
---|
| 6574 | foreach my $sub ($val->split(16)) {
|
---|
[644] | 6575 | $self->__publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, $zone, 1);
|
---|
[636] | 6576 | }
|
---|
| 6577 | } else {
|
---|
[644] | 6578 | $self->__publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, $zone, 1);
|
---|
[636] | 6579 | }
|
---|
[335] | 6580 |
|
---|
[636] | 6581 | } elsif ($type == 65283) { # A+PTR template
|
---|
[335] | 6582 |
|
---|
[636] | 6583 | $val = NetAddr::IP->new($val);
|
---|
| 6584 | # Just In Case. An A+PTR should be impossible to add to a v6 revzone via API.
|
---|
| 6585 | return if $val->{isv6};
|
---|
[339] | 6586 |
|
---|
[679] | 6587 | if ($val->masklen < 16) {
|
---|
[636] | 6588 | foreach my $sub ($val->split(16)) {
|
---|
[644] | 6589 | $self->__publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, $zone, 0);
|
---|
[636] | 6590 | }
|
---|
| 6591 | } else {
|
---|
[644] | 6592 | $self->__publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, $zone, 0);
|
---|
[636] | 6593 | }
|
---|
[335] | 6594 |
|
---|
[636] | 6595 | } elsif ($type == 65284) { # AAAA+PTR template
|
---|
| 6596 | # Stub for completeness. Could be exported to DNS software that supports
|
---|
| 6597 | # some degree of internal automagic in generic-record-creation
|
---|
| 6598 | # (eg http://search.cpan.org/dist/AllKnowingDNS/ )
|
---|
[333] | 6599 |
|
---|
[636] | 6600 | } elsif ($type == 65285) { # Delegation
|
---|
| 6601 | # This is intended for reverse zones, but may prove useful in forward zones.
|
---|
[345] | 6602 |
|
---|
[636] | 6603 | # All delegations need to create one or more NS records. The NS record handler knows what to do.
|
---|
[644] | 6604 | $self->_printrec_tiny($datafile,$recid,$revrec,$recflags,$zone,$host,$reverse_typemap{'NS'},
|
---|
[636] | 6605 | $val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
| 6606 | if ($revrec eq 'y') {
|
---|
| 6607 | # In the case of a sub-/24 v4 reverse delegation, we need to generate CNAMEs
|
---|
| 6608 | # to redirect all of the individual IP lookups as well.
|
---|
[637] | 6609 | # OR
|
---|
| 6610 | # create NS records for each IP
|
---|
[636] | 6611 | # Not sure how this would actually resolve if a /24 or larger was delegated
|
---|
| 6612 | # one way, and a sub-/24 in that >=/24 was delegated elsewhere...
|
---|
| 6613 | my $dblock = NetAddr::IP->new($val);
|
---|
| 6614 | if (!$dblock->{isv6} && $dblock->masklen > 24) {
|
---|
| 6615 | my @subs = $dblock->split;
|
---|
| 6616 | foreach (@subs) {
|
---|
| 6617 | next if $$recflags{"$_"};
|
---|
| 6618 | my ($oct) = ($_->addr =~ /(\d+)$/);
|
---|
| 6619 | print $datafile "C"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$oct.".
|
---|
| 6620 | _ZONE($dblock, 'ZONE.in-addr.arpa', 'r', '.').":$ttl:$stamp:$loc\n" or die $!;
|
---|
| 6621 | $$recflags{"$_"}++;
|
---|
| 6622 | }
|
---|
| 6623 | }
|
---|
| 6624 | }
|
---|
[345] | 6625 |
|
---|
[364] | 6626 | ##
|
---|
| 6627 | ## Uncommon types. These will need better UI support Any Day Sometime Maybe(TM).
|
---|
| 6628 | ##
|
---|
| 6629 |
|
---|
[636] | 6630 | } elsif ($type == 44) { # SSHFP
|
---|
[637] | 6631 |
|
---|
| 6632 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
| 6633 |
|
---|
[636] | 6634 | my ($algo,$fpt,$fp) = split /\s+/, $val;
|
---|
[364] | 6635 |
|
---|
[636] | 6636 | my $rec = sprintf ":$host:44:\\%0.3o\\%0.3o", $algo, $fpt;
|
---|
| 6637 | while (my ($byte) = ($fp =~ /^(..)/) ) {
|
---|
| 6638 | $rec .= sprintf "\\%0.3o", hex($byte);
|
---|
| 6639 | $fp =~ s/^..//;
|
---|
| 6640 | }
|
---|
| 6641 | print $datafile "$rec:$ttl:$stamp:$loc\n" or die $!;
|
---|
[364] | 6642 |
|
---|
[636] | 6643 | } else {
|
---|
| 6644 | # raw record. we don't know what's in here, so we ASS-U-ME the user has
|
---|
| 6645 | # put it in correctly, since either the user is messing directly with the
|
---|
| 6646 | # database, or the record was imported via AXFR
|
---|
| 6647 | # <split by char>
|
---|
| 6648 | # convert anything not a-zA-Z0-9.- to octal coding
|
---|
[108] | 6649 |
|
---|
| 6650 | ##fixme: add flag to export "unknown" record types - note we'll probably end up
|
---|
| 6651 | # mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
|
---|
[636] | 6652 | #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
|
---|
[108] | 6653 |
|
---|
[636] | 6654 | } # record type if-else
|
---|
[103] | 6655 |
|
---|
[329] | 6656 | } # end _printrec_tiny()
|
---|
[103] | 6657 |
|
---|
| 6658 |
|
---|
[197] | 6659 | ## DNSDB::mailNotify()
|
---|
[283] | 6660 | # Sends notification mail to recipients regarding a DNSDB operation
|
---|
[197] | 6661 | sub mailNotify {
|
---|
[483] | 6662 | my $self = shift;
|
---|
| 6663 | my $dbh = $self->{dbh};
|
---|
[197] | 6664 | my ($subj,$message) = @_;
|
---|
| 6665 |
|
---|
[517] | 6666 | return if $self->{mailhost} eq 'smtp.example.com'; # do nothing if still using default SMTP host.
|
---|
[197] | 6667 |
|
---|
[517] | 6668 | my $mailer = Net::SMTP->new($self->{mailhost}, Hello => "dnsadmin.$self->{domain}");
|
---|
[197] | 6669 |
|
---|
[517] | 6670 | my $mailsender = ($self->{mailsender} ? $self->{mailsender} : $self->{mailnotify});
|
---|
[197] | 6671 |
|
---|
| 6672 | $mailer->mail($mailsender);
|
---|
[517] | 6673 | $mailer->to($self->{mailnotify});
|
---|
| 6674 | $mailer->data("From: \"$self->{mailname}\" <$mailsender>\n",
|
---|
| 6675 | "To: <$self->{mailnotify}>\n",
|
---|
[197] | 6676 | "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
|
---|
| 6677 | "Subject: $subj\n",
|
---|
[529] | 6678 | "X-Mailer: DNSAdmin v".$DNSDB::VERSION." Notify\n",
|
---|
[517] | 6679 | "Organization: $self->{orgname}\n",
|
---|
[197] | 6680 | "\n$message\n");
|
---|
| 6681 | $mailer->quit;
|
---|
| 6682 | }
|
---|
| 6683 |
|
---|
[2] | 6684 | # shut Perl up
|
---|
| 6685 | 1;
|
---|