[2] | 1 | # dns/trunk/DNSDB.pm
|
---|
| 2 | # Abstraction functions for DNS administration
|
---|
[262] | 3 | ##
|
---|
| 4 | # $Id: DNSDB.pm 623 2014-04-29 20:16:33Z 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',
|
---|
[517] | 221 | );
|
---|
| 222 |
|
---|
| 223 | # Config file parse calls.
|
---|
| 224 | # If we are passed a blank argument for $args{configfile},
|
---|
| 225 | # we should NOT parse the default config file - we will
|
---|
| 226 | # rely on hardcoded defaults OR caller-specified values.
|
---|
| 227 | # If we are passed a non-blank argument, parse that file.
|
---|
| 228 | # If no config file is specified, parse the default one.
|
---|
| 229 | my %siteconfig;
|
---|
| 230 | if (defined($args{configfile})) {
|
---|
| 231 | if ($args{configfile}) {
|
---|
| 232 | return if !__cfgload($args{configfile}, \%siteconfig);
|
---|
| 233 | }
|
---|
| 234 | } else {
|
---|
| 235 | return if !__cfgload($defconfig{configfile}, \%siteconfig);
|
---|
[465] | 236 | }
|
---|
[517] | 237 |
|
---|
| 238 | # Assemble the object. Apply configuration hashes in order of precedence.
|
---|
| 239 | my $self = {
|
---|
| 240 | # Hardcoded defaults
|
---|
| 241 | %defconfig,
|
---|
| 242 | # Default config file OR caller-specified one, loaded above
|
---|
| 243 | %siteconfig,
|
---|
| 244 | # Caller-specified arguments
|
---|
| 245 | %args
|
---|
| 246 | };
|
---|
[465] | 247 | bless $self, $class;
|
---|
[517] | 248 |
|
---|
[524] | 249 | # Several settings are booleans. Handle multiple possible ways of setting them.
|
---|
[583] | 250 | for my $boolopt ('log_failures', 'force_refresh', 'lowercase', 'usecache') {
|
---|
[524] | 251 | if ($self->{$boolopt} ne '1' && $self->{$boolopt} ne '0') {
|
---|
| 252 | # true/false, on/off, yes/no all valid.
|
---|
| 253 | if ($self->{$boolopt} =~ /^(?:true|false|t|f|on|off|yes|no)$/) {
|
---|
| 254 | if ($self->{$boolopt} =~ /(?:true|t|on|yes)/) {
|
---|
| 255 | $self->{$boolopt} = 1;
|
---|
| 256 | } else {
|
---|
| 257 | $self->{$boolopt} = 0;
|
---|
| 258 | }
|
---|
| 259 | } else {
|
---|
[583] | 260 | warn "Bad $boolopt setting $self->{$boolopt}, using default\n";
|
---|
| 261 | $self->{$boolopt} = $defconfig{$boolopt};
|
---|
[524] | 262 | }
|
---|
| 263 | }
|
---|
| 264 | }
|
---|
| 265 |
|
---|
[583] | 266 | # Enum-ish option(s)
|
---|
| 267 | if (!grep /$self->{showrev_arpa}/, ('none','zone','record','all')) {
|
---|
| 268 | warn "Bad showrev_arpa setting $self->{showrev_arpa}, using default\n";
|
---|
| 269 | $self->{showrev_arpa} = 'none';
|
---|
| 270 | }
|
---|
| 271 |
|
---|
[517] | 272 | # Try to connect to the DB, and initialize a number of handy globals.
|
---|
[465] | 273 | $self->{dbh} = connectDB($self->{dbname}, $self->{dbuser}, $self->{dbpass}, $self->{dbhost}) or return;
|
---|
| 274 | $self->initGlobals();
|
---|
| 275 |
|
---|
| 276 | return $self;
|
---|
| 277 | }
|
---|
| 278 |
|
---|
| 279 | sub DESTROY {
|
---|
| 280 | my $self = shift;
|
---|
[517] | 281 | $self->{dbh}->disconnect if $self->{dbh};
|
---|
[465] | 282 | }
|
---|
| 283 |
|
---|
[495] | 284 | sub errstr { $DNSDB::errstr; }
|
---|
| 285 |
|
---|
[465] | 286 | ##
|
---|
[225] | 287 | ## utility functions
|
---|
[281] | 288 | ##
|
---|
| 289 |
|
---|
| 290 | ## DNSDB::_rectable()
|
---|
[224] | 291 | # Takes default+rdns flags, returns appropriate table name
|
---|
| 292 | sub _rectable {
|
---|
| 293 | my $def = shift;
|
---|
| 294 | my $rev = shift;
|
---|
| 295 |
|
---|
| 296 | return 'records' if $def ne 'y';
|
---|
| 297 | return 'default_records' if $rev ne 'y';
|
---|
| 298 | return 'default_rev_records';
|
---|
| 299 | } # end _rectable()
|
---|
| 300 |
|
---|
[281] | 301 | ## DNSDB::_recparent()
|
---|
[224] | 302 | # Takes default+rdns flags, returns appropriate parent-id column name
|
---|
| 303 | sub _recparent {
|
---|
| 304 | my $def = shift;
|
---|
| 305 | my $rev = shift;
|
---|
| 306 |
|
---|
| 307 | return 'group_id' if $def eq 'y';
|
---|
| 308 | return 'rdns_id' if $rev eq 'y';
|
---|
| 309 | return 'domain_id';
|
---|
| 310 | } # end _recparent()
|
---|
| 311 |
|
---|
[281] | 312 | ## DNSDB::_ipparent()
|
---|
[226] | 313 | # Check an IP to be added in a reverse zone to see if it's really in the requested parent.
|
---|
[466] | 314 | # Takes default and reverse flags, IP (fragment) to check, parent zone ID,
|
---|
[226] | 315 | # and a reference to a NetAddr::IP object (also used to pass back a fully-reconstructed IP for
|
---|
| 316 | # database insertion)
|
---|
| 317 | sub _ipparent {
|
---|
[466] | 318 | my $self = shift;
|
---|
| 319 | my $dbh = $self->{dbh};
|
---|
[226] | 320 | my $defrec = shift;
|
---|
| 321 | my $revrec = shift;
|
---|
| 322 | my $val = shift;
|
---|
| 323 | my $id = shift;
|
---|
| 324 | my $addr = shift;
|
---|
[224] | 325 |
|
---|
[232] | 326 | return if $revrec ne 'y'; # this sub not useful in forward zones
|
---|
| 327 |
|
---|
| 328 | $$addr = NetAddr::IP->new($$val); #necessary?
|
---|
| 329 |
|
---|
[226] | 330 | # subsub to split, reverse, and overlay an IP fragment on a netblock
|
---|
| 331 | sub __rev_overlay {
|
---|
| 332 | my $splitme = shift; # ':' or '.', m'lud?
|
---|
| 333 | my $parnet = shift;
|
---|
| 334 | my $val = shift;
|
---|
| 335 | my $addr = shift;
|
---|
| 336 |
|
---|
| 337 | my $joinme = $splitme;
|
---|
| 338 | $splitme = '\.' if $splitme eq '.';
|
---|
[232] | 339 | my @working = reverse(split($splitme, $parnet->addr));
|
---|
| 340 | my @parts = reverse(split($splitme, $$val));
|
---|
[226] | 341 | for (my $i = 0; $i <= $#parts; $i++) {
|
---|
| 342 | $working[$i] = $parts[$i];
|
---|
| 343 | }
|
---|
[232] | 344 | my $checkme = NetAddr::IP->new(join($joinme, reverse(@working))) or return 0;
|
---|
| 345 | return 0 unless $checkme->within($parnet);
|
---|
[226] | 346 | $$addr = $checkme; # force "correct" IP to be recorded.
|
---|
| 347 | return 1;
|
---|
| 348 | }
|
---|
| 349 |
|
---|
| 350 | my ($parstr) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id = ?", undef, ($id));
|
---|
| 351 | my $parnet = NetAddr::IP->new($parstr);
|
---|
| 352 |
|
---|
| 353 | # Fail early on v6-in-v4 or v4-in-v6. We're not accepting these ATM.
|
---|
[232] | 354 | return 0 if $parnet->addr =~ /\./ && $$val =~ /:/;
|
---|
| 355 | return 0 if $parnet->addr =~ /:/ && $$val =~ /\./;
|
---|
[226] | 356 |
|
---|
[340] | 357 | if ($$addr && ($$val =~ /^[\da-fA-F][\da-fA-F:]+[\da-fA-F]$/ || $$val =~ m|/\d+$|)) {
|
---|
| 358 | # the only case where NetAddr::IP's acceptance of legitimate IPs is "correct" is for a proper IPv6 address,
|
---|
| 359 | # or a netblock (only expected on templates)
|
---|
[232] | 360 | # the rest we have to restructure before fiddling. *sigh*
|
---|
| 361 | return 1 if $$addr->within($parnet);
|
---|
| 362 | } else {
|
---|
[340] | 363 | # We don't have a complete IP in $$val (yet)... unless we have a netblock
|
---|
[232] | 364 | if ($parnet->addr =~ /:/) {
|
---|
| 365 | $$val =~ s/^:+//; # gotta strip'em all...
|
---|
[226] | 366 | return __rev_overlay(':', $parnet, $val, $addr);
|
---|
| 367 | }
|
---|
[232] | 368 | if ($parnet->addr =~ /\./) {
|
---|
| 369 | $$val =~ s/^\.+//;
|
---|
| 370 | return __rev_overlay('.', $parnet, $val, $addr);
|
---|
| 371 | }
|
---|
[226] | 372 | # should be impossible to get here...
|
---|
| 373 | }
|
---|
| 374 | # ... and here.
|
---|
| 375 | # can't do nuttin' in forward zones
|
---|
| 376 | } # end _ipparent()
|
---|
| 377 |
|
---|
[609] | 378 | ## DNSDB::_maybeip()
|
---|
| 379 | # Wrapper for quick "does this look like an IP address?" regex, so we don't make dumb copy-paste mistakes
|
---|
| 380 | sub _maybeip {
|
---|
| 381 | my $izzit = shift; # reference
|
---|
| 382 | return 1 if $$izzit =~ m,^(?:[\d\./]+|[0-9a-fA-F:/]+)$,;
|
---|
| 383 | }
|
---|
| 384 |
|
---|
[610] | 385 | ## DNSDB::_inrev()
|
---|
| 386 | # Check if a given "hostname" is within a given reverse zone
|
---|
| 387 | # Takes a reference to the "hostname" and the reverse zone CIDR as a NetAddr::IP
|
---|
| 388 | # Returns true/false. Sets $errstr on errors.
|
---|
| 389 | sub _inrev {
|
---|
| 390 | my $self = shift;
|
---|
| 391 | my $dbh = $self->{dbh};
|
---|
| 392 | # References, since we might munge them
|
---|
| 393 | my $fq = shift;
|
---|
| 394 | my $zone = shift;
|
---|
| 395 |
|
---|
| 396 | # set default error
|
---|
| 397 | $errstr = "$$fq not within $zone";
|
---|
| 398 |
|
---|
| 399 | # Unlike forward zones, we will not coerce the data into the reverse zone - an A record
|
---|
| 400 | # in a reverse zone is already silly enough without appending a mess of 1.2.3.in-addr.arpa
|
---|
| 401 | # (or worse, 1.2.3.4.5.6.7.8.ip6.arpa) on the end of the nominal "hostname".
|
---|
| 402 | # We're also going to allow the "hostname" to be stored as .arpa or IP, because of
|
---|
| 403 | # non-IP FQDNs in .arpa
|
---|
| 404 | if ($$fq =~ /\.arpa$/) {
|
---|
| 405 | # "FQDN" could be any syntactically legitimate string, but it must be within the formal
|
---|
| 406 | # .arpa zone. Note we're not validating these for correct reverse-IP values.
|
---|
| 407 | # yes, we really need the v6 branch on the end here.
|
---|
| 408 | $zone = _ZONE($zone, 'ZONE', 'r', '.').($zone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 409 | return unless $$fq =~ /$zone$/;
|
---|
| 410 | } else {
|
---|
| 411 | # in most cases we should be getting a real IP as the "FQDN" to test
|
---|
| 412 | my $addr = new NetAddr::IP $$fq if _maybeip($fq);
|
---|
| 413 |
|
---|
| 414 | # "FQDN" should be a valid IP address. Normalize formatting if so.
|
---|
| 415 | if (!$addr) {
|
---|
| 416 | $errstr = "$$fq is not a valid IP address";
|
---|
| 417 | return;
|
---|
| 418 | }
|
---|
| 419 | return if !$zone->contains($addr);
|
---|
| 420 | ($$fq = $addr) =~ s{/(?:32|128)$}{};
|
---|
| 421 | }
|
---|
| 422 | return 1;
|
---|
| 423 | } # end _inrev()
|
---|
| 424 |
|
---|
[281] | 425 | ## DNSDB::_hostparent()
|
---|
[232] | 426 | # A little different than _ipparent above; this tries to *find* the parent zone of a hostname
|
---|
[466] | 427 | # Takes a hostname.
|
---|
[281] | 428 | # Returns the domain ID of the parent domain if one was found.
|
---|
[232] | 429 | sub _hostparent {
|
---|
[466] | 430 | my $self = shift;
|
---|
| 431 | my $dbh = $self->{dbh};
|
---|
[232] | 432 | my $hname = shift;
|
---|
[347] | 433 |
|
---|
| 434 | $hname =~ s/^\*\.//; # this should be impossible to find in the domains table.
|
---|
[232] | 435 | my @hostbits = split /\./, $hname;
|
---|
[349] | 436 | my $sth = $dbh->prepare("SELECT count(*),domain_id FROM domains WHERE lower(domain) = lower(?) GROUP BY domain_id");
|
---|
[232] | 437 | foreach (@hostbits) {
|
---|
| 438 | $sth->execute($hname);
|
---|
| 439 | my ($found, $parid) = $sth->fetchrow_array;
|
---|
| 440 | if ($found) {
|
---|
| 441 | return $parid;
|
---|
| 442 | }
|
---|
| 443 | $hname =~ s/^$_\.//;
|
---|
| 444 | }
|
---|
| 445 | } # end _hostparent()
|
---|
[228] | 446 |
|
---|
[281] | 447 | ## DNSDB::_log()
|
---|
| 448 | # Log an action
|
---|
[466] | 449 | # Takes a log entry hash containing at least:
|
---|
[282] | 450 | # group_id, log entry
|
---|
[281] | 451 | # and optionally one or more of:
|
---|
| 452 | # domain_id, rdns_id
|
---|
[282] | 453 | # The %userdata hash provides the user ID, username, and fullname
|
---|
[281] | 454 | sub _log {
|
---|
[466] | 455 | my $self = shift;
|
---|
| 456 | my $dbh = $self->{dbh};
|
---|
[281] | 457 |
|
---|
| 458 | my %args = @_;
|
---|
| 459 |
|
---|
| 460 | $args{rdns_id} = 0 if !$args{rdns_id};
|
---|
| 461 | $args{domain_id} = 0 if !$args{domain_id};
|
---|
| 462 |
|
---|
| 463 | ##fixme: farm out the actual logging to different subs for file, syslog, internal, etc based on config
|
---|
[517] | 464 | # if ($self->{log_channel} eq 'sql') {
|
---|
[281] | 465 | $dbh->do("INSERT INTO log (domain_id,rdns_id,group_id,entry,user_id,email,name) VALUES (?,?,?,?,?,?,?)",
|
---|
| 466 | undef,
|
---|
| 467 | ($args{domain_id}, $args{rdns_id}, $args{group_id}, $args{entry},
|
---|
[488] | 468 | $self->{loguserid}, $self->{logusername}, $self->{logfullname}) );
|
---|
[517] | 469 | # } elsif ($self->{log_channel} eq 'file') {
|
---|
| 470 | # } elsif ($self->{log_channel} eq 'syslog') {
|
---|
[281] | 471 | # }
|
---|
| 472 | } # end _log
|
---|
| 473 |
|
---|
| 474 |
|
---|
[224] | 475 | ##
|
---|
[228] | 476 | ## Record validation subs.
|
---|
| 477 | ##
|
---|
| 478 |
|
---|
[281] | 479 | ## All of these subs take substantially the same arguments:
|
---|
| 480 | # a hash containing at least the following keys:
|
---|
| 481 | # - defrec (default/live flag)
|
---|
| 482 | # - revrec (forward/reverse flag)
|
---|
| 483 | # - id (parent entity ID)
|
---|
| 484 | # - host (hostname)
|
---|
| 485 | # - rectype
|
---|
| 486 | # - val (IP, hostname [CNAME/MX/SRV] or text)
|
---|
| 487 | # - addr (NetAddr::IP object from val. May be undef.)
|
---|
| 488 | # MX and SRV record validation also expect distance, and SRV records expect weight and port as well.
|
---|
| 489 | # host, rectype, and addr should be references as these may be modified in validation
|
---|
| 490 |
|
---|
[228] | 491 | # A record
|
---|
| 492 | sub _validate_1 {
|
---|
[467] | 493 | my $self = shift;
|
---|
| 494 | my $dbh = $self->{dbh};
|
---|
[229] | 495 |
|
---|
[230] | 496 | my %args = @_;
|
---|
[229] | 497 |
|
---|
[606] | 498 | # only for strict type restrictions
|
---|
| 499 | # return ('FAIL', 'Reverse zones cannot contain A records') if $args{revrec} eq 'y';
|
---|
[229] | 500 |
|
---|
[606] | 501 | if ($args{revrec} eq 'y') {
|
---|
| 502 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 503 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
[229] | 504 |
|
---|
[610] | 505 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
[606] | 506 |
|
---|
[611] | 507 | # ${$args{val}} is either a valid IP or a string ending with the .arpa zone name;
|
---|
| 508 | # now check if it's a well-formed FQDN
|
---|
[613] | 509 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
[612] | 510 | ${$args{val}} =~ /\.arpa$/;
|
---|
[611] | 511 |
|
---|
[606] | 512 | # Check IP is well-formed, and that it's a v4 address
|
---|
| 513 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
|
---|
| 514 | return ('FAIL',"A record must be a valid IPv4 address")
|
---|
| 515 | unless ${$args{host}} =~ /^\d+\.\d+\.\d+\.\d+$/;
|
---|
| 516 | $args{addr} = new NetAddr::IP ${$args{host}};
|
---|
| 517 | return ('FAIL',"A record must be a valid IPv4 address")
|
---|
| 518 | unless $args{addr} && !$args{addr}->{isv6};
|
---|
| 519 | # coerce IP/value to normalized form for storage
|
---|
| 520 | ${$args{host}} = $args{addr}->addr;
|
---|
| 521 |
|
---|
| 522 | # I'm just going to ignore the utterly barmy idea of an A record in the *default*
|
---|
| 523 | # records for a reverse zone; it's bad enough to find one in funky legacy data.
|
---|
| 524 |
|
---|
| 525 | } else {
|
---|
| 526 | # revrec ne 'y'
|
---|
| 527 |
|
---|
| 528 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 529 | # or the intended parent domain for live records.
|
---|
| 530 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
| 531 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/);
|
---|
| 532 |
|
---|
[620] | 533 | # Check if it's a proper formal .arpa name for an IP, and renormalize it to the IP
|
---|
| 534 | # value if so. Done mainly for symmetry with PTR/A+PTR, and saves a conversion on export.
|
---|
| 535 | if (${$args{val}} =~ /\.arpa$/) {
|
---|
| 536 | my ($code,$tmp) = _zone2cidr(${$args{val}});
|
---|
| 537 | if ($code ne 'FAIL') {
|
---|
| 538 | ${$args{val}} = $tmp->addr;
|
---|
| 539 | $args{addr} = $tmp;
|
---|
| 540 | }
|
---|
| 541 | }
|
---|
[606] | 542 | # Check IP is well-formed, and that it's a v4 address
|
---|
| 543 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
|
---|
| 544 | return ('FAIL',"A record must be a valid IPv4 address")
|
---|
[234] | 545 | unless ${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/;
|
---|
[606] | 546 | return ('FAIL',"A record must be a valid IPv4 address")
|
---|
[230] | 547 | unless $args{addr} && !$args{addr}->{isv6};
|
---|
[606] | 548 | # coerce IP/value to normalized form for storage
|
---|
| 549 | ${$args{val}} = $args{addr}->addr;
|
---|
| 550 | }
|
---|
[229] | 551 |
|
---|
[228] | 552 | return ('OK','OK');
|
---|
| 553 | } # done A record
|
---|
| 554 |
|
---|
| 555 | # NS record
|
---|
| 556 | sub _validate_2 {
|
---|
[467] | 557 | my $self = shift;
|
---|
| 558 | my $dbh = $self->{dbh};
|
---|
[230] | 559 |
|
---|
| 560 | my %args = @_;
|
---|
| 561 |
|
---|
[616] | 562 | # NS target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 563 | if ($args{revrec} eq 'y') {
|
---|
| 564 | return ('FAIL', "NS records cannot point directly to an IP address")
|
---|
| 565 | if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
| 566 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
| 567 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 568 | } else {
|
---|
| 569 | return ('FAIL', "NS records cannot point directly to an IP address")
|
---|
| 570 | if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
| 571 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
| 572 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 573 | }
|
---|
| 574 |
|
---|
[328] | 575 | # Check that the target of the record is within the parent.
|
---|
| 576 | if ($args{defrec} eq 'n') {
|
---|
| 577 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
| 578 | if ($args{revrec} eq 'y') {
|
---|
[616] | 579 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 580 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
| 581 |
|
---|
| 582 | # Note the NS record may or may not be for the zone itself, it may be a pointer for a subzone
|
---|
| 583 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
| 584 |
|
---|
| 585 | # ${$args{val}} is either a valid IP or a string ending with the .arpa zone name;
|
---|
| 586 | # now check if it's a well-formed FQDN
|
---|
| 587 | ##enhance or ##fixme
|
---|
| 588 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design
|
---|
| 589 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
| 590 | ${$args{val}} =~ /\.arpa$/;
|
---|
[328] | 591 | } else {
|
---|
[616] | 592 | # Forcibly append the domain name if the hostname being added does not end with the current domain name
|
---|
[467] | 593 | my $pname = $self->domainName($args{id});
|
---|
[616] | 594 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
[328] | 595 | }
|
---|
[230] | 596 | } else {
|
---|
[616] | 597 | # Default reverse NS records should always refer to the implied parent.
|
---|
| 598 | if ($args{revrec} eq 'y') {
|
---|
| 599 | ${$args{val}} = 'ZONE';
|
---|
| 600 | } else {
|
---|
| 601 | ${$args{host}} = 'DOMAIN';
|
---|
| 602 | }
|
---|
[230] | 603 | }
|
---|
| 604 |
|
---|
[228] | 605 | return ('OK','OK');
|
---|
| 606 | } # done NS record
|
---|
| 607 |
|
---|
| 608 | # CNAME record
|
---|
| 609 | sub _validate_5 {
|
---|
[467] | 610 | my $self = shift;
|
---|
| 611 | my $dbh = $self->{dbh};
|
---|
[230] | 612 |
|
---|
| 613 | my %args = @_;
|
---|
| 614 |
|
---|
[618] | 615 | # CNAMEs in reverse zones shouldn't be handled manually, they should be generated on
|
---|
| 616 | # export by use of the "delegation" type. For the masochistic, and those importing
|
---|
| 617 | # legacy data from $deity-knows-where, we'll support them.
|
---|
[230] | 618 |
|
---|
[618] | 619 | if ($args{revrec} eq 'y') {
|
---|
| 620 | # CNAME target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 621 | return ('FAIL', "CNAME records cannot point directly to an IP address")
|
---|
| 622 | if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
[230] | 623 |
|
---|
[618] | 624 | if ($args{defrec} eq 'n') {
|
---|
| 625 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 626 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
| 627 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
| 628 | }
|
---|
| 629 |
|
---|
| 630 | ##enhance or ##fixme
|
---|
| 631 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design
|
---|
| 632 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
| 633 | ${$args{val}} =~ /\.arpa$/;
|
---|
| 634 |
|
---|
| 635 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
| 636 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 637 | } else {
|
---|
| 638 | # CNAME target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 639 | return ('FAIL', "CNAME records cannot point directly to an IP address")
|
---|
| 640 | if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
| 641 |
|
---|
| 642 | # Forcibly append the domain name if the hostname being added does not end with the current domain name
|
---|
| 643 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
| 644 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 645 |
|
---|
| 646 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
| 647 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 648 | }
|
---|
| 649 |
|
---|
[228] | 650 | return ('OK','OK');
|
---|
| 651 | } # done CNAME record
|
---|
| 652 |
|
---|
| 653 | # SOA record
|
---|
| 654 | sub _validate_6 {
|
---|
[230] | 655 | # Smart monkeys won't stick their fingers in here; we have
|
---|
| 656 | # separate dedicated routines to deal with SOA records.
|
---|
[228] | 657 | return ('OK','OK');
|
---|
| 658 | } # done SOA record
|
---|
| 659 |
|
---|
| 660 | # PTR record
|
---|
| 661 | sub _validate_12 {
|
---|
[467] | 662 | my $self = shift;
|
---|
| 663 | my $dbh = $self->{dbh};
|
---|
[232] | 664 |
|
---|
| 665 | my %args = @_;
|
---|
[620] | 666 | my $warnflag = '';
|
---|
[232] | 667 |
|
---|
[620] | 668 | if ($args{defrec} eq 'y') {
|
---|
| 669 | if ($args{revrec} eq 'y') {
|
---|
| 670 | if (${$args{val}} =~ /^[\d.]+$/) {
|
---|
| 671 | # v4 or bare number
|
---|
| 672 | if (${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/) {
|
---|
| 673 | # probable full IP. pointless but harmless. validate/normalize.
|
---|
| 674 | my $tmp = NetAddr::IP->new(${$args{val}})->addr
|
---|
| 675 | or return ('FAIL', "${$args{val}} is not a valid IP address");
|
---|
| 676 | ${$args{val}} = $tmp;
|
---|
| 677 | $warnflag = "${$args{val}} will only be added to a small number of zones\n";
|
---|
| 678 | } elsif (${$args{val}} =~ /^\d+$/) {
|
---|
| 679 | # bare number. This can be expanded to either a v4 or v6 zone
|
---|
| 680 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
| 681 | } else {
|
---|
| 682 | # $deity-only-knows what kind of gibberish we've been given. Only usable as a formal .arpa name.
|
---|
| 683 | # Append ARPAZONE to be replaced with the formal .arpa zone name when converted to a live record.
|
---|
| 684 | ${$args{val}} =~ s/\.*$/.ARPAZONE/ unless ${$args{val}} =~ /ARPAZONE$/;
|
---|
| 685 | }
|
---|
| 686 | } elsif (${$args{val}} =~ /^[a-fA-F0-9:]+$/) {
|
---|
| 687 | # v6 or fragment; pray it's not complete gibberish
|
---|
| 688 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
[234] | 689 | } else {
|
---|
[620] | 690 | # $deity-only-knows what kind of gibberish we've been given. Only usable as a formal .arpa name.
|
---|
| 691 | # Append ARPAZONE to be replaced with the formal .arpa zone name when converted to a live record.
|
---|
| 692 | ${$args{val}} .= ".ARPAZONE" unless ${$args{val}} =~ /ARPAZONE$/;
|
---|
[234] | 693 | }
|
---|
[620] | 694 | } else {
|
---|
| 695 | return ('FAIL', "PTR records are not supported in default record sets for forward zones (domains)");
|
---|
[232] | 696 | }
|
---|
[620] | 697 | } else {
|
---|
| 698 | if ($args{revrec} eq 'y') {
|
---|
| 699 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 700 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
[232] | 701 |
|
---|
[620] | 702 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
[249] | 703 |
|
---|
[620] | 704 | if (${$args{val}} =~ /\.arpa$/) {
|
---|
| 705 | # Check that it's well-formed
|
---|
| 706 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 707 |
|
---|
| 708 | # Check if it's a proper formal .arpa name for an IP, and renormalize it to the IP
|
---|
| 709 | # value if so. I can't see why someone would voluntarily work with those instead of
|
---|
| 710 | # the natural IP values but what the hey.
|
---|
| 711 | my ($code,$tmp) = _zone2cidr(${$args{val}});
|
---|
| 712 | ${$args{val}} = $tmp->addr if $code ne 'FAIL';
|
---|
[272] | 713 | } else {
|
---|
[620] | 714 | # not a formal .arpa name, so it should be an IP value. Validate...
|
---|
| 715 | return ('FAIL', "${$args{val}} is not a valid IP value")
|
---|
| 716 | unless ${$args{val}} =~ /^(?:\d+\.\d+\.\d+\.\d+|[a-fA-F0-9:]+)$/;
|
---|
| 717 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
| 718 | or return ('FAIL', "IP/value looks like an IP address but isn't valid");
|
---|
| 719 | # ... and normalize.
|
---|
| 720 | ${$args{val}} = $args{addr}->addr;
|
---|
[272] | 721 | }
|
---|
[620] | 722 | # Validate PTR target for form.
|
---|
| 723 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 724 | } else { # revrec ne 'y'
|
---|
| 725 | # Fetch the domain and append if the passed hostname isn't within it.
|
---|
| 726 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
| 727 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 728 | # Validate hostname and target for form
|
---|
| 729 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 730 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
[249] | 731 | }
|
---|
[620] | 732 | }
|
---|
[272] | 733 |
|
---|
[620] | 734 | # Multiple PTR records do NOT generally do what most people believe they do,
|
---|
| 735 | # and tend to fail in the most awkward way possible. Check and warn.
|
---|
| 736 |
|
---|
| 737 | my $chkbase = ${$args{val}};;
|
---|
| 738 | my $hostcol = 'val'; # Reverse zone hostnames are stored "backwards"
|
---|
| 739 | if ($args{revrec} eq 'n') { # PTRs in forward zones should be rare.
|
---|
| 740 | $chkbase = ${$args{host}};
|
---|
| 741 | $hostcol = 'host';
|
---|
[232] | 742 | }
|
---|
[620] | 743 | my @checkvals = ($chkbase);
|
---|
| 744 | if ($chkbase =~ /,/) {
|
---|
| 745 | # push . and :: variants into checkvals if $chkbase has ,
|
---|
| 746 | my $tmp;
|
---|
| 747 | ($tmp = $chkbase) =~ s/,/./;
|
---|
| 748 | push @checkvals, $tmp;
|
---|
| 749 | ($tmp = $chkbase) =~ s/,/::/;
|
---|
| 750 | push @checkvals, $tmp;
|
---|
| 751 | }
|
---|
[232] | 752 |
|
---|
[620] | 753 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE $hostcol = ?");
|
---|
| 754 | foreach my $checkme (@checkvals) {
|
---|
| 755 | if ($args{update}) {
|
---|
| 756 | # $args{update} contains the ID of the record being updated. If the list of records that matches
|
---|
| 757 | # the new hostname specification doesn't include this, the change effectively adds a new PTR that's
|
---|
| 758 | # the same as one or more existing ones.
|
---|
| 759 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 760 | " WHERE val = ?", undef, ($checkme)) };
|
---|
| 761 | $warnflag .= "PTR record for $checkme already exists; adding another will probably not do what you want"
|
---|
| 762 | if @ptrs && (!grep /^$args{update}$/, @ptrs);
|
---|
| 763 | } else {
|
---|
| 764 | # New record. Always warn if a PTR exists
|
---|
| 765 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 766 | " WHERE $hostcol = ?", undef, ($checkme));
|
---|
| 767 | $warnflag .= "PTR record for $checkme already exists; adding another will probably not do what you want"
|
---|
| 768 | if $ptrcount;
|
---|
| 769 | }
|
---|
| 770 | }
|
---|
| 771 |
|
---|
| 772 | return ('WARN',$warnflag) if $warnflag;
|
---|
| 773 |
|
---|
[228] | 774 | return ('OK','OK');
|
---|
| 775 | } # done PTR record
|
---|
| 776 |
|
---|
| 777 | # MX record
|
---|
| 778 | sub _validate_15 {
|
---|
[467] | 779 | my $self = shift;
|
---|
| 780 | my $dbh = $self->{dbh};
|
---|
[230] | 781 |
|
---|
| 782 | my %args = @_;
|
---|
| 783 |
|
---|
[622] | 784 | # only for strict type restrictions
|
---|
| 785 | # return ('FAIL', 'Reverse zones cannot contain MX records') if $args{revrec} eq 'y';
|
---|
[230] | 786 |
|
---|
| 787 | return ('FAIL', "Distance is required for MX records") unless defined(${$args{dist}});
|
---|
| 788 | ${$args{dist}} =~ s/\s*//g;
|
---|
| 789 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
|
---|
| 790 |
|
---|
| 791 | ${$args{fields}} = "distance,";
|
---|
| 792 | push @{$args{vallist}}, ${$args{dist}};
|
---|
| 793 |
|
---|
[622] | 794 | if ($args{revrec} eq 'n') {
|
---|
| 795 | # MX target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 796 | return ('FAIL', "MX records cannot point directly to an IP address")
|
---|
| 797 | if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
[230] | 798 |
|
---|
[622] | 799 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 800 | # or the intended parent domain for live records.
|
---|
| 801 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
| 802 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 803 | } else {
|
---|
| 804 | # MX target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
| 805 | return ('FAIL', "MX records cannot point directly to an IP address")
|
---|
| 806 | if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
[273] | 807 |
|
---|
[622] | 808 | # MX records in reverse zones get stricter treatment. The UI bars adding them in
|
---|
| 809 | # reverse record sets, but we "need" to allow editing existing ones. And we'll allow
|
---|
| 810 | # editing them if some loon manually munges one into a default reverse record set.
|
---|
| 811 | if ($args{defrec} eq 'n') {
|
---|
| 812 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 813 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
| 814 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
| 815 | }
|
---|
| 816 |
|
---|
| 817 | ##enhance or ##fixme
|
---|
| 818 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design
|
---|
| 819 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
| 820 | ${$args{val}} =~ /\.arpa$/;
|
---|
| 821 |
|
---|
| 822 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
| 823 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 824 |
|
---|
| 825 | }
|
---|
| 826 |
|
---|
[228] | 827 | return ('OK','OK');
|
---|
| 828 | } # done MX record
|
---|
| 829 |
|
---|
| 830 | # TXT record
|
---|
| 831 | sub _validate_16 {
|
---|
[586] | 832 | my $self = shift;
|
---|
| 833 |
|
---|
| 834 | my %args = @_;
|
---|
| 835 |
|
---|
[623] | 836 | if ($args{revrec} eq 'n') {
|
---|
[586] | 837 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 838 | # or the intended parent domain for live records.
|
---|
| 839 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
| 840 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
[623] | 841 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
| 842 | } else {
|
---|
| 843 | # We don't coerce reverse "hostnames" into the zone, mainly because we store most sane
|
---|
| 844 | # records as IP values, not .arpa names.
|
---|
| 845 | if ($args{defrec} eq 'n') {
|
---|
| 846 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
| 847 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
| 848 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
| 849 | }
|
---|
| 850 |
|
---|
| 851 | ##enhance or ##fixme
|
---|
| 852 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design
|
---|
| 853 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
| 854 | ${$args{val}} =~ /\.arpa$/;
|
---|
[586] | 855 | }
|
---|
| 856 |
|
---|
[231] | 857 | # Could arguably put a WARN return here on very long (>512) records
|
---|
[228] | 858 | return ('OK','OK');
|
---|
| 859 | } # done TXT record
|
---|
| 860 |
|
---|
| 861 | # RP record
|
---|
| 862 | sub _validate_17 {
|
---|
[623] | 863 | # Probably have to validate these separately some day. Call _validate_16() above since
|
---|
| 864 | # they're otherwise very similar
|
---|
| 865 | return _validate_16(@_);
|
---|
[228] | 866 | } # done RP record
|
---|
| 867 |
|
---|
| 868 | # AAAA record
|
---|
| 869 | sub _validate_28 {
|
---|
[467] | 870 | my $self = shift;
|
---|
| 871 | my $dbh = $self->{dbh};
|
---|
[229] | 872 |
|
---|
[230] | 873 | my %args = @_;
|
---|
[229] | 874 |
|
---|
[230] | 875 | return ('FAIL', 'Reverse zones cannot contain AAAA records') if $args{revrec} eq 'y';
|
---|
[229] | 876 |
|
---|
| 877 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 878 | # or the intended parent domain for live records.
|
---|
[467] | 879 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[230] | 880 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
[229] | 881 |
|
---|
| 882 | # Check IP is well-formed, and that it's a v6 address
|
---|
[232] | 883 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
|
---|
[230] | 884 | unless $args{addr} && $args{addr}->{isv6};
|
---|
[229] | 885 | # coerce IP/value to normalized form for storage
|
---|
[230] | 886 | ${$args{val}} = $args{addr}->addr;
|
---|
[229] | 887 |
|
---|
[228] | 888 | return ('OK','OK');
|
---|
| 889 | } # done AAAA record
|
---|
| 890 |
|
---|
| 891 | # SRV record
|
---|
| 892 | sub _validate_33 {
|
---|
[467] | 893 | my $self = shift;
|
---|
| 894 | my $dbh = $self->{dbh};
|
---|
[231] | 895 |
|
---|
| 896 | my %args = @_;
|
---|
| 897 |
|
---|
| 898 | # Not absolutely true but WTF use is an SRV record for a reverse zone?
|
---|
| 899 | return ('FAIL', 'Reverse zones cannot contain SRV records') if $args{revrec} eq 'y';
|
---|
| 900 |
|
---|
| 901 | return ('FAIL', "Distance is required for SRV records") unless defined(${$args{dist}});
|
---|
| 902 | ${$args{dist}} =~ s/\s*//g;
|
---|
| 903 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
|
---|
| 904 |
|
---|
[586] | 905 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 906 | # or the intended parent domain for live records.
|
---|
| 907 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
| 908 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 909 |
|
---|
[231] | 910 | return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]")
|
---|
| 911 | unless ${$args{host}} =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/;
|
---|
| 912 | return ('FAIL',"Port and weight are required for SRV records")
|
---|
| 913 | unless defined(${$args{weight}}) && defined(${$args{port}});
|
---|
| 914 | ${$args{weight}} =~ s/\s*//g;
|
---|
| 915 | ${$args{port}} =~ s/\s*//g;
|
---|
| 916 |
|
---|
| 917 | return ('FAIL',"Port and weight are required, and must be numeric")
|
---|
| 918 | unless ${$args{weight}} =~ /^\d+$/ && ${$args{port}} =~ /^\d+$/;
|
---|
| 919 |
|
---|
| 920 | ${$args{fields}} = "distance,weight,port,";
|
---|
| 921 | push @{$args{vallist}}, (${$args{dist}}, ${$args{weight}}, ${$args{port}});
|
---|
| 922 |
|
---|
[228] | 923 | return ('OK','OK');
|
---|
| 924 | } # done SRV record
|
---|
| 925 |
|
---|
| 926 | # Now the custom types
|
---|
| 927 |
|
---|
[232] | 928 | # A+PTR record. With a very little bit of magic we can also use this sub to validate AAAA+PTR. Whee!
|
---|
[228] | 929 | sub _validate_65280 {
|
---|
[467] | 930 | my $self = shift;
|
---|
| 931 | my $dbh = $self->{dbh};
|
---|
[232] | 932 |
|
---|
| 933 | my %args = @_;
|
---|
| 934 |
|
---|
| 935 | my $code = 'OK';
|
---|
| 936 | my $msg = 'OK';
|
---|
| 937 |
|
---|
| 938 | if ($args{defrec} eq 'n') {
|
---|
| 939 | # live record; revrec determines whether we validate the PTR or A component first.
|
---|
[233] | 940 |
|
---|
[232] | 941 | if ($args{revrec} eq 'y') {
|
---|
[467] | 942 | ($code,$msg) = $self->_validate_12(%args);
|
---|
[232] | 943 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 944 |
|
---|
[467] | 945 | # check A+PTR is really v4
|
---|
| 946 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
| 947 | if ${$args{rectype}} == 65280 && $args{addr}->{isv6};
|
---|
| 948 | # check AAAA+PTR is really v6
|
---|
| 949 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
|
---|
| 950 | if ${$args{rectype}} == 65281 && !$args{addr}->{isv6};
|
---|
| 951 |
|
---|
[232] | 952 | # Check if the reqested domain exists. If not, coerce the type down to PTR and warn.
|
---|
[467] | 953 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) {
|
---|
[272] | 954 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
| 955 | " as PTR instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
[232] | 956 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
| 957 | $msg = $addmsg if $code eq 'OK';
|
---|
| 958 | ${$args{rectype}} = $reverse_typemap{PTR};
|
---|
| 959 | return ('WARN', $msg);
|
---|
| 960 | }
|
---|
| 961 |
|
---|
[242] | 962 | # Add domain ID to field list and values
|
---|
| 963 | ${$args{fields}} .= "domain_id,";
|
---|
| 964 | push @{$args{vallist}}, ${$args{domid}};
|
---|
| 965 |
|
---|
[232] | 966 | } else {
|
---|
[467] | 967 | ($code,$msg) = $self->_validate_1(%args) if ${$args{rectype}} == 65280;
|
---|
| 968 | ($code,$msg) = $self->_validate_28(%args) if ${$args{rectype}} == 65281;
|
---|
[232] | 969 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 970 |
|
---|
| 971 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
| 972 | # work here since we don't *know* which parent to put it in.
|
---|
[233] | 973 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
[232] | 974 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
| 975 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
| 976 | if (!$revid) {
|
---|
[272] | 977 | $msg = "Record ".($args{update} ? 'updated' : 'added')." as ".(${$args{rectype}} == 65280 ? 'A' : 'AAAA').
|
---|
[232] | 978 | " instead of $typemap{${$args{rectype}}}; reverse zone not found for ${$args{val}}";
|
---|
| 979 | ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
| 980 | return ('WARN', $msg);
|
---|
| 981 | }
|
---|
| 982 |
|
---|
| 983 | # Check for duplicate PTRs. Note we don't have to play games with $code and $msg, because
|
---|
| 984 | # by definition there can't be duplicate PTRs if the reverse zone isn't managed here.
|
---|
[272] | 985 | if ($args{update}) {
|
---|
| 986 | # Record update. There should usually be an existing PTR (the record being updated)
|
---|
| 987 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 988 | " WHERE val = ?", undef, (${$args{val}})) };
|
---|
[273] | 989 | if (@ptrs && (!grep /^$args{update}$/, @ptrs)) {
|
---|
[272] | 990 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
|
---|
| 991 | $code = 'WARN';
|
---|
| 992 | }
|
---|
| 993 | } else {
|
---|
| 994 | # New record. Always warn if a PTR exists
|
---|
| 995 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 996 | " WHERE val = ?", undef, (${$args{val}}));
|
---|
| 997 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want"
|
---|
| 998 | if $ptrcount;
|
---|
| 999 | $code = 'WARN' if $ptrcount;
|
---|
[232] | 1000 | }
|
---|
| 1001 |
|
---|
[272] | 1002 | # my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 1003 | # " WHERE val = ?", undef, ${$args{val}});
|
---|
| 1004 | # if ($ptrcount) {
|
---|
| 1005 | # my $curid = $dbh->selectrow_array("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 1006 | # " WHERE val = ?
|
---|
| 1007 | # $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
|
---|
| 1008 | # $code = 'WARN';
|
---|
| 1009 | # }
|
---|
| 1010 |
|
---|
[232] | 1011 | ${$args{fields}} .= "rdns_id,";
|
---|
| 1012 | push @{$args{vallist}}, $revid;
|
---|
| 1013 | }
|
---|
| 1014 |
|
---|
[233] | 1015 | } else { # defrec eq 'y'
|
---|
| 1016 | if ($args{revrec} eq 'y') {
|
---|
[467] | 1017 | ($code,$msg) = $self->_validate_12(%args);
|
---|
[233] | 1018 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 1019 | if (${$args{rectype}} == 65280) {
|
---|
| 1020 | return ('FAIL',"A+PTR record must be a valid IPv4 address or fragment")
|
---|
| 1021 | if ${$args{val}} =~ /:/;
|
---|
[234] | 1022 | ${$args{val}} =~ s/^ZONE,/ZONE./; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
[233] | 1023 | } elsif (${$args{rectype}} == 65281) {
|
---|
| 1024 | return ('FAIL',"AAAA+PTR record must be a valid IPv6 address or fragment")
|
---|
| 1025 | if ${$args{val}} =~ /\./;
|
---|
[234] | 1026 | ${$args{val}} =~ s/^ZONE,/ZONE::/; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
[233] | 1027 | }
|
---|
| 1028 | } else {
|
---|
| 1029 | # This is easy. I also can't see a real use-case for A/AAAA+PTR in *all* forward
|
---|
| 1030 | # domains, since you wouldn't be able to substitute both domain and reverse zone
|
---|
| 1031 | # sanely, and you'd end up with guaranteed over-replicated PTR records that would
|
---|
| 1032 | # confuse the hell out of pretty much anything that uses them.
|
---|
[234] | 1033 | ##fixme: make this a config flag?
|
---|
[233] | 1034 | return ('FAIL', "$typemap{${$args{rectype}}} records not allowed in default domains");
|
---|
| 1035 | }
|
---|
[232] | 1036 | }
|
---|
| 1037 |
|
---|
| 1038 | return ($code, $msg);
|
---|
[228] | 1039 | } # done A+PTR record
|
---|
| 1040 |
|
---|
| 1041 | # AAAA+PTR record
|
---|
[232] | 1042 | # A+PTR above has been magicked to handle AAAA+PTR as well.
|
---|
[228] | 1043 | sub _validate_65281 {
|
---|
[232] | 1044 | return _validate_65280(@_);
|
---|
[228] | 1045 | } # done AAAA+PTR record
|
---|
| 1046 |
|
---|
| 1047 | # PTR template record
|
---|
| 1048 | sub _validate_65282 {
|
---|
[467] | 1049 | my $self = shift;
|
---|
| 1050 | my $dbh = $self->{dbh};
|
---|
[340] | 1051 |
|
---|
| 1052 | my %args = @_;
|
---|
| 1053 |
|
---|
| 1054 | # we're *this* >.< close to being able to just call _validate_12... unfortunately we can't, quite.
|
---|
| 1055 | if ($args{revrec} eq 'y') {
|
---|
| 1056 | if ($args{defrec} eq 'n') {
|
---|
[467] | 1057 | return ('FAIL', "Template block ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
| 1058 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
[340] | 1059 | ##fixme: warn if $args{val} is not /31 or larger block?
|
---|
| 1060 | ${$args{val}} = "$args{addr}";
|
---|
| 1061 | } else {
|
---|
| 1062 | if (${$args{val}} =~ /\./) {
|
---|
| 1063 | # looks like a v4 or fragment
|
---|
| 1064 | if (${$args{val}} =~ m|^\d+\.\d+\.\d+\.\d+(?:/\d+)?$|) {
|
---|
| 1065 | # woo! a complete IP! validate it and normalize, or fail.
|
---|
| 1066 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
| 1067 | or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
|
---|
| 1068 | ${$args{val}} = "$args{addr}";
|
---|
| 1069 | } else {
|
---|
| 1070 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
| 1071 | }
|
---|
| 1072 | } elsif (${$args{val}} =~ /[a-f:]/) {
|
---|
| 1073 | # looks like a v6 or fragment
|
---|
| 1074 | ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
|
---|
| 1075 | if ($args{addr}) {
|
---|
| 1076 | if ($args{addr}->addr =~ /^0/) {
|
---|
| 1077 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
| 1078 | } else {
|
---|
| 1079 | ${$args{val}} = "$args{addr}";
|
---|
| 1080 | }
|
---|
| 1081 | }
|
---|
| 1082 | } else {
|
---|
| 1083 | # bare number (probably). These could be v4 or v6, so we'll
|
---|
| 1084 | # expand on these on creation of a reverse zone.
|
---|
| 1085 | ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
|
---|
| 1086 | }
|
---|
| 1087 | }
|
---|
| 1088 | ##fixme: validate %-patterns?
|
---|
| 1089 |
|
---|
| 1090 | # Unlike single PTR records, there is absolutely no way to sanely support multiple
|
---|
| 1091 | # PTR templates for the same block, since they expect to expand to all the individual
|
---|
| 1092 | # IPs on export. Nested templates should be supported though.
|
---|
| 1093 |
|
---|
| 1094 | my @checkvals = (${$args{val}});
|
---|
| 1095 | if (${$args{val}} =~ /,/) {
|
---|
| 1096 | # push . and :: variants into checkvals if val has ,
|
---|
| 1097 | my $tmp;
|
---|
| 1098 | ($tmp = ${$args{val}}) =~ s/,/./;
|
---|
| 1099 | push @checkvals, $tmp;
|
---|
| 1100 | ($tmp = ${$args{val}}) =~ s/,/::/;
|
---|
| 1101 | push @checkvals, $tmp;
|
---|
| 1102 | }
|
---|
| 1103 | ##fixme: this feels wrong still - need to restrict template pseudorecords to One Of Each
|
---|
| 1104 | # Per Netblock such that they don't conflict on export
|
---|
| 1105 | my $typeck;
|
---|
| 1106 | # type 65282 -> ptr template -> look for any of 65282, 65283, 65284
|
---|
| 1107 | $typeck = 'type=65283 OR type=65284' if ${$args{rectype}} == 65282;
|
---|
| 1108 | # type 65283 -> a+ptr template -> v4 -> look for 65282 or 65283
|
---|
| 1109 | $typeck = 'type=65283' if ${$args{rectype}} == 65282;
|
---|
| 1110 | # type 65284 -> aaaa+ptr template -> v6 -> look for 65282 or 65284
|
---|
| 1111 | $typeck = 'type=65284' if ${$args{rectype}} == 65282;
|
---|
| 1112 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ? ".
|
---|
| 1113 | "AND (type=65282 OR $typeck)");
|
---|
| 1114 | foreach my $checkme (@checkvals) {
|
---|
| 1115 | $pcsth->execute($checkme);
|
---|
| 1116 | my ($rc) = $pcsth->fetchrow_array;
|
---|
[442] | 1117 | return ('FAIL', "Only one template pseudorecord may exist for a given IP block") if $rc > 1;
|
---|
[340] | 1118 | }
|
---|
| 1119 |
|
---|
| 1120 | } else {
|
---|
| 1121 | return ('FAIL', "Forward zones cannot contain PTR records");
|
---|
| 1122 | }
|
---|
| 1123 |
|
---|
[228] | 1124 | return ('OK','OK');
|
---|
| 1125 | } # done PTR template record
|
---|
| 1126 |
|
---|
| 1127 | # A+PTR template record
|
---|
| 1128 | sub _validate_65283 {
|
---|
[467] | 1129 | my $self = shift;
|
---|
| 1130 | my $dbh = $self->{dbh};
|
---|
[340] | 1131 |
|
---|
| 1132 | my %args = @_;
|
---|
| 1133 |
|
---|
| 1134 | my ($code,$msg) = ('OK','OK');
|
---|
| 1135 |
|
---|
| 1136 | ##fixme: need to fiddle things since A+PTR templates are acceptable in live
|
---|
| 1137 | # forward zones but not default records
|
---|
| 1138 | if ($args{defrec} eq 'n') {
|
---|
| 1139 | if ($args{revrec} eq 'n') {
|
---|
[467] | 1140 | ($code,$msg) = $self->_validate_1(%args) if ${$args{rectype}} == 65280;
|
---|
| 1141 | ($code,$msg) = $self->_validate_28(%args) if ${$args{rectype}} == 65281;
|
---|
[340] | 1142 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 1143 |
|
---|
| 1144 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
| 1145 | # work here since we don't *know* which parent to put it in.
|
---|
| 1146 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
| 1147 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
| 1148 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
| 1149 | # Fail if no match; we can't coerce a PTR-template type down to not include the PTR bit currently.
|
---|
| 1150 | if (!$revid) {
|
---|
| 1151 | $msg = "Can't ".($args{update} ? 'update' : 'add')." ${$args{host}}/${$args{val}} as ".
|
---|
| 1152 | "$typemap{${$args{rectype}}}: reverse zone not found for ${$args{val}}";
|
---|
| 1153 | ##fixme: add A template, AAAA template types?
|
---|
| 1154 | # ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
| 1155 | return ('FAIL', $msg);
|
---|
| 1156 | }
|
---|
| 1157 |
|
---|
| 1158 | # Add reverse zone ID to field list and values
|
---|
| 1159 | ${$args{fields}} .= "rdns_id,";
|
---|
| 1160 | push @{$args{vallist}}, $revid;
|
---|
| 1161 |
|
---|
| 1162 | } else {
|
---|
[467] | 1163 | return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
| 1164 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
[340] | 1165 | ${$args{val}} = "$args{addr}";
|
---|
| 1166 |
|
---|
[467] | 1167 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) {
|
---|
[340] | 1168 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
| 1169 | " as PTR template instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
| 1170 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
| 1171 | $msg = $addmsg if $code eq 'OK';
|
---|
| 1172 | ${$args{rectype}} = 65282;
|
---|
| 1173 | return ('WARN', $msg);
|
---|
| 1174 | }
|
---|
| 1175 |
|
---|
| 1176 | # Add domain ID to field list and values
|
---|
| 1177 | ${$args{fields}} .= "domain_id,";
|
---|
| 1178 | push @{$args{vallist}}, ${$args{domid}};
|
---|
| 1179 | }
|
---|
| 1180 |
|
---|
| 1181 | } else {
|
---|
[467] | 1182 | my ($code,$msg) = $self->_validate_65282(%args);
|
---|
[340] | 1183 | return ($code, $msg) if $code eq 'FAIL';
|
---|
| 1184 | # get domain, check against ${$args{name}}
|
---|
| 1185 | }
|
---|
| 1186 |
|
---|
[228] | 1187 | return ('OK','OK');
|
---|
| 1188 | } # done AAAA+PTR template record
|
---|
| 1189 |
|
---|
| 1190 | # AAAA+PTR template record
|
---|
| 1191 | sub _validate_65284 {
|
---|
| 1192 | return ('OK','OK');
|
---|
| 1193 | } # done AAAA+PTR template record
|
---|
| 1194 |
|
---|
[342] | 1195 | # Delegation record
|
---|
[345] | 1196 | # This is essentially a specialized clone of the NS record, primarily useful
|
---|
| 1197 | # for delegating IPv4 sub-/24 reverse blocks
|
---|
[342] | 1198 | sub _validate_65285 {
|
---|
[467] | 1199 | my $self = shift;
|
---|
| 1200 | my $dbh = $self->{dbh};
|
---|
[345] | 1201 |
|
---|
| 1202 | my %args = @_;
|
---|
| 1203 |
|
---|
| 1204 | # Almost, but not quite, identical to NS record validation.
|
---|
| 1205 |
|
---|
| 1206 | # Check that the target of the record is within the parent.
|
---|
| 1207 | # Yes, host<->val are mixed up here; can't see a way to avoid it. :(
|
---|
| 1208 | if ($args{defrec} eq 'n') {
|
---|
| 1209 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
| 1210 | if ($args{revrec} eq 'y') {
|
---|
| 1211 | my $tmpip = NetAddr::IP->new(${$args{val}});
|
---|
[467] | 1212 | my $pname = $self->revName($args{id});
|
---|
[345] | 1213 | return ('FAIL',"${$args{val}} not within $pname")
|
---|
[467] | 1214 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$tmpip);
|
---|
[345] | 1215 | # Normalize
|
---|
| 1216 | ${$args{val}} = "$tmpip";
|
---|
| 1217 | } else {
|
---|
[467] | 1218 | my $pname = $self->domainName($args{id});
|
---|
[345] | 1219 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 1220 | }
|
---|
| 1221 | } else {
|
---|
| 1222 | return ('FAIL',"Delegation records are not permitted in default record sets");
|
---|
| 1223 | }
|
---|
[342] | 1224 | return ('OK','OK');
|
---|
| 1225 | }
|
---|
[228] | 1226 |
|
---|
[617] | 1227 | # Subs not specific to a particular record type
|
---|
[342] | 1228 |
|
---|
[617] | 1229 | # Convert $$host and/or $$val to lowercase as appropriate.
|
---|
| 1230 | # Should only be called if $self->{lowercase} is true.
|
---|
| 1231 | # $rectype is also a reference for caller convenience
|
---|
| 1232 | sub _caseclean {
|
---|
| 1233 | my ($rectype, $host, $val, $defrec, $revrec) = @_;
|
---|
| 1234 |
|
---|
| 1235 | # Can't case-squash default records, due to DOMAIN, ZONE, and ADMINDOMAIN templating
|
---|
| 1236 | return if $defrec eq 'y';
|
---|
| 1237 |
|
---|
| 1238 | if ($typemap{$$rectype} eq 'TXT' || $typemap{$$rectype} eq 'SPF') {
|
---|
| 1239 | # TXT records should preserve user entry in the string.
|
---|
| 1240 | # SPF records are a duplicate of TXT with a new record type value (99)
|
---|
| 1241 | $$host = lc($$host) if $revrec eq 'n'; # only lowercase $$host on live forward TXT; preserve TXT content
|
---|
| 1242 | $$val = lc($$val) if $revrec eq 'y'; # only lowercase $$val on live reverse TXT; preserve TXT content
|
---|
| 1243 | } else {
|
---|
| 1244 | # Non-TXT, live records, are fully case-insensitive
|
---|
| 1245 | $$host = lc($$host);
|
---|
| 1246 | $$val = lc($$val);
|
---|
| 1247 | } # $typemap{$$rectype} else
|
---|
| 1248 |
|
---|
| 1249 | } # _caseclean()
|
---|
| 1250 |
|
---|
| 1251 |
|
---|
[265] | 1252 | ##
|
---|
| 1253 | ## Record data substitution subs
|
---|
| 1254 | ##
|
---|
[228] | 1255 |
|
---|
[298] | 1256 | # Replace ZONE in hostname, or create (most of) the actual proper zone name
|
---|
[265] | 1257 | sub _ZONE {
|
---|
| 1258 | my $zone = shift;
|
---|
| 1259 | my $string = shift;
|
---|
| 1260 | my $fr = shift || 'f'; # flag for forward/reverse order? nb: ignored for IP
|
---|
[298] | 1261 | my $sep = shift || '-'; # Separator character - unlikely we'll ever need more than . or -
|
---|
[265] | 1262 |
|
---|
[298] | 1263 | my $prefix;
|
---|
[265] | 1264 |
|
---|
| 1265 | $string =~ s/,/./ if !$zone->{isv6};
|
---|
| 1266 | $string =~ s/,/::/ if $zone->{isv6};
|
---|
| 1267 |
|
---|
[298] | 1268 | # Subbing ZONE in the host. We need to properly ID the netblock range
|
---|
| 1269 | # The subbed text should have "network IP with trailing zeros stripped" for
|
---|
| 1270 | # blocks lined up on octet (for v4) or hex-quad (for v6) boundaries
|
---|
| 1271 | # For blocks that do NOT line up on these boundaries, we take the most
|
---|
| 1272 | # significant octet or 16-bit chunk of the "broadcast" IP and append it
|
---|
| 1273 | # after a double-dash
|
---|
| 1274 | # ie:
|
---|
| 1275 | # 8.0.0.0/6 -> 8.0.0.0 -> 11.255.255.255; sub should be 8--11
|
---|
| 1276 | # 10.0.0.0/12 -> 10.0.0.0 -> 10.0.0.0 -> 10.15.255.255; sub should be 10-0--15
|
---|
| 1277 | # 192.168.4.0/22 -> 192.168.4.0 -> 192.168.7.255; sub should be 192-168-4--7
|
---|
| 1278 | # 192.168.0.8/29 -> 192.168.0.8 -> 192.168.0.15; sub should be 192-168-0-8--15
|
---|
| 1279 | # Similar for v6
|
---|
[265] | 1280 |
|
---|
[298] | 1281 | if (!$zone->{isv6}) { # IPv4
|
---|
| 1282 |
|
---|
| 1283 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
| 1284 | # a funky subnet that had host bits set.
|
---|
| 1285 | my $bc = $zone->broadcast->addr;
|
---|
| 1286 |
|
---|
| 1287 | if ($zone->masklen > 24) {
|
---|
| 1288 | $bc =~ s/^\d+\.\d+\.\d+\.//;
|
---|
| 1289 | } elsif ($zone->masklen > 16) {
|
---|
| 1290 | $prefix =~ s/\.0$//;
|
---|
| 1291 | $bc =~ s/^\d+\.\d+\.//;
|
---|
| 1292 | } elsif ($zone->masklen > 8) {
|
---|
| 1293 | $bc =~ s/^\d+\.//;
|
---|
| 1294 | $prefix =~ s/\.0\.0$//;
|
---|
| 1295 | } else {
|
---|
| 1296 | $prefix =~ s/\.0\.0\.0$//;
|
---|
| 1297 | }
|
---|
| 1298 | if ($zone->masklen % 8) {
|
---|
| 1299 | $bc =~ s/(\.255)+$//;
|
---|
| 1300 | $prefix .= "--$bc"; #"--".zone->masklen; # use range or mask length?
|
---|
| 1301 | }
|
---|
| 1302 | if ($fr eq 'f') {
|
---|
| 1303 | $prefix =~ s/\.+/$sep/g;
|
---|
| 1304 | } else {
|
---|
| 1305 | $prefix = join($sep, reverse(split(/\./, $prefix)));
|
---|
| 1306 | }
|
---|
| 1307 |
|
---|
| 1308 | } else { # IPv6
|
---|
| 1309 |
|
---|
| 1310 | if ($fr eq 'f') {
|
---|
| 1311 |
|
---|
| 1312 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
| 1313 | # a funky subnet that had host bits set.
|
---|
[265] | 1314 | my $bc = $zone->broadcast->addr;
|
---|
| 1315 | if (($zone->masklen % 16) != 0) {
|
---|
[298] | 1316 | # Strip trailing :0 off $prefix, and :ffff off the broadcast IP
|
---|
| 1317 | for (my $i=0; $i<(7-int($zone->masklen / 16)); $i++) {
|
---|
| 1318 | $prefix =~ s/:0$//;
|
---|
| 1319 | $bc =~ s/:ffff$//;
|
---|
| 1320 | }
|
---|
| 1321 | # Strip the leading 16-bit chunks off the front of the broadcast IP
|
---|
| 1322 | $bc =~ s/^([a-f0-9]+:)+//;
|
---|
| 1323 | # Append the remaining 16-bit chunk to the prefix after "--"
|
---|
| 1324 | $prefix .= "--$bc";
|
---|
[265] | 1325 | } else {
|
---|
[298] | 1326 | # Strip off :0 from the end until we reach the netblock length.
|
---|
| 1327 | for (my $i=0; $i<(8-$zone->masklen / 16); $i++) {
|
---|
[265] | 1328 | $prefix =~ s/:0$//;
|
---|
[298] | 1329 | }
|
---|
[265] | 1330 | }
|
---|
[298] | 1331 | # Actually deal with the separator
|
---|
| 1332 | $prefix =~ s/:/$sep/g;
|
---|
| 1333 |
|
---|
| 1334 | } else { # $fr eq 'f'
|
---|
| 1335 |
|
---|
| 1336 | $prefix = $zone->network->full; # Just In Case someone managed to slip in
|
---|
| 1337 | # a funky subnet that had host bits set.
|
---|
| 1338 | my $bc = $zone->broadcast->full;
|
---|
| 1339 | $prefix =~ s/://g; # clean these out since they're not spaced right for this case
|
---|
| 1340 | $bc =~ s/://g;
|
---|
| 1341 | # Strip trailing 0 off $prefix, and f off the broadcast IP, to match the mask length
|
---|
| 1342 | for (my $i=0; $i<(31-int($zone->masklen / 4)); $i++) {
|
---|
| 1343 | $prefix =~ s/0$//;
|
---|
| 1344 | $bc =~ s/f$//;
|
---|
| 1345 | }
|
---|
| 1346 | # Split and reverse the order of the nibbles in the network/broadcast IPs
|
---|
[332] | 1347 | # trim another 0 for nibble-aligned blocks first, but only if we really have a block, not an IP
|
---|
| 1348 | $prefix =~ s/0$// if $zone->masklen % 4 == 0 && $zone->masklen != 128;
|
---|
[298] | 1349 | my @nbits = reverse split //, $prefix;
|
---|
| 1350 | my @bbits = reverse split //, $bc;
|
---|
| 1351 | # Handle the sub-nibble case. Eww. I feel dirty supporting this...
|
---|
| 1352 | $nbits[0] = "$nbits[0]-$bbits[0]" if ($zone->masklen % 4) != 0;
|
---|
| 1353 | # Glue it back together
|
---|
| 1354 | $prefix = join($sep, @nbits);
|
---|
| 1355 |
|
---|
| 1356 | } # $fr ne 'f'
|
---|
| 1357 |
|
---|
| 1358 | } # $zone->{isv6}
|
---|
| 1359 |
|
---|
| 1360 | # Do the substitution, finally
|
---|
| 1361 | $string =~ s/ZONE/$prefix/;
|
---|
| 1362 | $string =~ s/--/-/ if $sep ne '-'; # - as separator needs extra help for sub-octet v4 netblocks
|
---|
| 1363 | return $string;
|
---|
| 1364 | } # done _ZONE()
|
---|
| 1365 |
|
---|
| 1366 | # Not quite a substitution sub, but placed here as it's basically the inverse of above;
|
---|
| 1367 | # given the .arpa zone name, return the CIDR netblock the zone is for.
|
---|
[304] | 1368 | # Supports v4 non-octet/non-classful netblocks as per the method outlined in the Grasshopper Book (2nd Ed p217-218)
|
---|
[298] | 1369 | # Does NOT support non-quad v6 netblocks via the same scheme; it shouldn't ever be necessary.
|
---|
| 1370 | # Takes a nominal .arpa zone name, returns a success code and NetAddr::IP, or a fail code and message
|
---|
| 1371 | sub _zone2cidr {
|
---|
| 1372 | my $zone = shift;
|
---|
| 1373 |
|
---|
| 1374 | my $cidr;
|
---|
[301] | 1375 | my $tmpcidr;
|
---|
| 1376 | my $warnmsg = '';
|
---|
[298] | 1377 |
|
---|
| 1378 | if ($zone =~ /\.in-addr\.arpa\.?$/) {
|
---|
| 1379 | # v4 revzone, formal zone name type
|
---|
| 1380 | my $tmpzone = $zone;
|
---|
[583] | 1381 | return ('FAIL', "Non-numerics in apparent IPv4 reverse zone name [$tmpzone]")
|
---|
| 1382 | if $tmpzone !~ m{^(?:\d+[/-])?[\d\.]+\.in-addr\.arpa\.?$};
|
---|
[298] | 1383 | $tmpzone =~ s/\.in-addr\.arpa\.?//;
|
---|
| 1384 |
|
---|
| 1385 | # Snag the octet pieces
|
---|
| 1386 | my @octs = split /\./, $tmpzone;
|
---|
| 1387 |
|
---|
| 1388 | # Map result of a range manipulation to a mask length change. Cheaper than finding the 2-root of $octets[0]+1.
|
---|
[304] | 1389 | # Note we will not support /31 blocks, mostly due to issues telling "24-31" -> .24/29 apart from
|
---|
| 1390 | # "24-31" -> .24/31", with a litte bit of "/31 is icky".
|
---|
| 1391 | my %maskmap = ( 3 => 2, 7 => 3, 15 => 4, 31 => 5, 63 => 6, 127 => 7,
|
---|
| 1392 | 30 => 2, 29 => 3, 28 => 4, 27 => 5, 26 => 6, 25 => 7
|
---|
| 1393 | );
|
---|
[298] | 1394 |
|
---|
| 1395 | # Handle "range" blocks, eg, 80-83.168.192.in-addr.arpa (192.168.80.0/22)
|
---|
| 1396 | # Need to take the size of the range to offset the basic octet-based mask length,
|
---|
| 1397 | # and make sure the first number in the range gets used as the network address for the block
|
---|
[304] | 1398 | # Alternate form: The second number is actually the real netmask, not the end of the range.
|
---|
[298] | 1399 | my $masklen = 0;
|
---|
[571] | 1400 | if ($octs[0] =~ m{^((\d+)[/-](\d+))$}) { # take the range...
|
---|
[307] | 1401 | if (24 < $3 && $3 < 31) {
|
---|
[304] | 1402 | # we have a real netmask
|
---|
[307] | 1403 | $masklen = -$maskmap{$3};
|
---|
[304] | 1404 | } else {
|
---|
| 1405 | # we have a range. NB: only real CIDR ranges are supported
|
---|
[307] | 1406 | $masklen -= $maskmap{-(eval $1)}; # find the mask base...
|
---|
[304] | 1407 | }
|
---|
[307] | 1408 | $octs[0] = $2; # set the base octet of the range...
|
---|
[265] | 1409 | }
|
---|
[298] | 1410 | @octs = reverse @octs; # We can reverse the octet pieces now that we've extracted and munged any ranges
|
---|
[265] | 1411 |
|
---|
[304] | 1412 | # arguably we should only allow sub-octet range/mask in-addr.arpa
|
---|
| 1413 | # specifications in the least significant octet, but the code is
|
---|
| 1414 | # simpler if we deal with sub-octet delegations at any level.
|
---|
| 1415 |
|
---|
[298] | 1416 | # Now we find the "true" mask with the aid of the "base" calculated above
|
---|
| 1417 | if ($#octs == 0) {
|
---|
| 1418 | $masklen += 8;
|
---|
| 1419 | $tmpcidr = "$octs[0].0.0.0/$masklen"; # really hope we don't see one of these very often.
|
---|
| 1420 | } elsif ($#octs == 1) {
|
---|
| 1421 | $masklen += 16;
|
---|
| 1422 | $tmpcidr = "$octs[0].$octs[1].0.0/$masklen";
|
---|
| 1423 | } elsif ($#octs == 2) {
|
---|
| 1424 | $masklen += 24;
|
---|
| 1425 | $tmpcidr = "$octs[0].$octs[1].$octs[2].0/$masklen";
|
---|
[265] | 1426 | } else {
|
---|
[298] | 1427 | $masklen += 32;
|
---|
| 1428 | $tmpcidr = "$octs[0].$octs[1].$octs[2].$octs[3]/$masklen";
|
---|
[265] | 1429 | }
|
---|
| 1430 |
|
---|
[583] | 1431 | } elsif ($zone =~ /\.ip6\.arpa\.?$/) {
|
---|
[298] | 1432 | # v6 revzone, formal zone name type
|
---|
| 1433 | my $tmpzone = $zone;
|
---|
[583] | 1434 | ##fixme: if-n-when we decide we can support sub-nibble v6 zone names, we'll need to change this segment
|
---|
| 1435 | return ('FAIL', "Non-hexadecimals in apparent IPv6 reverse zone name [$tmpzone]")
|
---|
| 1436 | if $tmpzone !~ /^[a-fA-F\d\.]+\.ip6\.arpa\.?$/;
|
---|
[298] | 1437 | $tmpzone =~ s/\.ip6\.arpa\.?//;
|
---|
| 1438 | my @quads = reverse(split(/\./, $tmpzone));
|
---|
| 1439 | $warnmsg .= "Apparent sub-/64 IPv6 reverse zone\n" if $#quads > 15;
|
---|
| 1440 | my $nc;
|
---|
| 1441 | foreach (@quads) {
|
---|
[301] | 1442 | $tmpcidr .= $_;
|
---|
[583] | 1443 | $tmpcidr .= ":" if ++$nc % 4 == 0 && $nc < $#quads;
|
---|
[298] | 1444 | }
|
---|
| 1445 | my $nq = 1 if $nc % 4 != 0;
|
---|
| 1446 | my $mask = $nc * 4; # need to do this here because we probably increment it below
|
---|
| 1447 | while ($nc++ % 4 != 0) {
|
---|
[301] | 1448 | $tmpcidr .= "0";
|
---|
[298] | 1449 | }
|
---|
[583] | 1450 | # polish it off with trailing ::/mask if this is a CIDR block instead of an IP
|
---|
| 1451 | $tmpcidr .= "::/$mask" if $mask != 128;
|
---|
[298] | 1452 | }
|
---|
[301] | 1453 |
|
---|
| 1454 | # Just to be sure, use NetAddr::IP to validate. Saves a lot of nasty regex watching for valid octet values.
|
---|
| 1455 | return ('FAIL', "Invalid zone $zone (apparent netblock $tmpcidr)")
|
---|
| 1456 | unless $cidr = NetAddr::IP->new($tmpcidr);
|
---|
| 1457 |
|
---|
| 1458 | if ($warnmsg) {
|
---|
| 1459 | $errstr = $warnmsg;
|
---|
| 1460 | return ('WARN', $cidr);
|
---|
| 1461 | }
|
---|
| 1462 | return ('OK', $cidr);
|
---|
[583] | 1463 | ##fixme: use wantarray() to decide what to return?
|
---|
[298] | 1464 | } # done _zone2cidr()
|
---|
[265] | 1465 |
|
---|
[337] | 1466 | # Record template %-parameter expansion, IPv4. Note that IPv6 doesn't
|
---|
| 1467 | # really have a sane way to handle this type of expansion at the moment
|
---|
| 1468 | # due to the size of the address space.
|
---|
| 1469 | # Takes a reference to a template string to be expanded, and an IP to use in the replacement.
|
---|
| 1470 | sub _template4_expand {
|
---|
| 1471 | my $tmpl = shift;
|
---|
| 1472 | my $ip = shift;
|
---|
[298] | 1473 |
|
---|
[337] | 1474 | my @ipparts = split /\./, $ip;
|
---|
| 1475 | my @iphex;
|
---|
| 1476 | my @ippad;
|
---|
| 1477 | for (@ipparts) {
|
---|
| 1478 | push @iphex, sprintf("%x", $_);
|
---|
[443] | 1479 | push @ippad, sprintf("%0.3u", $_);
|
---|
[337] | 1480 | }
|
---|
| 1481 |
|
---|
| 1482 | # IP substitutions in template records:
|
---|
| 1483 | #major patterns:
|
---|
| 1484 | #dashed IP, forward and reverse
|
---|
[532] | 1485 | #underscoreed IP, forward and reverse
|
---|
[337] | 1486 | #dotted IP, forward and reverse (even if forward is... dumb)
|
---|
[532] | 1487 | # -> %r for reverse, %i for forward, leading -, _, or . to indicate separator, defaults to -
|
---|
[337] | 1488 | # %r or %-r => %4d-%3d-%2d-%1d
|
---|
[532] | 1489 | # %_r => %4d_%3d_%2d_%1d
|
---|
[337] | 1490 | # %.r => %4d.%3d.%2d.%1d
|
---|
| 1491 | # %i or %-i => %1d-%2d-%3d-%4d
|
---|
[532] | 1492 | # %_i => %1d_%2d_%3d_%4d
|
---|
[337] | 1493 | # %.i => %1d.%2d.%3d.%4d
|
---|
| 1494 | $$tmpl =~ s/\%r/\%4d-\%3d-\%2d-\%1d/g;
|
---|
[532] | 1495 | $$tmpl =~ s/\%([-._])r/\%4d$1\%3d$1\%2d$1\%1d/g;
|
---|
[337] | 1496 | $$tmpl =~ s/\%i/\%1d-\%2d-\%3d-\%4d/g;
|
---|
[532] | 1497 | $$tmpl =~ s/\%([-._])i/\%1d$1\%2d$1\%3d$1\%4d/g;
|
---|
[337] | 1498 |
|
---|
| 1499 | #hex-coded IP
|
---|
| 1500 | # %h
|
---|
| 1501 | $$tmpl =~ s/\%h/$iphex[0]$iphex[1]$iphex[2]$iphex[3]/g;
|
---|
| 1502 |
|
---|
| 1503 | #IP as decimal-coded 32-bit value
|
---|
| 1504 | # %d
|
---|
| 1505 | my $iptmp = $ipparts[0]*256*256*256 + $ipparts[1]*256*256 + $ipparts[2]*256 + $ipparts[3];
|
---|
| 1506 | $$tmpl =~ s/\%d/$iptmp/g;
|
---|
| 1507 |
|
---|
| 1508 | #minor patterns (per-octet)
|
---|
| 1509 | # %[1234][dh0]
|
---|
| 1510 | #octet
|
---|
| 1511 | #hex-coded octet
|
---|
| 1512 | #0-padded octet
|
---|
| 1513 | $$tmpl =~ s/\%([1234])d/$ipparts[$1-1]/g;
|
---|
| 1514 | $$tmpl =~ s/\%([1234])h/$iphex[$1-1]/g;
|
---|
[443] | 1515 | $$tmpl =~ s/\%([1234])0/$ippad[$1-1]/g;
|
---|
[337] | 1516 | } # _template4_expand()
|
---|
| 1517 |
|
---|
[532] | 1518 | # Broad syntactic check on the hostname. Checks for valid characters, correctly-expandable template patterns.
|
---|
| 1519 | # Takes the hostname, type, and live/default and forward/reverse flags
|
---|
| 1520 | # Returns true/false, sets errstr on failures
|
---|
| 1521 | sub _check_hostname_form {
|
---|
| 1522 | my ($hname,$rectype,$defrec,$revrec) = @_;
|
---|
[337] | 1523 |
|
---|
[532] | 1524 | if ($hname =~ /\%/ && ($rectype == 65282 || $rectype == 65283) ) {
|
---|
| 1525 | my $tmphost = $hname;
|
---|
| 1526 | # we don't actually need to test with the real IP passed; that saves a bit of fiddling.
|
---|
| 1527 | _template4_expand(\$tmphost, '10.10.10.10');
|
---|
| 1528 | if ($tmphost =~ /\%/) {
|
---|
| 1529 | $errstr = "Invalid template $hname";
|
---|
| 1530 | return;
|
---|
| 1531 | }
|
---|
| 1532 | } elsif ($revrec eq 'y') {
|
---|
| 1533 | # Reverse zones don't support @ in hostnames
|
---|
| 1534 | # Also skip failure on revzone TXT records; the hostname contains the TXT content in that case.
|
---|
[619] | 1535 | if ($rectype != $reverse_typemap{TXT} && lc($hname) !~ /^(?:\*\.)?[0-9a-z_.-]+$/) {
|
---|
[532] | 1536 | $errstr = "Hostnames may not contain anything other than (0-9 a-z . _)";
|
---|
| 1537 | return;
|
---|
| 1538 | }
|
---|
| 1539 | } else {
|
---|
[600] | 1540 | if (lc($hname) !~ /^(?:\*\.)?(?:[0-9a-z_.-]+|@)$/) {
|
---|
[532] | 1541 | # Don't mention @, because it would be far too wordy to explain the nuance of @
|
---|
| 1542 | $errstr = "Hostnames may not contain anything other than (0-9 a-z . _)";
|
---|
| 1543 | return;
|
---|
| 1544 | }
|
---|
| 1545 | }
|
---|
| 1546 | return 1;
|
---|
| 1547 | } # _check_hostname_form()
|
---|
| 1548 |
|
---|
| 1549 |
|
---|
[228] | 1550 | ##
|
---|
[2] | 1551 | ## Initialization and cleanup subs
|
---|
| 1552 | ##
|
---|
| 1553 |
|
---|
[128] | 1554 | ## DNSDB::__cfgload()
|
---|
| 1555 | # Private sub to parse a config file and load it into %config
|
---|
[517] | 1556 | # Takes a filename and a hashref to put the parsed entries in
|
---|
[128] | 1557 | sub __cfgload {
|
---|
| 1558 | $errstr = '';
|
---|
| 1559 | my $cfgfile = shift;
|
---|
[517] | 1560 | my $cfg = shift;
|
---|
[131] | 1561 |
|
---|
[128] | 1562 | if (open CFG, "<$cfgfile") {
|
---|
| 1563 | while (<CFG>) {
|
---|
| 1564 | chomp;
|
---|
| 1565 | s/^\s*//;
|
---|
| 1566 | next if /^#/;
|
---|
| 1567 | next if /^$/;
|
---|
| 1568 | # hmm. more complex bits in this file might require [heading] headers, maybe?
|
---|
| 1569 | # $mode = $1 if /^\[(a-z)+]/;
|
---|
| 1570 | # DB connect info
|
---|
[517] | 1571 | $cfg->{dbname} = $1 if /^dbname\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1572 | $cfg->{dbuser} = $1 if /^dbuser\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1573 | $cfg->{dbpass} = $1 if /^dbpass\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1574 | $cfg->{dbhost} = $1 if /^dbhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
[128] | 1575 | # Mail settings
|
---|
[517] | 1576 | $cfg->{mailhost} = $1 if /^mailhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1577 | $cfg->{mailnotify} = $1 if /^mailnotify\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
| 1578 | $cfg->{mailsender} = $1 if /^mailsender\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
| 1579 | $cfg->{mailname} = $1 if /^mailname\s*=\s*([a-z0-9\s_.-]+)/i;
|
---|
| 1580 | $cfg->{orgname} = $1 if /^orgname\s*=\s*([a-z0-9\s_.,'-]+)/i;
|
---|
| 1581 | $cfg->{domain} = $1 if /^domain\s*=\s*([a-z0-9_.-]+)/i;
|
---|
[163] | 1582 | # session - note this is fed directly to CGI::Session
|
---|
[517] | 1583 | $cfg->{timeout} = $1 if /^[tT][iI][mM][eE][oO][uU][tT]\s*=\s*(\d+[smhdwMy]?)/;
|
---|
| 1584 | $cfg->{sessiondir} = $1 if m{^sessiondir\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
[201] | 1585 | # misc
|
---|
[517] | 1586 | $cfg->{log_failures} = $1 if /^log_failures\s*=\s*([a-z01]+)/i;
|
---|
| 1587 | $cfg->{perpage} = $1 if /^perpage\s*=\s*(\d+)/i;
|
---|
| 1588 | $cfg->{exportcache} = $1 if m{^exportcache\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
[559] | 1589 | $cfg->{usecache} = $1 if m{^usecache\s*=\s*([a-z01]+)}i;
|
---|
| 1590 | $cfg->{force_refresh} = $1 if /^force_refresh\s*=\s*([a-z01]+)/i;
|
---|
[542] | 1591 | $cfg->{lowercase} = $1 if /^lowercase\s*=\s*([a-z01]+)/i;
|
---|
[583] | 1592 | $cfg->{showrev_arpa} = $1 if /^showrev_arpa\s*=\s*([a-z]+)/i;
|
---|
[517] | 1593 | # not supported in dns.cgi yet
|
---|
| 1594 | # $cfg->{templatedir} = $1 if m{^templatedir\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
| 1595 | # $cfg->{templateoverride} = $1 if m{^templateoverride\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
[400] | 1596 | # RPC options
|
---|
[517] | 1597 | $cfg->{rpcmode} = $1 if /^rpc_mode\s*=\s*(socket|HTTP|XMLRPC)\s*$/i;
|
---|
| 1598 | $cfg->{maxfcgi} = $1 if /^max_fcgi_requests\s*=\s*(\d+)\s*$/i;
|
---|
[465] | 1599 | if (my ($tmp) = /^rpc_iplist\s*=\s*(.+)/i) {
|
---|
| 1600 | my @ips = split /[,\s]+/, $tmp;
|
---|
| 1601 | my $rpcsys = shift @ips;
|
---|
[517] | 1602 | push @{$cfg->{rpcacl}{$rpcsys}}, @ips;
|
---|
[400] | 1603 | }
|
---|
[128] | 1604 | }
|
---|
| 1605 | close CFG;
|
---|
| 1606 | } else {
|
---|
[517] | 1607 | $errstr = "Couldn't load configuration file $cfgfile: $!";
|
---|
[128] | 1608 | return;
|
---|
| 1609 | }
|
---|
| 1610 | return 1;
|
---|
| 1611 | } # end __cfgload()
|
---|
| 1612 |
|
---|
| 1613 |
|
---|
[2] | 1614 | ## DNSDB::connectDB()
|
---|
| 1615 | # Creates connection to DNS database.
|
---|
| 1616 | # Requires the database name, username, and password.
|
---|
[465] | 1617 | # Returns a handle to the db or undef on failure.
|
---|
[2] | 1618 | # Set up for a PostgreSQL db; could be any transactional DBMS with the
|
---|
| 1619 | # right changes.
|
---|
[465] | 1620 | # Called by new(); not intended to be called publicly.
|
---|
[2] | 1621 | sub connectDB {
|
---|
| 1622 | $errstr = '';
|
---|
[15] | 1623 | my $dbname = shift;
|
---|
| 1624 | my $user = shift;
|
---|
| 1625 | my $pass = shift;
|
---|
[2] | 1626 | my $dbh;
|
---|
| 1627 | my $DSN = "DBI:Pg:dbname=$dbname";
|
---|
| 1628 |
|
---|
| 1629 | my $host = shift;
|
---|
| 1630 | $DSN .= ";host=$host" if $host;
|
---|
| 1631 |
|
---|
| 1632 | # Note that we want to autocommit by default, and we will turn it off locally as necessary.
|
---|
| 1633 | # We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
|
---|
| 1634 | $dbh = DBI->connect($DSN, $user, $pass, {
|
---|
| 1635 | AutoCommit => 1,
|
---|
| 1636 | PrintError => 0
|
---|
[465] | 1637 | });
|
---|
| 1638 | if (!$dbh) {
|
---|
| 1639 | $errstr = $DBI::errstr;
|
---|
| 1640 | return;
|
---|
| 1641 | }
|
---|
| 1642 | #) if(!$dbh);
|
---|
[2] | 1643 |
|
---|
[465] | 1644 | local $dbh->{RaiseError} = 1;
|
---|
| 1645 |
|
---|
| 1646 | eval {
|
---|
[212] | 1647 | ##fixme: initialize the DB if we can't find the table (since, by definition, there's
|
---|
| 1648 | # nothing there if we can't select from it...)
|
---|
[465] | 1649 | my $tblsth = $dbh->prepare("SELECT count(*) FROM pg_catalog.pg_class WHERE relkind='r' AND relname=?");
|
---|
| 1650 | my ($tblcount) = $dbh->selectrow_array($tblsth, undef, ('misc'));
|
---|
| 1651 | # return (undef,$DBI::errstr) if $dbh->err;
|
---|
[212] | 1652 |
|
---|
| 1653 | #if ($tblcount == 0) {
|
---|
| 1654 | # # create tables one at a time, checking for each.
|
---|
| 1655 | # return (undef, "check table misc missing");
|
---|
| 1656 | #}
|
---|
| 1657 |
|
---|
| 1658 | # Return here if we can't select.
|
---|
| 1659 | # This should retrieve the dbversion key.
|
---|
[465] | 1660 | my $sth = $dbh->prepare("SELECT key,value FROM misc WHERE misc_id=1");
|
---|
| 1661 | $sth->execute();
|
---|
| 1662 | # return (undef,$DBI::errstr) if ($sth->err);
|
---|
[2] | 1663 |
|
---|
[212] | 1664 | ##fixme: do stuff to the DB on version mismatch
|
---|
| 1665 | # x.y series should upgrade on $DNSDB::VERSION > misc(key=>version)
|
---|
| 1666 | # DB should be downward-compatible; column defaults should give sane (if possibly
|
---|
| 1667 | # useless-and-needs-help) values in columns an older software stack doesn't know about.
|
---|
| 1668 |
|
---|
[2] | 1669 | # See if the select returned anything (or null data). This should
|
---|
| 1670 | # succeed if the select executed, but...
|
---|
[465] | 1671 | $sth->fetchrow();
|
---|
| 1672 | # return (undef,$DBI::errstr) if ($sth->err);
|
---|
[2] | 1673 |
|
---|
[465] | 1674 | $sth->finish;
|
---|
[2] | 1675 |
|
---|
[465] | 1676 | }; # wrapped DB checks
|
---|
| 1677 | if ($@) {
|
---|
| 1678 | $errstr = $@;
|
---|
| 1679 | return;
|
---|
| 1680 | }
|
---|
| 1681 |
|
---|
[2] | 1682 | # If we get here, we should be OK.
|
---|
[465] | 1683 | return $dbh;
|
---|
[2] | 1684 | } # end connectDB
|
---|
| 1685 |
|
---|
| 1686 |
|
---|
| 1687 | ## DNSDB::finish()
|
---|
| 1688 | # Cleans up after database handles and so on.
|
---|
| 1689 | # Requires a database handle
|
---|
| 1690 | sub finish {
|
---|
[465] | 1691 | my $self = shift;
|
---|
| 1692 | $self->{dbh}->disconnect;
|
---|
[2] | 1693 | } # end finish
|
---|
| 1694 |
|
---|
| 1695 |
|
---|
| 1696 | ## DNSDB::initGlobals()
|
---|
| 1697 | # Initialize global variables
|
---|
| 1698 | # NB: this does NOT include web-specific session variables!
|
---|
| 1699 | sub initGlobals {
|
---|
[465] | 1700 | my $self = shift;
|
---|
| 1701 | my $dbh = $self->{dbh};
|
---|
[2] | 1702 |
|
---|
[208] | 1703 | # load record types from database
|
---|
[228] | 1704 | my $sth = $dbh->prepare("SELECT val,name,stdflag FROM rectypes");
|
---|
[2] | 1705 | $sth->execute;
|
---|
[228] | 1706 | while (my ($recval,$recname,$stdflag) = $sth->fetchrow_array()) {
|
---|
[2] | 1707 | $typemap{$recval} = $recname;
|
---|
| 1708 | $reverse_typemap{$recname} = $recval;
|
---|
[228] | 1709 | # now we fill the record validation function hash
|
---|
| 1710 | if ($stdflag < 5) {
|
---|
| 1711 | my $fn = "_validate_$recval";
|
---|
| 1712 | $validators{$recval} = \&$fn;
|
---|
| 1713 | } else {
|
---|
| 1714 | my $fn = "sub { return ('FAIL','Type $recval ($recname) not supported'); }";
|
---|
| 1715 | $validators{$recval} = eval $fn;
|
---|
| 1716 | }
|
---|
[2] | 1717 | }
|
---|
| 1718 | } # end initGlobals
|
---|
| 1719 |
|
---|
| 1720 |
|
---|
[401] | 1721 | ## DNSDB::initRPC()
|
---|
[469] | 1722 | # Takes a remote username and remote fullname.
|
---|
[401] | 1723 | # Sets up the RPC logging-pseudouser if needed.
|
---|
| 1724 | # Sets the %userdata hash for logging.
|
---|
| 1725 | # Returns undef on failure
|
---|
| 1726 | sub initRPC {
|
---|
[469] | 1727 | my $self = shift;
|
---|
| 1728 | my $dbh = $self->{dbh};
|
---|
[401] | 1729 | my %args = @_;
|
---|
| 1730 |
|
---|
| 1731 | return if !$args{username};
|
---|
| 1732 | return if !$args{fullname};
|
---|
| 1733 |
|
---|
[406] | 1734 | $args{username} = "$args{username}/$args{rpcsys}";
|
---|
| 1735 |
|
---|
| 1736 | my $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
|
---|
[404] | 1737 | " FROM users WHERE username=?", undef, ($args{username}) );
|
---|
[406] | 1738 | if (!$tmpuser) {
|
---|
[401] | 1739 | $dbh->do("INSERT INTO users (username,password,firstname,type) VALUES (?,'RPC',?,'R')", undef,
|
---|
| 1740 | ($args{username}, $args{fullname}) );
|
---|
[406] | 1741 | $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
|
---|
[404] | 1742 | " FROM users WHERE username=?", undef, ($args{username}) );
|
---|
[401] | 1743 | }
|
---|
[488] | 1744 | $tmpuser->{lastname} = '' if !$tmpuser->{lastname};
|
---|
| 1745 | $self->{loguserid} = $tmpuser->{userid};
|
---|
| 1746 | $self->{logusername} = $tmpuser->{username};
|
---|
| 1747 | $self->{logfullname} = "$tmpuser->{firstname} $tmpuser->{lastname} ($args{rpcsys})";
|
---|
[406] | 1748 | return 1 if $tmpuser;
|
---|
[401] | 1749 | } # end initRPC()
|
---|
| 1750 |
|
---|
| 1751 |
|
---|
[278] | 1752 | ## DNSDB::login()
|
---|
| 1753 | # Takes a database handle, username and password
|
---|
[316] | 1754 | # Returns a userdata hash (UID, GID, username, fullname parts) if username exists,
|
---|
| 1755 | # password matches the one on file, and account is not disabled
|
---|
[278] | 1756 | # Returns undef otherwise
|
---|
| 1757 | sub login {
|
---|
[469] | 1758 | my $self = shift;
|
---|
| 1759 | my $dbh = $self->{dbh};
|
---|
[278] | 1760 | my $user = shift;
|
---|
| 1761 | my $pass = shift;
|
---|
| 1762 |
|
---|
[316] | 1763 | my $userinfo = $dbh->selectrow_hashref("SELECT user_id,group_id,password,firstname,lastname,status".
|
---|
| 1764 | " FROM users WHERE username=?",
|
---|
[279] | 1765 | undef, ($user) );
|
---|
| 1766 | return if !$userinfo;
|
---|
[316] | 1767 | return if !$userinfo->{status};
|
---|
[278] | 1768 |
|
---|
[279] | 1769 | if ($userinfo->{password} =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
|
---|
[278] | 1770 | # native passwords (crypt-md5)
|
---|
[279] | 1771 | return if $userinfo->{password} ne unix_md5_crypt($pass,$1);
|
---|
| 1772 | } elsif ($userinfo->{password} =~ /^[0-9a-f]{32}$/) {
|
---|
[278] | 1773 | # VegaDNS import (hex-coded MD5)
|
---|
[279] | 1774 | return if $userinfo->{password} ne md5_hex($pass);
|
---|
[278] | 1775 | } else {
|
---|
| 1776 | # plaintext (convenient now and then)
|
---|
[279] | 1777 | return if $userinfo->{password} ne $pass;
|
---|
[278] | 1778 | }
|
---|
| 1779 |
|
---|
[279] | 1780 | return $userinfo;
|
---|
[278] | 1781 | } # end login()
|
---|
| 1782 |
|
---|
| 1783 |
|
---|
[279] | 1784 | ## DNSDB::initActionLog()
|
---|
| 1785 | # Set up action logging. Takes a database handle and user ID
|
---|
| 1786 | # Sets some internal globals and Does The Right Thing to set up a logging channel.
|
---|
| 1787 | # This sets up _log() to spew out log entries to the defined channel without worrying
|
---|
| 1788 | # about having to open a file or a syslog channel
|
---|
| 1789 | ##fixme Need to call _initActionLog_blah() for various logging channels, configured
|
---|
[517] | 1790 | # via dnsdb.conf, in $self->{log_channel} or something
|
---|
[279] | 1791 | # See https://secure.deepnet.cx/trac/dnsadmin/ticket/21
|
---|
| 1792 | sub initActionLog {
|
---|
[469] | 1793 | my $self = shift;
|
---|
| 1794 | my $dbh = $self->{dbh};
|
---|
[279] | 1795 | my $uid = shift;
|
---|
| 1796 |
|
---|
| 1797 | return if !$uid;
|
---|
| 1798 |
|
---|
| 1799 | # snag user info for logging. there's got to be a way to not have to pass this back
|
---|
| 1800 | # and forth from a caller, but web usage means no persistence we can rely on from
|
---|
| 1801 | # the server side.
|
---|
| 1802 | my ($username,$fullname) = $dbh->selectrow_array("SELECT username, firstname || ' ' || lastname".
|
---|
| 1803 | " FROM users WHERE user_id=?", undef, ($uid));
|
---|
| 1804 | ##fixme: errors are unpossible!
|
---|
| 1805 |
|
---|
[488] | 1806 | $self->{logusername} = $username;
|
---|
| 1807 | $self->{loguserid} = $uid;
|
---|
| 1808 | $self->{logfullname} = $fullname;
|
---|
[279] | 1809 |
|
---|
| 1810 | # convert to real check once we have other logging channels
|
---|
[517] | 1811 | # if ($self->{log_channel} eq 'sql') {
|
---|
[279] | 1812 | # Open Log, Sez Me!
|
---|
| 1813 | # }
|
---|
| 1814 |
|
---|
| 1815 | } # end initActionLog
|
---|
| 1816 |
|
---|
| 1817 |
|
---|
[65] | 1818 | ## DNSDB::getPermissions()
|
---|
| 1819 | # Get permissions from DB
|
---|
| 1820 | # Requires DB handle, group or user flag, ID, and hashref.
|
---|
| 1821 | sub getPermissions {
|
---|
[469] | 1822 | my $self = shift;
|
---|
| 1823 | my $dbh = $self->{dbh};
|
---|
| 1824 |
|
---|
[65] | 1825 | my $type = shift;
|
---|
| 1826 | my $id = shift;
|
---|
| 1827 | my $hash = shift;
|
---|
| 1828 |
|
---|
| 1829 | my $sql = qq(
|
---|
| 1830 | SELECT
|
---|
| 1831 | p.admin,p.self_edit,
|
---|
| 1832 | p.group_create,p.group_edit,p.group_delete,
|
---|
| 1833 | p.user_create,p.user_edit,p.user_delete,
|
---|
| 1834 | p.domain_create,p.domain_edit,p.domain_delete,
|
---|
[387] | 1835 | p.record_create,p.record_edit,p.record_delete,p.record_locchg,
|
---|
[382] | 1836 | p.location_create,p.location_edit,p.location_delete,p.location_view
|
---|
[65] | 1837 | FROM permissions p
|
---|
| 1838 | );
|
---|
| 1839 | if ($type eq 'group') {
|
---|
| 1840 | $sql .= qq(
|
---|
| 1841 | JOIN groups g ON g.permission_id=p.permission_id
|
---|
| 1842 | WHERE g.group_id=?
|
---|
| 1843 | );
|
---|
| 1844 | } else {
|
---|
| 1845 | $sql .= qq(
|
---|
| 1846 | JOIN users u ON u.permission_id=p.permission_id
|
---|
| 1847 | WHERE u.user_id=?
|
---|
| 1848 | );
|
---|
| 1849 | }
|
---|
| 1850 |
|
---|
| 1851 | my $sth = $dbh->prepare($sql);
|
---|
| 1852 |
|
---|
[514] | 1853 | ##fixme? we don't trap other plain SELECT errors
|
---|
| 1854 | $sth->execute($id);
|
---|
[65] | 1855 |
|
---|
| 1856 | # my $permref = $sth->fetchrow_hashref;
|
---|
| 1857 | # return $permref;
|
---|
| 1858 | # $hash = $permref;
|
---|
| 1859 | # Eww. Need to learn how to forcibly drop a hashref onto an existing hash.
|
---|
| 1860 | ($hash->{admin},$hash->{self_edit},
|
---|
| 1861 | $hash->{group_create},$hash->{group_edit},$hash->{group_delete},
|
---|
| 1862 | $hash->{user_create},$hash->{user_edit},$hash->{user_delete},
|
---|
| 1863 | $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete},
|
---|
[387] | 1864 | $hash->{record_create},$hash->{record_edit},$hash->{record_delete},$hash->{record_locchg},
|
---|
[382] | 1865 | $hash->{location_create},$hash->{location_edit},$hash->{location_delete},$hash->{location_view}
|
---|
| 1866 | ) = $sth->fetchrow_array;
|
---|
[65] | 1867 |
|
---|
| 1868 | } # end getPermissions()
|
---|
| 1869 |
|
---|
| 1870 |
|
---|
| 1871 | ## DNSDB::changePermissions()
|
---|
| 1872 | # Update an ACL entry
|
---|
| 1873 | # Takes a db handle, type, owner-id, and hashref for the changed permissions.
|
---|
| 1874 | sub changePermissions {
|
---|
[474] | 1875 | my $self = shift;
|
---|
| 1876 | my $dbh = $self->{dbh};
|
---|
[65] | 1877 | my $type = shift;
|
---|
| 1878 | my $id = shift;
|
---|
| 1879 | my $newperms = shift;
|
---|
[87] | 1880 | my $inherit = shift || 0;
|
---|
[65] | 1881 |
|
---|
[294] | 1882 | my $resultmsg = '';
|
---|
[66] | 1883 |
|
---|
[87] | 1884 | # see if we're switching from inherited to custom. for bonus points,
|
---|
| 1885 | # snag the permid and parent permid anyway, since we'll need the permid
|
---|
| 1886 | # to set/alter custom perms, and both if we're switching from custom to
|
---|
| 1887 | # inherited.
|
---|
[294] | 1888 | my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id,".
|
---|
| 1889 | ($type eq 'user' ? 'u.group_id,u.username' : 'u.parent_group_id,u.group_name').
|
---|
[65] | 1890 | " FROM ".($type eq 'user' ? 'users' : 'groups')." u ".
|
---|
[66] | 1891 | " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ".
|
---|
[65] | 1892 | " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?");
|
---|
| 1893 | $sth->execute($id);
|
---|
| 1894 |
|
---|
[294] | 1895 | my ($wasinherited,$permid,$parpermid,$parid,$name) = $sth->fetchrow_array;
|
---|
[66] | 1896 |
|
---|
[78] | 1897 | # hack phtoui
|
---|
| 1898 | # group id 1 is "special" in that it's it's own parent (err... possibly.)
|
---|
| 1899 | # may make its parent id 0 which doesn't exist, and as a bonus is Perl-false.
|
---|
| 1900 | $wasinherited = 0 if ($type eq 'group' && $id == 1);
|
---|
| 1901 |
|
---|
[66] | 1902 | local $dbh->{AutoCommit} = 0;
|
---|
| 1903 | local $dbh->{RaiseError} = 1;
|
---|
| 1904 |
|
---|
| 1905 | # Wrap all the SQL in a transaction
|
---|
| 1906 | eval {
|
---|
[87] | 1907 | if ($inherit) {
|
---|
| 1908 |
|
---|
| 1909 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ".
|
---|
| 1910 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) );
|
---|
| 1911 | $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) );
|
---|
| 1912 |
|
---|
| 1913 | } else {
|
---|
| 1914 |
|
---|
| 1915 | if ($wasinherited) { # munge new permission entry in if we're switching from inherited perms
|
---|
[66] | 1916 | ##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users
|
---|
[87] | 1917 | # ... if'n'when we have groups with fully inherited permissions.
|
---|
| 1918 | # SQL is coo
|
---|
| 1919 | $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ".
|
---|
| 1920 | "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) );
|
---|
| 1921 | ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ".
|
---|
| 1922 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) );
|
---|
| 1923 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ".
|
---|
| 1924 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) );
|
---|
[66] | 1925 | }
|
---|
[78] | 1926 |
|
---|
[87] | 1927 | # and now set the permissions we were passed
|
---|
| 1928 | foreach (@permtypes) {
|
---|
| 1929 | if (defined ($newperms->{$_})) {
|
---|
| 1930 | $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) );
|
---|
| 1931 | }
|
---|
| 1932 | }
|
---|
| 1933 |
|
---|
| 1934 | } # (inherited->)? custom
|
---|
| 1935 |
|
---|
[294] | 1936 | if ($type eq 'user') {
|
---|
| 1937 | $resultmsg = "Updated permissions for user $name";
|
---|
| 1938 | } else {
|
---|
| 1939 | $resultmsg = "Updated default permissions for group $name";
|
---|
| 1940 | }
|
---|
[487] | 1941 | $self->_log(group_id => ($type eq 'user' ? $parid : $id), entry => $resultmsg);
|
---|
[66] | 1942 | $dbh->commit;
|
---|
| 1943 | }; # end eval
|
---|
| 1944 | if ($@) {
|
---|
| 1945 | my $msg = $@;
|
---|
| 1946 | eval { $dbh->rollback; };
|
---|
[294] | 1947 | return ('FAIL',"Error changing permissions: $msg");
|
---|
[66] | 1948 | }
|
---|
| 1949 |
|
---|
[294] | 1950 | return ('OK',$resultmsg);
|
---|
[65] | 1951 | } # end changePermissions()
|
---|
| 1952 |
|
---|
| 1953 |
|
---|
[67] | 1954 | ## DNSDB::comparePermissions()
|
---|
| 1955 | # Compare two permission hashes
|
---|
| 1956 | # Returns '>', '<', '=', '!'
|
---|
| 1957 | sub comparePermissions {
|
---|
[592] | 1958 | my $self = shift;
|
---|
[67] | 1959 | my $p1 = shift;
|
---|
| 1960 | my $p2 = shift;
|
---|
| 1961 |
|
---|
| 1962 | my $retval = '='; # assume equality until proven otherwise
|
---|
| 1963 |
|
---|
| 1964 | no warnings "uninitialized";
|
---|
| 1965 |
|
---|
| 1966 | foreach (@permtypes) {
|
---|
| 1967 | next if $p1->{$_} == $p2->{$_}; # equal is good
|
---|
| 1968 | if ($p1->{$_} && !$p2->{$_}) {
|
---|
| 1969 | if ($retval eq '<') { # if we've already found an unequal pair where
|
---|
| 1970 | $retval = '!'; # $p2 has more access, and we now find a pair
|
---|
| 1971 | last; # where $p1 has more access, the overall access
|
---|
| 1972 | } # is neither greater or lesser, it's unequal.
|
---|
| 1973 | $retval = '>';
|
---|
| 1974 | }
|
---|
| 1975 | if (!$p1->{$_} && $p2->{$_}) {
|
---|
| 1976 | if ($retval eq '>') { # if we've already found an unequal pair where
|
---|
| 1977 | $retval = '!'; # $p1 has more access, and we now find a pair
|
---|
| 1978 | last; # where $p2 has more access, the overall access
|
---|
| 1979 | } # is neither greater or lesser, it's unequal.
|
---|
| 1980 | $retval = '<';
|
---|
| 1981 | }
|
---|
| 1982 | }
|
---|
| 1983 | return $retval;
|
---|
| 1984 | } # end comparePermissions()
|
---|
| 1985 |
|
---|
| 1986 |
|
---|
[112] | 1987 | ## DNSDB::changeGroup()
|
---|
| 1988 | # Change group ID of an entity
|
---|
| 1989 | # Takes a database handle, entity type, entity ID, and new group ID
|
---|
| 1990 | sub changeGroup {
|
---|
[476] | 1991 | my $self = shift;
|
---|
| 1992 | my $dbh = $self->{dbh};
|
---|
[112] | 1993 | my $type = shift;
|
---|
| 1994 | my $id = shift;
|
---|
| 1995 | my $newgrp = shift;
|
---|
| 1996 |
|
---|
| 1997 | ##fixme: fail on not enough args
|
---|
| 1998 | #return ('FAIL', "Missing
|
---|
| 1999 |
|
---|
[295] | 2000 | return ('FAIL', "Can't change the group of a $type")
|
---|
| 2001 | unless grep /^$type$/, ('domain','revzone','user','group'); # could be extended for defrecs?
|
---|
| 2002 |
|
---|
| 2003 | # Collect some names for logging and messages
|
---|
| 2004 | my $entname;
|
---|
[112] | 2005 | if ($type eq 'domain') {
|
---|
[473] | 2006 | $entname = $self->domainName($id);
|
---|
[295] | 2007 | } elsif ($type eq 'revzone') {
|
---|
[473] | 2008 | $entname = $self->revName($id);
|
---|
[112] | 2009 | } elsif ($type eq 'user') {
|
---|
[473] | 2010 | $entname = $self->userFullName($id, '%u');
|
---|
[112] | 2011 | } elsif ($type eq 'group') {
|
---|
[473] | 2012 | $entname = $self->groupName($id);
|
---|
[112] | 2013 | }
|
---|
[295] | 2014 |
|
---|
| 2015 | my ($oldgid) = $dbh->selectrow_array("SELECT group_id FROM $par_tbl{$type} WHERE $id_col{$type}=?",
|
---|
| 2016 | undef, ($id));
|
---|
[473] | 2017 | my $oldgname = $self->groupName($oldgid);
|
---|
| 2018 | my $newgname = $self->groupName($newgrp);
|
---|
[295] | 2019 |
|
---|
| 2020 | return ('FAIL', "Can't move things into a group that doesn't exist") if !$newgname;
|
---|
| 2021 |
|
---|
| 2022 | return ('WARN', "Nothing to do, new group is the same as the old group") if $oldgid == $newgrp;
|
---|
| 2023 |
|
---|
| 2024 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2025 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2026 | local $dbh->{AutoCommit} = 0;
|
---|
| 2027 | local $dbh->{RaiseError} = 1;
|
---|
| 2028 |
|
---|
| 2029 | eval {
|
---|
| 2030 | $dbh->do("UPDATE $par_tbl{$type} SET group_id=? WHERE $id_col{$type}=?", undef, ($newgrp, $id));
|
---|
| 2031 | # Log the change in both the old and new groups
|
---|
[487] | 2032 | $self->_log(group_id => $oldgid, entry => "Moved $type $entname from $oldgname to $newgname");
|
---|
| 2033 | $self->_log(group_id => $newgrp, entry => "Moved $type $entname from $oldgname to $newgname");
|
---|
[295] | 2034 | $dbh->commit;
|
---|
| 2035 | };
|
---|
| 2036 | if ($@) {
|
---|
| 2037 | my $msg = $@;
|
---|
| 2038 | eval { $dbh->rollback; };
|
---|
[517] | 2039 | if ($self->{log_failures}) {
|
---|
[487] | 2040 | $self->_log(group_id => $oldgid, entry => "Error moving $type $entname to $newgname: $msg");
|
---|
[295] | 2041 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2042 | }
|
---|
| 2043 | return ('FAIL',"Error moving $type $entname to $newgname: $msg");
|
---|
| 2044 | }
|
---|
| 2045 |
|
---|
| 2046 | return ('OK',"Moved $type $entname from $oldgname to $newgname");
|
---|
[112] | 2047 | } # end changeGroup()
|
---|
| 2048 |
|
---|
| 2049 |
|
---|
[2] | 2050 | ##
|
---|
| 2051 | ## Processing subs
|
---|
| 2052 | ##
|
---|
| 2053 |
|
---|
| 2054 | ## DNSDB::addDomain()
|
---|
| 2055 | # Add a domain
|
---|
[190] | 2056 | # Takes a database handle, domain name, numeric group, boolean(ish) state (active/inactive),
|
---|
| 2057 | # and user info hash (for logging).
|
---|
[2] | 2058 | # Returns a status code and message
|
---|
| 2059 | sub addDomain {
|
---|
| 2060 | $errstr = '';
|
---|
[477] | 2061 | my $self = shift;
|
---|
| 2062 | my $dbh = $self->{dbh};
|
---|
[2] | 2063 | my $domain = shift;
|
---|
[497] | 2064 | return ('FAIL',"Domain must not be blank\n") if !$domain;
|
---|
[2] | 2065 | my $group = shift;
|
---|
[497] | 2066 | return ('FAIL',"Group must be specified\n") if !defined($group);
|
---|
[2] | 2067 | my $state = shift;
|
---|
[497] | 2068 | return ('FAIL',"Domain status must be specified\n") if !defined($state);
|
---|
[516] | 2069 | my $defloc = shift || '';
|
---|
[2] | 2070 |
|
---|
[116] | 2071 | $state = 1 if $state =~ /^active$/;
|
---|
| 2072 | $state = 1 if $state =~ /^on$/;
|
---|
| 2073 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 2074 | $state = 0 if $state =~ /^off$/;
|
---|
| 2075 |
|
---|
| 2076 | return ('FAIL',"Invalid domain status") if $state !~ /^\d+$/;
|
---|
| 2077 |
|
---|
[542] | 2078 | $domain = lc($domain) if $self->{lowercase};
|
---|
| 2079 |
|
---|
[190] | 2080 | return ('FAIL', "Invalid characters in domain") if $domain !~ /^[a-zA-Z0-9_.-]+$/;
|
---|
| 2081 |
|
---|
[349] | 2082 | my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)");
|
---|
[3] | 2083 | my $dom_id;
|
---|
| 2084 |
|
---|
[38] | 2085 | # quick check to start to see if we've already got one
|
---|
| 2086 | $sth->execute($domain);
|
---|
| 2087 | ($dom_id) = $sth->fetchrow_array;
|
---|
| 2088 |
|
---|
| 2089 | return ('FAIL', "Domain already exists") if $dom_id;
|
---|
| 2090 |
|
---|
[2] | 2091 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2092 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2093 | local $dbh->{AutoCommit} = 0;
|
---|
| 2094 | local $dbh->{RaiseError} = 1;
|
---|
| 2095 |
|
---|
| 2096 | # Wrap all the SQL in a transaction
|
---|
| 2097 | eval {
|
---|
| 2098 | # insert the domain...
|
---|
[516] | 2099 | $dbh->do("INSERT INTO domains (domain,group_id,status,default_location) VALUES (?,?,?,?)", undef,
|
---|
| 2100 | ($domain, $group, $state, $defloc));
|
---|
[2] | 2101 |
|
---|
| 2102 | # get the ID...
|
---|
[349] | 2103 | ($dom_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
| 2104 | undef, ($domain));
|
---|
[2] | 2105 |
|
---|
[487] | 2106 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
| 2107 | entry => "Added ".($state ? 'active' : 'inactive')." domain $domain");
|
---|
[190] | 2108 |
|
---|
[2] | 2109 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
[190] | 2110 | my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
[516] | 2111 | my $sth_in = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,distance,weight,port,ttl,location)".
|
---|
| 2112 | " VALUES ($dom_id,?,?,?,?,?,?,?,?)");
|
---|
[190] | 2113 | $sth->execute($group);
|
---|
[516] | 2114 | while (my ($host, $type, $val, $dist, $weight, $port, $ttl) = $sth->fetchrow_array()) {
|
---|
[2] | 2115 | $host =~ s/DOMAIN/$domain/g;
|
---|
[37] | 2116 | $val =~ s/DOMAIN/$domain/g;
|
---|
[617] | 2117 | _caseclean(\$type, \$host, \$val, 'n', 'n') if $self->{lowercase};
|
---|
[516] | 2118 | $sth_in->execute($host, $type, $val, $dist, $weight, $port, $ttl, $defloc);
|
---|
[190] | 2119 | if ($typemap{$type} eq 'SOA') {
|
---|
| 2120 | my @tmp1 = split /:/, $host;
|
---|
| 2121 | my @tmp2 = split /:/, $val;
|
---|
[487] | 2122 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
[284] | 2123 | entry => "[new $domain] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
[487] | 2124 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl");
|
---|
[190] | 2125 | } else {
|
---|
| 2126 | my $logentry = "[new $domain] Added record '$host $typemap{$type}";
|
---|
| 2127 | $logentry .= " [distance $dist]" if $typemap{$type} eq 'MX';
|
---|
| 2128 | $logentry .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$type} eq 'SRV';
|
---|
[487] | 2129 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
| 2130 | entry => $logentry." $val', TTL $ttl");
|
---|
[190] | 2131 | }
|
---|
[2] | 2132 | }
|
---|
| 2133 |
|
---|
| 2134 | # once we get here, we should have suceeded.
|
---|
| 2135 | $dbh->commit;
|
---|
| 2136 | }; # end eval
|
---|
| 2137 |
|
---|
| 2138 | if ($@) {
|
---|
| 2139 | my $msg = $@;
|
---|
| 2140 | eval { $dbh->rollback; };
|
---|
[487] | 2141 | $self->_log(group_id => $group, entry => "Failed adding domain $domain ($msg)")
|
---|
[517] | 2142 | if $self->{log_failures};
|
---|
[284] | 2143 | $dbh->commit; # since we enabled transactions earlier
|
---|
[193] | 2144 | return ('FAIL',$msg);
|
---|
[2] | 2145 | } else {
|
---|
[3] | 2146 | return ('OK',$dom_id);
|
---|
[2] | 2147 | }
|
---|
| 2148 | } # end addDomain
|
---|
| 2149 |
|
---|
| 2150 |
|
---|
[274] | 2151 | ## DNSDB::delZone()
|
---|
| 2152 | # Delete a forward or reverse zone.
|
---|
| 2153 | # Takes a database handle, zone ID, and forward/reverse flag.
|
---|
[3] | 2154 | # for now, just delete the records, then the domain.
|
---|
| 2155 | # later we may want to archive it in some way instead (status code 2, for example?)
|
---|
[274] | 2156 | sub delZone {
|
---|
[477] | 2157 | my $self = shift;
|
---|
| 2158 | my $dbh = $self->{dbh};
|
---|
[274] | 2159 | my $zoneid = shift;
|
---|
| 2160 | my $revrec = shift;
|
---|
[3] | 2161 |
|
---|
| 2162 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2163 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2164 | local $dbh->{AutoCommit} = 0;
|
---|
| 2165 | local $dbh->{RaiseError} = 1;
|
---|
| 2166 |
|
---|
[285] | 2167 | my $msg = '';
|
---|
[23] | 2168 | my $failmsg = '';
|
---|
[473] | 2169 | my $zone = ($revrec eq 'n' ? $self->domainName($zoneid) : $self->revName($zoneid));
|
---|
[23] | 2170 |
|
---|
[343] | 2171 | return ('FAIL', ($revrec eq 'n' ? 'Domain' : 'Reverse zone')." ID $zoneid doesn't exist") if !$zone;
|
---|
| 2172 |
|
---|
[517] | 2173 | # Set this up here since we may use if if $self->{log_failures} is enabled
|
---|
[285] | 2174 | my %loghash;
|
---|
| 2175 | $loghash{domain_id} = $zoneid if $revrec eq 'n';
|
---|
| 2176 | $loghash{rdns_id} = $zoneid if $revrec eq 'y';
|
---|
[473] | 2177 | $loghash{group_id} = $self->parentID(
|
---|
| 2178 | id => $zoneid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec);
|
---|
[285] | 2179 |
|
---|
[3] | 2180 | # Wrap all the SQL in a transaction
|
---|
| 2181 | eval {
|
---|
[274] | 2182 | # Disentangle custom record types before removing the
|
---|
| 2183 | # ones that are only in the zone to be deleted
|
---|
| 2184 | if ($revrec eq 'n') {
|
---|
| 2185 | my $sth = $dbh->prepare("UPDATE records SET type=?,domain_id=0 WHERE domain_id=? AND type=?");
|
---|
| 2186 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
| 2187 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65280);
|
---|
| 2188 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65281);
|
---|
| 2189 | $sth->execute(65282, $zoneid, 65283);
|
---|
| 2190 | $sth->execute(65282, $zoneid, 65284);
|
---|
| 2191 | $failmsg = "Failure removing domain records";
|
---|
| 2192 | $dbh->do("DELETE FROM records WHERE domain_id=?", undef, ($zoneid));
|
---|
| 2193 | $failmsg = "Failure removing domain";
|
---|
| 2194 | $dbh->do("DELETE FROM domains WHERE domain_id=?", undef, ($zoneid));
|
---|
| 2195 | } else {
|
---|
| 2196 | my $sth = $dbh->prepare("UPDATE records SET type=?,rdns_id=0 WHERE rdns_id=? AND type=?");
|
---|
| 2197 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
| 2198 | $sth->execute($reverse_typemap{A}, $zoneid, 65280);
|
---|
| 2199 | $sth->execute($reverse_typemap{AAAA}, $zoneid, 65281);
|
---|
| 2200 | # We don't have an "A template" or "AAAA template" type, although it might be useful for symmetry.
|
---|
[345] | 2201 | # $sth->execute(65286?, $zoneid, 65283);
|
---|
| 2202 | # $sth->execute(65286?, $zoneid, 65284);
|
---|
[274] | 2203 | $failmsg = "Failure removing reverse records";
|
---|
| 2204 | $dbh->do("DELETE FROM records WHERE rdns_id=?", undef, ($zoneid));
|
---|
| 2205 | $failmsg = "Failure removing reverse zone";
|
---|
| 2206 | $dbh->do("DELETE FROM revzones WHERE rdns_id=?", undef, ($zoneid));
|
---|
| 2207 | }
|
---|
[3] | 2208 |
|
---|
[285] | 2209 | $msg = "Deleted ".($revrec eq 'n' ? 'domain' : 'reverse zone')." $zone";
|
---|
| 2210 | $loghash{entry} = $msg;
|
---|
[487] | 2211 | $self->_log(%loghash);
|
---|
[285] | 2212 |
|
---|
[3] | 2213 | # once we get here, we should have suceeded.
|
---|
[23] | 2214 | $dbh->commit;
|
---|
[3] | 2215 | }; # end eval
|
---|
| 2216 |
|
---|
| 2217 | if ($@) {
|
---|
[285] | 2218 | $msg = $@;
|
---|
[3] | 2219 | eval { $dbh->rollback; };
|
---|
[295] | 2220 | $loghash{entry} = "Error deleting $zone: $msg ($failmsg)";
|
---|
[517] | 2221 | if ($self->{log_failures}) {
|
---|
[487] | 2222 | $self->_log(%loghash);
|
---|
[295] | 2223 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2224 | }
|
---|
| 2225 | return ('FAIL', $loghash{entry});
|
---|
[3] | 2226 | } else {
|
---|
[295] | 2227 | return ('OK', $msg);
|
---|
[3] | 2228 | }
|
---|
| 2229 |
|
---|
[274] | 2230 | } # end delZone()
|
---|
[3] | 2231 |
|
---|
| 2232 |
|
---|
[2] | 2233 | ## DNSDB::domainName()
|
---|
| 2234 | # Return the domain name based on a domain ID
|
---|
| 2235 | # Takes a database handle and the domain ID
|
---|
| 2236 | # Returns the domain name or undef on failure
|
---|
| 2237 | sub domainName {
|
---|
| 2238 | $errstr = '';
|
---|
[473] | 2239 | my $self = shift;
|
---|
| 2240 | my $dbh = $self->{dbh};
|
---|
[2] | 2241 | my $domid = shift;
|
---|
[91] | 2242 | my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
|
---|
[2] | 2243 | $errstr = $DBI::errstr if !$domname;
|
---|
| 2244 | return $domname if $domname;
|
---|
[91] | 2245 | } # end domainName()
|
---|
[2] | 2246 |
|
---|
| 2247 |
|
---|
[224] | 2248 | ## DNSDB::revName()
|
---|
| 2249 | # Return the reverse zone name based on an rDNS ID
|
---|
[583] | 2250 | # Takes a database handle and the rDNS ID, and an optional flag to force return of the CIDR zone
|
---|
| 2251 | # instead of the formal .arpa zone name
|
---|
[224] | 2252 | # Returns the reverse zone name or undef on failure
|
---|
| 2253 | sub revName {
|
---|
| 2254 | $errstr = '';
|
---|
[473] | 2255 | my $self = shift;
|
---|
| 2256 | my $dbh = $self->{dbh};
|
---|
[224] | 2257 | my $revid = shift;
|
---|
[583] | 2258 | my $cidrflag = shift || 'n';
|
---|
[224] | 2259 | my ($revname) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id=?", undef, ($revid) );
|
---|
| 2260 | $errstr = $DBI::errstr if !$revname;
|
---|
[583] | 2261 | my $tmp = new NetAddr::IP $revname;
|
---|
| 2262 | $revname = _ZONE($tmp, 'ZONE', 'r', '.').($tmp->{isv6} ? '.ip6.arpa' : '.in-addr.arpa')
|
---|
| 2263 | if ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all') && $cidrflag eq 'n';
|
---|
[224] | 2264 | return $revname if $revname;
|
---|
| 2265 | } # end revName()
|
---|
| 2266 |
|
---|
| 2267 |
|
---|
[91] | 2268 | ## DNSDB::domainID()
|
---|
| 2269 | # Takes a database handle and domain name
|
---|
| 2270 | # Returns the domain ID number
|
---|
| 2271 | sub domainID {
|
---|
| 2272 | $errstr = '';
|
---|
[473] | 2273 | my $self = shift;
|
---|
| 2274 | my $dbh = $self->{dbh};
|
---|
[91] | 2275 | my $domain = shift;
|
---|
[349] | 2276 | my ($domid) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
| 2277 | undef, ($domain) );
|
---|
[501] | 2278 | if (!$domid) {
|
---|
| 2279 | if ($dbh->err) {
|
---|
| 2280 | $errstr = $DBI::errstr;
|
---|
| 2281 | } else {
|
---|
| 2282 | $errstr = "Domain $domain not present";
|
---|
| 2283 | }
|
---|
| 2284 | }
|
---|
[91] | 2285 | return $domid if $domid;
|
---|
| 2286 | } # end domainID()
|
---|
| 2287 |
|
---|
| 2288 |
|
---|
[276] | 2289 | ## DNSDB::revID()
|
---|
| 2290 | # Takes a database handle and reverse zone name
|
---|
| 2291 | # Returns the rDNS ID number
|
---|
| 2292 | sub revID {
|
---|
| 2293 | $errstr = '';
|
---|
[473] | 2294 | my $self = shift;
|
---|
| 2295 | my $dbh = $self->{dbh};
|
---|
[276] | 2296 | my $revzone = shift;
|
---|
| 2297 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ($revzone) );
|
---|
[501] | 2298 | if (!$revid) {
|
---|
| 2299 | if ($dbh->err) {
|
---|
| 2300 | $errstr = $DBI::errstr;
|
---|
| 2301 | } else {
|
---|
| 2302 | $errstr = "Reverse zone $revzone not present";
|
---|
| 2303 | }
|
---|
| 2304 | }
|
---|
[276] | 2305 | return $revid if $revid;
|
---|
| 2306 | } # end revID()
|
---|
| 2307 |
|
---|
| 2308 |
|
---|
[260] | 2309 | ## DNSDB::addRDNS
|
---|
| 2310 | # Adds a reverse DNS zone
|
---|
[286] | 2311 | # Takes a database handle, CIDR block, reverse DNS pattern, numeric group,
|
---|
| 2312 | # and boolean(ish) state (active/inactive)
|
---|
[260] | 2313 | # Returns a status code and message
|
---|
| 2314 | sub addRDNS {
|
---|
[477] | 2315 | my $self = shift;
|
---|
| 2316 | my $dbh = $self->{dbh};
|
---|
[583] | 2317 | my $zone = shift;
|
---|
[446] | 2318 |
|
---|
[583] | 2319 | # Autodetect formal .arpa zones
|
---|
| 2320 | if ($zone =~ /\.arpa\.?$/) {
|
---|
| 2321 | my $code;
|
---|
| 2322 | ($code,$zone) = _zone2cidr($zone);
|
---|
| 2323 | return ('FAIL', $zone) if $code eq 'FAIL';
|
---|
| 2324 | }
|
---|
| 2325 | $zone = NetAddr::IP->new($zone);
|
---|
| 2326 |
|
---|
[260] | 2327 | return ('FAIL',"Zone name must be a valid CIDR netblock") unless ($zone && $zone->addr !~ /^0/);
|
---|
[270] | 2328 | my $revpatt = shift; # construct a custom (A/AAAA+)? PTR template record
|
---|
[260] | 2329 | my $group = shift;
|
---|
| 2330 | my $state = shift;
|
---|
[446] | 2331 | my $defloc = shift || '';
|
---|
[260] | 2332 |
|
---|
| 2333 | $state = 1 if $state =~ /^active$/;
|
---|
| 2334 | $state = 1 if $state =~ /^on$/;
|
---|
| 2335 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 2336 | $state = 0 if $state =~ /^off$/;
|
---|
| 2337 |
|
---|
| 2338 | return ('FAIL',"Invalid zone status") if $state !~ /^\d+$/;
|
---|
| 2339 |
|
---|
| 2340 | # quick check to start to see if we've already got one
|
---|
[299] | 2341 | my ($rdns_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ("$zone"));
|
---|
[260] | 2342 |
|
---|
| 2343 | return ('FAIL', "Zone already exists") if $rdns_id;
|
---|
| 2344 |
|
---|
| 2345 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2346 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2347 | local $dbh->{AutoCommit} = 0;
|
---|
| 2348 | local $dbh->{RaiseError} = 1;
|
---|
| 2349 |
|
---|
[264] | 2350 | my $warnstr = '';
|
---|
[270] | 2351 | my $defttl = 3600; # 1 hour should be reasonable. And unless things have gone horribly
|
---|
| 2352 | # wrong, we should have a value to override this anyway.
|
---|
[264] | 2353 |
|
---|
[260] | 2354 | # Wrap all the SQL in a transaction
|
---|
| 2355 | eval {
|
---|
[446] | 2356 | # insert the zone...
|
---|
| 2357 | $dbh->do("INSERT INTO revzones (revnet,group_id,status,default_location) VALUES (?,?,?,?)", undef,
|
---|
| 2358 | ($zone, $group, $state, $defloc) );
|
---|
[260] | 2359 |
|
---|
| 2360 | # get the ID...
|
---|
| 2361 | ($rdns_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
| 2362 |
|
---|
[487] | 2363 | $self->_log(rdns_id => $rdns_id, group_id => $group,
|
---|
| 2364 | entry => "Added ".($state ? 'active' : 'inactive')." reverse zone $zone");
|
---|
[260] | 2365 |
|
---|
| 2366 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
| 2367 | my $sth = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
[446] | 2368 | my $sth_in = $dbh->prepare("INSERT INTO records (rdns_id,domain_id,host,type,val,ttl,location)".
|
---|
| 2369 | " VALUES ($rdns_id,?,?,?,?,?,?)");
|
---|
[260] | 2370 | $sth->execute($group);
|
---|
| 2371 | while (my ($host,$type,$val,$ttl) = $sth->fetchrow_array()) {
|
---|
[264] | 2372 | # Silently skip v4/v6 mismatches. This is not an error, this is expected.
|
---|
| 2373 | if ($zone->{isv6}) {
|
---|
| 2374 | next if ($type == 65280 || $type == 65283);
|
---|
| 2375 | } else {
|
---|
| 2376 | next if ($type == 65281 || $type == 65284);
|
---|
| 2377 | }
|
---|
[269] | 2378 |
|
---|
[517] | 2379 | $host =~ s/ADMINDOMAIN/$self->{domain}/g;
|
---|
[264] | 2380 |
|
---|
[265] | 2381 | # Check to make sure the IP stubs will fit in the zone. Under most usage failures here should be rare.
|
---|
| 2382 | # On failure, tack a note on to a warning string and continue without adding this record.
|
---|
| 2383 | # While we're at it, we substitute $zone for ZONE in the value.
|
---|
| 2384 | if ($val eq 'ZONE') {
|
---|
[444] | 2385 | # If we've got a pattern, we skip the default record version on (A+)PTR-template types
|
---|
| 2386 | next if $revpatt && ($type == 65282 || $type == 65283);
|
---|
[269] | 2387 | ##fixme? do we care if we have multiple whole-zone templates?
|
---|
[265] | 2388 | $val = $zone->network;
|
---|
| 2389 | } elsif ($val =~ /ZONE/) {
|
---|
| 2390 | my $tmpval = $val;
|
---|
| 2391 | $tmpval =~ s/ZONE//;
|
---|
[269] | 2392 | # Bend the rules and allow single-trailing-number PTR or PTR template records to be inserted
|
---|
| 2393 | # as either v4 or v6. May make this an off-by-default config flag
|
---|
| 2394 | # Note that the origin records that may trigger this **SHOULD** already have ZONE,\d
|
---|
| 2395 | if ($type == 12 || $type == 65282) {
|
---|
| 2396 | $tmpval =~ s/[,.]/::/ if ($tmpval =~ /^[,.]\d+$/ && $zone->{isv6});
|
---|
| 2397 | $tmpval =~ s/[,:]+/./ if ($tmpval =~ /^(?:,|::)\d+$/ && !$zone->{isv6});
|
---|
| 2398 | }
|
---|
[265] | 2399 | my $addr;
|
---|
[471] | 2400 | if ($self->_ipparent('n', 'y', \$tmpval, $rdns_id, \$addr)) {
|
---|
[265] | 2401 | $val = $addr->addr;
|
---|
| 2402 | } else {
|
---|
[269] | 2403 | $warnstr .= "\nDefault record '$val $typemap{$type} $host' doesn't fit in $zone, skipping";
|
---|
[264] | 2404 | next;
|
---|
| 2405 | }
|
---|
| 2406 | }
|
---|
| 2407 |
|
---|
[328] | 2408 | # Substitute $zone for ZONE in the hostname, but only for non-NS records.
|
---|
| 2409 | # NS records get this substitution on the value instead.
|
---|
| 2410 | $host = _ZONE($zone, $host) if $type != 2;
|
---|
[265] | 2411 |
|
---|
[269] | 2412 | # Fill in the forward domain ID if we can find it, otherwise:
|
---|
| 2413 | # Coerce type down to PTR or PTR template if we can't
|
---|
| 2414 | my $domid = 0;
|
---|
| 2415 | if ($type >= 65280) {
|
---|
[471] | 2416 | if (!($domid = $self->_hostparent($host))) {
|
---|
[269] | 2417 | $warnstr .= "\nRecord added as PTR instead of $typemap{$type}; domain not found for $host";
|
---|
| 2418 | $type = $reverse_typemap{PTR};
|
---|
| 2419 | $domid = 0; # just to be explicit.
|
---|
| 2420 | }
|
---|
| 2421 | }
|
---|
| 2422 |
|
---|
[617] | 2423 | _caseclean(\$type, \$host, \$val, 'n', 'y') if $self->{lowercase};
|
---|
| 2424 |
|
---|
[446] | 2425 | $sth_in->execute($domid,$host,$type,$val,$ttl,$defloc);
|
---|
[269] | 2426 |
|
---|
[260] | 2427 | if ($typemap{$type} eq 'SOA') {
|
---|
| 2428 | my @tmp1 = split /:/, $host;
|
---|
| 2429 | my @tmp2 = split /:/, $val;
|
---|
[487] | 2430 | $self->_log(rdns_id => $rdns_id, group_id => $group,
|
---|
[286] | 2431 | entry => "[new $zone] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
[487] | 2432 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl");
|
---|
[270] | 2433 | $defttl = $tmp2[3];
|
---|
[260] | 2434 | } else {
|
---|
[446] | 2435 | my $logentry = "[new $zone] Added record '$host $typemap{$type} $val', TTL $ttl";
|
---|
[480] | 2436 | $logentry .= ", default location ".$self->getLoc($defloc)->{description} if $defloc;
|
---|
[487] | 2437 | $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group, entry => $logentry);
|
---|
[260] | 2438 | }
|
---|
| 2439 | }
|
---|
| 2440 |
|
---|
[270] | 2441 | # Generate record based on provided pattern.
|
---|
| 2442 | if ($revpatt) {
|
---|
| 2443 | my $host;
|
---|
| 2444 | my $type = ($zone->{isv6} ? 65284 : 65283);
|
---|
| 2445 | my $val = $zone->network;
|
---|
[269] | 2446 |
|
---|
[270] | 2447 | # Substitute $zone for ZONE in the hostname.
|
---|
| 2448 | $host = _ZONE($zone, $revpatt);
|
---|
| 2449 |
|
---|
| 2450 | my $domid = 0;
|
---|
[471] | 2451 | if (!($domid = $self->_hostparent($host))) {
|
---|
[270] | 2452 | $warnstr .= "\nDefault pattern added as PTR template instead of $typemap{$type}; domain not found for $host";
|
---|
| 2453 | $type = 65282;
|
---|
| 2454 | $domid = 0; # just to be explicit.
|
---|
| 2455 | }
|
---|
| 2456 |
|
---|
[446] | 2457 | $sth_in->execute($domid,$host,$type,$val,$defttl,$defloc);
|
---|
[286] | 2458 | my $logentry = "[new $zone] Added record '$host $typemap{$type}";
|
---|
[487] | 2459 | $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group,
|
---|
| 2460 | entry => $logentry." $val', TTL $defttl from pattern");
|
---|
[270] | 2461 | }
|
---|
| 2462 |
|
---|
[264] | 2463 | # If there are warnings (presumably about default records skipped for cause) log them
|
---|
[487] | 2464 | $self->_log(rdns_id => $rdns_id, group_id => $group, entry => "Warning(s) adding $zone:$warnstr")
|
---|
[264] | 2465 | if $warnstr;
|
---|
[269] | 2466 |
|
---|
[260] | 2467 | # once we get here, we should have suceeded.
|
---|
| 2468 | $dbh->commit;
|
---|
| 2469 | }; # end eval
|
---|
| 2470 |
|
---|
| 2471 | if ($@) {
|
---|
| 2472 | my $msg = $@;
|
---|
| 2473 | eval { $dbh->rollback; };
|
---|
[487] | 2474 | $self->_log(group_id => $group, entry => "Failed adding reverse zone $zone ($msg)")
|
---|
[517] | 2475 | if $self->{log_failures};
|
---|
[286] | 2476 | $dbh->commit; # since we enabled transactions earlier
|
---|
[260] | 2477 | return ('FAIL',$msg);
|
---|
| 2478 | } else {
|
---|
[286] | 2479 | my $retcode = 'OK';
|
---|
| 2480 | if ($warnstr) {
|
---|
| 2481 | $resultstr = $warnstr;
|
---|
| 2482 | $retcode = 'WARN';
|
---|
| 2483 | }
|
---|
| 2484 | return ($retcode, $rdns_id);
|
---|
[260] | 2485 | }
|
---|
| 2486 |
|
---|
| 2487 | } # end addRDNS()
|
---|
| 2488 |
|
---|
| 2489 |
|
---|
[237] | 2490 | ## DNSDB::getZoneCount
|
---|
| 2491 | # Get count of zones in group or groups
|
---|
| 2492 | # Takes a database handle and hash containing:
|
---|
| 2493 | # - the "current" group
|
---|
| 2494 | # - an array of "acceptable" groups
|
---|
| 2495 | # - a flag for forward/reverse zones
|
---|
| 2496 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
| 2497 | # Returns an integer count of the resulting zone list.
|
---|
| 2498 | sub getZoneCount {
|
---|
[477] | 2499 | my $self = shift;
|
---|
| 2500 | my $dbh = $self->{dbh};
|
---|
[237] | 2501 |
|
---|
| 2502 | my %args = @_;
|
---|
| 2503 |
|
---|
[509] | 2504 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 2505 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 2506 | $errstr = "Bad or missing curgroup argument";
|
---|
| 2507 | return;
|
---|
| 2508 | }
|
---|
| 2509 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 2510 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 2511 | $errstr = "Bad childlist argument";
|
---|
| 2512 | return;
|
---|
| 2513 | }
|
---|
| 2514 |
|
---|
[237] | 2515 | my @filterargs;
|
---|
[239] | 2516 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2517 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2518 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
[237] | 2519 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2520 |
|
---|
| 2521 | my $sql;
|
---|
| 2522 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
| 2523 | if ($args{revrec} eq 'n') {
|
---|
| 2524 | $sql = "SELECT count(*) FROM domains".
|
---|
| 2525 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2526 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
| 2527 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
| 2528 | } else {
|
---|
| 2529 | $sql = "SELECT count(*) FROM revzones".
|
---|
| 2530 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
[583] | 2531 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2532 | # if ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all') {
|
---|
| 2533 | # Just In Case the UI is using formal .arpa notation, and someone enters something reversed,
|
---|
| 2534 | # we want to match both the formal and natural zone name
|
---|
| 2535 | $sql .= ($args{filter} ? " AND (CAST(revnet AS VARCHAR) ~* ? OR CAST(revnet AS VARCHAR) ~* ?)" : '');
|
---|
| 2536 | push @filterargs, join('[.]',reverse(split(/\[\.\]/,$args{filter}))) if $args{filter};
|
---|
| 2537 | # } else {
|
---|
| 2538 | # $sql .= ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2539 | # }
|
---|
[237] | 2540 | }
|
---|
| 2541 | my ($count) = $dbh->selectrow_array($sql, undef, @filterargs);
|
---|
| 2542 | return $count;
|
---|
| 2543 | } # end getZoneCount()
|
---|
| 2544 |
|
---|
| 2545 |
|
---|
| 2546 | ## DNSDB::getZoneList()
|
---|
| 2547 | # Get a list of zones in the specified group(s)
|
---|
| 2548 | # Takes the same arguments as getZoneCount() above
|
---|
| 2549 | # Returns a reference to an array of hashrefs suitable for feeding to HTML::Template
|
---|
| 2550 | sub getZoneList {
|
---|
[477] | 2551 | my $self = shift;
|
---|
| 2552 | my $dbh = $self->{dbh};
|
---|
[237] | 2553 |
|
---|
| 2554 | my %args = @_;
|
---|
| 2555 |
|
---|
| 2556 | my @zonelist;
|
---|
| 2557 |
|
---|
[475] | 2558 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
[239] | 2559 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[237] | 2560 |
|
---|
[509] | 2561 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 2562 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 2563 | $errstr = "Bad or missing curgroup argument";
|
---|
| 2564 | return;
|
---|
| 2565 | }
|
---|
| 2566 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 2567 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 2568 | $errstr = "Bad childlist argument";
|
---|
| 2569 | return;
|
---|
| 2570 | }
|
---|
| 2571 |
|
---|
[237] | 2572 | my @filterargs;
|
---|
[239] | 2573 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2574 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2575 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
[237] | 2576 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2577 |
|
---|
| 2578 | my $sql;
|
---|
| 2579 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
| 2580 | if ($args{revrec} eq 'n') {
|
---|
[475] | 2581 | $args{sortby} = 'domain' if !$args{sortby} || !grep /^$args{sortby}$/, ('domain','group','status');
|
---|
[572] | 2582 | $sql = "SELECT domain_id AS zoneid,domain AS zone,status,groups.group_name AS group FROM domains".
|
---|
[237] | 2583 | " INNER JOIN groups ON domains.group_id=groups.group_id".
|
---|
| 2584 | " WHERE domains.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2585 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
| 2586 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
| 2587 | } else {
|
---|
[239] | 2588 | ##fixme: arguably startwith here is irrelevant. depends on the UI though.
|
---|
[475] | 2589 | $args{sortby} = 'revnet' if !$args{sortby} || !grep /^$args{sortby}$/, ('revnet','group','status');
|
---|
[572] | 2590 | $sql = "SELECT rdns_id AS zoneid,revnet AS zone,status,groups.group_name AS group FROM revzones".
|
---|
[237] | 2591 | " INNER JOIN groups ON revzones.group_id=groups.group_id".
|
---|
| 2592 | " WHERE revzones.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
[583] | 2593 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2594 | # if ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all') {
|
---|
| 2595 | # Just In Case the UI is using formal .arpa notation, and someone enters something reversed,
|
---|
| 2596 | # we want to match both the formal and natural zone name
|
---|
| 2597 | $sql .= ($args{filter} ? " AND (CAST(revnet AS VARCHAR) ~* ? OR CAST(revnet AS VARCHAR) ~* ?)" : '');
|
---|
| 2598 | push @filterargs, join('[.]',reverse(split(/\[\.\]/,$args{filter}))) if $args{filter};
|
---|
| 2599 | # } else {
|
---|
| 2600 | # $sql .= ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2601 | # }
|
---|
[237] | 2602 | }
|
---|
| 2603 | # A common tail.
|
---|
[239] | 2604 | $sql .= " ORDER BY ".($args{sortby} eq 'group' ? 'groups.group_name' : $args{sortby})." $args{sortorder} ".
|
---|
[517] | 2605 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage}".
|
---|
| 2606 | " OFFSET ".$args{offset}*$self->{perpage});
|
---|
[237] | 2607 |
|
---|
[583] | 2608 | my @working;
|
---|
| 2609 | my $zsth = $dbh->prepare($sql);
|
---|
| 2610 | $zsth->execute(@filterargs);
|
---|
| 2611 | while (my $zone = $zsth->fetchrow_hashref) {
|
---|
| 2612 | if ($args{revrec} eq 'y' && ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all')) {
|
---|
| 2613 | my $tmp = new NetAddr::IP $zone->{zone};
|
---|
| 2614 | $zone->{zone} = DNSDB::_ZONE($tmp, 'ZONE', 'r', '.').($tmp->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 2615 | }
|
---|
| 2616 | push @working, $zone;
|
---|
| 2617 | }
|
---|
| 2618 | return \@working;
|
---|
[237] | 2619 | } # end getZoneList()
|
---|
| 2620 |
|
---|
| 2621 |
|
---|
[383] | 2622 | ## DNSDB::getZoneLocation()
|
---|
[387] | 2623 | # Retrieve the default location for a zone.
|
---|
[383] | 2624 | # Takes a database handle, forward/reverse flag, and zone ID
|
---|
| 2625 | sub getZoneLocation {
|
---|
[477] | 2626 | my $self = shift;
|
---|
| 2627 | my $dbh = $self->{dbh};
|
---|
[383] | 2628 | my $revrec = shift;
|
---|
| 2629 | my $zoneid = shift;
|
---|
| 2630 |
|
---|
| 2631 | my ($loc) = $dbh->selectrow_array("SELECT default_location FROM ".
|
---|
| 2632 | ($revrec eq 'n' ? 'domains WHERE domain_id = ?' : 'revzones WHERE rdns_id = ?'),
|
---|
| 2633 | undef, ($zoneid));
|
---|
| 2634 | return $loc;
|
---|
| 2635 | } # end getZoneLocation()
|
---|
| 2636 |
|
---|
| 2637 |
|
---|
[18] | 2638 | ## DNSDB::addGroup()
|
---|
| 2639 | # Add a group
|
---|
[66] | 2640 | # Takes a database handle, group name, parent group, hashref for permissions,
|
---|
[292] | 2641 | # and optional template-vs-cloneme flag for the default records
|
---|
[18] | 2642 | # Returns a status code and message
|
---|
| 2643 | sub addGroup {
|
---|
| 2644 | $errstr = '';
|
---|
[476] | 2645 | my $self = shift;
|
---|
| 2646 | my $dbh = $self->{dbh};
|
---|
[20] | 2647 | my $groupname = shift;
|
---|
| 2648 | my $pargroup = shift;
|
---|
[66] | 2649 | my $permissions = shift;
|
---|
[18] | 2650 |
|
---|
[66] | 2651 | # 0 indicates "custom", hardcoded.
|
---|
[18] | 2652 | # Any other value clones that group's default records, if it exists.
|
---|
[66] | 2653 | my $inherit = shift || 0;
|
---|
| 2654 | ##fixme: need a flag to indicate clone records or <?> ?
|
---|
[18] | 2655 |
|
---|
| 2656 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2657 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2658 | local $dbh->{AutoCommit} = 0;
|
---|
| 2659 | local $dbh->{RaiseError} = 1;
|
---|
| 2660 |
|
---|
[292] | 2661 | my ($group_id) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($groupname));
|
---|
[38] | 2662 |
|
---|
| 2663 | return ('FAIL', "Group already exists") if $group_id;
|
---|
| 2664 |
|
---|
[18] | 2665 | # Wrap all the SQL in a transaction
|
---|
| 2666 | eval {
|
---|
[292] | 2667 | $dbh->do("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)", undef, ($pargroup, $groupname) );
|
---|
[18] | 2668 |
|
---|
[292] | 2669 | my ($groupid) = $dbh->selectrow_array("SELECT currval('groups_group_id_seq')");
|
---|
[18] | 2670 |
|
---|
[292] | 2671 | # We work through the whole set of permissions instead of specifying them so
|
---|
| 2672 | # that when we add a new permission, we don't have to change the code anywhere
|
---|
| 2673 | # that doesn't explicitly deal with that specific permission.
|
---|
| 2674 | my @permvals;
|
---|
| 2675 | foreach (@permtypes) {
|
---|
| 2676 | if (!defined ($permissions->{$_})) {
|
---|
| 2677 | push @permvals, 0;
|
---|
| 2678 | } else {
|
---|
| 2679 | push @permvals, $permissions->{$_};
|
---|
[66] | 2680 | }
|
---|
[292] | 2681 | }
|
---|
| 2682 | $dbh->do("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")",
|
---|
| 2683 | undef, ($groupid, @permvals) );
|
---|
| 2684 | my ($permid) = $dbh->selectrow_array("SELECT currval('permissions_permission_id_seq')");
|
---|
| 2685 | $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
|
---|
[66] | 2686 |
|
---|
[292] | 2687 | # Default records
|
---|
[255] | 2688 | my $sthf = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
|
---|
[20] | 2689 | "VALUES ($groupid,?,?,?,?,?,?,?)");
|
---|
[255] | 2690 | my $sthr = $dbh->prepare("INSERT INTO default_rev_records (group_id,host,type,val,ttl) ".
|
---|
| 2691 | "VALUES ($groupid,?,?,?,?)");
|
---|
[66] | 2692 | if ($inherit) {
|
---|
[87] | 2693 | # Duplicate records from parent. Actually relying on inherited records feels
|
---|
| 2694 | # very fragile, and it would be problematic to roll over at a later time.
|
---|
[18] | 2695 | my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
[87] | 2696 | $sth2->execute($pargroup);
|
---|
[18] | 2697 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
[255] | 2698 | $sthf->execute(@clonedata);
|
---|
[18] | 2699 | }
|
---|
[255] | 2700 | # And now the reverse records
|
---|
[292] | 2701 | $sth2 = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
[255] | 2702 | $sth2->execute($pargroup);
|
---|
| 2703 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
| 2704 | $sthr->execute(@clonedata);
|
---|
| 2705 | }
|
---|
[18] | 2706 | } else {
|
---|
[66] | 2707 | ##fixme: Hardcoding is Bad, mmmmkaaaay?
|
---|
[18] | 2708 | # reasonable basic defaults for SOA, MX, NS, and minimal hosting
|
---|
| 2709 | # could load from a config file, but somewhere along the line we need hardcoded bits.
|
---|
[255] | 2710 | $sthf->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
|
---|
| 2711 | $sthf->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
|
---|
| 2712 | $sthf->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
|
---|
| 2713 | $sthf->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
|
---|
| 2714 | $sthf->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
|
---|
| 2715 | $sthf->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
|
---|
| 2716 | # reasonable basic defaults for generic reverse zone. Same as initial SQL tabledef.
|
---|
| 2717 | $sthr->execute('hostmaster.ADMINDOMAIN:ns1.ADMINDOMAIN', 6, '10800:3600:604800:10800', 86400);
|
---|
| 2718 | $sthr->execute('unused-%r.ADMINDOMAIN', 65283, 'ZONE', 3600);
|
---|
[18] | 2719 | }
|
---|
| 2720 |
|
---|
[487] | 2721 | $self->_log(group_id => $pargroup, entry => "Added group $groupname");
|
---|
[292] | 2722 |
|
---|
[18] | 2723 | # once we get here, we should have suceeded.
|
---|
| 2724 | $dbh->commit;
|
---|
| 2725 | }; # end eval
|
---|
| 2726 |
|
---|
| 2727 | if ($@) {
|
---|
| 2728 | my $msg = $@;
|
---|
| 2729 | eval { $dbh->rollback; };
|
---|
[517] | 2730 | if ($self->{log_failures}) {
|
---|
[487] | 2731 | $self->_log(group_id => $pargroup, entry => "Failed to add group $groupname: $msg");
|
---|
[292] | 2732 | $dbh->commit;
|
---|
| 2733 | }
|
---|
[18] | 2734 | return ('FAIL',$msg);
|
---|
| 2735 | }
|
---|
| 2736 |
|
---|
[292] | 2737 | return ('OK','OK');
|
---|
[18] | 2738 | } # end addGroup()
|
---|
| 2739 |
|
---|
| 2740 |
|
---|
[22] | 2741 | ## DNSDB::delGroup()
|
---|
| 2742 | # Delete a group.
|
---|
| 2743 | # Takes a group ID
|
---|
| 2744 | # Returns a status code and message
|
---|
| 2745 | sub delGroup {
|
---|
[476] | 2746 | my $self = shift;
|
---|
| 2747 | my $dbh = $self->{dbh};
|
---|
[22] | 2748 | my $groupid = shift;
|
---|
| 2749 |
|
---|
| 2750 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2751 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2752 | local $dbh->{AutoCommit} = 0;
|
---|
| 2753 | local $dbh->{RaiseError} = 1;
|
---|
| 2754 |
|
---|
| 2755 | ##fixme: locate "knowable" error conditions and deal with them before the eval
|
---|
[23] | 2756 | # ... or inside, whatever.
|
---|
[22] | 2757 | # -> domains still exist in group
|
---|
| 2758 | # -> ...
|
---|
[23] | 2759 | my $failmsg = '';
|
---|
[293] | 2760 | my $resultmsg = '';
|
---|
[22] | 2761 |
|
---|
[293] | 2762 | # collect some pieces for logging and error messages
|
---|
[473] | 2763 | my $groupname = $self->groupName($groupid);
|
---|
| 2764 | my $parid = $self->parentID(id => $groupid, type => 'group');
|
---|
[293] | 2765 |
|
---|
[22] | 2766 | # Wrap all the SQL in a transaction
|
---|
| 2767 | eval {
|
---|
[293] | 2768 | # Check for Things in the group
|
---|
| 2769 | $failmsg = "Can't remove group $groupname";
|
---|
| 2770 | my ($grpcnt) = $dbh->selectrow_array("SELECT count(*) FROM groups WHERE parent_group_id=?", undef, ($groupid));
|
---|
| 2771 | die "$grpcnt groups still in group\n" if $grpcnt;
|
---|
| 2772 | my ($domcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($groupid));
|
---|
[23] | 2773 | die "$domcnt domains still in group\n" if $domcnt;
|
---|
[512] | 2774 | my ($revcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($groupid));
|
---|
| 2775 | die "$revcnt reverse zones still in group\n" if $revcnt;
|
---|
[293] | 2776 | my ($usercnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($groupid));
|
---|
| 2777 | die "$usercnt users still in group\n" if $usercnt;
|
---|
[23] | 2778 |
|
---|
[293] | 2779 | $failmsg = "Failed to delete default records for $groupname";
|
---|
| 2780 | $dbh->do("DELETE from default_records WHERE group_id=?", undef, ($groupid));
|
---|
| 2781 | $failmsg = "Failed to delete default reverse records for $groupname";
|
---|
| 2782 | $dbh->do("DELETE from default_rev_records WHERE group_id=?", undef, ($groupid));
|
---|
| 2783 | $failmsg = "Failed to remove group $groupname";
|
---|
| 2784 | $dbh->do("DELETE from groups WHERE group_id=?", undef, ($groupid));
|
---|
[22] | 2785 |
|
---|
[487] | 2786 | $self->_log(group_id => $parid, entry => "Deleted group $groupname");
|
---|
[293] | 2787 | $resultmsg = "Deleted group $groupname";
|
---|
| 2788 |
|
---|
[22] | 2789 | # once we get here, we should have suceeded.
|
---|
| 2790 | $dbh->commit;
|
---|
| 2791 | }; # end eval
|
---|
| 2792 |
|
---|
| 2793 | if ($@) {
|
---|
| 2794 | my $msg = $@;
|
---|
| 2795 | eval { $dbh->rollback; };
|
---|
[517] | 2796 | if ($self->{log_failures}) {
|
---|
[487] | 2797 | $self->_log(group_id => $parid, entry => "$failmsg: $msg");
|
---|
[293] | 2798 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2799 | }
|
---|
[23] | 2800 | return ('FAIL',"$failmsg: $msg");
|
---|
[22] | 2801 | }
|
---|
[293] | 2802 |
|
---|
| 2803 | return ('OK',$resultmsg);
|
---|
[22] | 2804 | } # end delGroup()
|
---|
| 2805 |
|
---|
| 2806 |
|
---|
[19] | 2807 | ## DNSDB::getChildren()
|
---|
| 2808 | # Get a list of all groups whose parent^n is group <n>
|
---|
[24] | 2809 | # Takes a database handle, group ID, reference to an array to put the group IDs in,
|
---|
| 2810 | # and an optional flag to return only immediate children or all children-of-children
|
---|
| 2811 | # default to returning all children
|
---|
[19] | 2812 | # Calls itself
|
---|
| 2813 | sub getChildren {
|
---|
| 2814 | $errstr = '';
|
---|
[476] | 2815 | my $self = shift;
|
---|
| 2816 | my $dbh = $self->{dbh};
|
---|
[20] | 2817 | my $rootgroup = shift;
|
---|
| 2818 | my $groupdest = shift;
|
---|
[24] | 2819 | my $immed = shift || 'all';
|
---|
[19] | 2820 |
|
---|
| 2821 | # special break for default group; otherwise we get stuck.
|
---|
[20] | 2822 | if ($rootgroup == 1) {
|
---|
[19] | 2823 | # by definition, group 1 is the Root Of All Groups
|
---|
[24] | 2824 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
|
---|
[331] | 2825 | ($immed ne 'all' ? " AND parent_group_id=1" : '')." ORDER BY group_name");
|
---|
[19] | 2826 | $sth->execute;
|
---|
| 2827 | while (my @this = $sth->fetchrow_array) {
|
---|
[20] | 2828 | push @$groupdest, @this;
|
---|
[19] | 2829 | }
|
---|
| 2830 | } else {
|
---|
[331] | 2831 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=? ORDER BY group_name");
|
---|
[20] | 2832 | $sth->execute($rootgroup);
|
---|
[19] | 2833 | return if $sth->rows == 0;
|
---|
[20] | 2834 | my @grouplist;
|
---|
| 2835 | while (my ($group) = $sth->fetchrow_array) {
|
---|
| 2836 | push @$groupdest, $group;
|
---|
[476] | 2837 | $self->getChildren($group, $groupdest) if $immed eq 'all';
|
---|
[19] | 2838 | }
|
---|
| 2839 | }
|
---|
| 2840 | } # end getChildren()
|
---|
| 2841 |
|
---|
| 2842 |
|
---|
[20] | 2843 | ## DNSDB::groupName()
|
---|
[17] | 2844 | # Return the group name based on a group ID
|
---|
| 2845 | # Takes a database handle and the group ID
|
---|
| 2846 | # Returns the group name or undef on failure
|
---|
[20] | 2847 | sub groupName {
|
---|
[13] | 2848 | $errstr = '';
|
---|
[473] | 2849 | my $self = shift;
|
---|
| 2850 | my $dbh = $self->{dbh};
|
---|
[20] | 2851 | my $groupid = shift;
|
---|
| 2852 | my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
|
---|
| 2853 | $sth->execute($groupid);
|
---|
| 2854 | my ($groupname) = $sth->fetchrow_array();
|
---|
| 2855 | $errstr = $DBI::errstr if !$groupname;
|
---|
| 2856 | return $groupname if $groupname;
|
---|
| 2857 | } # end groupName
|
---|
[13] | 2858 |
|
---|
| 2859 |
|
---|
[314] | 2860 | ## DNSDB::getGroupCount()
|
---|
| 2861 | # Get count of subgroups in group or groups
|
---|
| 2862 | # Takes a database handle and hash containing:
|
---|
| 2863 | # - the "current" group
|
---|
| 2864 | # - an array of "acceptable" groups
|
---|
| 2865 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
| 2866 | # Returns an integer count of the resulting group list.
|
---|
| 2867 | sub getGroupCount {
|
---|
[476] | 2868 | my $self = shift;
|
---|
| 2869 | my $dbh = $self->{dbh};
|
---|
[314] | 2870 |
|
---|
| 2871 | my %args = @_;
|
---|
| 2872 |
|
---|
[509] | 2873 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 2874 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 2875 | $errstr = "Bad or missing curgroup argument";
|
---|
| 2876 | return;
|
---|
| 2877 | }
|
---|
| 2878 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 2879 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 2880 | $errstr = "Bad childlist argument";
|
---|
| 2881 | return;
|
---|
| 2882 | }
|
---|
| 2883 |
|
---|
[314] | 2884 | my @filterargs;
|
---|
| 2885 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2886 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2887 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2888 |
|
---|
| 2889 | my $sql = "SELECT count(*) FROM groups ".
|
---|
| 2890 | "WHERE parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2891 | ($args{startwith} ? " AND group_name ~* ?" : '').
|
---|
| 2892 | ($args{filter} ? " AND group_name ~* ?" : '');
|
---|
| 2893 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 2894 | $errstr = $dbh->errstr if !$count;
|
---|
| 2895 | return $count;
|
---|
| 2896 | } # end getGroupCount
|
---|
| 2897 |
|
---|
| 2898 |
|
---|
| 2899 | ## DNSDB::getGroupList()
|
---|
| 2900 | # Get a list of sub^n-groups in the specified group(s)
|
---|
| 2901 | # Takes the same arguments as getGroupCount() above
|
---|
| 2902 | # Returns an arrayref containing hashrefs suitable for feeding straight to HTML::Template
|
---|
| 2903 | sub getGroupList {
|
---|
[476] | 2904 | my $self = shift;
|
---|
| 2905 | my $dbh = $self->{dbh};
|
---|
[314] | 2906 |
|
---|
| 2907 | my %args = @_;
|
---|
| 2908 |
|
---|
[509] | 2909 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 2910 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 2911 | $errstr = "Bad or missing curgroup argument";
|
---|
| 2912 | return;
|
---|
| 2913 | }
|
---|
| 2914 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 2915 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 2916 | $errstr = "Bad childlist argument";
|
---|
| 2917 | return;
|
---|
| 2918 | }
|
---|
| 2919 |
|
---|
[314] | 2920 | my @filterargs;
|
---|
| 2921 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2922 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2923 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2924 |
|
---|
| 2925 | # protection against bad or missing arguments
|
---|
[508] | 2926 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
| 2927 | $args{sortby} = 'group' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
[397] | 2928 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[314] | 2929 |
|
---|
| 2930 | # munge sortby for columns in database
|
---|
| 2931 | $args{sortby} = 'g.group_name' if $args{sortby} eq 'group';
|
---|
| 2932 | $args{sortby} = 'g2.group_name' if $args{sortby} eq 'parent';
|
---|
| 2933 |
|
---|
[385] | 2934 | my $sql = q(SELECT g.group_id AS groupid, g.group_name AS groupname, g2.group_name AS pgroup
|
---|
[314] | 2935 | FROM groups g
|
---|
| 2936 | INNER JOIN groups g2 ON g2.group_id=g.parent_group_id
|
---|
| 2937 | ).
|
---|
[385] | 2938 | " WHERE g.parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
[314] | 2939 | ($args{startwith} ? " AND g.group_name ~* ?" : '').
|
---|
| 2940 | ($args{filter} ? " AND g.group_name ~* ?" : '').
|
---|
| 2941 | " GROUP BY g.group_id, g.group_name, g2.group_name ".
|
---|
| 2942 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
[517] | 2943 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
[314] | 2944 | my $glist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 2945 | $errstr = $dbh->errstr if !$glist;
|
---|
[385] | 2946 |
|
---|
| 2947 | # LEFT JOINs make the result set balloon beyond sanity just to include counts;
|
---|
| 2948 | # this means there's lots of crunching needed to trim the result set back down.
|
---|
| 2949 | # So instead we track the order of the groups, and push the counts into the
|
---|
| 2950 | # arrayref result separately.
|
---|
| 2951 | ##fixme: put this whole sub in a transaction? might be
|
---|
| 2952 | # needed for accurate results on very busy systems.
|
---|
[386] | 2953 | ##fixme: large group lists need prepared statements?
|
---|
| 2954 | #my $ucsth = $dbh->prepare("SELECT count(*) FROM users WHERE group_id=?");
|
---|
| 2955 | #my $dcsth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
|
---|
| 2956 | #my $rcsth = $dbh->prepare("SELECT count(*) FROM revzones WHERE group_id=?");
|
---|
[385] | 2957 | foreach (@{$glist}) {
|
---|
[386] | 2958 | my ($ucnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 2959 | $$_{nusers} = $ucnt;
|
---|
| 2960 | my ($dcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 2961 | $$_{ndomains} = $dcnt;
|
---|
| 2962 | my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 2963 | $$_{nrevzones} = $rcnt;
|
---|
[385] | 2964 | }
|
---|
| 2965 |
|
---|
[314] | 2966 | return $glist;
|
---|
| 2967 | } # end getGroupList
|
---|
| 2968 |
|
---|
| 2969 |
|
---|
[118] | 2970 | ## DNSDB::groupID()
|
---|
| 2971 | # Return the group ID based on the group name
|
---|
| 2972 | # Takes a database handle and the group name
|
---|
| 2973 | # Returns the group ID or undef on failure
|
---|
| 2974 | sub groupID {
|
---|
| 2975 | $errstr = '';
|
---|
[473] | 2976 | my $self = shift;
|
---|
| 2977 | my $dbh = $self->{dbh};
|
---|
[118] | 2978 | my $group = shift;
|
---|
[406] | 2979 | my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($group) );
|
---|
[118] | 2980 | $errstr = $DBI::errstr if !$grpid;
|
---|
| 2981 | return $grpid if $grpid;
|
---|
| 2982 | } # end groupID()
|
---|
| 2983 |
|
---|
| 2984 |
|
---|
[24] | 2985 | ## DNSDB::addUser()
|
---|
[87] | 2986 | # Add a user.
|
---|
| 2987 | # Takes a DB handle, username, group ID, password, state (active/inactive).
|
---|
| 2988 | # Optionally accepts:
|
---|
| 2989 | # user type (user/admin) - defaults to user
|
---|
| 2990 | # permissions string - defaults to inherit from group
|
---|
| 2991 | # three valid forms:
|
---|
| 2992 | # i - Inherit permissions
|
---|
| 2993 | # c:<user_id> - Clone permissions from <user_id>
|
---|
| 2994 | # C:<permission list> - Set these specific permissions
|
---|
| 2995 | # first name - defaults to username
|
---|
| 2996 | # last name - defaults to blank
|
---|
| 2997 | # phone - defaults to blank (could put other data within column def)
|
---|
[90] | 2998 | # Returns (OK,<uid>) on success, (FAIL,<message>) on failure
|
---|
[24] | 2999 | sub addUser {
|
---|
| 3000 | $errstr = '';
|
---|
[479] | 3001 | my $self = shift;
|
---|
| 3002 | my $dbh = $self->{dbh};
|
---|
[24] | 3003 | my $username = shift;
|
---|
| 3004 | my $group = shift;
|
---|
| 3005 | my $pass = shift;
|
---|
| 3006 | my $state = shift;
|
---|
[25] | 3007 |
|
---|
[90] | 3008 | return ('FAIL', "Missing one or more required entries") if !defined($state);
|
---|
| 3009 | return ('FAIL', "Username must not be blank") if !$username;
|
---|
[87] | 3010 |
|
---|
[408] | 3011 | # Munge in some alternate state values
|
---|
| 3012 | $state = 1 if $state =~ /^active$/;
|
---|
| 3013 | $state = 1 if $state =~ /^on$/;
|
---|
| 3014 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 3015 | $state = 0 if $state =~ /^off$/;
|
---|
| 3016 |
|
---|
[25] | 3017 | my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
|
---|
| 3018 |
|
---|
[67] | 3019 | my $permstring = shift || 'i'; # default is to inhert permissions from group
|
---|
| 3020 |
|
---|
[25] | 3021 | my $fname = shift || $username;
|
---|
[24] | 3022 | my $lname = shift || '';
|
---|
[25] | 3023 | my $phone = shift || ''; # not going format-check
|
---|
[24] | 3024 |
|
---|
[38] | 3025 | my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
|
---|
[24] | 3026 | my $user_id;
|
---|
| 3027 |
|
---|
[38] | 3028 | # quick check to start to see if we've already got one
|
---|
| 3029 | $sth->execute($username);
|
---|
| 3030 | ($user_id) = $sth->fetchrow_array;
|
---|
| 3031 |
|
---|
| 3032 | return ('FAIL', "User already exists") if $user_id;
|
---|
| 3033 |
|
---|
[24] | 3034 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3035 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3036 | local $dbh->{AutoCommit} = 0;
|
---|
| 3037 | local $dbh->{RaiseError} = 1;
|
---|
| 3038 |
|
---|
| 3039 | # Wrap all the SQL in a transaction
|
---|
| 3040 | eval {
|
---|
[87] | 3041 | # insert the user... note we set inherited perms by default since
|
---|
| 3042 | # it's simple and cleans up some other bits of state
|
---|
[592] | 3043 | ##fixme: need better handling of case of inherited or missing (!!) permissions entries
|
---|
[87] | 3044 | my $sth = $dbh->prepare("INSERT INTO users ".
|
---|
| 3045 | "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
|
---|
| 3046 | "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
|
---|
| 3047 | $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);
|
---|
[24] | 3048 |
|
---|
| 3049 | # get the ID...
|
---|
[94] | 3050 | ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");
|
---|
[24] | 3051 |
|
---|
[87] | 3052 | # Permissions! Gotta set'em all!
|
---|
[401] | 3053 | die "Invalid permission string $permstring\n"
|
---|
[87] | 3054 | if $permstring !~ /^(?:
|
---|
| 3055 | i # inherit
|
---|
| 3056 | |c:\d+ # clone
|
---|
| 3057 | # custom. no, the leading , is not a typo
|
---|
[391] | 3058 | |C:(?:,(?:group|user|domain|record|location|self)_(?:edit|create|delete|locchg|view))*
|
---|
[87] | 3059 | )$/x;
|
---|
| 3060 | # bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
|
---|
| 3061 | if ($permstring ne 'i') {
|
---|
| 3062 | # for cloned or custom permissions, we have to create a new permissions entry.
|
---|
| 3063 | my $clonesrc = $group;
|
---|
| 3064 | if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
|
---|
| 3065 | $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
|
---|
| 3066 | "SELECT $permlist,? FROM permissions WHERE permission_id=".
|
---|
| 3067 | "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
|
---|
| 3068 | undef, ($user_id,$clonesrc) );
|
---|
| 3069 | $dbh->do("UPDATE users SET permission_id=".
|
---|
| 3070 | "(SELECT permission_id FROM permissions WHERE user_id=?) ".
|
---|
| 3071 | "WHERE user_id=?", undef, ($user_id, $user_id) );
|
---|
| 3072 | }
|
---|
| 3073 | if ($permstring =~ /^C:/) {
|
---|
| 3074 | # finally for custom permissions, we set the passed-in permissions (and unset
|
---|
| 3075 | # any that might have been brought in by the clone operation above)
|
---|
| 3076 | my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
|
---|
| 3077 | undef, ($user_id) );
|
---|
| 3078 | foreach (@permtypes) {
|
---|
| 3079 | if ($permstring =~ /,$_/) {
|
---|
| 3080 | $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
|
---|
| 3081 | } else {
|
---|
| 3082 | $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
|
---|
| 3083 | }
|
---|
| 3084 | }
|
---|
| 3085 | }
|
---|
| 3086 |
|
---|
| 3087 | $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
|
---|
| 3088 |
|
---|
[25] | 3089 | ##fixme: add another table to hold name/email for log table?
|
---|
| 3090 |
|
---|
[487] | 3091 | $self->_log(group_id => $group, entry => "Added user $username ($fname $lname)");
|
---|
[24] | 3092 | # once we get here, we should have suceeded.
|
---|
| 3093 | $dbh->commit;
|
---|
| 3094 | }; # end eval
|
---|
| 3095 |
|
---|
| 3096 | if ($@) {
|
---|
| 3097 | my $msg = $@;
|
---|
| 3098 | eval { $dbh->rollback; };
|
---|
[517] | 3099 | if ($self->{log_failures}) {
|
---|
[487] | 3100 | $self->_log(group_id => $group, entry => "Error adding user $username: $msg");
|
---|
[294] | 3101 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 3102 | }
|
---|
| 3103 | return ('FAIL',"Error adding user $username: $msg");
|
---|
[24] | 3104 | }
|
---|
[294] | 3105 |
|
---|
| 3106 | return ('OK',"User $username ($fname $lname) added");
|
---|
[24] | 3107 | } # end addUser
|
---|
| 3108 |
|
---|
| 3109 |
|
---|
[325] | 3110 | ## DNSDB::getUserCount()
|
---|
| 3111 | # Get count of users in group
|
---|
| 3112 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
| 3113 | # - a reference list of secondary groups
|
---|
| 3114 | # - a filter string
|
---|
| 3115 | # - a "Starts with" string
|
---|
| 3116 | sub getUserCount {
|
---|
[479] | 3117 | my $self = shift;
|
---|
| 3118 | my $dbh = $self->{dbh};
|
---|
[325] | 3119 |
|
---|
| 3120 | my %args = @_;
|
---|
| 3121 |
|
---|
[509] | 3122 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 3123 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 3124 | $errstr = "Bad or missing curgroup argument";
|
---|
| 3125 | return;
|
---|
| 3126 | }
|
---|
| 3127 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 3128 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 3129 | $errstr = "Bad childlist argument";
|
---|
| 3130 | return;
|
---|
| 3131 | }
|
---|
| 3132 |
|
---|
[325] | 3133 | my @filterargs;
|
---|
| 3134 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3135 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3136 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3137 |
|
---|
| 3138 | my $sql = "SELECT count(*) FROM users ".
|
---|
| 3139 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3140 | ($args{startwith} ? " AND username ~* ?" : '').
|
---|
| 3141 | ($args{filter} ? " AND username ~* ?" : '');
|
---|
| 3142 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 3143 | $errstr = $dbh->errstr if !$count;
|
---|
| 3144 | return $count;
|
---|
| 3145 | } # end getUserCount()
|
---|
| 3146 |
|
---|
| 3147 |
|
---|
| 3148 | ## DNSDB::getUserList()
|
---|
| 3149 | # Get list of users
|
---|
| 3150 | # Takes the same arguments as getUserCount() above, plus optional:
|
---|
| 3151 | # - sort field
|
---|
| 3152 | # - sort order
|
---|
| 3153 | # - offset/return-all-everything flag (defaults to $perpage records)
|
---|
| 3154 | sub getUserList {
|
---|
[479] | 3155 | my $self = shift;
|
---|
| 3156 | my $dbh = $self->{dbh};
|
---|
[325] | 3157 |
|
---|
| 3158 | my %args = @_;
|
---|
| 3159 |
|
---|
[509] | 3160 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 3161 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 3162 | $errstr = "Bad or missing curgroup argument";
|
---|
| 3163 | return;
|
---|
| 3164 | }
|
---|
| 3165 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 3166 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 3167 | $errstr = "Bad childlist argument";
|
---|
| 3168 | return;
|
---|
| 3169 | }
|
---|
| 3170 |
|
---|
[325] | 3171 | my @filterargs;
|
---|
| 3172 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3173 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3174 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3175 |
|
---|
| 3176 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
| 3177 | my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
| 3178 | fname => 'fname');
|
---|
| 3179 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 3180 |
|
---|
| 3181 | # protection against bad or missing arguments
|
---|
[508] | 3182 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
| 3183 | $args{sortby} = 'u.username' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
[397] | 3184 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[325] | 3185 |
|
---|
| 3186 | my $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ".
|
---|
| 3187 | "FROM users u ".
|
---|
| 3188 | "INNER JOIN groups g ON u.group_id=g.group_id ".
|
---|
| 3189 | "WHERE u.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3190 | ($args{startwith} ? " AND u.username ~* ?" : '').
|
---|
| 3191 | ($args{filter} ? " AND u.username ~* ?" : '').
|
---|
[401] | 3192 | " AND NOT u.type = 'R' ".
|
---|
[325] | 3193 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
[517] | 3194 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
[325] | 3195 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 3196 | $errstr = $dbh->errstr if !$ulist;
|
---|
| 3197 | return $ulist;
|
---|
| 3198 | } # end getUserList()
|
---|
| 3199 |
|
---|
| 3200 |
|
---|
[326] | 3201 | ## DNSDB::getUserDropdown()
|
---|
| 3202 | # Get a list of usernames for use in a dropdown menu.
|
---|
| 3203 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
| 3204 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
| 3205 | sub getUserDropdown {
|
---|
[479] | 3206 | my $self = shift;
|
---|
| 3207 | my $dbh = $self->{dbh};
|
---|
[326] | 3208 | my $grp = shift;
|
---|
| 3209 | my $sel = shift || 0;
|
---|
| 3210 |
|
---|
| 3211 | my $sth = $dbh->prepare("SELECT username,user_id FROM users WHERE group_id=?");
|
---|
| 3212 | $sth->execute($grp);
|
---|
| 3213 |
|
---|
| 3214 | my @userlist;
|
---|
| 3215 | while (my ($username,$uid) = $sth->fetchrow_array) {
|
---|
| 3216 | my %row = (
|
---|
| 3217 | username => $username,
|
---|
| 3218 | uid => $uid,
|
---|
| 3219 | selected => ($sel == $uid ? 1 : 0)
|
---|
| 3220 | );
|
---|
| 3221 | push @userlist, \%row;
|
---|
| 3222 | }
|
---|
| 3223 | return \@userlist;
|
---|
| 3224 | } # end getUserDropdown()
|
---|
| 3225 |
|
---|
| 3226 |
|
---|
[83] | 3227 | ## DNSDB:: updateUser()
|
---|
[90] | 3228 | # Update general data about user
|
---|
[83] | 3229 | sub updateUser {
|
---|
[479] | 3230 | my $self = shift;
|
---|
| 3231 | my $dbh = $self->{dbh};
|
---|
[118] | 3232 |
|
---|
| 3233 | ##fixme: tweak calling convention so that we can update any given bit of data
|
---|
[83] | 3234 | my $uid = shift;
|
---|
| 3235 | my $username = shift;
|
---|
| 3236 | my $group = shift;
|
---|
| 3237 | my $pass = shift;
|
---|
| 3238 | my $state = shift;
|
---|
[87] | 3239 | my $type = shift || 'u';
|
---|
[83] | 3240 | my $fname = shift || $username;
|
---|
| 3241 | my $lname = shift || '';
|
---|
| 3242 | my $phone = shift || ''; # not going format-check
|
---|
| 3243 |
|
---|
[294] | 3244 | my $resultmsg = '';
|
---|
[83] | 3245 |
|
---|
[411] | 3246 | # Munge in some alternate state values
|
---|
| 3247 | $state = 1 if $state =~ /^active$/;
|
---|
| 3248 | $state = 1 if $state =~ /^on$/;
|
---|
| 3249 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 3250 | $state = 0 if $state =~ /^off$/;
|
---|
| 3251 |
|
---|
[83] | 3252 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3253 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3254 | local $dbh->{AutoCommit} = 0;
|
---|
| 3255 | local $dbh->{RaiseError} = 1;
|
---|
| 3256 |
|
---|
| 3257 | my $sth;
|
---|
| 3258 |
|
---|
| 3259 | # Password can be left blank; if so we assume there's one on file.
|
---|
| 3260 | # Actual blank passwords are bad, mm'kay?
|
---|
| 3261 | if (!$pass) {
|
---|
[294] | 3262 | ($pass) = $dbh->selectrow_array("SELECT password FROM users WHERE user_id=?", undef, ($uid));
|
---|
[83] | 3263 | } else {
|
---|
| 3264 | $pass = unix_md5_crypt($pass);
|
---|
| 3265 | }
|
---|
| 3266 |
|
---|
| 3267 | eval {
|
---|
[294] | 3268 | $dbh->do("UPDATE users SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?".
|
---|
| 3269 | " WHERE user_id=?", undef, ($username, $pass, $fname, $lname, $phone, $type, $state, $uid));
|
---|
| 3270 | $resultmsg = "Updated user info for $username ($fname $lname)";
|
---|
[487] | 3271 | $self->_log(group_id => $group, entry => $resultmsg);
|
---|
[83] | 3272 | $dbh->commit;
|
---|
| 3273 | };
|
---|
| 3274 | if ($@) {
|
---|
| 3275 | my $msg = $@;
|
---|
| 3276 | eval { $dbh->rollback; };
|
---|
[517] | 3277 | if ($self->{log_failures}) {
|
---|
[487] | 3278 | $self->_log(group_id => $group, entry => "Error updating user $username: $msg");
|
---|
[294] | 3279 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 3280 | }
|
---|
| 3281 | return ('FAIL',"Error updating user $username: $msg");
|
---|
[83] | 3282 | }
|
---|
[294] | 3283 |
|
---|
| 3284 | return ('OK',$resultmsg);
|
---|
[83] | 3285 | } # end updateUser()
|
---|
| 3286 |
|
---|
| 3287 |
|
---|
[24] | 3288 | ## DNSDB::delUser()
|
---|
[297] | 3289 | # Delete a user.
|
---|
| 3290 | # Takes a database handle and user ID
|
---|
| 3291 | # Returns a success/failure code and matching message
|
---|
[24] | 3292 | sub delUser {
|
---|
[479] | 3293 | my $self = shift;
|
---|
| 3294 | my $dbh = $self->{dbh};
|
---|
[25] | 3295 | my $userid = shift;
|
---|
| 3296 |
|
---|
[297] | 3297 | return ('FAIL',"Bad userid") if !defined($userid);
|
---|
[25] | 3298 |
|
---|
[479] | 3299 | my $userdata = $self->getUserData($userid);
|
---|
[25] | 3300 |
|
---|
[297] | 3301 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3302 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3303 | local $dbh->{AutoCommit} = 0;
|
---|
| 3304 | local $dbh->{RaiseError} = 1;
|
---|
[25] | 3305 |
|
---|
[297] | 3306 | eval {
|
---|
| 3307 | $dbh->do("DELETE FROM users WHERE user_id=?", undef, ($userid));
|
---|
[487] | 3308 | $self->_log(group_id => $userdata->{group_id},
|
---|
[297] | 3309 | entry => "Deleted user ID $userid/".$userdata->{username}.
|
---|
[487] | 3310 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")");
|
---|
[297] | 3311 | $dbh->commit;
|
---|
| 3312 | };
|
---|
| 3313 | if ($@) {
|
---|
| 3314 | my $msg = $@;
|
---|
| 3315 | eval { $dbh->rollback; };
|
---|
[517] | 3316 | if ($self->{log_failures}) {
|
---|
[487] | 3317 | $self->_log(group_id => $userdata->{group_id}, entry => "Error deleting user ID ".
|
---|
| 3318 | "$userid/".$userdata->{username}.": $msg");
|
---|
[297] | 3319 | $dbh->commit;
|
---|
| 3320 | }
|
---|
| 3321 | return ('FAIL',"Error deleting user $userid/".$userdata->{username}.": $msg");
|
---|
| 3322 | }
|
---|
| 3323 |
|
---|
| 3324 | return ('OK',"Deleted user ".$userdata->{username}." (".$userdata->{firstname}." ".$userdata->{lastname}.")");
|
---|
[24] | 3325 | } # end delUser
|
---|
| 3326 |
|
---|
| 3327 |
|
---|
[25] | 3328 | ## DNSDB::userFullName()
|
---|
| 3329 | # Return a pretty string!
|
---|
| 3330 | # Takes a user_id and optional printf-ish string to indicate which pieces where:
|
---|
| 3331 | # %u for the username
|
---|
| 3332 | # %f for the first name
|
---|
| 3333 | # %l for the last name
|
---|
| 3334 | # All other text in the passed string will be left as-is.
|
---|
| 3335 | ##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
|
---|
| 3336 | sub userFullName {
|
---|
| 3337 | $errstr = '';
|
---|
[473] | 3338 | my $self = shift;
|
---|
| 3339 | my $dbh = $self->{dbh};
|
---|
[25] | 3340 | my $userid = shift;
|
---|
| 3341 | my $fullformat = shift || '%f %l (%u)';
|
---|
| 3342 | my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
|
---|
| 3343 | $sth->execute($userid);
|
---|
| 3344 | my ($uname,$fname,$lname) = $sth->fetchrow_array();
|
---|
| 3345 | $errstr = $DBI::errstr if !$uname;
|
---|
| 3346 |
|
---|
| 3347 | $fullformat =~ s/\%u/$uname/g;
|
---|
| 3348 | $fullformat =~ s/\%f/$fname/g;
|
---|
| 3349 | $fullformat =~ s/\%l/$lname/g;
|
---|
| 3350 |
|
---|
| 3351 | return $fullformat;
|
---|
| 3352 | } # end userFullName
|
---|
| 3353 |
|
---|
| 3354 |
|
---|
[51] | 3355 | ## DNSDB::userStatus()
|
---|
| 3356 | # Sets and/or returns a user's status
|
---|
| 3357 | # Takes a database handle, user ID and optionally a status argument
|
---|
| 3358 | # Returns undef on errors.
|
---|
| 3359 | sub userStatus {
|
---|
[479] | 3360 | my $self = shift;
|
---|
| 3361 | my $dbh = $self->{dbh};
|
---|
[51] | 3362 | my $id = shift;
|
---|
[296] | 3363 | my $newstatus = shift || 'mu';
|
---|
[51] | 3364 |
|
---|
| 3365 | return undef if $id !~ /^\d+$/;
|
---|
| 3366 |
|
---|
[479] | 3367 | my $userdata = $self->getUserData($id);
|
---|
[51] | 3368 |
|
---|
[296] | 3369 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3370 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3371 | local $dbh->{AutoCommit} = 0;
|
---|
| 3372 | local $dbh->{RaiseError} = 1;
|
---|
| 3373 |
|
---|
| 3374 | if ($newstatus ne 'mu') {
|
---|
| 3375 | # ooo, fun! let's see what we were passed for status
|
---|
| 3376 | eval {
|
---|
| 3377 | $newstatus = 0 if $newstatus eq 'useroff';
|
---|
| 3378 | $newstatus = 1 if $newstatus eq 'useron';
|
---|
| 3379 | $dbh->do("UPDATE users SET status=? WHERE user_id=?", undef, ($newstatus, $id));
|
---|
| 3380 |
|
---|
[297] | 3381 | $resultstr = ($newstatus ? 'Enabled' : 'Disabled')." user ".$userdata->{username}.
|
---|
| 3382 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")";
|
---|
[296] | 3383 |
|
---|
| 3384 | my %loghash;
|
---|
[473] | 3385 | $loghash{group_id} = $self->parentID(id => $id, type => 'user');
|
---|
[296] | 3386 | $loghash{entry} = $resultstr;
|
---|
[487] | 3387 | $self->_log(%loghash);
|
---|
[296] | 3388 |
|
---|
| 3389 | $dbh->commit;
|
---|
| 3390 | };
|
---|
| 3391 | if ($@) {
|
---|
| 3392 | my $msg = $@;
|
---|
| 3393 | eval { $dbh->rollback; };
|
---|
| 3394 | $resultstr = '';
|
---|
| 3395 | $errstr = $msg;
|
---|
| 3396 | ##fixme: failure logging?
|
---|
| 3397 | return;
|
---|
[51] | 3398 | }
|
---|
| 3399 | }
|
---|
| 3400 |
|
---|
[296] | 3401 | my ($status) = $dbh->selectrow_array("SELECT status FROM users WHERE user_id=?", undef, ($id));
|
---|
[51] | 3402 | return $status;
|
---|
| 3403 | } # end userStatus()
|
---|
| 3404 |
|
---|
| 3405 |
|
---|
[83] | 3406 | ## DNSDB::getUserData()
|
---|
| 3407 | # Get misc user data for display
|
---|
| 3408 | sub getUserData {
|
---|
[479] | 3409 | my $self = shift;
|
---|
| 3410 | my $dbh = $self->{dbh};
|
---|
[83] | 3411 | my $uid = shift;
|
---|
| 3412 |
|
---|
| 3413 | my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
|
---|
| 3414 | "FROM users WHERE user_id=?");
|
---|
| 3415 | $sth->execute($uid);
|
---|
| 3416 | return $sth->fetchrow_hashref();
|
---|
| 3417 | } # end getUserData()
|
---|
| 3418 |
|
---|
| 3419 |
|
---|
[370] | 3420 | ## DNSDB::addLoc()
|
---|
[375] | 3421 | # Add a new location.
|
---|
| 3422 | # Takes a database handle, group ID, short and long description, and a comma-separated
|
---|
| 3423 | # list of IP addresses.
|
---|
| 3424 | # Returns ('OK',<location>) on success, ('FAIL',<failmsg>) on failure
|
---|
| 3425 | sub addLoc {
|
---|
[480] | 3426 | my $self = shift;
|
---|
| 3427 | my $dbh = $self->{dbh};
|
---|
[375] | 3428 | my $grp = shift;
|
---|
| 3429 | my $shdesc = shift;
|
---|
| 3430 | my $comments = shift;
|
---|
| 3431 | my $iplist = shift;
|
---|
[370] | 3432 |
|
---|
[375] | 3433 | # $shdesc gets set to the generated location ID if possible, but these can be de-undefined here.
|
---|
| 3434 | $comments = '' if !$comments;
|
---|
| 3435 | $iplist = '' if !$iplist;
|
---|
| 3436 |
|
---|
| 3437 | my $loc;
|
---|
| 3438 |
|
---|
| 3439 | # Generate a location ID. This is, by spec, a two-character widget. We'll use [a-z][a-z]
|
---|
| 3440 | # for now; 676 locations should satisfy all but the largest of the huge networks.
|
---|
| 3441 | # Not sure whether these are case-sensitive, or what other rules might apply - in any case
|
---|
| 3442 | # the absolute maximum is 16K (256*256) since it's parsed by tinydns as a two-character field.
|
---|
| 3443 |
|
---|
| 3444 | # add just after "my $origloc = $loc;":
|
---|
| 3445 | # # These expand the possible space from 26^2 to 52^2 [* note in testing only 2052 were achieved],
|
---|
| 3446 | # # and wrap it around.
|
---|
| 3447 | # # Yes, they skip a couple of possibles. No, I don't care.
|
---|
| 3448 | # $loc = 'aA' if $loc eq 'zz';
|
---|
| 3449 | # $loc = 'Aa' if $loc eq 'zZ';
|
---|
| 3450 | # $loc = 'ZA' if $loc eq 'Zz';
|
---|
| 3451 | # $loc = 'aa' if $loc eq 'ZZ';
|
---|
| 3452 |
|
---|
| 3453 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3454 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3455 | local $dbh->{AutoCommit} = 0;
|
---|
| 3456 | local $dbh->{RaiseError} = 1;
|
---|
| 3457 |
|
---|
| 3458 | ##fixme: There is probably a far better way to do this. Sequential increments
|
---|
| 3459 | # are marginally less stupid that pure random generation though, and the existence
|
---|
| 3460 | # check makes sure we don't stomp on an imported one.
|
---|
| 3461 |
|
---|
| 3462 | eval {
|
---|
| 3463 | # Get the "last" location. Note this is the only use for loc_id, because selecting on location Does Funky Things
|
---|
| 3464 | ($loc) = $dbh->selectrow_array("SELECT location FROM locations ORDER BY loc_id DESC LIMIT 1");
|
---|
[478] | 3465 | ($loc) = ($loc =~ /^(..)/) if $loc;
|
---|
[375] | 3466 | my $origloc = $loc;
|
---|
[446] | 3467 | $loc = 'aa' if !$loc;
|
---|
[375] | 3468 | # Make a change...
|
---|
| 3469 | $loc++;
|
---|
| 3470 | # ... and keep changing if it exists
|
---|
| 3471 | while ($dbh->selectrow_array("SELECT count(*) FROM locations WHERE location LIKE ?", undef, ($loc.'%'))) {
|
---|
| 3472 | $loc++;
|
---|
| 3473 | ($loc) = ($loc =~ /^(..)/);
|
---|
| 3474 | die "too many locations in use, can't add another one\n" if $loc eq $origloc;
|
---|
| 3475 | ##fixme: really need to handle this case faster somehow
|
---|
| 3476 | #if $loc eq $origloc die "<thwap> bad admin: all locations used, your network is too fragmented";
|
---|
| 3477 | }
|
---|
| 3478 | # And now we should have a unique location. tinydns fundamentally limits the
|
---|
| 3479 | # number of these but there's no doc on what characters are valid.
|
---|
| 3480 | $shdesc = $loc if !$shdesc;
|
---|
| 3481 | $dbh->do("INSERT INTO locations (location, group_id, iplist, description, comments) VALUES (?,?,?,?,?)",
|
---|
| 3482 | undef, ($loc, $grp, $iplist, $shdesc, $comments) );
|
---|
[487] | 3483 | $self->_log(entry => "Added location ($shdesc, '$iplist')");
|
---|
[377] | 3484 | $dbh->commit;
|
---|
[375] | 3485 | };
|
---|
| 3486 | if ($@) {
|
---|
| 3487 | my $msg = $@;
|
---|
| 3488 | eval { $dbh->rollback; };
|
---|
[517] | 3489 | if ($self->{log_failures}) {
|
---|
[375] | 3490 | $shdesc = $loc if !$shdesc;
|
---|
[487] | 3491 | $self->_log(entry => "Failed adding location ($shdesc, '$iplist'): $msg");
|
---|
[375] | 3492 | $dbh->commit;
|
---|
| 3493 | }
|
---|
| 3494 | return ('FAIL',$msg);
|
---|
| 3495 | }
|
---|
| 3496 |
|
---|
| 3497 | return ('OK',$loc);
|
---|
[377] | 3498 | } # end addLoc()
|
---|
[375] | 3499 |
|
---|
| 3500 |
|
---|
[370] | 3501 | ## DNSDB::updateLoc()
|
---|
[428] | 3502 | # Update details of a location.
|
---|
| 3503 | # Takes a database handle, location ID, group ID, short description,
|
---|
| 3504 | # long comments/notes, and comma/space-separated IP list
|
---|
| 3505 | # Returns a result code and message
|
---|
[377] | 3506 | sub updateLoc {
|
---|
[480] | 3507 | my $self = shift;
|
---|
| 3508 | my $dbh = $self->{dbh};
|
---|
[377] | 3509 | my $loc = shift;
|
---|
| 3510 | my $grp = shift;
|
---|
| 3511 | my $shdesc = shift;
|
---|
| 3512 | my $comments = shift;
|
---|
| 3513 | my $iplist = shift;
|
---|
[370] | 3514 |
|
---|
[377] | 3515 | $shdesc = '' if !$shdesc;
|
---|
| 3516 | $comments = '' if !$comments;
|
---|
| 3517 | $iplist = '' if !$iplist;
|
---|
| 3518 |
|
---|
| 3519 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3520 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3521 | local $dbh->{AutoCommit} = 0;
|
---|
| 3522 | local $dbh->{RaiseError} = 1;
|
---|
| 3523 |
|
---|
[480] | 3524 | my $oldloc = $self->getLoc($loc);
|
---|
[377] | 3525 | my $okmsg = "Updated location (".$oldloc->{description}.", '".$oldloc->{iplist}."') to ($shdesc, '$iplist')";
|
---|
| 3526 |
|
---|
| 3527 | eval {
|
---|
| 3528 | $dbh->do("UPDATE locations SET group_id=?,iplist=?,description=?,comments=? WHERE location=?",
|
---|
| 3529 | undef, ($grp, $iplist, $shdesc, $comments, $loc) );
|
---|
[487] | 3530 | $self->_log(entry => $okmsg);
|
---|
[377] | 3531 | $dbh->commit;
|
---|
| 3532 | };
|
---|
| 3533 | if ($@) {
|
---|
| 3534 | my $msg = $@;
|
---|
| 3535 | eval { $dbh->rollback; };
|
---|
[517] | 3536 | if ($self->{log_failures}) {
|
---|
[377] | 3537 | $shdesc = $loc if !$shdesc;
|
---|
[487] | 3538 | $self->_log(entry => "Failed updating location ($shdesc, '$iplist'): $msg");
|
---|
[377] | 3539 | $dbh->commit;
|
---|
| 3540 | }
|
---|
| 3541 | return ('FAIL',$msg);
|
---|
| 3542 | }
|
---|
| 3543 |
|
---|
| 3544 | return ('OK',$okmsg);
|
---|
| 3545 | } # end updateLoc()
|
---|
| 3546 |
|
---|
| 3547 |
|
---|
[370] | 3548 | ## DNSDB::delLoc()
|
---|
[428] | 3549 | sub delLoc {
|
---|
[480] | 3550 | my $self = shift;
|
---|
| 3551 | my $dbh = $self->{dbh};
|
---|
[428] | 3552 | my $loc = shift;
|
---|
[370] | 3553 |
|
---|
[428] | 3554 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3555 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3556 | local $dbh->{AutoCommit} = 0;
|
---|
| 3557 | local $dbh->{RaiseError} = 1;
|
---|
[370] | 3558 |
|
---|
[480] | 3559 | my $oldloc = $self->getLoc($loc);
|
---|
[428] | 3560 | my $olddesc = ($oldloc->{description} ? $oldloc->{description} : $loc);
|
---|
| 3561 | my $okmsg = "Deleted location ($olddesc, '".$oldloc->{iplist}."')";
|
---|
| 3562 |
|
---|
| 3563 | eval {
|
---|
| 3564 | # Check for records with this location first. Deleting a location without deleting records
|
---|
| 3565 | # tagged for that location will render them unpublished without other warning.
|
---|
| 3566 | my ($r) = $dbh->selectrow_array("SELECT record_id FROM records WHERE location=? LIMIT 1", undef, ($loc) );
|
---|
| 3567 | die "Records still exist in location $olddesc\n" if $r;
|
---|
| 3568 | $dbh->do("DELETE FROM locations WHERE location=?", undef, ($loc) );
|
---|
[487] | 3569 | $self->_log(entry => $okmsg);
|
---|
[428] | 3570 | $dbh->commit;
|
---|
| 3571 | };
|
---|
| 3572 | if ($@) {
|
---|
| 3573 | my $msg = $@;
|
---|
| 3574 | eval { $dbh->rollback; };
|
---|
[517] | 3575 | if ($self->{log_failures}) {
|
---|
[487] | 3576 | $self->_log(entry => "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
|
---|
[428] | 3577 | $dbh->commit;
|
---|
| 3578 | }
|
---|
| 3579 | return ('FAIL', "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
|
---|
| 3580 | }
|
---|
| 3581 |
|
---|
| 3582 | return ('OK',$okmsg);
|
---|
| 3583 | } # end delLoc()
|
---|
| 3584 |
|
---|
| 3585 |
|
---|
[375] | 3586 | ## DNSDB::getLoc()
|
---|
[428] | 3587 | # Get details about a location/view
|
---|
| 3588 | # Takes a database handle and location ID.
|
---|
| 3589 | # Returns a reference to a hash containing the group ID, IP list, description, and comments/notes
|
---|
[375] | 3590 | sub getLoc {
|
---|
[480] | 3591 | my $self = shift;
|
---|
| 3592 | my $dbh = $self->{dbh};
|
---|
[375] | 3593 | my $loc = shift;
|
---|
| 3594 |
|
---|
| 3595 | my $sth = $dbh->prepare("SELECT group_id,iplist,description,comments FROM locations WHERE location=?");
|
---|
| 3596 | $sth->execute($loc);
|
---|
| 3597 | return $sth->fetchrow_hashref();
|
---|
| 3598 | } # end getLoc()
|
---|
| 3599 |
|
---|
| 3600 |
|
---|
[370] | 3601 | ## DNSDB::getLocCount()
|
---|
| 3602 | # Get count of locations/views
|
---|
| 3603 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
| 3604 | # - a reference list of secondary groups
|
---|
| 3605 | # - a filter string
|
---|
| 3606 | # - a "Starts with" string
|
---|
| 3607 | sub getLocCount {
|
---|
[480] | 3608 | my $self = shift;
|
---|
| 3609 | my $dbh = $self->{dbh};
|
---|
[370] | 3610 |
|
---|
| 3611 | my %args = @_;
|
---|
| 3612 |
|
---|
[509] | 3613 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 3614 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 3615 | $errstr = "Bad or missing curgroup argument";
|
---|
| 3616 | return;
|
---|
| 3617 | }
|
---|
| 3618 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 3619 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 3620 | $errstr = "Bad childlist argument";
|
---|
| 3621 | return;
|
---|
| 3622 | }
|
---|
| 3623 |
|
---|
[370] | 3624 | my @filterargs;
|
---|
| 3625 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3626 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3627 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3628 |
|
---|
| 3629 | my $sql = "SELECT count(*) FROM locations ".
|
---|
| 3630 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3631 | ($args{startwith} ? " AND description ~* ?" : '').
|
---|
| 3632 | ($args{filter} ? " AND description ~* ?" : '');
|
---|
| 3633 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 3634 | $errstr = $dbh->errstr if !$count;
|
---|
| 3635 | return $count;
|
---|
| 3636 | } # end getLocCount()
|
---|
| 3637 |
|
---|
| 3638 |
|
---|
| 3639 | ## DNSDB::getLocList()
|
---|
| 3640 | sub getLocList {
|
---|
[480] | 3641 | my $self = shift;
|
---|
| 3642 | my $dbh = $self->{dbh};
|
---|
[370] | 3643 |
|
---|
| 3644 | my %args = @_;
|
---|
| 3645 |
|
---|
[509] | 3646 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 3647 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 3648 | $errstr = "Bad or missing curgroup argument";
|
---|
| 3649 | return;
|
---|
| 3650 | }
|
---|
| 3651 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 3652 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 3653 | $errstr = "Bad childlist argument";
|
---|
| 3654 | return;
|
---|
| 3655 | }
|
---|
| 3656 |
|
---|
[370] | 3657 | my @filterargs;
|
---|
| 3658 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3659 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3660 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3661 |
|
---|
| 3662 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
| 3663 | # my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
| 3664 | # fname => 'fname');
|
---|
| 3665 | # $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 3666 |
|
---|
| 3667 | # protection against bad or missing arguments
|
---|
[508] | 3668 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
| 3669 | $args{sortby} = 'l.description' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
[397] | 3670 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[370] | 3671 |
|
---|
| 3672 | my $sql = "SELECT l.location, l.description, l.iplist, g.group_name ".
|
---|
| 3673 | "FROM locations l ".
|
---|
| 3674 | "INNER JOIN groups g ON l.group_id=g.group_id ".
|
---|
| 3675 | "WHERE l.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3676 | ($args{startwith} ? " AND l.description ~* ?" : '').
|
---|
| 3677 | ($args{filter} ? " AND l.description ~* ?" : '').
|
---|
| 3678 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
[517] | 3679 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
[370] | 3680 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 3681 | $errstr = $dbh->errstr if !$ulist;
|
---|
| 3682 | return $ulist;
|
---|
| 3683 | } # end getLocList()
|
---|
| 3684 |
|
---|
| 3685 |
|
---|
| 3686 | ## DNSDB::getLocDropdown()
|
---|
[383] | 3687 | # Get a list of location names for use in a dropdown menu.
|
---|
| 3688 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
| 3689 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
| 3690 | sub getLocDropdown {
|
---|
[480] | 3691 | my $self = shift;
|
---|
| 3692 | my $dbh = $self->{dbh};
|
---|
[383] | 3693 | my $grp = shift;
|
---|
| 3694 | my $sel = shift || '';
|
---|
[370] | 3695 |
|
---|
[383] | 3696 | my $sth = $dbh->prepare(qq(
|
---|
| 3697 | SELECT description,location FROM locations
|
---|
| 3698 | WHERE group_id=?
|
---|
| 3699 | ORDER BY description
|
---|
| 3700 | ) );
|
---|
| 3701 | $sth->execute($grp);
|
---|
[370] | 3702 |
|
---|
[383] | 3703 | my @loclist;
|
---|
[446] | 3704 | push @loclist, { locname => "(Default/All)", loc => '', selected => ($sel ? 0 : ($sel eq '' ? 1 : 0)) };
|
---|
[383] | 3705 | while (my ($locname, $loc) = $sth->fetchrow_array) {
|
---|
| 3706 | my %row = (
|
---|
| 3707 | locname => $locname,
|
---|
| 3708 | loc => $loc,
|
---|
| 3709 | selected => ($sel eq $loc ? 1 : 0)
|
---|
| 3710 | );
|
---|
| 3711 | push @loclist, \%row;
|
---|
| 3712 | }
|
---|
| 3713 | return \@loclist;
|
---|
| 3714 | } # end getLocDropdown()
|
---|
| 3715 |
|
---|
| 3716 |
|
---|
[2] | 3717 | ## DNSDB::getSOA()
|
---|
| 3718 | # Return all suitable fields from an SOA record in separate elements of a hash
|
---|
[224] | 3719 | # Takes a database handle, default/live flag, domain/reverse flag, and parent ID
|
---|
[2] | 3720 | sub getSOA {
|
---|
| 3721 | $errstr = '';
|
---|
[481] | 3722 | my $self = shift;
|
---|
| 3723 | my $dbh = $self->{dbh};
|
---|
[2] | 3724 | my $def = shift;
|
---|
[224] | 3725 | my $rev = shift;
|
---|
[2] | 3726 | my $id = shift;
|
---|
| 3727 |
|
---|
[224] | 3728 | # (ab)use distance and weight columns to store SOA data? can't for default_rev_records...
|
---|
| 3729 | # - should really attach serial to the zone parent somewhere
|
---|
[101] | 3730 |
|
---|
[224] | 3731 | my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev).
|
---|
| 3732 | " WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}";
|
---|
[311] | 3733 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
| 3734 | return if !$ret;
|
---|
[246] | 3735 | ##fixme: stick a flag somewhere if the record doesn't exist. by the API, this is an impossible case, but...
|
---|
[2] | 3736 |
|
---|
[311] | 3737 | ($ret->{contact},$ret->{prins}) = split /:/, $ret->{host};
|
---|
| 3738 | delete $ret->{host};
|
---|
| 3739 | ($ret->{refresh},$ret->{retry},$ret->{expire},$ret->{minttl}) = split /:/, $ret->{val};
|
---|
| 3740 | delete $ret->{val};
|
---|
[2] | 3741 |
|
---|
[311] | 3742 | return $ret;
|
---|
[2] | 3743 | } # end getSOA()
|
---|
| 3744 |
|
---|
| 3745 |
|
---|
[246] | 3746 | ## DNSDB::updateSOA()
|
---|
| 3747 | # Update the specified SOA record
|
---|
| 3748 | # Takes a database handle, default/live flag, forward/reverse flag, and SOA data hash
|
---|
[277] | 3749 | # Returns a two-element list with a result code and message
|
---|
[246] | 3750 | sub updateSOA {
|
---|
[473] | 3751 | my $self = shift;
|
---|
| 3752 | my $dbh = $self->{dbh};
|
---|
[246] | 3753 | my $defrec = shift;
|
---|
[248] | 3754 | my $revrec = shift;
|
---|
[246] | 3755 |
|
---|
| 3756 | my %soa = @_;
|
---|
| 3757 |
|
---|
[473] | 3758 | my $oldsoa = $self->getSOA($defrec, $revrec, $soa{id});
|
---|
[277] | 3759 |
|
---|
[311] | 3760 | my $msg;
|
---|
| 3761 | my %logdata;
|
---|
| 3762 | if ($defrec eq 'n') {
|
---|
| 3763 | $logdata{domain_id} = $soa{id} if $revrec eq 'n';
|
---|
| 3764 | $logdata{rdns_id} = $soa{id} if $revrec eq 'y';
|
---|
[473] | 3765 | $logdata{group_id} = $self->parentID(id => $soa{id}, revrec => $revrec,
|
---|
| 3766 | type => ($revrec eq 'n' ? 'domain' : 'revzone') );
|
---|
[311] | 3767 | } else {
|
---|
| 3768 | $logdata{group_id} = $soa{id};
|
---|
| 3769 | }
|
---|
[473] | 3770 | my $parname = ($defrec eq 'y' ? $self->groupName($soa{id}) :
|
---|
| 3771 | ($revrec eq 'n' ? $self->domainName($soa{id}) : $self->revName($soa{id})) );
|
---|
[311] | 3772 |
|
---|
[277] | 3773 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3774 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3775 | local $dbh->{AutoCommit} = 0;
|
---|
| 3776 | local $dbh->{RaiseError} = 1;
|
---|
| 3777 |
|
---|
| 3778 | eval {
|
---|
[565] | 3779 | if (!$oldsoa) {
|
---|
| 3780 | # old SOA record is missing for some reason. create a new one.
|
---|
[583] | 3781 | my $sql = "INSERT INTO "._rectable($defrec, $revrec)." ("._recparent($defrec, $revrec).
|
---|
| 3782 | ", host, type, val, ttl) VALUES (?,?,6,?,?)";
|
---|
[565] | 3783 | $dbh->do($sql, undef, ($soa{id}, "$soa{contact}:$soa{prins}",
|
---|
| 3784 | "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}", $soa{ttl}) );
|
---|
| 3785 | $msg = ($defrec eq 'y' ? ($revrec eq 'y' ? 'Default reverse ' : 'Default ') : '').
|
---|
| 3786 | "SOA missing for $parname; added (ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
|
---|
| 3787 | " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})";
|
---|
| 3788 | } else {
|
---|
| 3789 | my $sql = "UPDATE "._rectable($defrec, $revrec)." SET host=?, val=?, ttl=? WHERE record_id=? AND type=6";
|
---|
| 3790 | $dbh->do($sql, undef, ("$soa{contact}:$soa{prins}", "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}",
|
---|
[311] | 3791 | $soa{ttl}, $oldsoa->{record_id}) );
|
---|
[565] | 3792 | $msg = "Updated ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse ' : 'default ') : '').
|
---|
[311] | 3793 | "SOA for $parname: ".
|
---|
| 3794 | "(ns $oldsoa->{prins}, contact $oldsoa->{contact}, refresh $oldsoa->{refresh},".
|
---|
| 3795 | " retry $oldsoa->{retry}, expire $oldsoa->{expire}, minTTL $oldsoa->{minttl}, TTL $oldsoa->{ttl}) to ".
|
---|
[277] | 3796 | "(ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
|
---|
| 3797 | " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})";
|
---|
[565] | 3798 | }
|
---|
[311] | 3799 | $logdata{entry} = $msg;
|
---|
[487] | 3800 | $self->_log(%logdata);
|
---|
[277] | 3801 |
|
---|
| 3802 | $dbh->commit;
|
---|
| 3803 | };
|
---|
| 3804 | if ($@) {
|
---|
| 3805 | $msg = $@;
|
---|
| 3806 | eval { $dbh->rollback; };
|
---|
[311] | 3807 | $logdata{entry} = "Error updating ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse zone ' : 'default ') : '').
|
---|
| 3808 | "SOA record for $parname: $msg";
|
---|
[517] | 3809 | if ($self->{log_failures}) {
|
---|
[487] | 3810 | $self->_log(%logdata);
|
---|
[311] | 3811 | $dbh->commit;
|
---|
| 3812 | }
|
---|
| 3813 | return ('FAIL', $logdata{entry});
|
---|
[277] | 3814 | } else {
|
---|
| 3815 | return ('OK', $msg);
|
---|
| 3816 | }
|
---|
[246] | 3817 | } # end updateSOA()
|
---|
| 3818 |
|
---|
| 3819 |
|
---|
[2] | 3820 | ## DNSDB::getRecLine()
|
---|
| 3821 | # Return all data fields for a zone record in separate elements of a hash
|
---|
[243] | 3822 | # Takes a database handle, default/live flag, forward/reverse flag, and record ID
|
---|
[2] | 3823 | sub getRecLine {
|
---|
| 3824 | $errstr = '';
|
---|
[481] | 3825 | my $self = shift;
|
---|
| 3826 | my $dbh = $self->{dbh};
|
---|
[243] | 3827 | my $defrec = shift;
|
---|
| 3828 | my $revrec = shift;
|
---|
[2] | 3829 | my $id = shift;
|
---|
| 3830 |
|
---|
[543] | 3831 | ##fixme: do we need a knob to twist to switch between unix epoch and postgres time string?
|
---|
[429] | 3832 | my $sql = "SELECT record_id,host,type,val,ttl".
|
---|
| 3833 | ($defrec eq 'n' ? ',location' : '').
|
---|
| 3834 | ($revrec eq 'n' ? ',distance,weight,port' : '').
|
---|
[543] | 3835 | (($defrec eq 'y') ? ',group_id FROM ' : ',domain_id,rdns_id,stamp,stamp < now() AS ispast,expires,stampactive FROM ').
|
---|
[243] | 3836 | _rectable($defrec,$revrec)." WHERE record_id=?";
|
---|
[123] | 3837 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
[2] | 3838 |
|
---|
[90] | 3839 | if ($dbh->err) {
|
---|
[2] | 3840 | $errstr = $DBI::errstr;
|
---|
| 3841 | return undef;
|
---|
| 3842 | }
|
---|
| 3843 |
|
---|
[123] | 3844 | if (!$ret) {
|
---|
| 3845 | $errstr = "No such record";
|
---|
| 3846 | return undef;
|
---|
| 3847 | }
|
---|
| 3848 |
|
---|
[243] | 3849 | # explicitly set a parent id
|
---|
| 3850 | if ($defrec eq 'y') {
|
---|
| 3851 | $ret->{parid} = $ret->{group_id};
|
---|
| 3852 | } else {
|
---|
| 3853 | $ret->{parid} = (($revrec eq 'n') ? $ret->{domain_id} : $ret->{rdns_id});
|
---|
| 3854 | # and a secondary if we have a custom type that lives in both a forward and reverse zone
|
---|
| 3855 | $ret->{secid} = (($revrec eq 'y') ? $ret->{domain_id} : $ret->{rdns_id}) if $ret->{type} > 65279;
|
---|
| 3856 | }
|
---|
[451] | 3857 | $ret->{address} = $ret->{val}; # because.
|
---|
[90] | 3858 |
|
---|
| 3859 | return $ret;
|
---|
[2] | 3860 | }
|
---|
| 3861 |
|
---|
| 3862 |
|
---|
| 3863 | ##fixme: should use above (getRecLine()) to get lines for below?
|
---|
[495] | 3864 | ## DNSDB::getRecList()
|
---|
| 3865 | # Return records for a group or zone
|
---|
| 3866 | # Takes a default/live flag, group or zone ID, start,
|
---|
[2] | 3867 | # number of records, sort field, and sort order
|
---|
| 3868 | # Returns a reference to an array of hashes
|
---|
[495] | 3869 | sub getRecList {
|
---|
[2] | 3870 | $errstr = '';
|
---|
[481] | 3871 | my $self = shift;
|
---|
| 3872 | my $dbh = $self->{dbh};
|
---|
[2] | 3873 |
|
---|
[397] | 3874 | my %args = @_;
|
---|
[4] | 3875 |
|
---|
[397] | 3876 | # protection against bad or missing arguments
|
---|
[508] | 3877 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
[510] | 3878 | my $defsort;
|
---|
| 3879 | $defsort = 'host' if $args{revrec} eq 'n'; # default sort by host on domain record list
|
---|
| 3880 | $defsort = 'val' if $args{revrec} eq 'y'; # default sort by IP on revzone record list
|
---|
[513] | 3881 | $args{sortby} = '' if !$args{sortby};
|
---|
[508] | 3882 | $args{sortby} = $defsort if !$args{revrec};
|
---|
[512] | 3883 | $args{sortby} = $defsort if $args{sortby} !~ /^[\w_,.]+$/;
|
---|
[397] | 3884 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[517] | 3885 | my $perpage = ($args{nrecs} ? $args{nrecs} : $self->{perpage});
|
---|
[397] | 3886 |
|
---|
[352] | 3887 | # sort reverse zones on IP, correctly
|
---|
[397] | 3888 | # do other fiddling with $args{sortby} while we're at it.
|
---|
[420] | 3889 | # whee! multisort means just passing comma-separated fields in sortby!
|
---|
| 3890 | my $newsort = '';
|
---|
| 3891 | foreach my $sf (split /,/, $args{sortby}) {
|
---|
| 3892 | $sf = "r.$sf";
|
---|
[599] | 3893 | $sf =~ s/r\.val/inetlazy(r.val)/
|
---|
[420] | 3894 | if $args{revrec} eq 'y' && $args{defrec} eq 'n';
|
---|
| 3895 | $sf =~ s/r\.type/t.alphaorder/;
|
---|
| 3896 | $newsort .= ",$sf";
|
---|
| 3897 | }
|
---|
| 3898 | $newsort =~ s/^,//;
|
---|
[352] | 3899 |
|
---|
[584] | 3900 | my @bindvars = ($args{id});
|
---|
| 3901 | push @bindvars, ($args{filter},$args{filter}) if $args{filter};
|
---|
| 3902 |
|
---|
[543] | 3903 | ##fixme: do we need a knob to twist to switch from unix epoch to postgres time string?
|
---|
[224] | 3904 | my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.ttl";
|
---|
[543] | 3905 | $sql .= ",l.description AS locname,stamp,r.stamp < now() AS ispast,r.expires,r.stampactive"
|
---|
| 3906 | if $args{defrec} eq 'n';
|
---|
[397] | 3907 | $sql .= ",r.distance,r.weight,r.port" if $args{revrec} eq 'n';
|
---|
| 3908 | $sql .= " FROM "._rectable($args{defrec},$args{revrec})." r ";
|
---|
[104] | 3909 | $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
|
---|
[397] | 3910 | $sql .= "LEFT JOIN locations l ON r.location=l.location " if $args{defrec} eq 'n';
|
---|
| 3911 | $sql .= "WHERE "._recparent($args{defrec},$args{revrec})." = ?";
|
---|
[104] | 3912 | $sql .= " AND NOT r.type=$reverse_typemap{SOA}";
|
---|
[614] | 3913 | if ($args{filter}) {
|
---|
| 3914 | $sql .= " AND (r.host ~* ? OR r.val ~* ? OR r.host ~* ? OR r.val ~* ?)";
|
---|
| 3915 | my $tmp = join('.',reverse(split(/\./,$args{filter})));
|
---|
| 3916 | push @bindvars, ($tmp, $tmp);
|
---|
| 3917 | }
|
---|
[420] | 3918 | $sql .= " ORDER BY $newsort $args{sortorder}";
|
---|
[324] | 3919 | # ensure consistent ordering by sorting on record_id too
|
---|
[397] | 3920 | $sql .= ", record_id $args{sortorder}";
|
---|
[501] | 3921 | $sql .= ($args{offset} eq 'all' ? '' : " LIMIT $perpage OFFSET ".$args{offset}*$perpage);
|
---|
[4] | 3922 |
|
---|
[583] | 3923 | my @working;
|
---|
| 3924 | my $recsth = $dbh->prepare($sql);
|
---|
| 3925 | $recsth->execute(@bindvars);
|
---|
| 3926 | while (my $rec = $recsth->fetchrow_hashref) {
|
---|
[594] | 3927 | if ($args{revrec} eq 'y' && $args{defrec} eq 'n' &&
|
---|
[607] | 3928 | ($self->{showrev_arpa} eq 'record' || $self->{showrev_arpa} eq 'all') &&
|
---|
| 3929 | $rec->{val} !~ /\.arpa$/ ) {
|
---|
[608] | 3930 | # skip all reverse zone .arpa "hostnames" since they're already .arpa names.
|
---|
[583] | 3931 | ##enhance: extend {showrev_arpa} eq 'record' to specify record types
|
---|
[607] | 3932 | my $tmpip = new NetAddr::IP $rec->{val};
|
---|
| 3933 | $rec->{val} = DNSDB::_ZONE($tmpip, 'ZONE', 'r', '.').($tmpip->{isv6} ? '.ip6.arpa' : '.in-addr.arpa') if $tmpip;
|
---|
[583] | 3934 | }
|
---|
| 3935 | push @working, $rec;
|
---|
| 3936 | }
|
---|
| 3937 | return \@working;
|
---|
[495] | 3938 | } # end getRecList()
|
---|
[2] | 3939 |
|
---|
| 3940 |
|
---|
[91] | 3941 | ## DNSDB::getRecCount()
|
---|
[224] | 3942 | # Return count of non-SOA records in zone (or default records in a group)
|
---|
| 3943 | # Takes a database handle, default/live flag, reverse/forward flag, group/domain ID,
|
---|
| 3944 | # and optional filtering modifier
|
---|
[91] | 3945 | # Returns the count
|
---|
| 3946 | sub getRecCount {
|
---|
[481] | 3947 | my $self = shift;
|
---|
| 3948 | my $dbh = $self->{dbh};
|
---|
[91] | 3949 | my $defrec = shift;
|
---|
[224] | 3950 | my $revrec = shift;
|
---|
[91] | 3951 | my $id = shift;
|
---|
[135] | 3952 | my $filter = shift || '';
|
---|
[91] | 3953 |
|
---|
[135] | 3954 | # keep the nasties down, since we can't ?-sub this bit. :/
|
---|
| 3955 | # note this is chars allowed in DNS hostnames
|
---|
| 3956 | $filter =~ s/[^a-zA-Z0-9_.:-]//g;
|
---|
| 3957 |
|
---|
[222] | 3958 | my @bindvars = ($id);
|
---|
[584] | 3959 | push @bindvars, ($filter,$filter) if $filter;
|
---|
[224] | 3960 | my $sql = "SELECT count(*) FROM ".
|
---|
| 3961 | _rectable($defrec,$revrec).
|
---|
| 3962 | " WHERE "._recparent($defrec,$revrec)."=? ".
|
---|
[584] | 3963 | "AND NOT type=$reverse_typemap{SOA}";
|
---|
[615] | 3964 | if ($filter) {
|
---|
[614] | 3965 | $sql .= " AND (r.host ~* ? OR r.val ~* ? OR r.host ~* ? OR r.val ~* ?)";
|
---|
[615] | 3966 | my $tmp = join('.',reverse(split(/\./,$filter)));
|
---|
[614] | 3967 | push @bindvars, ($tmp, $tmp);
|
---|
| 3968 | }
|
---|
| 3969 | $sql .= " AND (host ~* ? OR val ~* ? OR host ~* ? OR val ~* ?)" if $filter;
|
---|
| 3970 | my $tmp = join('.',reverse(split(/\./,$filter)));
|
---|
| 3971 | push @bindvars, ($tmp, $tmp) if $filter;
|
---|
[584] | 3972 |
|
---|
[224] | 3973 | my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) );
|
---|
[91] | 3974 |
|
---|
| 3975 | return $count;
|
---|
| 3976 |
|
---|
| 3977 | } # end getRecCount()
|
---|
| 3978 |
|
---|
| 3979 |
|
---|
[3] | 3980 | ## DNSDB::addRec()
|
---|
[2] | 3981 | # Add a new record to a domain or a group's default records
|
---|
| 3982 | # Takes a database handle, default/live flag, group/domain ID,
|
---|
| 3983 | # host, type, value, and TTL
|
---|
| 3984 | # Some types require additional detail: "distance" for MX and SRV,
|
---|
| 3985 | # and weight/port for SRV
|
---|
| 3986 | # Returns a status code and detail message in case of error
|
---|
[234] | 3987 | ##fixme: pass a hash with the record data, not a series of separate values
|
---|
[2] | 3988 | sub addRec {
|
---|
| 3989 | $errstr = '';
|
---|
[481] | 3990 | my $self = shift;
|
---|
| 3991 | my $dbh = $self->{dbh};
|
---|
[2] | 3992 | my $defrec = shift;
|
---|
[226] | 3993 | my $revrec = shift;
|
---|
| 3994 | my $id = shift; # parent (group_id for defrecs, rdns_id for reverse records,
|
---|
| 3995 | # domain_id for domain records)
|
---|
[2] | 3996 |
|
---|
| 3997 | my $host = shift;
|
---|
[234] | 3998 | my $rectype = shift; # reference so we can coerce it if "+"-types can't find both zones
|
---|
[2] | 3999 | my $val = shift;
|
---|
| 4000 | my $ttl = shift;
|
---|
[389] | 4001 | my $location = shift;
|
---|
| 4002 | $location = '' if !$location;
|
---|
[2] | 4003 |
|
---|
[543] | 4004 | my $expires = shift;
|
---|
| 4005 | $expires = 1 if $expires eq 'until'; # Turn some special values into the appropriate booleans.
|
---|
| 4006 | $expires = 0 if $expires eq 'after';
|
---|
| 4007 | my $stamp = shift;
|
---|
| 4008 | $stamp = '' if !$stamp; # Timestamp should be a string at this point.
|
---|
| 4009 |
|
---|
[417] | 4010 | # Spaces are evil.
|
---|
| 4011 | $$host =~ s/^\s+//;
|
---|
| 4012 | $$host =~ s/\s+$//;
|
---|
[418] | 4013 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
[417] | 4014 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 4015 | $$val =~ s/^\s+//;
|
---|
| 4016 | $$val =~ s/\s+$//;
|
---|
| 4017 | }
|
---|
| 4018 |
|
---|
[617] | 4019 | _caseclean($rectype, $host, $val, $defrec, $revrec) if $self->{lowercase};
|
---|
[542] | 4020 |
|
---|
[226] | 4021 | # prep for validation
|
---|
[609] | 4022 | my $addr = NetAddr::IP->new($$val) if _maybeip($val);
|
---|
[252] | 4023 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
[226] | 4024 |
|
---|
| 4025 | my $domid = 0;
|
---|
| 4026 | my $revid = 0;
|
---|
| 4027 |
|
---|
| 4028 | my $retcode = 'OK'; # assume everything will go OK
|
---|
| 4029 | my $retmsg = '';
|
---|
| 4030 |
|
---|
| 4031 | # do simple validation first
|
---|
[559] | 4032 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^-?\d+$/;
|
---|
[226] | 4033 |
|
---|
[234] | 4034 | # Collect these even if we're only doing a simple A record so we can call *any* validation sub
|
---|
| 4035 | my $dist = shift;
|
---|
[281] | 4036 | my $weight = shift;
|
---|
[234] | 4037 | my $port = shift;
|
---|
[226] | 4038 |
|
---|
[234] | 4039 | my $fields;
|
---|
| 4040 | my @vallist;
|
---|
[226] | 4041 |
|
---|
[234] | 4042 | # Call the validation sub for the type requested.
|
---|
[481] | 4043 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec, id => $id,
|
---|
[249] | 4044 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
[234] | 4045 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
[481] | 4046 | fields => \$fields, vallist => \@vallist);
|
---|
[129] | 4047 |
|
---|
[234] | 4048 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
[209] | 4049 |
|
---|
[234] | 4050 | # Set up database fields and bind parameters
|
---|
[481] | 4051 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
| 4052 | push @vallist, ($$host,$$rectype,$$val,$ttl,$id);
|
---|
| 4053 |
|
---|
| 4054 | if ($defrec eq 'n') {
|
---|
[543] | 4055 | # locations are not for default records, silly coder!
|
---|
[481] | 4056 | $fields .= ",location";
|
---|
| 4057 | push @vallist, $location;
|
---|
[543] | 4058 | # timestamps are rare.
|
---|
| 4059 | if ($stamp) {
|
---|
| 4060 | $fields .= ",stamp,expires,stampactive";
|
---|
| 4061 | push @vallist, $stamp, $expires, 'y';
|
---|
| 4062 | } else {
|
---|
| 4063 | $fields .= ",stampactive";
|
---|
| 4064 | push @vallist, 'n';
|
---|
| 4065 | }
|
---|
[481] | 4066 | }
|
---|
[543] | 4067 |
|
---|
| 4068 | # a little magic to get the right number of ? placeholders based on how many values we're providing
|
---|
[234] | 4069 | my $vallen = '?'.(',?'x$#vallist);
|
---|
[2] | 4070 |
|
---|
[287] | 4071 | # Put together the success log entry. We have to use this horrible kludge
|
---|
| 4072 | # because domain_id and rdns_id may or may not be present, and if they are,
|
---|
| 4073 | # they're not at a guaranteed consistent index in the array. wheee!
|
---|
| 4074 | my %logdata;
|
---|
| 4075 | my @ftmp = split /,/, $fields;
|
---|
| 4076 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
| 4077 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
| 4078 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
| 4079 | }
|
---|
| 4080 | $logdata{group_id} = $id if $defrec eq 'y';
|
---|
[473] | 4081 | $logdata{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec)
|
---|
[287] | 4082 | if $defrec eq 'n';
|
---|
[328] | 4083 | $logdata{entry} = "Added ".($defrec eq 'y' ? 'default record' : 'record');
|
---|
[621] | 4084 | # Log reverse records to match the formal .arpa tree
|
---|
| 4085 | if ($revrec eq 'y') {
|
---|
[328] | 4086 | $logdata{entry} .= " '$$val $typemap{$$rectype} $$host";
|
---|
| 4087 | } else {
|
---|
| 4088 | $logdata{entry} .= " '$$host $typemap{$$rectype} $$val";
|
---|
| 4089 | }
|
---|
| 4090 |
|
---|
[287] | 4091 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
| 4092 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]"
|
---|
| 4093 | if $typemap{$$rectype} eq 'SRV';
|
---|
[425] | 4094 | $logdata{entry} .= "', TTL $ttl";
|
---|
[480] | 4095 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location;
|
---|
[543] | 4096 | $logdata{entry} .= ($expires eq 'after' ? ', valid after ' : ', expires at ').$stamp if $stamp;
|
---|
[287] | 4097 |
|
---|
[90] | 4098 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4099 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4100 | local $dbh->{AutoCommit} = 0;
|
---|
| 4101 | local $dbh->{RaiseError} = 1;
|
---|
[2] | 4102 |
|
---|
[90] | 4103 | eval {
|
---|
[236] | 4104 | $dbh->do("INSERT INTO "._rectable($defrec, $revrec)." ($fields) VALUES ($vallen)",
|
---|
[90] | 4105 | undef, @vallist);
|
---|
[487] | 4106 | $self->_log(%logdata);
|
---|
[90] | 4107 | $dbh->commit;
|
---|
| 4108 | };
|
---|
| 4109 | if ($@) {
|
---|
| 4110 | my $msg = $@;
|
---|
| 4111 | eval { $dbh->rollback; };
|
---|
[517] | 4112 | if ($self->{log_failures}) {
|
---|
[289] | 4113 | $logdata{entry} = "Failed adding ".($defrec eq 'y' ? 'default ' : '').
|
---|
| 4114 | "record '$$host $typemap{$$rectype} $$val', TTL $ttl ($msg)";
|
---|
[487] | 4115 | $self->_log(%logdata);
|
---|
[289] | 4116 | $dbh->commit;
|
---|
| 4117 | }
|
---|
[90] | 4118 | return ('FAIL',$msg);
|
---|
| 4119 | }
|
---|
[2] | 4120 |
|
---|
[287] | 4121 | $resultstr = $logdata{entry};
|
---|
[226] | 4122 | return ($retcode, $retmsg);
|
---|
[90] | 4123 |
|
---|
[2] | 4124 | } # end addRec()
|
---|
| 4125 |
|
---|
| 4126 |
|
---|
[16] | 4127 | ## DNSDB::updateRec()
|
---|
| 4128 | # Update a record
|
---|
[273] | 4129 | # Takes a database handle, default and reverse flags, record ID, immediate parent ID, and new record data.
|
---|
| 4130 | # Returns a status code and message
|
---|
[16] | 4131 | sub updateRec {
|
---|
| 4132 | $errstr = '';
|
---|
[17] | 4133 |
|
---|
[481] | 4134 | my $self = shift;
|
---|
| 4135 | my $dbh = $self->{dbh};
|
---|
[16] | 4136 | my $defrec = shift;
|
---|
[272] | 4137 | my $revrec = shift;
|
---|
[16] | 4138 | my $id = shift;
|
---|
[272] | 4139 | my $parid = shift; # immediate parent entity that we're descending from to update the record
|
---|
[16] | 4140 |
|
---|
[273] | 4141 | # all records have these
|
---|
[16] | 4142 | my $host = shift;
|
---|
[272] | 4143 | my $hostbk = $$host; # Keep a backup copy of the original, so we can WARN if the update mangles the domain
|
---|
| 4144 | my $rectype = shift;
|
---|
[16] | 4145 | my $val = shift;
|
---|
| 4146 | my $ttl = shift;
|
---|
[389] | 4147 | my $location = shift; # may be empty/null/undef depending on caller
|
---|
| 4148 | $location = '' if !$location;
|
---|
[16] | 4149 |
|
---|
[543] | 4150 | my $expires = shift;
|
---|
| 4151 | $expires = 1 if $expires eq 'until'; # Turn some special values into the appropriate booleans.
|
---|
| 4152 | $expires = 0 if $expires eq 'after';
|
---|
| 4153 | my $stamp = shift;
|
---|
| 4154 | $stamp = '' if !$stamp; # Timestamp should be a string at this point.
|
---|
| 4155 |
|
---|
[510] | 4156 | # just set it to an empty string; failures will be caught later.
|
---|
| 4157 | $$host = '' if !$$host;
|
---|
| 4158 |
|
---|
[417] | 4159 | # Spaces are evil.
|
---|
| 4160 | $$host =~ s/^\s+//;
|
---|
| 4161 | $$host =~ s/\s+$//;
|
---|
[418] | 4162 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
[417] | 4163 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 4164 | $$val =~ s/^\s+//;
|
---|
| 4165 | $$val =~ s/\s+$//;
|
---|
| 4166 | }
|
---|
| 4167 |
|
---|
[617] | 4168 | _caseclean($rectype, $host, $val, $defrec, $revrec) if $self->{lowercase};
|
---|
[542] | 4169 |
|
---|
[272] | 4170 | # prep for validation
|
---|
[609] | 4171 | my $addr = NetAddr::IP->new($$val) if _maybeip($val);
|
---|
[272] | 4172 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
[16] | 4173 |
|
---|
[272] | 4174 | my $domid = 0;
|
---|
| 4175 | my $revid = 0;
|
---|
| 4176 |
|
---|
| 4177 | my $retcode = 'OK'; # assume everything will go OK
|
---|
| 4178 | my $retmsg = '';
|
---|
| 4179 |
|
---|
[273] | 4180 | # do simple validation first
|
---|
[559] | 4181 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^-?\d+$/;
|
---|
[272] | 4182 |
|
---|
[273] | 4183 | # only MX and SRV will use these
|
---|
[288] | 4184 | my $dist = shift || 0;
|
---|
| 4185 | my $weight = shift || 0;
|
---|
| 4186 | my $port = shift || 0;
|
---|
[16] | 4187 |
|
---|
[272] | 4188 | my $fields;
|
---|
| 4189 | my @vallist;
|
---|
[16] | 4190 |
|
---|
[273] | 4191 | # get old record data so we have the right parent ID
|
---|
| 4192 | # and for logging (eventually)
|
---|
[481] | 4193 | my $oldrec = $self->getRecLine($defrec, $revrec, $id);
|
---|
[223] | 4194 |
|
---|
[272] | 4195 | # Call the validation sub for the type requested.
|
---|
| 4196 | # Note the ID to pass here is the *parent*, not the record
|
---|
[481] | 4197 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec,
|
---|
[272] | 4198 | id => ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})),
|
---|
| 4199 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
| 4200 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
| 4201 | fields => \$fields, vallist => \@vallist,
|
---|
[481] | 4202 | update => $id);
|
---|
[272] | 4203 |
|
---|
| 4204 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
| 4205 |
|
---|
[273] | 4206 | # Set up database fields and bind parameters. Note only the optional fields
|
---|
| 4207 | # (distance, weight, port, secondary parent ID) are added in the validation call above
|
---|
[448] | 4208 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
| 4209 | push @vallist, ($$host,$$rectype,$$val,$ttl,
|
---|
[273] | 4210 | ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})) );
|
---|
[272] | 4211 |
|
---|
[448] | 4212 | if ($defrec eq 'n') {
|
---|
[543] | 4213 | # locations are not for default records, silly coder!
|
---|
[448] | 4214 | $fields .= ",location";
|
---|
| 4215 | push @vallist, $location;
|
---|
[543] | 4216 | # timestamps are rare.
|
---|
| 4217 | if ($stamp) {
|
---|
| 4218 | $fields .= ",stamp,expires,stampactive";
|
---|
| 4219 | push @vallist, $stamp, $expires, 'y';
|
---|
| 4220 | } else {
|
---|
| 4221 | $fields .= ",stampactive";
|
---|
| 4222 | push @vallist, 'n';
|
---|
| 4223 | }
|
---|
[448] | 4224 | }
|
---|
| 4225 |
|
---|
[273] | 4226 | # hack hack PTHUI
|
---|
| 4227 | # need to forcibly make sure we disassociate a record with a parent it's no longer related to.
|
---|
| 4228 | # eg, PTR records may not have a domain parent, or A/AAAA records may not have a revzone parent.
|
---|
[605] | 4229 | # needed for crossover types that got coerced down to "standard" types due to data changes
|
---|
| 4230 | # need to *avoid* funky records being updated like A/AAAA records in revzones, or PTRs in forward zones.
|
---|
| 4231 | if ($defrec eq 'n' && $oldrec->{type} > 65000) {
|
---|
[273] | 4232 | if ($$rectype == $reverse_typemap{PTR}) {
|
---|
| 4233 | $fields .= ",domain_id";
|
---|
| 4234 | push @vallist, 0;
|
---|
| 4235 | }
|
---|
| 4236 | if ($$rectype == $reverse_typemap{A} || $$rectype == $reverse_typemap{AAAA}) {
|
---|
| 4237 | $fields .= ",rdns_id";
|
---|
| 4238 | push @vallist, 0;
|
---|
| 4239 | }
|
---|
| 4240 | }
|
---|
[345] | 4241 | # fix fat-finger-originated record type changes
|
---|
[605] | 4242 | if ($$rectype == 65285) { # delegation
|
---|
[345] | 4243 | $fields .= ",rdns_id" if $revrec eq 'n';
|
---|
| 4244 | $fields .= ",domain_id" if $revrec eq 'y';
|
---|
| 4245 | push @vallist, 0;
|
---|
| 4246 | }
|
---|
[605] | 4247 | # ... and now make sure we *do* associate a record with the "calling" parent
|
---|
[341] | 4248 | if ($defrec eq 'n') {
|
---|
| 4249 | $domid = $parid if $revrec eq 'n';
|
---|
| 4250 | $revid = $parid if $revrec eq 'y';
|
---|
| 4251 | }
|
---|
[272] | 4252 |
|
---|
[288] | 4253 | # Put together the success log entry. Horrible kludge from addRec() copied as-is since
|
---|
| 4254 | # we don't know whether the passed arguments or retrieved values for domain_id and rdns_id
|
---|
| 4255 | # will be maintained (due to "not-in-zone" validation changes)
|
---|
| 4256 | my %logdata;
|
---|
[341] | 4257 | $logdata{domain_id} = $domid;
|
---|
| 4258 | $logdata{rdns_id} = $revid;
|
---|
[288] | 4259 | my @ftmp = split /,/, $fields;
|
---|
| 4260 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
| 4261 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
| 4262 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
| 4263 | }
|
---|
| 4264 | $logdata{group_id} = $parid if $defrec eq 'y';
|
---|
[473] | 4265 | $logdata{group_id} = $self->parentID(id => $parid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec)
|
---|
[288] | 4266 | if $defrec eq 'n';
|
---|
[328] | 4267 | $logdata{entry} = "Updated ".($defrec eq 'y' ? 'default record' : 'record')." from\n";
|
---|
[621] | 4268 | # Log reverse records "naturally", since they're stored, um, unnaturally.
|
---|
| 4269 | if ($revrec eq 'y') {
|
---|
[328] | 4270 | $logdata{entry} .= " '$oldrec->{val} $typemap{$oldrec->{type}} $oldrec->{host}";
|
---|
| 4271 | } else {
|
---|
| 4272 | $logdata{entry} .= " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
| 4273 | }
|
---|
[288] | 4274 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
| 4275 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
| 4276 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
[425] | 4277 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
[480] | 4278 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location};
|
---|
[543] | 4279 | $logdata{entry} .= ($oldrec->{expires} ? ', expires at ' : ', valid after ').$oldrec->{stamp}
|
---|
| 4280 | if $oldrec->{stampactive};
|
---|
[425] | 4281 | $logdata{entry} .= "\nto\n";
|
---|
[621] | 4282 | # Log reverse records "naturally", since they're stored, um, unnaturally.
|
---|
| 4283 | if ($revrec eq 'y') {
|
---|
[328] | 4284 | $logdata{entry} .= "'$$val $typemap{$$rectype} $$host";
|
---|
| 4285 | } else {
|
---|
| 4286 | $logdata{entry} .= "'$$host $typemap{$$rectype} $$val";
|
---|
| 4287 | }
|
---|
[288] | 4288 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
| 4289 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$$rectype} eq 'SRV';
|
---|
[425] | 4290 | $logdata{entry} .= "', TTL $ttl";
|
---|
[480] | 4291 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location;
|
---|
[543] | 4292 | $logdata{entry} .= ($expires eq 'after' ? ', valid after ' : ', expires at ').$stamp if $stamp;
|
---|
[288] | 4293 |
|
---|
[90] | 4294 | local $dbh->{AutoCommit} = 0;
|
---|
| 4295 | local $dbh->{RaiseError} = 1;
|
---|
| 4296 |
|
---|
[341] | 4297 | # Fiddle the field list into something suitable for updates
|
---|
| 4298 | $fields =~ s/,/=?,/g;
|
---|
| 4299 | $fields .= "=?";
|
---|
| 4300 |
|
---|
[90] | 4301 | eval {
|
---|
[273] | 4302 | $dbh->do("UPDATE "._rectable($defrec,$revrec)." SET $fields WHERE record_id=?", undef, (@vallist, $id) );
|
---|
[487] | 4303 | $self->_log(%logdata);
|
---|
[130] | 4304 | $dbh->commit;
|
---|
[90] | 4305 | };
|
---|
| 4306 | if ($@) {
|
---|
| 4307 | my $msg = $@;
|
---|
[288] | 4308 | eval { $dbh->rollback; };
|
---|
[517] | 4309 | if ($self->{log_failures}) {
|
---|
[289] | 4310 | $logdata{entry} = "Failed updating ".($defrec eq 'y' ? 'default ' : '').
|
---|
| 4311 | "record '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
[487] | 4312 | $self->_log(%logdata);
|
---|
[289] | 4313 | $dbh->commit;
|
---|
| 4314 | }
|
---|
[90] | 4315 | return ('FAIL', $msg);
|
---|
| 4316 | }
|
---|
| 4317 |
|
---|
[288] | 4318 | $resultstr = $logdata{entry};
|
---|
[272] | 4319 | return ($retcode, $retmsg);
|
---|
[16] | 4320 | } # end updateRec()
|
---|
| 4321 |
|
---|
| 4322 |
|
---|
[459] | 4323 | ## DNSDB::downconvert()
|
---|
| 4324 | # A mostly internal (not exported) semiutilty sub to downconvert from pseudotype <x>
|
---|
| 4325 | # to a compatible component type. Only a handful of operations are valid, anything
|
---|
| 4326 | # else is a null-op.
|
---|
| 4327 | # Takes the record ID and the new type. Returns boolean.
|
---|
| 4328 | sub downconvert {
|
---|
[481] | 4329 | my $self = shift;
|
---|
| 4330 | my $dbh = $self->{dbh};
|
---|
[459] | 4331 | my $recid = shift;
|
---|
| 4332 | my $newtype = shift;
|
---|
| 4333 |
|
---|
| 4334 | # also, only work on live records; little to no value trying to do this on default records.
|
---|
[481] | 4335 | my $rec = $self->getRecLine('n', 'y', $recid);
|
---|
[459] | 4336 |
|
---|
| 4337 | # hm?
|
---|
| 4338 | #return 1 if !$rec;
|
---|
| 4339 |
|
---|
| 4340 | return 1 if $rec->{type} < 65000; # Only the reverse-record pseudotypes can be downconverted
|
---|
| 4341 | return 1 if $rec->{type} == 65282; # Nowhere to go
|
---|
| 4342 |
|
---|
| 4343 | my $delpar;
|
---|
| 4344 | my @sqlargs;
|
---|
| 4345 | if ($rec->{type} == 65280) {
|
---|
| 4346 | return 1 if $newtype != 1 && $newtype != 12;
|
---|
| 4347 | $delpar = ($newtype == 1 ? 'rdns_id' : 'domain_id');
|
---|
| 4348 | push @sqlargs, 0, $newtype, $recid;
|
---|
| 4349 | } elsif ($rec->{type} == 65281) {
|
---|
| 4350 | return 1 if $newtype != 28 && $newtype != 12;
|
---|
| 4351 | $delpar = ($newtype == 28 ? 'rdns_id' : 'domain_id');
|
---|
| 4352 | push @sqlargs, 0, $newtype, $recid;
|
---|
| 4353 | } elsif ($rec->{type} == 65283) {
|
---|
| 4354 | return 1 if $newtype != 65282;
|
---|
| 4355 | $delpar = 'rdns_id';
|
---|
| 4356 | } elsif ($rec->{type} == 65284) {
|
---|
| 4357 | return 1 if $newtype != 65282;
|
---|
| 4358 | $delpar = 'rdns_id';
|
---|
| 4359 | } else {
|
---|
| 4360 | # Your llama is on fire.
|
---|
| 4361 | }
|
---|
| 4362 |
|
---|
| 4363 | local $dbh->{AutoCommit} = 0;
|
---|
| 4364 | local $dbh->{RaiseError} = 1;
|
---|
| 4365 |
|
---|
| 4366 | eval {
|
---|
| 4367 | $dbh->do("UPDATE records SET $delpar = ?, type = ? WHERE record_id = ?", undef, @sqlargs);
|
---|
| 4368 | $dbh->commit;
|
---|
| 4369 | };
|
---|
| 4370 | if ($@) {
|
---|
| 4371 | $errstr = $@;
|
---|
| 4372 | eval { $dbh->rollback; };
|
---|
| 4373 | return 0;
|
---|
| 4374 | }
|
---|
| 4375 | return 1;
|
---|
| 4376 | } # end downconvert()
|
---|
| 4377 |
|
---|
| 4378 |
|
---|
[3] | 4379 | ## DNSDB::delRec()
|
---|
| 4380 | # Delete a record.
|
---|
| 4381 | sub delRec {
|
---|
| 4382 | $errstr = '';
|
---|
[481] | 4383 | my $self = shift;
|
---|
| 4384 | my $dbh = $self->{dbh};
|
---|
[3] | 4385 | my $defrec = shift;
|
---|
[243] | 4386 | my $revrec = shift;
|
---|
[3] | 4387 | my $id = shift;
|
---|
| 4388 |
|
---|
[481] | 4389 | my $oldrec = $self->getRecLine($defrec, $revrec, $id);
|
---|
[3] | 4390 |
|
---|
[290] | 4391 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4392 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4393 | local $dbh->{AutoCommit} = 0;
|
---|
| 4394 | local $dbh->{RaiseError} = 1;
|
---|
[3] | 4395 |
|
---|
[290] | 4396 | # Put together the log entry
|
---|
| 4397 | my %logdata;
|
---|
| 4398 | $logdata{domain_id} = $oldrec->{domain_id};
|
---|
| 4399 | $logdata{rdns_id} = $oldrec->{rdns_id};
|
---|
| 4400 | $logdata{group_id} = $oldrec->{group_id} if $defrec eq 'y';
|
---|
[473] | 4401 | $logdata{group_id} = $self->parentID(id => $oldrec->{domain_id}, type => ($revrec eq 'n' ? 'domain' : 'revzone'),
|
---|
| 4402 | revrec => $revrec)
|
---|
[290] | 4403 | if $defrec eq 'n';
|
---|
| 4404 | $logdata{entry} = "Deleted ".($defrec eq 'y' ? 'default record ' : 'record ').
|
---|
| 4405 | "'$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
| 4406 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
| 4407 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
| 4408 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
[425] | 4409 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
[480] | 4410 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location};
|
---|
[290] | 4411 |
|
---|
| 4412 | eval {
|
---|
| 4413 | my $sth = $dbh->do("DELETE FROM "._rectable($defrec,$revrec)." WHERE record_id=?", undef, ($id));
|
---|
[487] | 4414 | $self->_log(%logdata);
|
---|
[290] | 4415 | $dbh->commit;
|
---|
| 4416 | };
|
---|
| 4417 | if ($@) {
|
---|
| 4418 | my $msg = $@;
|
---|
| 4419 | eval { $dbh->rollback; };
|
---|
[517] | 4420 | if ($self->{log_failures}) {
|
---|
[290] | 4421 | $logdata{entry} = "Error deleting ".($defrec eq 'y' ? 'default record' : 'record').
|
---|
| 4422 | " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
[487] | 4423 | $self->_log(%logdata);
|
---|
[290] | 4424 | $dbh->commit;
|
---|
| 4425 | }
|
---|
| 4426 | return ('FAIL', $msg);
|
---|
| 4427 | }
|
---|
| 4428 |
|
---|
| 4429 | return ('OK',$logdata{entry});
|
---|
[3] | 4430 | } # end delRec()
|
---|
| 4431 |
|
---|
| 4432 |
|
---|
[323] | 4433 | ## DNSDB::getLogCount()
|
---|
| 4434 | # Get a count of log entries
|
---|
| 4435 | # Takes a database handle and a hash containing at least:
|
---|
| 4436 | # - Entity ID and entity type as the primary log "slice"
|
---|
| 4437 | sub getLogCount {
|
---|
[483] | 4438 | my $self = shift;
|
---|
| 4439 | my $dbh = $self->{dbh};
|
---|
[323] | 4440 |
|
---|
| 4441 | my %args = @_;
|
---|
| 4442 |
|
---|
| 4443 | my @filterargs;
|
---|
| 4444 | ##fixme: which fields do we want to filter on?
|
---|
| 4445 | # push @filterargs,
|
---|
| 4446 |
|
---|
| 4447 | $errstr = 'Missing primary parent ID and/or type';
|
---|
| 4448 | # fail early if we don't have a "prime" ID to look for log entries for
|
---|
| 4449 | return if !$args{id};
|
---|
| 4450 |
|
---|
| 4451 | # or if the prime id type is missing or invalid
|
---|
| 4452 | return if !$args{logtype};
|
---|
| 4453 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
| 4454 | $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
|
---|
| 4455 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
|
---|
| 4456 |
|
---|
| 4457 | my $sql = "SELECT count(*) FROM log ".
|
---|
| 4458 | "WHERE $id_col{$args{logtype}}=?".
|
---|
| 4459 | ($args{filter} ? " AND entry ~* ?" : '');
|
---|
| 4460 | my ($count) = $dbh->selectrow_array($sql, undef, ($args{id}, @filterargs) );
|
---|
| 4461 | $errstr = $dbh->errstr if !$count;
|
---|
| 4462 | return $count;
|
---|
| 4463 | } # end getLogCount()
|
---|
| 4464 |
|
---|
| 4465 |
|
---|
| 4466 | ## DNSDB::getLogEntries()
|
---|
| 4467 | # Get a list of log entries
|
---|
| 4468 | # Takes arguments as with getLogCount() above, plus optional:
|
---|
| 4469 | # - sort field
|
---|
| 4470 | # - sort order
|
---|
| 4471 | # - offset for pagination
|
---|
| 4472 | sub getLogEntries {
|
---|
[483] | 4473 | my $self = shift;
|
---|
| 4474 | my $dbh = $self->{dbh};
|
---|
[323] | 4475 |
|
---|
| 4476 | my %args = @_;
|
---|
| 4477 |
|
---|
| 4478 | my @filterargs;
|
---|
| 4479 |
|
---|
| 4480 | # fail early if we don't have a "prime" ID to look for log entries for
|
---|
| 4481 | return if !$args{id};
|
---|
| 4482 |
|
---|
| 4483 | # or if the prime id type is missing or invalid
|
---|
| 4484 | return if !$args{logtype};
|
---|
| 4485 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
| 4486 | $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
|
---|
| 4487 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
|
---|
| 4488 |
|
---|
| 4489 | # Sorting defaults
|
---|
[508] | 4490 | $args{sortorder} = 'DESC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
| 4491 | $args{sortby} = 'stamp' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
[397] | 4492 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[323] | 4493 |
|
---|
[324] | 4494 | my %sortmap = (fname => 'name', username => 'email', entry => 'entry', stamp => 'stamp');
|
---|
[323] | 4495 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 4496 |
|
---|
| 4497 | my $sql = "SELECT user_id AS userid, email AS useremail, name AS userfname, entry AS logentry, ".
|
---|
| 4498 | "date_trunc('second',stamp) AS logtime ".
|
---|
| 4499 | "FROM log ".
|
---|
| 4500 | "WHERE $id_col{$args{logtype}}=?".
|
---|
| 4501 | ($args{filter} ? " AND entry ~* ?" : '').
|
---|
[324] | 4502 | " ORDER BY $args{sortby} $args{sortorder}, log_id $args{sortorder}".
|
---|
[517] | 4503 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
[323] | 4504 | my $loglist = $dbh->selectall_arrayref($sql, { Slice => {} }, ($args{id}, @filterargs) );
|
---|
| 4505 | $errstr = $dbh->errstr if !$loglist;
|
---|
| 4506 | return $loglist;
|
---|
| 4507 | } # end getLogEntries()
|
---|
| 4508 |
|
---|
| 4509 |
|
---|
[452] | 4510 | ## IPDB::getRevPattern()
|
---|
| 4511 | # Get the narrowest template pattern applicable to a passed CIDR address (may be a netblock or an IP)
|
---|
| 4512 | sub getRevPattern {
|
---|
[483] | 4513 | my $self = shift;
|
---|
| 4514 | my $dbh = $self->{dbh};
|
---|
[452] | 4515 | my $cidr = shift;
|
---|
| 4516 | my $group = shift || 1; # just in case
|
---|
| 4517 |
|
---|
[462] | 4518 | # for speed! Casting and comparing even ~7K records takes ~2.5s, so narrow it down to one revzone first.
|
---|
| 4519 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >>= ? AND group_id = ?",
|
---|
| 4520 | undef, ($cidr, $group) );
|
---|
| 4521 |
|
---|
| 4522 | ##fixme? may need to narrow things down more by octet-chopping and doing text comparisons before casting.
|
---|
| 4523 | my ($revpatt) = $dbh->selectrow_array("SELECT host FROM records ".
|
---|
[599] | 4524 | "WHERE (type in (12,65280,65281,65282,65283,65284)) AND rdns_id = ? AND inetlazy(val) >>= ? ".
|
---|
| 4525 | "ORDER BY inetlazy(val) DESC LIMIT 1", undef, ($revid, $cidr) );
|
---|
[452] | 4526 | return $revpatt;
|
---|
| 4527 | } # end getRevPattern()
|
---|
| 4528 |
|
---|
| 4529 |
|
---|
[225] | 4530 | ## DNSDB::getTypelist()
|
---|
| 4531 | # Get a list of record types for various UI dropdowns
|
---|
| 4532 | # Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A)
|
---|
| 4533 | # Returns an arrayref to list of hashrefs perfect for HTML::Template
|
---|
| 4534 | sub getTypelist {
|
---|
[483] | 4535 | my $self = shift;
|
---|
| 4536 | my $dbh = $self->{dbh};
|
---|
[225] | 4537 | my $recgroup = shift;
|
---|
| 4538 | my $type = shift || $reverse_typemap{A};
|
---|
| 4539 |
|
---|
| 4540 | # also accepting $webvar{revrec}!
|
---|
| 4541 | $recgroup = 'f' if $recgroup eq 'n';
|
---|
| 4542 | $recgroup = 'r' if $recgroup eq 'y';
|
---|
| 4543 |
|
---|
| 4544 | my $sql = "SELECT val,name FROM rectypes WHERE ";
|
---|
| 4545 | if ($recgroup eq 'r') {
|
---|
| 4546 | # reverse zone types
|
---|
| 4547 | $sql .= "stdflag=2 OR stdflag=3";
|
---|
| 4548 | } elsif ($recgroup eq 'l') {
|
---|
| 4549 | # DNS lookup types. Note we avoid our custom types >= 65280, since those are entirely internal.
|
---|
| 4550 | $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280";
|
---|
| 4551 | } else {
|
---|
| 4552 | # default; forward zone types. technically $type eq 'f' but not worth the error message.
|
---|
| 4553 | $sql .= "stdflag=1 OR stdflag=2";
|
---|
[506] | 4554 | $sql .= " AND val < 65280" if $recgroup eq 'fo'; # An extra flag to trim off the pseudotypes as well.
|
---|
[225] | 4555 | }
|
---|
| 4556 | $sql .= " ORDER BY listorder";
|
---|
| 4557 |
|
---|
| 4558 | my $sth = $dbh->prepare($sql);
|
---|
| 4559 | $sth->execute;
|
---|
| 4560 | my @typelist;
|
---|
[603] | 4561 | # track whether the passed type is in the list at all. allows you to edit a record
|
---|
| 4562 | # that wouldn't otherwise be generally available in that zone (typically, reverse zones)
|
---|
| 4563 | # without changing its type (accidentally or otherwise)
|
---|
| 4564 | my $selflag = 0;
|
---|
[225] | 4565 | while (my ($rval,$rname) = $sth->fetchrow_array()) {
|
---|
| 4566 | my %row = ( recval => $rval, recname => $rname );
|
---|
[603] | 4567 | if ($rval == $type) {
|
---|
| 4568 | $row{tselect} = 1;
|
---|
| 4569 | $selflag = 1;
|
---|
| 4570 | }
|
---|
[225] | 4571 | push @typelist, \%row;
|
---|
| 4572 | }
|
---|
| 4573 |
|
---|
[603] | 4574 | # add the passed type if it wasn't in the list
|
---|
| 4575 | if (!$selflag) {
|
---|
| 4576 | my %row = ( recval => $type, recname => $typemap{$type}, tselect => 1 );
|
---|
| 4577 | push @typelist, \%row;
|
---|
| 4578 | }
|
---|
| 4579 |
|
---|
[225] | 4580 | # Add SOA on lookups since it's not listed in other dropdowns.
|
---|
| 4581 | if ($recgroup eq 'l') {
|
---|
| 4582 | my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
|
---|
| 4583 | $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
|
---|
| 4584 | push @typelist, \%row;
|
---|
| 4585 | }
|
---|
| 4586 |
|
---|
| 4587 | return \@typelist;
|
---|
| 4588 | } # end getTypelist()
|
---|
| 4589 |
|
---|
| 4590 |
|
---|
[254] | 4591 | ## DNSDB::parentID()
|
---|
| 4592 | # Get ID of entity that is nearest parent to requested id
|
---|
| 4593 | # Takes a database handle and a hash of entity ID, entity type, optional parent type flag
|
---|
| 4594 | # (domain/reverse zone or group), and optional default/live and forward/reverse flags
|
---|
| 4595 | # Returns the ID or undef on failure
|
---|
| 4596 | sub parentID {
|
---|
[473] | 4597 | my $self = shift;
|
---|
| 4598 | my $dbh = $self->{dbh};
|
---|
[116] | 4599 |
|
---|
[254] | 4600 | my %args = @_;
|
---|
[116] | 4601 |
|
---|
[254] | 4602 | # clean up the parent-type. Set it to group if not set; coerce revzone to domain for simpler logic
|
---|
| 4603 | $args{partype} = 'group' if !$args{partype};
|
---|
| 4604 | $args{partype} = 'domain' if $args{partype} eq 'revzone';
|
---|
[116] | 4605 |
|
---|
[254] | 4606 | # clean up defrec and revrec. default to live record, forward zone
|
---|
| 4607 | $args{defrec} = 'n' if !$args{defrec};
|
---|
| 4608 | $args{revrec} = 'n' if !$args{revrec};
|
---|
[116] | 4609 |
|
---|
[254] | 4610 | if ($par_type{$args{partype}} eq 'domain') {
|
---|
| 4611 | # only live records can have a domain/zone parent
|
---|
| 4612 | return unless ($args{type} eq 'record' && $args{defrec} eq 'n');
|
---|
| 4613 | my $result = $dbh->selectrow_hashref("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
| 4614 | " FROM records WHERE record_id = ?",
|
---|
| 4615 | undef, ($args{id}) ) or return;
|
---|
| 4616 | return $result;
|
---|
| 4617 | } else {
|
---|
| 4618 | # snag some arguments that will either fall through or be overwritten to save some code duplication
|
---|
| 4619 | my $tmpid = $args{id};
|
---|
| 4620 | my $type = $args{type};
|
---|
| 4621 | if ($type eq 'record' && $args{defrec} eq 'n') {
|
---|
| 4622 | # Live records go through the records table first.
|
---|
| 4623 | ($tmpid) = $dbh->selectrow_array("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
| 4624 | " FROM records WHERE record_id = ?",
|
---|
| 4625 | undef, ($args{id}) ) or return;
|
---|
| 4626 | $type = ($args{revrec} eq 'n' ? 'domain' : 'revzone');
|
---|
| 4627 | }
|
---|
| 4628 | my ($result) = $dbh->selectrow_array("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
|
---|
| 4629 | undef, ($tmpid) );
|
---|
| 4630 | return $result;
|
---|
| 4631 | }
|
---|
| 4632 | # should be impossible to get here with even remotely sane arguments
|
---|
| 4633 | return;
|
---|
| 4634 | } # end parentID()
|
---|
[116] | 4635 |
|
---|
| 4636 |
|
---|
[117] | 4637 | ## DNSDB::isParent()
|
---|
| 4638 | # Returns true if $id1 is a parent of $id2, false otherwise
|
---|
| 4639 | sub isParent {
|
---|
[470] | 4640 | my $self = shift;
|
---|
| 4641 | my $dbh = $self->{dbh};
|
---|
[117] | 4642 | my $id1 = shift;
|
---|
| 4643 | my $type1 = shift;
|
---|
| 4644 | my $id2 = shift;
|
---|
| 4645 | my $type2 = shift;
|
---|
| 4646 | ##todo: immediate, secondary, full (default)
|
---|
| 4647 |
|
---|
[157] | 4648 | # Return false on invalid types
|
---|
[244] | 4649 | return 0 if !grep /^$type1$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
| 4650 | return 0 if !grep /^$type2$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
[157] | 4651 |
|
---|
[117] | 4652 | # Return false on impossible relations
|
---|
| 4653 | return 0 if $type1 eq 'record'; # nothing may be a child of a record
|
---|
| 4654 | return 0 if $type1 eq 'defrec'; # nothing may be a child of a record
|
---|
[244] | 4655 | return 0 if $type1 eq 'defrevrec'; # nothing may be a child of a record
|
---|
[117] | 4656 | return 0 if $type1 eq 'user'; # nothing may be child of a user
|
---|
| 4657 | return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record
|
---|
[244] | 4658 | return 0 if $type1 eq 'revzone' && $type2 ne 'record';# reverse zone may not be a parent of anything other than a record
|
---|
[117] | 4659 |
|
---|
[186] | 4660 | # ennnhhhh.... if we're passed an id of 0, it will never be found. usual
|
---|
| 4661 | # case would be the UI creating a new <thing>, and so we don't have an ID for
|
---|
| 4662 | # <thing> to look up yet. in that case the UI should check the parent as well.
|
---|
| 4663 | return 0 if $id1 == 0; # nothing can have a parent id of 0
|
---|
| 4664 | return 1 if $id2 == 0; # anything could have a child id of 0 (or "unknown")
|
---|
| 4665 |
|
---|
[117] | 4666 | # group 1 is the ultimate root parent
|
---|
| 4667 | return 1 if $type1 eq 'group' && $id1 == 1;
|
---|
| 4668 |
|
---|
[155] | 4669 | # groups are always (a) parent of themselves
|
---|
| 4670 | return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2;
|
---|
| 4671 |
|
---|
[117] | 4672 | my $id = $id2;
|
---|
| 4673 | my $type = $type2;
|
---|
| 4674 | my $foundparent = 0;
|
---|
[155] | 4675 |
|
---|
[244] | 4676 | # Records are the only entity with two possible parents. We need to split the parent checks on
|
---|
| 4677 | # domain/rdns.
|
---|
| 4678 | if ($type eq 'record') {
|
---|
| 4679 | my ($dom,$rdns) = $dbh->selectrow_array("SELECT domain_id,rdns_id FROM records WHERE record_id=?",
|
---|
| 4680 | undef, ($id));
|
---|
| 4681 | # check immediate parent against request
|
---|
| 4682 | return 1 if $type1 eq 'domain' && $id1 == $dom;
|
---|
| 4683 | return 1 if $type1 eq 'revzone' && $id1 == $rdns;
|
---|
| 4684 | # if request is group, check *both* parents. Only check if the parent is nonzero though.
|
---|
[470] | 4685 | return 1 if $dom && $self->isParent($id1, $type1, $dom, 'domain');
|
---|
| 4686 | return 1 if $rdns && $self->isParent($id1, $type1, $rdns, 'revzone');
|
---|
[244] | 4687 | # exit here since we've executed the loop below by proxy in the above recursive calls.
|
---|
| 4688 | return 0;
|
---|
| 4689 | }
|
---|
| 4690 |
|
---|
| 4691 | # almost the same loop as getParents() above
|
---|
[186] | 4692 | my $limiter = 0;
|
---|
[117] | 4693 | while (1) {
|
---|
[155] | 4694 | my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
|
---|
[117] | 4695 | my $result = $dbh->selectrow_hashref($sql,
|
---|
[157] | 4696 | undef, ($id) );
|
---|
[186] | 4697 | if (!$result) {
|
---|
| 4698 | $limiter++;
|
---|
[244] | 4699 | ##fixme: how often will this happen on a live site? fail at max limiter <n>?
|
---|
[541] | 4700 | # 2013/10/22 only seems to happen when you request an entity that doesn't exist.
|
---|
[186] | 4701 | warn "no results looking for $sql with id $id (depth $limiter)\n";
|
---|
| 4702 | last;
|
---|
| 4703 | }
|
---|
[157] | 4704 | if ($result && $result->{$par_col{$type}} == $id1) {
|
---|
[117] | 4705 | $foundparent = 1;
|
---|
| 4706 | last;
|
---|
[157] | 4707 | } else {
|
---|
| 4708 | ##fixme: do we care about trying to return a "no such record/domain/user/group" error?
|
---|
[244] | 4709 | # should be impossible to create an inconsistent DB just with API calls.
|
---|
[157] | 4710 | warn $dbh->errstr." $sql, $id" if $dbh->errstr;
|
---|
[117] | 4711 | }
|
---|
| 4712 | # group 1 is its own parent. need this here more to break strange loops than for detecting a parent
|
---|
| 4713 | last if $result->{$par_col{$type}} == 1;
|
---|
[152] | 4714 | $id = $result->{$par_col{$type}};
|
---|
[117] | 4715 | $type = $par_type{$type};
|
---|
| 4716 | }
|
---|
| 4717 |
|
---|
| 4718 | return $foundparent;
|
---|
| 4719 | } # end isParent()
|
---|
| 4720 |
|
---|
| 4721 |
|
---|
[275] | 4722 | ## DNSDB::zoneStatus()
|
---|
| 4723 | # Returns and optionally sets a zone's status
|
---|
| 4724 | # Takes a database handle, domain/revzone ID, forward/reverse flag, and optionally a status argument
|
---|
| 4725 | # Returns status, or undef on errors.
|
---|
| 4726 | sub zoneStatus {
|
---|
[477] | 4727 | my $self = shift;
|
---|
| 4728 | my $dbh = $self->{dbh};
|
---|
[3] | 4729 | my $id = shift;
|
---|
[275] | 4730 | my $revrec = shift;
|
---|
| 4731 | my $newstatus = shift || 'mu';
|
---|
[3] | 4732 |
|
---|
| 4733 | return undef if $id !~ /^\d+$/;
|
---|
| 4734 |
|
---|
[283] | 4735 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4736 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4737 | local $dbh->{AutoCommit} = 0;
|
---|
| 4738 | local $dbh->{RaiseError} = 1;
|
---|
| 4739 |
|
---|
[275] | 4740 | if ($newstatus ne 'mu') {
|
---|
[283] | 4741 | # ooo, fun! let's see what we were passed for status
|
---|
| 4742 | eval {
|
---|
| 4743 | $newstatus = 0 if $newstatus eq 'domoff';
|
---|
| 4744 | $newstatus = 1 if $newstatus eq 'domon';
|
---|
| 4745 | $dbh->do("UPDATE ".($revrec eq 'n' ? 'domains' : 'revzones')." SET status=? WHERE ".
|
---|
[275] | 4746 | ($revrec eq 'n' ? 'domain_id' : 'rdns_id')."=?", undef, ($newstatus,$id) );
|
---|
[283] | 4747 |
|
---|
| 4748 | ##fixme switch to more consise "Enabled <domain"/"Disabled <domain>" as with users?
|
---|
[473] | 4749 | $resultstr = "Changed ".($revrec eq 'n' ? $self->domainName($id) : $self->revName($id)).
|
---|
[283] | 4750 | " state to ".($newstatus ? 'active' : 'inactive');
|
---|
| 4751 |
|
---|
| 4752 | my %loghash;
|
---|
| 4753 | $loghash{domain_id} = $id if $revrec eq 'n';
|
---|
| 4754 | $loghash{rdns_id} = $id if $revrec eq 'y';
|
---|
[473] | 4755 | $loghash{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec);
|
---|
[283] | 4756 | $loghash{entry} = $resultstr;
|
---|
[487] | 4757 | $self->_log(%loghash);
|
---|
[283] | 4758 |
|
---|
| 4759 | $dbh->commit;
|
---|
| 4760 | };
|
---|
| 4761 | if ($@) {
|
---|
| 4762 | my $msg = $@;
|
---|
| 4763 | eval { $dbh->rollback; };
|
---|
| 4764 | $resultstr = '';
|
---|
| 4765 | $errstr = $msg;
|
---|
| 4766 | return;
|
---|
| 4767 | }
|
---|
[3] | 4768 | }
|
---|
| 4769 |
|
---|
[275] | 4770 | my ($status) = $dbh->selectrow_array("SELECT status FROM ".
|
---|
| 4771 | ($revrec eq 'n' ? "domains WHERE domain_id=?" : "revzones WHERE rdns_id=?"),
|
---|
| 4772 | undef, ($id) );
|
---|
[3] | 4773 | return $status;
|
---|
[275] | 4774 | } # end zoneStatus()
|
---|
[3] | 4775 |
|
---|
| 4776 |
|
---|
[452] | 4777 | ## DNSDB::getZonesByCIDR()
|
---|
| 4778 | # Get a list of zone names and IDs that records for a passed CIDR block are within.
|
---|
| 4779 | sub getZonesByCIDR {
|
---|
[477] | 4780 | my $self = shift;
|
---|
| 4781 | my $dbh = $self->{dbh};
|
---|
[452] | 4782 | my %args = @_;
|
---|
| 4783 |
|
---|
| 4784 | my $result = $dbh->selectall_arrayref("SELECT rdns_id,revnet FROM revzones WHERE revnet >>= ? OR revnet <<= ?",
|
---|
| 4785 | { Slice => {} }, ($args{cidr}, $args{cidr}) );
|
---|
| 4786 | return $result;
|
---|
| 4787 | } # end getZonesByCIDR()
|
---|
| 4788 |
|
---|
| 4789 |
|
---|
[33] | 4790 | ## DNSDB::importAXFR
|
---|
| 4791 | # Import a domain via AXFR
|
---|
[37] | 4792 | # Takes AXFR host, domain to transfer, group to put the domain in,
|
---|
[484] | 4793 | # and an optional hash containing:
|
---|
| 4794 | # status - active/inactive state flag (defaults to active)
|
---|
| 4795 | # rwsoa - overwrite-SOA flag (defaults to off)
|
---|
| 4796 | # rwns - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
|
---|
| 4797 | # merge - flag to automerge A or AAAA records with matching PTR records
|
---|
[37] | 4798 | # Returns a status code (OK, WARN, or FAIL) and message - message should be blank
|
---|
| 4799 | # if status is OK, but WARN includes conditions that are not fatal but should
|
---|
| 4800 | # really be reported.
|
---|
[33] | 4801 | sub importAXFR {
|
---|
[484] | 4802 | my $self = shift;
|
---|
| 4803 | my $dbh = $self->{dbh};
|
---|
[35] | 4804 | my $ifrom_in = shift;
|
---|
[301] | 4805 | my $zone = shift;
|
---|
[33] | 4806 | my $group = shift;
|
---|
[484] | 4807 |
|
---|
| 4808 | my %args = @_;
|
---|
| 4809 |
|
---|
[33] | 4810 | ##fixme: add mode to delete&replace, merge+overwrite, merge new?
|
---|
| 4811 |
|
---|
[484] | 4812 | $args{status} = (defined($args{status}) ? $args{status} : 0);
|
---|
| 4813 | $args{status} = 1 if $args{status} eq 'on';
|
---|
| 4814 |
|
---|
[37] | 4815 | my $nrecs = 0;
|
---|
| 4816 | my $soaflag = 0;
|
---|
| 4817 | my $nsflag = 0;
|
---|
| 4818 | my $warnmsg = '';
|
---|
| 4819 | my $ifrom;
|
---|
[33] | 4820 |
|
---|
[301] | 4821 | my $rev = 'n';
|
---|
[302] | 4822 | my $code = 'OK';
|
---|
| 4823 | my $msg = 'foobar?';
|
---|
[301] | 4824 |
|
---|
[35] | 4825 | # choke on possible bad setting in ifrom
|
---|
[37] | 4826 | # IPv4 and v6, and valid hostnames!
|
---|
[35] | 4827 | ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
| 4828 | return ('FAIL', "Bad AXFR source host $ifrom")
|
---|
| 4829 | unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
| 4830 |
|
---|
[301] | 4831 | my $errmsg;
|
---|
| 4832 |
|
---|
| 4833 | my $zone_id;
|
---|
| 4834 | my $domain_id = 0;
|
---|
| 4835 | my $rdns_id = 0;
|
---|
| 4836 | my $cidr;
|
---|
| 4837 |
|
---|
| 4838 | # magic happens! detect if we're importing a domain or a reverse zone
|
---|
| 4839 | # while we're at it, figure out what the CIDR netblock is (if we got a .arpa)
|
---|
| 4840 | # or what the formal .arpa zone is (if we got a CIDR netblock)
|
---|
| 4841 | # Handles sub-octet v4 zones in the format specified in the Cricket Book, 2nd Ed, p217-218
|
---|
| 4842 |
|
---|
[601] | 4843 | if ($zone =~ m{(?:\.arpa\.?|/\d+|^[\d.]+|^[a-fA-F0-9:]+)$}) {
|
---|
[301] | 4844 | # we seem to have a reverse zone
|
---|
| 4845 | $rev = 'y';
|
---|
| 4846 |
|
---|
| 4847 | if ($zone =~ /\.arpa\.?$/) {
|
---|
| 4848 | # we have a formal reverse zone. call _zone2cidr and get the CIDR block.
|
---|
| 4849 | ($code,$msg) = _zone2cidr($zone);
|
---|
| 4850 | return ($code, $msg) if $code eq 'FAIL';
|
---|
| 4851 | $cidr = $msg;
|
---|
| 4852 | } elsif ($zone =~ m|^[\d.]+/\d+$|) {
|
---|
| 4853 | # v4 revzone, CIDR netblock
|
---|
| 4854 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 4855 | $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
[601] | 4856 | } elsif ($zone =~ /^[\d.]+$/) {
|
---|
| 4857 | # v4 revzone, leading-octet format
|
---|
| 4858 | my $mask = 32;
|
---|
| 4859 | while ($zone !~ /^\d+\.\d+\.\d+\.\d+$/) {
|
---|
| 4860 | $zone .= '.0';
|
---|
| 4861 | $mask -= 8;
|
---|
| 4862 | }
|
---|
| 4863 | $zone .= "/$mask";
|
---|
| 4864 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 4865 | $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
[301] | 4866 | } elsif ($zone =~ m|^[a-fA-F\d:]+/\d+$|) {
|
---|
| 4867 | # v6 revzone, CIDR netblock
|
---|
| 4868 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 4869 | return ('FAIL', "$zone is not a nibble-aligned block") if $cidr->masklen % 4 != 0;
|
---|
| 4870 | $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.');
|
---|
[601] | 4871 | } elsif ($zone =~ /^[a-fA-F\d:]+$/) {
|
---|
| 4872 | # v6 revzone, leading-group format
|
---|
| 4873 | $zone =~ s/::$//;
|
---|
| 4874 | my $mask = 128;
|
---|
| 4875 | while ($zone !~ /^(?:[a-fA-F\d]{1,4}:){7}[a-fA-F\d]$/) {
|
---|
| 4876 | $zone .= ":0";
|
---|
| 4877 | $mask -= 16;
|
---|
| 4878 | }
|
---|
| 4879 | $zone .= "/$mask";
|
---|
| 4880 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 4881 | $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.');
|
---|
[301] | 4882 | } else {
|
---|
| 4883 | # there is. no. else!
|
---|
[601] | 4884 | return ('FAIL', "Unknown zone name format '$zone'");
|
---|
[301] | 4885 | }
|
---|
| 4886 |
|
---|
[601] | 4887 | # several places this can be triggered from; better to do it once.
|
---|
| 4888 | $warnmsg .= "Apparent sub-/64 IPv6 reverse zone\n" if $cidr->masklen > 64;
|
---|
| 4889 |
|
---|
[301] | 4890 | # quick check to start to see if we've already got one
|
---|
| 4891 |
|
---|
| 4892 | ($zone_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?",
|
---|
| 4893 | undef, ("$cidr"));
|
---|
| 4894 | $rdns_id = $zone_id;
|
---|
| 4895 | } else {
|
---|
| 4896 | # default to domain
|
---|
[349] | 4897 | ($zone_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
[301] | 4898 | undef, ($zone));
|
---|
| 4899 | $domain_id = $zone_id;
|
---|
| 4900 | }
|
---|
| 4901 |
|
---|
| 4902 | return ('FAIL', ($rev eq 'n' ? 'Domain' : 'Reverse zone')." already exists") if $zone_id;
|
---|
| 4903 |
|
---|
[303] | 4904 | # little local utility sub to swap $val and $host for revzone records.
|
---|
| 4905 | sub _revswap {
|
---|
| 4906 | my $rechost = shift;
|
---|
| 4907 | my $recdata = shift;
|
---|
| 4908 |
|
---|
| 4909 | if ($rechost =~ /\.in-addr\.arpa\.?$/) {
|
---|
| 4910 | $rechost =~ s/\.in-addr\.arpa\.?$//;
|
---|
| 4911 | $rechost = join '.', reverse split /\./, $rechost;
|
---|
| 4912 | } else {
|
---|
| 4913 | $rechost =~ s/\.ip6\.arpa\.?$//;
|
---|
| 4914 | my @nibs = reverse split /\./, $rechost;
|
---|
| 4915 | $rechost = '';
|
---|
| 4916 | my $nc;
|
---|
| 4917 | foreach (@nibs) {
|
---|
| 4918 | $rechost.= $_;
|
---|
| 4919 | $rechost .= ":" if ++$nc % 4 == 0 && $nc < 32;
|
---|
| 4920 | }
|
---|
[307] | 4921 | $rechost .= ":" if $nc < 32 && $rechost !~ /\*$/; # close netblock records?
|
---|
| 4922 | ##fixme: there's a case that ends up with a partial entry here:
|
---|
| 4923 | # ip:add:re:ss::
|
---|
| 4924 | # can't reproduce after letting it sit overnight after discovery. :(
|
---|
| 4925 | #print "$rechost\n";
|
---|
[303] | 4926 | # canonicalize with NetAddr::IP
|
---|
| 4927 | $rechost = NetAddr::IP->new($rechost)->addr unless $rechost =~ /\*$/;
|
---|
| 4928 | }
|
---|
| 4929 | return ($recdata,$rechost)
|
---|
| 4930 | }
|
---|
| 4931 |
|
---|
| 4932 |
|
---|
[33] | 4933 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4934 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4935 | local $dbh->{AutoCommit} = 0;
|
---|
| 4936 | local $dbh->{RaiseError} = 1;
|
---|
| 4937 |
|
---|
[301] | 4938 | my $sth;
|
---|
| 4939 | eval {
|
---|
[34] | 4940 |
|
---|
[301] | 4941 | if ($rev eq 'n') {
|
---|
[33] | 4942 | ##fixme: serial
|
---|
[484] | 4943 | $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef,
|
---|
| 4944 | ($zone, $group, $args{status}) );
|
---|
[301] | 4945 | # get domain id so we can do the records
|
---|
| 4946 | ($zone_id) = $dbh->selectrow_array("SELECT currval('domains_domain_id_seq')");
|
---|
| 4947 | $domain_id = $zone_id;
|
---|
[487] | 4948 | $self->_log(group_id => $group, domain_id => $domain_id,
|
---|
| 4949 | entry => "[Added ".($args{status} ? 'active' : 'inactive')." domain $zone via AXFR]");
|
---|
[301] | 4950 | } else {
|
---|
| 4951 | ##fixme: serial
|
---|
[484] | 4952 | $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef,
|
---|
| 4953 | ($cidr,$group,$args{status}) );
|
---|
[301] | 4954 | # get revzone id so we can do the records
|
---|
| 4955 | ($zone_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
| 4956 | $rdns_id = $zone_id;
|
---|
[487] | 4957 | $self->_log(group_id => $group, rdns_id => $rdns_id,
|
---|
| 4958 | entry => "[Added ".($args{status} ? 'active' : 'inactive')." reverse zone $cidr via AXFR]");
|
---|
[301] | 4959 | }
|
---|
[33] | 4960 |
|
---|
[35] | 4961 | ## bizarre DBI<->Net::DNS interaction bug:
|
---|
| 4962 | ## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
|
---|
[37] | 4963 | ## fixed, apparently I was doing *something* odd, but not certain what it was that
|
---|
| 4964 | ## caused a commit instead of barfing
|
---|
[35] | 4965 |
|
---|
[34] | 4966 | my $res = Net::DNS::Resolver->new;
|
---|
[35] | 4967 | $res->nameservers($ifrom);
|
---|
[301] | 4968 | $res->axfr_start($zone)
|
---|
[35] | 4969 | or die "Couldn't begin AXFR\n";
|
---|
[34] | 4970 |
|
---|
[301] | 4971 | $sth = $dbh->prepare("INSERT INTO records (domain_id,rdns_id,host,type,val,distance,weight,port,ttl)".
|
---|
| 4972 | " VALUES (?,?,?,?,?,?,?,?,?)");
|
---|
| 4973 |
|
---|
[307] | 4974 | # Stash info about sub-octet v4 revzones here so we don't have
|
---|
| 4975 | # to store the CNAMEs used to delegate a suboctet zone
|
---|
| 4976 | # $suboct{zone}{ns}[] -> array of nameservers
|
---|
| 4977 | # $suboct{zone}{cname}[] -> array of extant CNAMEs (Just In Case someone did something bizarre)
|
---|
| 4978 | ## commented pending actual use of this data. for now, we'll just
|
---|
| 4979 | ## auto-(re)create the CNAMEs in revzones on export
|
---|
| 4980 | # my %suboct;
|
---|
| 4981 |
|
---|
[35] | 4982 | while (my $rr = $res->axfr_next()) {
|
---|
[301] | 4983 |
|
---|
[596] | 4984 | # Discard out-of-zone records. After trying for a while to replicate this with
|
---|
| 4985 | # *nix-based DNS servers, it appears that only MS DNS is prone to including these
|
---|
| 4986 | # in the AXFR data in the first place, and possibly only older versions at that...
|
---|
| 4987 | # so it can't be reasonably tested. Yay Microsoft.
|
---|
| 4988 | if ($rr->name !~ /$zone$/i) {
|
---|
| 4989 | $warnmsg .= "Discarding out-of-zone record ".$rr->string."\n";
|
---|
| 4990 | }
|
---|
| 4991 |
|
---|
[301] | 4992 | my $val;
|
---|
| 4993 | my $distance = 0;
|
---|
| 4994 | my $weight = 0;
|
---|
| 4995 | my $port = 0;
|
---|
[303] | 4996 | my $logfrag = '';
|
---|
[301] | 4997 |
|
---|
[602] | 4998 | # Collect some record parts
|
---|
[33] | 4999 | my $type = $rr->type;
|
---|
[301] | 5000 | my $host = $rr->name;
|
---|
[484] | 5001 | my $ttl = ($args{newttl} ? $args{newttl} : $rr->ttl); # allow force-override TTLs
|
---|
[35] | 5002 |
|
---|
[602] | 5003 | # Info flags for SOA and NS records
|
---|
[37] | 5004 | $soaflag = 1 if $type eq 'SOA';
|
---|
| 5005 | $nsflag = 1 if $type eq 'NS';
|
---|
[35] | 5006 |
|
---|
[34] | 5007 | # "Primary" types:
|
---|
| 5008 | # A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
|
---|
| 5009 | # maybe KEY
|
---|
| 5010 |
|
---|
[302] | 5011 | # BIND supports:
|
---|
| 5012 | # [standard]
|
---|
| 5013 | # A AAAA CNAME MX NS PTR SOA TXT
|
---|
| 5014 | # [variously experimental, obsolete, or obscure]
|
---|
| 5015 | # 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
|
---|
| 5016 | # ... if one can ever find the right magic to format them correctly
|
---|
| 5017 |
|
---|
| 5018 | # Net::DNS supports:
|
---|
| 5019 | # RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
|
---|
| 5020 | # EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
|
---|
| 5021 | # DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
|
---|
| 5022 |
|
---|
[35] | 5023 | # nasty big ugly case-like thing here, since we have to do *some* different
|
---|
| 5024 | # processing depending on the record. le sigh.
|
---|
| 5025 |
|
---|
[602] | 5026 | # do the initial processing as if the record was in a forward zone. If we're
|
---|
| 5027 | # doing a revzone, we can flip $host and $val as needed, once, after this
|
---|
| 5028 | # monster if-elsif-...-elsif-else. This actually simplifies things a lot.
|
---|
| 5029 |
|
---|
[105] | 5030 | ##fixme: what record types other than TXT can/will have >255-byte payloads?
|
---|
| 5031 |
|
---|
[34] | 5032 | if ($type eq 'A') {
|
---|
[301] | 5033 | $val = $rr->address;
|
---|
[34] | 5034 | } elsif ($type eq 'NS') {
|
---|
[37] | 5035 | # hmm. should we warn here if subdomain NS'es are left alone?
|
---|
[602] | 5036 | next if ($args{rwns} && ($host eq $zone));
|
---|
| 5037 | $val = $rr->nsdname;
|
---|
[35] | 5038 | $nsflag = 1;
|
---|
[34] | 5039 | } elsif ($type eq 'CNAME') {
|
---|
[602] | 5040 | $val = $rr->cname;
|
---|
[34] | 5041 | } elsif ($type eq 'SOA') {
|
---|
[484] | 5042 | next if $args{rwsoa};
|
---|
[307] | 5043 | $host = $rr->rname.":".$rr->mname;
|
---|
[301] | 5044 | $val = $rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum;
|
---|
[35] | 5045 | $soaflag = 1;
|
---|
[34] | 5046 | } elsif ($type eq 'PTR') {
|
---|
[602] | 5047 | $val = $rr->ptrdname;
|
---|
[34] | 5048 | } elsif ($type eq 'MX') {
|
---|
[301] | 5049 | $val = $rr->exchange;
|
---|
| 5050 | $distance = $rr->preference;
|
---|
[34] | 5051 | } elsif ($type eq 'TXT') {
|
---|
| 5052 | ##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
|
---|
| 5053 | ## but don't really seem enthusiastic about it.
|
---|
[303] | 5054 | #print "should use rdatastr:\n\t".$rr->rdatastr."\n or char_str_list:\n\t".join(' ',$rr->char_str_list())."\n";
|
---|
| 5055 | # rdatastr returns a BIND-targetted logical string, including opening and closing quotes
|
---|
| 5056 | # char_str_list returns a list of the individual string fragments in the record
|
---|
[307] | 5057 | # txtdata returns the more useful all-in-one form (since we want to push such protocol
|
---|
| 5058 | # details as far down the stack as we can)
|
---|
[303] | 5059 | # NB: this may turn out to be more troublesome if we ever have need of >512-byte TXT records.
|
---|
[602] | 5060 | $val = $rr->txtdata;
|
---|
[34] | 5061 | } elsif ($type eq 'SPF') {
|
---|
| 5062 | ##fixme: and the same caveat here, since it is apparently a clone of ::TXT
|
---|
[301] | 5063 | $val = $rr->txtdata;
|
---|
[34] | 5064 | } elsif ($type eq 'AAAA') {
|
---|
[301] | 5065 | $val = $rr->address;
|
---|
[34] | 5066 | } elsif ($type eq 'SRV') {
|
---|
[301] | 5067 | $val = $rr->target;
|
---|
| 5068 | $distance = $rr->priority;
|
---|
| 5069 | $weight = $rr->weight;
|
---|
| 5070 | $port = $rr->port;
|
---|
[34] | 5071 | } elsif ($type eq 'KEY') {
|
---|
[35] | 5072 | # we don't actually know what to do with these...
|
---|
[301] | 5073 | $val = $rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname;
|
---|
[35] | 5074 | } else {
|
---|
[301] | 5075 | $val = $rr->rdatastr;
|
---|
[35] | 5076 | # Finding a different record type is not fatal.... just problematic.
|
---|
[37] | 5077 | # We may not be able to export it correctly.
|
---|
[35] | 5078 | $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
|
---|
[33] | 5079 | }
|
---|
| 5080 |
|
---|
[602] | 5081 | if ($rev eq 'y' && $type ne 'SOA') {
|
---|
| 5082 | # up to this point we haven't meddled with the record's hostname part or rdata part.
|
---|
| 5083 | # for reverse records, (except SOA) we must swap the two.
|
---|
| 5084 | $host = $val;
|
---|
| 5085 | $val = $rr->name;
|
---|
| 5086 | my ($tmpcode,$tmpmsg) = _zone2cidr($val);
|
---|
| 5087 | if ($tmpcode eq 'FAIL') {
|
---|
| 5088 | # $val did not have a valid IP value. It's syntactically valid but WTF?
|
---|
| 5089 | $warnmsg .= "Suspect record '".$rr->string."' may not be imported correctly: $tmpmsg\n";
|
---|
| 5090 | } else {
|
---|
| 5091 | # $val has a valid IP value. See if we can store it as that IP value.
|
---|
| 5092 | # Note we're enumerating do-nothing cases for clarity.
|
---|
| 5093 | ##enhance: this is where we will implement the more subtle variations on #53
|
---|
| 5094 | if ($type ne 'PTR' && $type ne 'NS' && $type ne 'CNAME' && $type ne 'TXT') {
|
---|
| 5095 | # case: the record is "weird" - ie, not a PTR, NS, CNAME, or TXT
|
---|
| 5096 | # $warnmsg .= "Discarding suspect record '".$rr->string."'\n" if $self->{strict} eq 'full';
|
---|
| 5097 | } elsif ($type eq 'PTR' && $tmpmsg->masklen != 32 && $tmpmsg->masklen != 128) {
|
---|
| 5098 | # case: PTR with netblock value, not IP value
|
---|
| 5099 | # eg, "@ PTR foo" in zone f.e.e.b.d.a.e.d.ip6.arpa should not be
|
---|
| 5100 | # stored/displayed as dead:beef::/32 PTR foo
|
---|
| 5101 |
|
---|
| 5102 | ## hrm. WTF is this case for, anyway? Needs testing to check the logic.
|
---|
| 5103 | # } elsif ( ($type eq 'PTR' || $type eq 'NS' || $type eq 'CNAME' || $type eq 'TXT') &&
|
---|
| 5104 | # ($tmpmsg->masklen != $cidr->masklen)
|
---|
| 5105 | # ) {
|
---|
| 5106 | # # leave $val as-is if the record is "normal" (a PTR, NS, CNAME, or TXT),
|
---|
| 5107 | # # and the mask does not match the zone
|
---|
| 5108 | #$warnmsg .= "WTF case: $host $type $val\n";
|
---|
| 5109 | # # $warnmsg .= "Discarding suspect record '".$rr->string."'\n" if $self->{strict} eq 'full';
|
---|
| 5110 |
|
---|
| 5111 | } else {
|
---|
| 5112 | $val = $tmpmsg;
|
---|
| 5113 | $val =~ s/\/(?:32|128)$//; # automagically converts $val back to a string before s///
|
---|
| 5114 | #$val =~ s/:0$//g;
|
---|
| 5115 | }
|
---|
| 5116 | }
|
---|
| 5117 | # magic? convert * records to PTR template (not sure this actually makes sense)
|
---|
| 5118 | #if ($val =~ /^\*/) {
|
---|
| 5119 | # $val =~ s/\*\.//;
|
---|
| 5120 | # ($tmpcode,$tmpmsg) = _zone2cidr($val);
|
---|
| 5121 | # if ($tmpcode eq 'FAIL') {
|
---|
| 5122 | # $val = "*.$val";
|
---|
| 5123 | # $warnmsg .= "Suspect record '".$rr->string."' may not be converted to PTR template correctly: $tmpmsg\n";
|
---|
| 5124 | # } else {
|
---|
| 5125 | # $type = 'PTR template';
|
---|
| 5126 | # $val = $tmpmsg; if $tmp
|
---|
| 5127 | # $val =~ s/\/(?:32|128)$//; # automagically converts $val back to a string before s///
|
---|
| 5128 | # }
|
---|
| 5129 | #}
|
---|
| 5130 | } # non-SOA revrec $host/$val inversion and munging
|
---|
| 5131 |
|
---|
[303] | 5132 | my $logentry = "[AXFR ".($rev eq 'n' ? $zone : $cidr)."] ";
|
---|
[34] | 5133 |
|
---|
[484] | 5134 | if ($args{merge}) {
|
---|
[307] | 5135 | if ($rev eq 'n') {
|
---|
| 5136 | # importing a domain; we have A and AAAA records that could be merged with matching PTR records
|
---|
| 5137 | my $etype;
|
---|
| 5138 | my ($erdns,$erid,$ettl) = $dbh->selectrow_array("SELECT rdns_id,record_id,ttl FROM records ".
|
---|
| 5139 | "WHERE host=? AND val=? AND type=12",
|
---|
| 5140 | undef, ($host, $val) );
|
---|
| 5141 | if ($erid) {
|
---|
| 5142 | if ($type eq 'A') { # PTR -> A+PTR
|
---|
| 5143 | $etype = 65280;
|
---|
| 5144 | $logentry .= "Merged A record with existing PTR record '$host A+PTR $val', TTL $ettl";
|
---|
| 5145 | }
|
---|
| 5146 | if ($type eq 'AAAA') { # PTR -> AAAA+PTR
|
---|
| 5147 | $etype = 65281;
|
---|
| 5148 | $logentry .= "Merged AAAA record with existing PTR record '$host AAAA+PTR $val', TTL $ettl";
|
---|
| 5149 | }
|
---|
| 5150 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
| 5151 | $dbh->do("UPDATE records SET domain_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
| 5152 | ($domain_id, $ettl, $etype, $erid));
|
---|
| 5153 | $nrecs++;
|
---|
[487] | 5154 | $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $erdns, entry => $logentry);
|
---|
[307] | 5155 | next; # while axfr_next
|
---|
| 5156 | }
|
---|
| 5157 | } # $rev eq 'n'
|
---|
| 5158 | else {
|
---|
| 5159 | # importing a revzone, we have PTR records that could be merged with matching A/AAAA records
|
---|
| 5160 | my ($domid,$erid,$ettl,$etype) = $dbh->selectrow_array("SELECT domain_id,record_id,ttl,type FROM records ".
|
---|
| 5161 | "WHERE host=? AND val=? AND (type=1 OR type=28)",
|
---|
| 5162 | undef, ($host, $val) );
|
---|
| 5163 | if ($erid) {
|
---|
| 5164 | if ($etype == 1) { # A -> A+PTR
|
---|
| 5165 | $etype = 65280;
|
---|
| 5166 | $logentry .= "Merged PTR record with existing matching A record '$host A+PTR $val', TTL $ettl";
|
---|
| 5167 | }
|
---|
| 5168 | if ($etype == 28) { # AAAA -> AAAA+PTR
|
---|
| 5169 | $etype = 65281;
|
---|
| 5170 | $logentry .= "Merged PTR record with existing matching AAAA record '$host AAAA+PTR $val', TTL $ettl";
|
---|
| 5171 | }
|
---|
| 5172 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
| 5173 | $dbh->do("UPDATE records SET rdns_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
| 5174 | ($rdns_id, $ettl, $etype, $erid));
|
---|
| 5175 | $nrecs++;
|
---|
[487] | 5176 | $self->_log(group_id => $group, domain_id => $domid, rdns_id => $rdns_id, entry => $logentry);
|
---|
[307] | 5177 | next; # while axfr_next
|
---|
| 5178 | }
|
---|
| 5179 | } # $rev eq 'y'
|
---|
[484] | 5180 | } # if $args{merge}
|
---|
[34] | 5181 |
|
---|
[302] | 5182 | # Insert the new record
|
---|
[301] | 5183 | $sth->execute($domain_id, $rdns_id, $host, $reverse_typemap{$type}, $val,
|
---|
| 5184 | $distance, $weight, $port, $ttl);
|
---|
| 5185 |
|
---|
[37] | 5186 | $nrecs++;
|
---|
[34] | 5187 |
|
---|
[301] | 5188 | if ($type eq 'SOA') {
|
---|
[484] | 5189 | # also !$args{rwsoa}, but if that's set, it should be impossible to get here.
|
---|
[301] | 5190 | my @tmp1 = split /:/, $host;
|
---|
| 5191 | my @tmp2 = split /:/, $val;
|
---|
| 5192 | $logentry .= "Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
| 5193 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl";
|
---|
[303] | 5194 | } elsif ($logfrag) {
|
---|
| 5195 | # special case for log entries we need to meddle with a little.
|
---|
| 5196 | $logentry .= $logfrag;
|
---|
[301] | 5197 | } else {
|
---|
[602] | 5198 | $logentry .= "Added record '".($rev eq 'y' ? $val : $host)." $type";
|
---|
[301] | 5199 | $logentry .= " [distance $distance]" if $type eq 'MX';
|
---|
| 5200 | $logentry .= " [priority $distance] [weight $weight] [port $port]" if $type eq 'SRV';
|
---|
[602] | 5201 | $logentry .= " ".($rev eq 'y' ? $host : $val)."', TTL $ttl";
|
---|
[301] | 5202 | }
|
---|
[487] | 5203 | $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $rdns_id, entry => $logentry);
|
---|
[301] | 5204 |
|
---|
[37] | 5205 | } # while axfr_next
|
---|
| 5206 |
|
---|
[307] | 5207 | # Detect and handle delegated subzones
|
---|
| 5208 | # Placeholder for when we decide what to actually do with this, see previous comments in NS and CNAME handling.
|
---|
| 5209 | #foreach (keys %suboct) {
|
---|
| 5210 | # print "found ".($suboct{$_}{ns} ? @{$suboct{$_}{ns}} : '0')." NS records and ".
|
---|
| 5211 | # ($suboct{$_}{cname} ? @{$suboct{$_}{cname}} : '0')." CNAMEs for $_\n";
|
---|
| 5212 | #}
|
---|
| 5213 |
|
---|
[37] | 5214 | # Overwrite SOA record
|
---|
[484] | 5215 | if ($args{rwsoa}) {
|
---|
[37] | 5216 | $soaflag = 1;
|
---|
[573] | 5217 | my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM "._rectable('y', $rev)." WHERE group_id=? AND type=?");
|
---|
| 5218 | my $sthputsoa = $dbh->prepare("INSERT INTO records (".
|
---|
| 5219 | ($rev eq 'n' ? 'domain_id' : 'rdns_id').",host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
[37] | 5220 | $sthgetsoa->execute($group,$reverse_typemap{SOA});
|
---|
| 5221 | while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
|
---|
[573] | 5222 | if ($rev eq 'n') {
|
---|
| 5223 | $host =~ s/DOMAIN/$zone/g;
|
---|
| 5224 | $val =~ s/DOMAIN/$zone/g; # arguably useless
|
---|
| 5225 | } else {
|
---|
| 5226 | $host =~ s/ADMINDOMAIN/$self->{domain}/g;
|
---|
| 5227 | }
|
---|
[301] | 5228 | $sthputsoa->execute($zone_id,$host,$reverse_typemap{SOA},$val,$ttl);
|
---|
[34] | 5229 | }
|
---|
[37] | 5230 | }
|
---|
[34] | 5231 |
|
---|
[573] | 5232 | # Add standard NS records. The old one(s) should have been skipped by this point.
|
---|
[484] | 5233 | if ($args{rwns}) {
|
---|
[37] | 5234 | $nsflag = 1;
|
---|
[573] | 5235 | my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM "._rectable('y',$rev)." WHERE group_id=? AND type=?");
|
---|
| 5236 | my $sthputns = $dbh->prepare("INSERT INTO records (".
|
---|
| 5237 | ($rev eq 'n' ? 'domain_id' : 'rdns_id').",host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
[37] | 5238 | $sthgetns->execute($group,$reverse_typemap{NS});
|
---|
| 5239 | while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
|
---|
[573] | 5240 | if ($rev eq 'n') {
|
---|
| 5241 | $host =~ s/DOMAIN/$zone/g;
|
---|
| 5242 | $val =~ s/DOMAIN/$zone/g; #hmm.
|
---|
| 5243 | } else {
|
---|
| 5244 | $host =~ s/ADMINDOMAIN/$self->{domain}/g; #hmm.
|
---|
| 5245 | $val =~ s/ZONE/$cidr/g;
|
---|
| 5246 | }
|
---|
[301] | 5247 | $sthputns->execute($zone_id,$host,$reverse_typemap{NS},$val,$ttl);
|
---|
[37] | 5248 | }
|
---|
| 5249 | }
|
---|
[34] | 5250 |
|
---|
[35] | 5251 | die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
|
---|
| 5252 | die "Bad zone: No SOA record!\n" if !$soaflag;
|
---|
| 5253 | die "Bad zone: No NS records!\n" if !$nsflag;
|
---|
| 5254 |
|
---|
[37] | 5255 | $dbh->commit;
|
---|
[35] | 5256 |
|
---|
[33] | 5257 | };
|
---|
| 5258 |
|
---|
| 5259 | if ($@) {
|
---|
| 5260 | my $msg = $@;
|
---|
| 5261 | eval { $dbh->rollback; };
|
---|
[34] | 5262 | return ('FAIL',$msg." $warnmsg");
|
---|
[33] | 5263 | } else {
|
---|
[35] | 5264 | return ('WARN', $warnmsg) if $warnmsg;
|
---|
[91] | 5265 | return ('OK',"Imported OK");
|
---|
[33] | 5266 | }
|
---|
| 5267 |
|
---|
[37] | 5268 | # it should be impossible to get here.
|
---|
[34] | 5269 | return ('WARN',"OOOK!");
|
---|
[33] | 5270 | } # end importAXFR()
|
---|
| 5271 |
|
---|
| 5272 |
|
---|
[302] | 5273 | ## DNSDB::importBIND()
|
---|
| 5274 | sub importBIND {
|
---|
| 5275 | } # end importBIND()
|
---|
| 5276 |
|
---|
| 5277 |
|
---|
| 5278 | ## DNSDB::import_tinydns()
|
---|
| 5279 | sub import_tinydns {
|
---|
| 5280 | } # end import_tinydns()
|
---|
| 5281 |
|
---|
| 5282 |
|
---|
[103] | 5283 | ## DNSDB::export()
|
---|
| 5284 | # Export the DNS database, or a part of it
|
---|
[485] | 5285 | # Takes a string indicating the export type, plus optional arguments depending on type
|
---|
[103] | 5286 | # Writes zone data to targets as appropriate for type
|
---|
| 5287 | sub export {
|
---|
[485] | 5288 | my $self = shift;
|
---|
[103] | 5289 | my $target = shift;
|
---|
| 5290 |
|
---|
| 5291 | if ($target eq 'tiny') {
|
---|
[567] | 5292 | eval {
|
---|
| 5293 | $self->__export_tiny(@_);
|
---|
| 5294 | };
|
---|
| 5295 | if ($@) {
|
---|
| 5296 | $errstr = $@;
|
---|
| 5297 | return undef;
|
---|
| 5298 | }
|
---|
[103] | 5299 | }
|
---|
| 5300 | # elsif ($target eq 'foo') {
|
---|
[485] | 5301 | # __export_foo(@_);
|
---|
[103] | 5302 | #}
|
---|
| 5303 | # etc
|
---|
| 5304 |
|
---|
[567] | 5305 | return 1;
|
---|
[103] | 5306 | } # end export()
|
---|
| 5307 |
|
---|
| 5308 |
|
---|
| 5309 | ## DNSDB::__export_tiny
|
---|
| 5310 | # Internal sub to implement tinyDNS (compatible) export
|
---|
[485] | 5311 | # Takes filehandle to write export to, optional argument(s)
|
---|
[103] | 5312 | # to determine which data gets exported
|
---|
| 5313 | sub __export_tiny {
|
---|
[485] | 5314 | my $self = shift;
|
---|
| 5315 | my $dbh = $self->{dbh};
|
---|
[103] | 5316 | my $datafile = shift;
|
---|
[559] | 5317 | my $zonefilehandle = $datafile; # makes cache/no-cache a little simpler
|
---|
[103] | 5318 |
|
---|
| 5319 | ##fixme: slurp up further options to specify particular zone(s) to export
|
---|
| 5320 |
|
---|
| 5321 | ##fixme: fail if $datafile isn't an open, writable file
|
---|
| 5322 |
|
---|
[566] | 5323 | # Error check - does the cache dir exist, if we're using one?
|
---|
| 5324 | if ($self->{usecache}) {
|
---|
| 5325 | die "Cache directory does not exist\n" if !-e $self->{exportcache};
|
---|
| 5326 | die "$self->{exportcache} is not a directory\n" if !-d $self->{exportcache};
|
---|
| 5327 | die "$self->{exportcache} must be both readable and writable\n"
|
---|
| 5328 | if !-r $self->{exportcache} || !-w $self->{exportcache};
|
---|
| 5329 | }
|
---|
| 5330 |
|
---|
[103] | 5331 | # easy case - export all evarything
|
---|
| 5332 | # not-so-easy case - export item(s) specified
|
---|
| 5333 | # todo: figure out what kind of list we use to export items
|
---|
| 5334 |
|
---|
[329] | 5335 | # raw packet in unknown format: first byte indicates length
|
---|
| 5336 | # of remaining data, allows up to 255 raw bytes
|
---|
| 5337 |
|
---|
[566] | 5338 | # note: the only I/O failures we seem to be able to actually catch
|
---|
| 5339 | # here are "closed filehandle" errors. we're probably not writing
|
---|
| 5340 | # enough data at this point to properly trigger an "out of space"
|
---|
| 5341 | # error. :/
|
---|
| 5342 | eval {
|
---|
| 5343 | use warnings FATAL => ('io');
|
---|
| 5344 | # Locations/views - worth including in the caching setup?
|
---|
| 5345 | my $lochash = $dbh->selectall_hashref("SELECT location,iplist FROM locations", 'location');
|
---|
| 5346 | foreach my $location (keys %$lochash) {
|
---|
| 5347 | foreach my $ipprefix (split /[,\s]+/, $lochash->{$location}{iplist}) {
|
---|
| 5348 | $ipprefix =~ s/\s+//g;
|
---|
| 5349 | $ipprefix = new NetAddr::IP $ipprefix;
|
---|
[449] | 5350 | ##fixme: how to handle IPv6?
|
---|
| 5351 | next if $ipprefix->{isv6};
|
---|
[566] | 5352 | # have to account for /nn CIDR entries. tinydns only speaks octet-sliced prefix.
|
---|
| 5353 | if ($ipprefix->masklen <= 8) {
|
---|
| 5354 | foreach ($ipprefix->split(8)) {
|
---|
| 5355 | my $tmp = $_->addr;
|
---|
| 5356 | $tmp =~ s/\.\d+\.\d+\.\d+$//;
|
---|
| 5357 | print $datafile "%$location:$tmp\n";
|
---|
| 5358 | }
|
---|
| 5359 | } elsif ($ipprefix->masklen <= 16) {
|
---|
| 5360 | foreach ($ipprefix->split(16)) {
|
---|
| 5361 | my $tmp = $_->addr;
|
---|
| 5362 | $tmp =~ s/\.\d+\.\d+$//;
|
---|
| 5363 | print $datafile "%$location:$tmp\n";
|
---|
| 5364 | }
|
---|
| 5365 | } elsif ($ipprefix->masklen <= 24) {
|
---|
| 5366 | foreach ($ipprefix->split(24)) {
|
---|
| 5367 | my $tmp = $_->addr;
|
---|
| 5368 | $tmp =~ s/\.\d+$//;
|
---|
| 5369 | print $datafile "%$location:$tmp\n";
|
---|
| 5370 | }
|
---|
| 5371 | } else {
|
---|
| 5372 | foreach ($ipprefix->split(32)) {
|
---|
| 5373 | print $datafile "%$location:".$_->addr."\n";
|
---|
| 5374 | }
|
---|
[449] | 5375 | }
|
---|
| 5376 | }
|
---|
[566] | 5377 | print $datafile "%$location\n" if !$lochash->{$location}{iplist};
|
---|
[372] | 5378 | }
|
---|
[566] | 5379 | };
|
---|
| 5380 | if ($@) {
|
---|
| 5381 | die "Error writing locations to master file: $@, $!\n";
|
---|
[372] | 5382 | }
|
---|
| 5383 |
|
---|
[329] | 5384 | # tracking hash so we don't double-export A+PTR or AAAA+PTR records.
|
---|
| 5385 | my %recflags;
|
---|
| 5386 |
|
---|
[523] | 5387 | # For reasons unknown, we can't sanely UNION these statements. Feh.
|
---|
| 5388 | # Supposedly it should work though (note last 3 lines):
|
---|
| 5389 | ## PG manual
|
---|
| 5390 | #UNION Clause
|
---|
| 5391 | #
|
---|
| 5392 | #The UNION clause has this general form:
|
---|
| 5393 | #
|
---|
| 5394 | # select_statement UNION [ ALL ] select_statement
|
---|
| 5395 | #
|
---|
| 5396 | #select_statement is any SELECT statement without an ORDER BY, LIMIT, FOR UPDATE, or FOR SHARE clause. (ORDER BY
|
---|
| 5397 | #and LIMIT can be attached to a subexpression if it is enclosed in parentheses. Without parentheses, these
|
---|
| 5398 | #clauses will be taken to apply to the result of the UNION, not to its right-hand input expression.)
|
---|
| 5399 | my $soasth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
| 5400 | "FROM records WHERE rdns_id=? AND type=6");
|
---|
[543] | 5401 | my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location,extract(epoch from stamp),expires,stampactive ".
|
---|
[576] | 5402 | "FROM records WHERE rdns_id=? AND NOT type=6 ".
|
---|
[599] | 5403 | "ORDER BY masklen(inetlazy(val)) DESC, inetlazy(val)");
|
---|
[523] | 5404 | my $revsth = $dbh->prepare("SELECT rdns_id,revnet,status,changed FROM revzones WHERE status=1 ".
|
---|
[566] | 5405 | "ORDER BY masklen(revnet) DESC, rdns_id");
|
---|
[523] | 5406 | my $zonesth = $dbh->prepare("UPDATE revzones SET changed='n' WHERE rdns_id=?");
|
---|
| 5407 | $revsth->execute();
|
---|
| 5408 | while (my ($revid,$revzone,$revstat,$changed) = $revsth->fetchrow_array) {
|
---|
[368] | 5409 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
| 5410 | # O_NOFOLLOW
|
---|
| 5411 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
| 5412 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
| 5413 | # still be followed.
|
---|
| 5414 | # but that doesn't help other platforms. :/
|
---|
[523] | 5415 | my $tmpzone = NetAddr::IP->new($revzone);
|
---|
| 5416 | ##fixme: locations/views? subnet mask? need to avoid possible collisions with zone/superzone
|
---|
| 5417 | ## (eg /20 vs /24, starting on .0.0)
|
---|
| 5418 | my $cz = $tmpzone->network->addr."-".$tmpzone->masklen;
|
---|
| 5419 | my $cachefile = "$self->{exportcache}/$cz";
|
---|
| 5420 | my $tmpcache = "$self->{exportcache}/tmp.$cz.$$";
|
---|
[521] | 5421 | eval {
|
---|
[108] | 5422 |
|
---|
[559] | 5423 | # write fresh records if:
|
---|
| 5424 | # - we are not using the cache
|
---|
| 5425 | # - force_refresh is set
|
---|
| 5426 | # - the zone has changed
|
---|
| 5427 | # - the cache file does not exist
|
---|
| 5428 | # - the cache file is empty
|
---|
| 5429 | if (!$self->{usecache} || $self->{force_refresh} || $changed || !-e $cachefile || -z $cachefile) {
|
---|
| 5430 | if ($self->{usecache}) {
|
---|
| 5431 | open ZONECACHE, ">$tmpcache" or die "Error creating temporary file $tmpcache: $!\n";
|
---|
| 5432 | $zonefilehandle = *ZONECACHE;
|
---|
| 5433 | }
|
---|
[521] | 5434 |
|
---|
[523] | 5435 | # need to fetch this separately since the rest of the records all (should) have real IPs in val
|
---|
| 5436 | $soasth->execute($revid);
|
---|
| 5437 | my (@zsoa) = $soasth->fetchrow_array();
|
---|
[573] | 5438 | _printrec_tiny($zonefilehandle, $zsoa[7], 'y',\%recflags,$revzone,
|
---|
[523] | 5439 | $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],'');
|
---|
| 5440 |
|
---|
| 5441 | $recsth->execute($revid);
|
---|
[596] | 5442 | my $fullzone = _ZONE($tmpzone, 'ZONE', 'r', '.').($tmpzone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 5443 |
|
---|
[573] | 5444 | while (my ($host, $type, $val, $dist, $weight, $port, $ttl, $recid, $loc, $stamp, $expires, $stampactive)
|
---|
| 5445 | = $recsth->fetchrow_array) {
|
---|
[523] | 5446 | next if $recflags{$recid};
|
---|
[521] | 5447 |
|
---|
[596] | 5448 | # Check for out-of-zone data
|
---|
| 5449 | if ($val =~ /\.arpa$/) {
|
---|
| 5450 | # val is non-IP
|
---|
| 5451 | if ($val !~ /$fullzone$/) {
|
---|
| 5452 | warn "Not exporting out-of-zone record $val $typemap{$type} $host, $ttl (zone $tmpzone)\n";
|
---|
| 5453 | next;
|
---|
| 5454 | }
|
---|
| 5455 | } else {
|
---|
| 5456 | my $ipval = new NetAddr::IP $val;
|
---|
| 5457 | if (!$tmpzone->contains($ipval)) {
|
---|
| 5458 | warn "Not exporting out-of-zone record $val $typemap{$type} $host, $ttl (zone $tmpzone)\n";
|
---|
| 5459 | next;
|
---|
| 5460 | }
|
---|
| 5461 | } # is $val a raw .arpa name?
|
---|
| 5462 |
|
---|
[597] | 5463 | # Spaces are evil.
|
---|
| 5464 | $val =~ s/^\s+//;
|
---|
| 5465 | $val =~ s/\s+$//;
|
---|
| 5466 | if ($typemap{$type} ne 'TXT') {
|
---|
| 5467 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 5468 | $host =~ s/^\s+//;
|
---|
| 5469 | $host =~ s/\s+$//;
|
---|
| 5470 | }
|
---|
[372] | 5471 |
|
---|
[573] | 5472 | _printrec_tiny($zonefilehandle, $recid, 'y', \%recflags, $revzone,
|
---|
[559] | 5473 | $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp, $expires, $stampactive);
|
---|
[450] | 5474 |
|
---|
[523] | 5475 | $recflags{$recid} = 1;
|
---|
[368] | 5476 |
|
---|
[521] | 5477 | } # while ($recsth)
|
---|
| 5478 |
|
---|
[559] | 5479 | if ($self->{usecache}) {
|
---|
| 5480 | close ZONECACHE; # force the file to be written
|
---|
| 5481 | # catch obvious write errors that leave an empty temp file
|
---|
| 5482 | if (-s $tmpcache) {
|
---|
| 5483 | rename $tmpcache, $cachefile
|
---|
| 5484 | or die "Error overwriting cache file $cachefile with temporary file: $!\n";
|
---|
| 5485 | }
|
---|
[521] | 5486 | }
|
---|
| 5487 |
|
---|
| 5488 | } # if $changed or cache filesize is 0
|
---|
| 5489 |
|
---|
| 5490 | };
|
---|
| 5491 | if ($@) {
|
---|
[566] | 5492 | die "error writing ".($self->{usecache} ? 'new data for ' : '')."$revzone: $@\n";
|
---|
[521] | 5493 | # error! something borked, and we should be able to fall back on the old cache file
|
---|
| 5494 | # report the error, somehow.
|
---|
| 5495 | } else {
|
---|
[523] | 5496 | # mark zone as unmodified. Only do this if no errors, that way
|
---|
[521] | 5497 | # export failures should recover a little more automatically.
|
---|
[523] | 5498 | $zonesth->execute($revid);
|
---|
[368] | 5499 | }
|
---|
[521] | 5500 |
|
---|
[559] | 5501 | if ($self->{usecache}) {
|
---|
| 5502 | # We've already made as sure as we can that a cached zone file is "good",
|
---|
| 5503 | # although possibly stale/obsolete due to errors creating a new one.
|
---|
[566] | 5504 | eval {
|
---|
| 5505 | open CACHE, "<$cachefile" or die $!;
|
---|
| 5506 | print $datafile $_ or die "error copying cached $revzone to master file: $!" while <CACHE>;
|
---|
| 5507 | close CACHE;
|
---|
| 5508 | };
|
---|
| 5509 | die $@ if $@;
|
---|
[559] | 5510 | }
|
---|
| 5511 |
|
---|
[523] | 5512 | } # while ($revsth)
|
---|
[329] | 5513 |
|
---|
[576] | 5514 | $soasth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
[578] | 5515 | "FROM records WHERE domain_id=? AND type=6");
|
---|
[543] | 5516 | $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location,extract(epoch from stamp),expires,stampactive ".
|
---|
[576] | 5517 | "FROM records WHERE domain_id=? AND NOT type=6"); # Just exclude all types relating to rDNS
|
---|
[523] | 5518 | # "FROM records WHERE domain_id=? AND type < 65280"); # Just exclude all types relating to rDNS
|
---|
[576] | 5519 | my $domsth = $dbh->prepare("SELECT domain_id,domain,status,changed FROM domains WHERE status=1 ORDER BY domain_id");
|
---|
[523] | 5520 | $zonesth = $dbh->prepare("UPDATE domains SET changed='n' WHERE domain_id=?");
|
---|
| 5521 | $domsth->execute();
|
---|
| 5522 | while (my ($domid,$dom,$domstat,$changed) = $domsth->fetchrow_array) {
|
---|
[368] | 5523 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
| 5524 | # O_NOFOLLOW
|
---|
| 5525 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
| 5526 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
| 5527 | # still be followed.
|
---|
| 5528 | # but that doesn't help other platforms. :/
|
---|
[523] | 5529 | my $cachefile = "$self->{exportcache}/$dom";
|
---|
| 5530 | my $tmpcache = "$self->{exportcache}/tmp.$dom.$$";
|
---|
[521] | 5531 | eval {
|
---|
[344] | 5532 |
|
---|
[559] | 5533 | # write fresh records if:
|
---|
| 5534 | # - we are not using the cache
|
---|
| 5535 | # - force_refresh is set
|
---|
| 5536 | # - the zone has changed
|
---|
| 5537 | # - the cache file does not exist
|
---|
| 5538 | # - the cache file is empty
|
---|
| 5539 | if (!$self->{usecache} || $self->{force_refresh} || $changed || !-e $cachefile || -z $cachefile) {
|
---|
| 5540 | if ($self->{usecache}) {
|
---|
| 5541 | open ZONECACHE, ">$tmpcache" or die "Error creating temporary file $tmpcache: $!\n";
|
---|
| 5542 | $zonefilehandle = *ZONECACHE;
|
---|
| 5543 | }
|
---|
[329] | 5544 |
|
---|
[576] | 5545 | # need to fetch this separately so the SOA comes first in the flatfile....
|
---|
| 5546 | # Just In Case we need/want to reimport from the flatfile later on.
|
---|
| 5547 | $soasth->execute($domid);
|
---|
| 5548 | my (@zsoa) = $soasth->fetchrow_array();
|
---|
[577] | 5549 | _printrec_tiny($zonefilehandle, $zsoa[7], 'n',\%recflags,$dom,
|
---|
[576] | 5550 | $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],'');
|
---|
| 5551 |
|
---|
[523] | 5552 | $recsth->execute($domid);
|
---|
[543] | 5553 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc,$stamp,$expires,$stampactive) = $recsth->fetchrow_array) {
|
---|
[523] | 5554 | next if $recflags{$recid};
|
---|
[521] | 5555 |
|
---|
[596] | 5556 | # Check for out-of-zone data
|
---|
| 5557 | if ($host !~ /$dom$/) {
|
---|
| 5558 | warn "Not exporting out-of-zone record $host $type $val, $ttl (zone $dom)\n";
|
---|
| 5559 | next;
|
---|
| 5560 | }
|
---|
| 5561 |
|
---|
[523] | 5562 | # Spaces are evil.
|
---|
| 5563 | $host =~ s/^\s+//;
|
---|
| 5564 | $host =~ s/\s+$//;
|
---|
| 5565 | if ($typemap{$type} ne 'TXT') {
|
---|
| 5566 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 5567 | $val =~ s/^\s+//;
|
---|
| 5568 | $val =~ s/\s+$//;
|
---|
| 5569 | }
|
---|
| 5570 |
|
---|
[573] | 5571 | _printrec_tiny($zonefilehandle, $recid, 'n', \%recflags,
|
---|
[559] | 5572 | $dom, $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp, $expires, $stampactive);
|
---|
[329] | 5573 |
|
---|
[523] | 5574 | $recflags{$recid} = 1;
|
---|
[450] | 5575 |
|
---|
[521] | 5576 | } # while ($recsth)
|
---|
| 5577 |
|
---|
| 5578 |
|
---|
[559] | 5579 | if ($self->{usecache}) {
|
---|
| 5580 | close ZONECACHE; # force the file to be written
|
---|
| 5581 | # catch obvious write errors that leave an empty temp file
|
---|
| 5582 | if (-s $tmpcache) {
|
---|
| 5583 | rename $tmpcache, $cachefile
|
---|
| 5584 | or die "Error overwriting cache file $cachefile with temporary file: $!\n";
|
---|
| 5585 | }
|
---|
[521] | 5586 | }
|
---|
| 5587 |
|
---|
| 5588 | } # if $changed or cache filesize is 0
|
---|
| 5589 |
|
---|
| 5590 | };
|
---|
| 5591 | if ($@) {
|
---|
[566] | 5592 | die "error writing ".($self->{usecache} ? 'new data for ' : '')."$dom: $@\n";
|
---|
[521] | 5593 | # error! something borked, and we should be able to fall back on the old cache file
|
---|
| 5594 | # report the error, somehow.
|
---|
| 5595 | } else {
|
---|
[523] | 5596 | # mark domain as unmodified. Only do this if no errors, that way
|
---|
[521] | 5597 | # export failures should recover a little more automatically.
|
---|
[523] | 5598 | $zonesth->execute($domid);
|
---|
[368] | 5599 | }
|
---|
[521] | 5600 |
|
---|
[559] | 5601 | if ($self->{usecache}) {
|
---|
| 5602 | # We've already made as sure as we can that a cached zone file is "good",
|
---|
| 5603 | # although possibly stale/obsolete due to errors creating a new one.
|
---|
[566] | 5604 | eval {
|
---|
| 5605 | open CACHE, "<$cachefile" or die $!;
|
---|
| 5606 | print $datafile $_ or die "error copying cached $dom to master file: $!" while <CACHE>;
|
---|
| 5607 | close CACHE;
|
---|
| 5608 | };
|
---|
| 5609 | die $@ if $@;
|
---|
[559] | 5610 | }
|
---|
| 5611 |
|
---|
[329] | 5612 | } # while ($domsth)
|
---|
| 5613 |
|
---|
[566] | 5614 | return 1;
|
---|
[329] | 5615 | } # end __export_tiny()
|
---|
| 5616 |
|
---|
| 5617 |
|
---|
| 5618 | # Utility sub for __export_tiny above
|
---|
| 5619 | sub _printrec_tiny {
|
---|
[573] | 5620 | my ($datafile, $recid, $revrec, $recflags, $zone, $host, $type, $val, $dist, $weight, $port, $ttl,
|
---|
| 5621 | $loc, $stamp, $expires, $stampactive) = @_;
|
---|
[329] | 5622 |
|
---|
[543] | 5623 | $loc = '' if !$loc; # de-nullify - just in case
|
---|
| 5624 | ##fixme: handle case of record-with-location-that-doesn't-exist better.
|
---|
| 5625 | # note this currently fails safe (tested) - records with a location that
|
---|
| 5626 | # doesn't exist will not be sent to any client
|
---|
| 5627 | # $loc = '' if !$lochash->{$loc};
|
---|
| 5628 |
|
---|
| 5629 |
|
---|
| 5630 | ## Records that are valid only before or after a set time
|
---|
| 5631 |
|
---|
| 5632 | # record due to expire sometime is the complex case. we don't want to just
|
---|
| 5633 | # rely on tinydns' auto-adjusting TTLs, because the default TTL in that case
|
---|
| 5634 | # is one day instead of the SOA minttl as BIND might do.
|
---|
| 5635 |
|
---|
| 5636 | # consider the case where a record is set to expire a week ahead, but the next
|
---|
| 5637 | # day later you want to change it NOW (or as NOWish as you get with your DNS
|
---|
| 5638 | # management practice). but now you're stuck, because someone, somewhere,
|
---|
| 5639 | # has just done a lookup before your latest change was published, and they'll
|
---|
| 5640 | # be caching that old, broken record for 1 day instead of your zone default
|
---|
| 5641 | # TTL.
|
---|
| 5642 |
|
---|
| 5643 | # $stamp-$ttl is the *latest* we can publish the record with the defined TTL
|
---|
| 5644 | # to still have the expiry happen as scheduled, but we need to find some
|
---|
| 5645 | # *earlier* point. We can maybe guess, and 2x TTL is probably reasonable,
|
---|
| 5646 | # but we need info on the export frequency.
|
---|
| 5647 |
|
---|
| 5648 | # export the normal, non-expiring record up until $stamp-<guesstimate>, then
|
---|
| 5649 | # switch to exporting a record with the TAI64 stamp and a 0 TTL so tinydns
|
---|
| 5650 | # takes over TTL management.
|
---|
| 5651 |
|
---|
| 5652 | if ($stampactive) {
|
---|
| 5653 | if ($expires) {
|
---|
| 5654 | # record expires at $stamp; decide if we need to keep the TTL and ignore
|
---|
| 5655 | # the stamp for a time or if we need to change the TTL to 0 and convert
|
---|
| 5656 | # $stamp to TAI64 so tinydns can use $stamp to autoadjust the TTL on the fly.
|
---|
| 5657 | # extra hack, optimally needs more knowledge of data export frequency
|
---|
| 5658 | # smack the idiot customer who insists on 0 TTLs; they can suck up and
|
---|
| 5659 | # deal with a 10-minute TTL. especially on scheduled changes. note this
|
---|
| 5660 | # should be (export freq * 2), but we don't know the actual export frequency.
|
---|
| 5661 | $ttl = 300 if $ttl == 0; #hack phtui
|
---|
| 5662 | my $ahead = (86400 < $ttl*2 ? 86400 : $ttl*2);
|
---|
| 5663 | if ((time() + $ahead) < $stamp) {
|
---|
| 5664 | # more than 2x TTL OR more than one day (whichever is less) from expiry time; publish normal record
|
---|
| 5665 | $stamp = '';
|
---|
| 5666 | } else {
|
---|
| 5667 | # less than 2x TTL from expiry time, let tinydns take over TTL management and publish the TAI64 stamp.
|
---|
| 5668 | $ttl = 0;
|
---|
| 5669 | $stamp = unixtai64($stamp);
|
---|
| 5670 | $stamp =~ s/\@//;
|
---|
| 5671 | }
|
---|
| 5672 | } else {
|
---|
| 5673 | # record is "active after"; convert epoch from database to TAI64, publish, and collect $200.
|
---|
| 5674 | $stamp = unixtai64($stamp);
|
---|
| 5675 | $stamp =~ s/\@//;
|
---|
| 5676 | }
|
---|
| 5677 | } else {
|
---|
| 5678 | # flag for active timestamp is false; don't actually put a timestamp in the output
|
---|
| 5679 | $stamp = '';
|
---|
| 5680 | }
|
---|
| 5681 |
|
---|
| 5682 | # support tinydns' auto-TTL
|
---|
| 5683 | $ttl = '' if $ttl == -1;
|
---|
| 5684 | # these are WAY FREAKING HIGH - higher even than most TLD registry TTLs!
|
---|
| 5685 | # NS 259200 => 3d
|
---|
| 5686 | # all others 86400 => 1d
|
---|
| 5687 |
|
---|
[531] | 5688 | if ($revrec eq 'y') {
|
---|
| 5689 | $val = $zone if $val eq '@';
|
---|
| 5690 | } else {
|
---|
| 5691 | $host = $zone if $host eq '@';
|
---|
| 5692 | }
|
---|
| 5693 |
|
---|
[329] | 5694 | ## Convert a bare number into an octal-coded pair of octets.
|
---|
| 5695 | # Take optional arg to indicate a decimal or hex input. Defaults to hex.
|
---|
| 5696 | sub octalize {
|
---|
| 5697 | my $tmp = shift;
|
---|
| 5698 | my $srctype = shift || 'h'; # default assumes hex string
|
---|
| 5699 | $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
|
---|
| 5700 | $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
|
---|
| 5701 | my @o = ($tmp =~ /^(..)(..)$/); # split into octets
|
---|
| 5702 | return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);;
|
---|
| 5703 | }
|
---|
| 5704 |
|
---|
[339] | 5705 | ## WARNING: This works to export even the whole Internet's worth of IP space...
|
---|
| 5706 | ## if you have the disk/RAM to handle the dataset, and you call this sub based on /16-sized chunks
|
---|
| 5707 | ## A /16 took ~3 seconds with a handful of separate records; adding a /8 pushed export time out to ~13m:40s
|
---|
| 5708 | ## 0/0 is estimated to take ~54 hours and ~256G of disk
|
---|
| 5709 | ## RAM usage depends on how many non-template entries you have in the set.
|
---|
| 5710 | ## This should probably be done on record addition rather than export; large blocks may need to be done in a
|
---|
| 5711 | ## forked process
|
---|
| 5712 | sub __publish_subnet {
|
---|
| 5713 | my $sub = shift;
|
---|
| 5714 | my $recflags = shift;
|
---|
| 5715 | my $hpat = shift;
|
---|
| 5716 | my $fh = shift;
|
---|
| 5717 | my $ttl = shift;
|
---|
| 5718 | my $stamp = shift;
|
---|
| 5719 | my $loc = shift;
|
---|
| 5720 | my $ptronly = shift || 0;
|
---|
| 5721 |
|
---|
| 5722 | my $iplist = $sub->splitref(32);
|
---|
| 5723 | foreach (@$iplist) {
|
---|
| 5724 | my $ip = $_->addr;
|
---|
| 5725 | # make as if we split the non-octet-aligned block into octet-aligned blocks as with SOA
|
---|
| 5726 | next if $ip =~ /\.(0|255)$/;
|
---|
| 5727 | next if $$recflags{$ip};
|
---|
| 5728 | $$recflags{$ip}++;
|
---|
[463] | 5729 | next if $hpat eq '%blank%'; # Allows blanking a subnet so no records are published.
|
---|
[339] | 5730 | my $rec = $hpat; # start fresh with the template for each IP
|
---|
| 5731 | _template4_expand(\$rec, $ip);
|
---|
| 5732 | print $fh ($ptronly ? "^"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$rec" : "=$rec:$ip").
|
---|
[566] | 5733 | ":$ttl:$stamp:$loc\n" or die $!;
|
---|
[339] | 5734 | }
|
---|
| 5735 | }
|
---|
| 5736 |
|
---|
[103] | 5737 | ##fixme? append . to all host/val hostnames
|
---|
| 5738 | if ($typemap{$type} eq 'SOA') {
|
---|
| 5739 |
|
---|
| 5740 | # host contains pri-ns:responsible
|
---|
| 5741 | # val is abused to contain refresh:retry:expire:minttl
|
---|
| 5742 | ##fixme: "manual" serial vs tinydns-autoserial
|
---|
[202] | 5743 | # let's be explicit about abusing $host and $val
|
---|
| 5744 | my ($email, $primary) = (split /:/, $host)[0,1];
|
---|
| 5745 | my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
|
---|
[330] | 5746 | if ($revrec eq 'y') {
|
---|
[337] | 5747 | ##fixme: have to publish SOA records for each v4 /24 in sub-/16, and each /16 in sub-/8
|
---|
| 5748 | # what about v6?
|
---|
| 5749 | # -> only need SOA for local chunks offset from reverse delegation boundaries, so v6 is fine
|
---|
[330] | 5750 | $zone = NetAddr::IP->new($zone);
|
---|
[337] | 5751 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
| 5752 | if (!$zone->{isv6} && ($zone->masklen < 24) && ($zone->masklen % 8 != 0)) {
|
---|
| 5753 | foreach my $szone ($zone->split($zone->masklen + (8 - $zone->masklen % 8))) {
|
---|
| 5754 | $szone = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
[566] | 5755 | print $datafile "Z$szone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n"
|
---|
| 5756 | or die $!;
|
---|
[337] | 5757 | }
|
---|
| 5758 | return; # skips "default" bits just below
|
---|
| 5759 | }
|
---|
[330] | 5760 | $zone = _ZONE($zone, 'ZONE', 'r', '.').($zone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 5761 | }
|
---|
[566] | 5762 | print $datafile "Z$zone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n"
|
---|
| 5763 | or die $!;
|
---|
[103] | 5764 |
|
---|
| 5765 | } elsif ($typemap{$type} eq 'A') {
|
---|
| 5766 |
|
---|
[566] | 5767 | print $datafile "+$host:$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
[103] | 5768 |
|
---|
| 5769 | } elsif ($typemap{$type} eq 'NS') {
|
---|
| 5770 |
|
---|
[330] | 5771 | if ($revrec eq 'y') {
|
---|
| 5772 | $val = NetAddr::IP->new($val);
|
---|
[345] | 5773 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
| 5774 | if (!$val->{isv6} && ($val->masklen < 24) && ($val->masklen % 8 != 0)) {
|
---|
[346] | 5775 | foreach my $szone ($val->split($val->masklen + (8 - $val->masklen % 8))) {
|
---|
[345] | 5776 | my $szone2 = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
[346] | 5777 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
[566] | 5778 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
[346] | 5779 | $$recflags{$szone2} = $val->masklen;
|
---|
[345] | 5780 | }
|
---|
[346] | 5781 | } elsif ($val->{isv6} && ($val->masklen < 64) && ($val->masklen % 4 !=0)) {
|
---|
| 5782 | foreach my $szone ($val->split($val->masklen + (4 - $val->masklen % 4))) {
|
---|
| 5783 | my $szone2 = _ZONE($szone, 'ZONE.ip6.arpa', 'r', '.');
|
---|
| 5784 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
[566] | 5785 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
[346] | 5786 | $$recflags{$szone2} = $val->masklen;
|
---|
| 5787 | }
|
---|
| 5788 | } else {
|
---|
| 5789 | my $val2 = _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
[566] | 5790 | print $datafile "\&$val2"."::$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
[346] | 5791 | $$recflags{$val2} = $val->masklen;
|
---|
[345] | 5792 | }
|
---|
[330] | 5793 | } else {
|
---|
[566] | 5794 | print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
[330] | 5795 | }
|
---|
[103] | 5796 |
|
---|
| 5797 | } elsif ($typemap{$type} eq 'AAAA') {
|
---|
| 5798 |
|
---|
[566] | 5799 | # print $datafile ":$host:28:";
|
---|
[103] | 5800 | my $altgrp = 0;
|
---|
| 5801 | my @altconv;
|
---|
[108] | 5802 | # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
|
---|
[103] | 5803 | foreach (split /:/, $val) {
|
---|
| 5804 | if (/^$/) {
|
---|
| 5805 | # flag blank entry; this is a series of 0's of (currently) unknown length
|
---|
| 5806 | $altconv[$altgrp++] = 's';
|
---|
| 5807 | } else {
|
---|
| 5808 | # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
|
---|
| 5809 | $altconv[$altgrp++] = octalize($_)
|
---|
| 5810 | }
|
---|
| 5811 | }
|
---|
[566] | 5812 | my $prefix = ":$host:28:";
|
---|
[103] | 5813 | foreach my $octet (@altconv) {
|
---|
| 5814 | # if not 's', output
|
---|
[566] | 5815 | $prefix .= $octet unless $octet =~ /^s$/;
|
---|
[103] | 5816 | # if 's', output (9-array length)x literal '\000\000'
|
---|
[566] | 5817 | $prefix .= '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
|
---|
[103] | 5818 | }
|
---|
[566] | 5819 | print $datafile "$prefix:$ttl:$stamp:$loc\n" or die $!;
|
---|
[103] | 5820 |
|
---|
| 5821 | } elsif ($typemap{$type} eq 'MX') {
|
---|
| 5822 |
|
---|
[566] | 5823 | ##fixme: what if we get an MX AXFRed into a reverse zone?
|
---|
| 5824 | print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n" or die $!;
|
---|
[103] | 5825 |
|
---|
| 5826 | } elsif ($typemap{$type} eq 'TXT') {
|
---|
| 5827 |
|
---|
| 5828 | ##fixme: split v-e-r-y long TXT strings? will need to do so for BIND export, at least
|
---|
[350] | 5829 | if ($revrec eq 'n') {
|
---|
| 5830 | $val =~ s/:/\\072/g; # may need to replace other symbols
|
---|
[566] | 5831 | print $datafile "'$host:$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
[350] | 5832 | } else {
|
---|
| 5833 | $host =~ s/:/\\072/g; # may need to replace other symbols
|
---|
| 5834 | my $val2 = NetAddr::IP->new($val);
|
---|
| 5835 | print $datafile "'"._ZONE($val2, 'ZONE', 'r', '.').($val2->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
[566] | 5836 | ":$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
[350] | 5837 | }
|
---|
[103] | 5838 |
|
---|
| 5839 | # by-hand TXT
|
---|
| 5840 | #:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
|
---|
| 5841 | #@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
|
---|
| 5842 | #'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
|
---|
| 5843 |
|
---|
| 5844 | #txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
|
---|
| 5845 | #: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
|
---|
| 5846 |
|
---|
| 5847 | # very long TXT record as brought in by axfr-get
|
---|
| 5848 | # note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
|
---|
| 5849 | # also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
|
---|
| 5850 | #:longtxt.deepnet.cx:16:
|
---|
| 5851 | #\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
|
---|
| 5852 | #\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.
|
---|
| 5853 | #\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.
|
---|
| 5854 | #:3600
|
---|
| 5855 |
|
---|
| 5856 | } elsif ($typemap{$type} eq 'CNAME') {
|
---|
| 5857 |
|
---|
[372] | 5858 | if ($revrec eq 'n') {
|
---|
[566] | 5859 | print $datafile "C$host:$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
[372] | 5860 | } else {
|
---|
| 5861 | my $val2 = NetAddr::IP->new($val);
|
---|
| 5862 | print $datafile "C"._ZONE($val2, 'ZONE', 'r', '.').($val2->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
[566] | 5863 | ":$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
[372] | 5864 | }
|
---|
[103] | 5865 |
|
---|
| 5866 | } elsif ($typemap{$type} eq 'SRV') {
|
---|
| 5867 |
|
---|
| 5868 | # data is two-byte values for priority, weight, port, in that order,
|
---|
| 5869 | # followed by length/string data
|
---|
| 5870 |
|
---|
[566] | 5871 | print $datafile ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d') or die $!;
|
---|
[103] | 5872 |
|
---|
| 5873 | $val .= '.' if $val !~ /\.$/;
|
---|
| 5874 | foreach (split /\./, $val) {
|
---|
[566] | 5875 | printf $datafile "\\%0.3o%s", length($_), $_ or die $!;
|
---|
[103] | 5876 | }
|
---|
[566] | 5877 | print $datafile "\\000:$ttl:$stamp:$loc\n" or die $!;
|
---|
[103] | 5878 |
|
---|
| 5879 | } elsif ($typemap{$type} eq 'RP') {
|
---|
| 5880 |
|
---|
| 5881 | # RP consists of two mostly free-form strings.
|
---|
| 5882 | # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
|
---|
| 5883 | # The second is the "hostname" of a TXT record with more info.
|
---|
[566] | 5884 | my $prefix = ":$host:17:";
|
---|
[103] | 5885 | my ($who,$what) = split /\s/, $val;
|
---|
| 5886 | foreach (split /\./, $who) {
|
---|
[566] | 5887 | $prefix .= sprintf "\\%0.3o%s", length($_), $_;
|
---|
[103] | 5888 | }
|
---|
[566] | 5889 | $prefix .= '\000';
|
---|
[103] | 5890 | foreach (split /\./, $what) {
|
---|
[566] | 5891 | $prefix .= sprintf "\\%0.3o%s", length($_), $_;
|
---|
[103] | 5892 | }
|
---|
[566] | 5893 | print $datafile "$prefix\\000:$ttl:$stamp:$loc\n" or die $!;
|
---|
[103] | 5894 |
|
---|
| 5895 | } elsif ($typemap{$type} eq 'PTR') {
|
---|
| 5896 |
|
---|
[332] | 5897 | $zone = NetAddr::IP->new($zone);
|
---|
[337] | 5898 | $$recflags{$val}++;
|
---|
[332] | 5899 | if (!$zone->{isv6} && $zone->masklen > 24) {
|
---|
| 5900 | ($val) = ($val =~ /\.(\d+)$/);
|
---|
| 5901 | print $datafile "^$val."._ZONE($zone, 'ZONE', 'r', '.').'.in-addr.arpa'.
|
---|
[595] | 5902 | ":$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
[332] | 5903 | } else {
|
---|
| 5904 | $val = NetAddr::IP->new($val);
|
---|
| 5905 | print $datafile "^".
|
---|
| 5906 | _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
[566] | 5907 | ":$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
[332] | 5908 | }
|
---|
[103] | 5909 |
|
---|
[333] | 5910 | } elsif ($type == 65280) { # A+PTR
|
---|
[334] | 5911 |
|
---|
[337] | 5912 | $$recflags{$val}++;
|
---|
[566] | 5913 | print $datafile "=$host:$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
[334] | 5914 |
|
---|
[333] | 5915 | } elsif ($type == 65281) { # AAAA+PTR
|
---|
| 5916 |
|
---|
[526] | 5917 | $$recflags{$val}++;
|
---|
[333] | 5918 | # treat these as two separate records. since tinydns doesn't have
|
---|
| 5919 | # a native combined type, we have to create them separately anyway.
|
---|
[526] | 5920 | # print both; a dangling record is harmless, and impossible via web
|
---|
| 5921 | # UI anyway
|
---|
| 5922 | _printrec_tiny($datafile,$revrec,$recflags,$zone,$host,28,$val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
| 5923 | _printrec_tiny($datafile,$revrec,$recflags,$zone,$host,12,$val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
[335] | 5924 | ##fixme: add a config flag to indicate use of the patch from http://www.fefe.de/dns/
|
---|
| 5925 | # type 6 is for AAAA+PTR, type 3 is for AAAA
|
---|
[333] | 5926 |
|
---|
| 5927 | } elsif ($type == 65282) { # PTR template
|
---|
[335] | 5928 |
|
---|
| 5929 | # only useful for v4 with standard DNS software, since this expands all
|
---|
| 5930 | # IPs in $zone (or possibly $val?) with autogenerated records
|
---|
[337] | 5931 | $val = NetAddr::IP->new($val);
|
---|
| 5932 | return if $val->{isv6};
|
---|
[336] | 5933 |
|
---|
[339] | 5934 | if ($val->masklen <= 16) {
|
---|
| 5935 | foreach my $sub ($val->split(16)) {
|
---|
| 5936 | __publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, 1);
|
---|
| 5937 | }
|
---|
| 5938 | } else {
|
---|
| 5939 | __publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, 1);
|
---|
[337] | 5940 | }
|
---|
[335] | 5941 |
|
---|
[333] | 5942 | } elsif ($type == 65283) { # A+PTR template
|
---|
[335] | 5943 |
|
---|
[337] | 5944 | $val = NetAddr::IP->new($val);
|
---|
| 5945 | # Just In Case. An A+PTR should be impossible to add to a v6 revzone via API.
|
---|
| 5946 | return if $val->{isv6};
|
---|
[339] | 5947 |
|
---|
| 5948 | if ($val->masklen <= 16) {
|
---|
| 5949 | foreach my $sub ($val->split(16)) {
|
---|
| 5950 | __publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, 0);
|
---|
| 5951 | }
|
---|
| 5952 | } else {
|
---|
| 5953 | __publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, 0);
|
---|
[337] | 5954 | }
|
---|
[335] | 5955 |
|
---|
[333] | 5956 | } elsif ($type == 65284) { # AAAA+PTR template
|
---|
[335] | 5957 | # Stub for completeness. Could be exported to DNS software that supports
|
---|
| 5958 | # some degree of internal automagic in generic-record-creation
|
---|
| 5959 | # (eg http://search.cpan.org/dist/AllKnowingDNS/ )
|
---|
[333] | 5960 |
|
---|
[345] | 5961 | } elsif ($type == 65285) { # Delegation
|
---|
| 5962 | # This is intended for reverse zones, but may prove useful in forward zones.
|
---|
| 5963 |
|
---|
[346] | 5964 | # All delegations need to create one or more NS records. The NS record handler knows what to do.
|
---|
| 5965 | _printrec_tiny($datafile,$revrec,$recflags,$zone,$host,$reverse_typemap{'NS'},
|
---|
| 5966 | $val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
| 5967 | if ($revrec eq 'y') {
|
---|
| 5968 | # In the case of a sub-/24 v4 reverse delegation, we need to generate CNAMEs
|
---|
| 5969 | # to redirect all of the individual IP lookups as well.
|
---|
| 5970 | # Not sure how this would actually resolve if a /24 or larger was delegated
|
---|
| 5971 | # one way, and a sub-/24 in that >=/24 was delegated elsewhere...
|
---|
| 5972 | my $dblock = NetAddr::IP->new($val);
|
---|
| 5973 | if (!$dblock->{isv6} && $dblock->masklen > 24) {
|
---|
| 5974 | my @subs = $dblock->split;
|
---|
| 5975 | foreach (@subs) {
|
---|
| 5976 | next if $$recflags{"$_"};
|
---|
| 5977 | my ($oct) = ($_->addr =~ /(\d+)$/);
|
---|
| 5978 | print $datafile "C"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$oct.".
|
---|
[566] | 5979 | _ZONE($dblock, 'ZONE.in-addr.arpa', 'r', '.').":$ttl:$stamp:$loc\n" or die $!;
|
---|
[346] | 5980 | $$recflags{"$_"}++;
|
---|
| 5981 | }
|
---|
| 5982 | }
|
---|
| 5983 | }
|
---|
[345] | 5984 |
|
---|
[364] | 5985 | ##
|
---|
| 5986 | ## Uncommon types. These will need better UI support Any Day Sometime Maybe(TM).
|
---|
| 5987 | ##
|
---|
| 5988 |
|
---|
| 5989 | } elsif ($type == 44) { # SSHFP
|
---|
| 5990 | my ($algo,$fpt,$fp) = split /\s+/, $val;
|
---|
| 5991 |
|
---|
| 5992 | my $rec = sprintf ":$host:44:\\%0.3o\\%0.3o", $algo, $fpt;
|
---|
| 5993 | while (my ($byte) = ($fp =~ /^(..)/) ) {
|
---|
| 5994 | $rec .= sprintf "\\%0.3o", hex($byte);
|
---|
| 5995 | $fp =~ s/^..//;
|
---|
| 5996 | }
|
---|
[566] | 5997 | print $datafile "$rec:$ttl:$stamp:$loc\n" or die $!;
|
---|
[364] | 5998 |
|
---|
[345] | 5999 | } else {
|
---|
[108] | 6000 | # raw record. we don't know what's in here, so we ASS-U-ME the user has
|
---|
| 6001 | # put it in correctly, since either the user is messing directly with the
|
---|
| 6002 | # database, or the record was imported via AXFR
|
---|
| 6003 | # <split by char>
|
---|
| 6004 | # convert anything not a-zA-Z0-9.- to octal coding
|
---|
| 6005 |
|
---|
| 6006 | ##fixme: add flag to export "unknown" record types - note we'll probably end up
|
---|
| 6007 | # mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
|
---|
| 6008 | #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
|
---|
| 6009 |
|
---|
[103] | 6010 | } # record type if-else
|
---|
| 6011 |
|
---|
[329] | 6012 | } # end _printrec_tiny()
|
---|
[103] | 6013 |
|
---|
| 6014 |
|
---|
[197] | 6015 | ## DNSDB::mailNotify()
|
---|
[283] | 6016 | # Sends notification mail to recipients regarding a DNSDB operation
|
---|
[197] | 6017 | sub mailNotify {
|
---|
[483] | 6018 | my $self = shift;
|
---|
| 6019 | my $dbh = $self->{dbh};
|
---|
[197] | 6020 | my ($subj,$message) = @_;
|
---|
| 6021 |
|
---|
[517] | 6022 | return if $self->{mailhost} eq 'smtp.example.com'; # do nothing if still using default SMTP host.
|
---|
[197] | 6023 |
|
---|
[517] | 6024 | my $mailer = Net::SMTP->new($self->{mailhost}, Hello => "dnsadmin.$self->{domain}");
|
---|
[197] | 6025 |
|
---|
[517] | 6026 | my $mailsender = ($self->{mailsender} ? $self->{mailsender} : $self->{mailnotify});
|
---|
[197] | 6027 |
|
---|
| 6028 | $mailer->mail($mailsender);
|
---|
[517] | 6029 | $mailer->to($self->{mailnotify});
|
---|
| 6030 | $mailer->data("From: \"$self->{mailname}\" <$mailsender>\n",
|
---|
| 6031 | "To: <$self->{mailnotify}>\n",
|
---|
[197] | 6032 | "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
|
---|
| 6033 | "Subject: $subj\n",
|
---|
[529] | 6034 | "X-Mailer: DNSAdmin v".$DNSDB::VERSION." Notify\n",
|
---|
[517] | 6035 | "Organization: $self->{orgname}\n",
|
---|
[197] | 6036 | "\n$message\n");
|
---|
| 6037 | $mailer->quit;
|
---|
| 6038 | }
|
---|
| 6039 |
|
---|
[2] | 6040 | # shut Perl up
|
---|
| 6041 | 1;
|
---|