[2] | 1 | # dns/trunk/DNSDB.pm
|
---|
| 2 | # Abstraction functions for DNS administration
|
---|
[262] | 3 | ##
|
---|
| 4 | # $Id: DNSDB.pm 543 2013-12-10 21:22:10Z kdeugau $
|
---|
[496] | 5 | # Copyright 2008-2013 Kris Deugau <kdeugau@deepnet.cx>
|
---|
[262] | 6 | #
|
---|
| 7 | # This program is free software: you can redistribute it and/or modify
|
---|
| 8 | # it under the terms of the GNU General Public License as published by
|
---|
| 9 | # the Free Software Foundation, either version 3 of the License, or
|
---|
| 10 | # (at your option) any later version.
|
---|
| 11 | #
|
---|
| 12 | # This program is distributed in the hope that it will be useful,
|
---|
| 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
|
---|
| 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
---|
| 15 | # GNU General Public License for more details.
|
---|
| 16 | #
|
---|
| 17 | # You should have received a copy of the GNU General Public License
|
---|
| 18 | # along with this program. If not, see <http://www.gnu.org/licenses/>.
|
---|
| 19 | ##
|
---|
[2] | 20 |
|
---|
| 21 | package DNSDB;
|
---|
| 22 |
|
---|
| 23 | use strict;
|
---|
| 24 | use warnings;
|
---|
| 25 | use Exporter;
|
---|
| 26 | use DBI;
|
---|
[33] | 27 | use Net::DNS;
|
---|
[65] | 28 | use Crypt::PasswdMD5;
|
---|
[198] | 29 | use Net::SMTP;
|
---|
[539] | 30 | use NetAddr::IP 4.027 qw(:lower);
|
---|
[198] | 31 | use POSIX;
|
---|
[368] | 32 | use Fcntl qw(:flock);
|
---|
[543] | 33 | use Time::TAI64 qw(:tai64);
|
---|
[368] | 34 |
|
---|
[2] | 35 | use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
|
---|
| 36 |
|
---|
[321] | 37 | $VERSION = 1.1; ##VERSION##
|
---|
[2] | 38 | @ISA = qw(Exporter);
|
---|
| 39 | @EXPORT_OK = qw(
|
---|
[279] | 40 | &initGlobals &login &initActionLog
|
---|
[489] | 41 | &getPermissions &changePermissions &comparePermissions
|
---|
[112] | 42 | &changeGroup
|
---|
[517] | 43 | &connectDB &finish
|
---|
[276] | 44 | &addDomain &delZone &domainName &revName &domainID &revID &addRDNS
|
---|
[383] | 45 | &getZoneCount &getZoneList &getZoneLocation
|
---|
[22] | 46 | &addGroup &delGroup &getChildren &groupName
|
---|
[314] | 47 | &getGroupCount &getGroupList
|
---|
[83] | 48 | &addUser &updateUser &delUser &userFullName &userStatus &getUserData
|
---|
[326] | 49 | &getUserCount &getUserList &getUserDropdown
|
---|
[375] | 50 | &addLoc &updateLoc &delLoc &getLoc
|
---|
[370] | 51 | &getLocCount &getLocList &getLocDropdown
|
---|
[495] | 52 | &getSOA &updateSOA &getRecLine &getRecList &getRecCount
|
---|
[22] | 53 | &addRec &updateRec &delRec
|
---|
[323] | 54 | &getLogCount &getLogEntries
|
---|
[452] | 55 | &getRevPattern
|
---|
[225] | 56 | &getTypelist
|
---|
[254] | 57 | &parentID
|
---|
[117] | 58 | &isParent
|
---|
[452] | 59 | &zoneStatus &getZonesByCIDR &importAXFR
|
---|
[103] | 60 | &export
|
---|
[197] | 61 | &mailNotify
|
---|
[517] | 62 | %typemap %reverse_typemap
|
---|
[489] | 63 | @permtypes $permlist %permchains
|
---|
[2] | 64 | );
|
---|
| 65 |
|
---|
[489] | 66 | @EXPORT = qw(%typemap %reverse_typemap @permtypes $permlist %permchains);
|
---|
[2] | 67 | %EXPORT_TAGS = ( ALL => [qw(
|
---|
[279] | 68 | &initGlobals &login &initActionLog
|
---|
[489] | 69 | &getPermissions &changePermissions &comparePermissions
|
---|
[112] | 70 | &changeGroup
|
---|
[517] | 71 | &connectDB &finish
|
---|
[276] | 72 | &addDomain &delZone &domainName &revName &domainID &revID &addRDNS
|
---|
[383] | 73 | &getZoneCount &getZoneList &getZoneLocation
|
---|
[22] | 74 | &addGroup &delGroup &getChildren &groupName
|
---|
[314] | 75 | &getGroupCount &getGroupList
|
---|
[83] | 76 | &addUser &updateUser &delUser &userFullName &userStatus &getUserData
|
---|
[326] | 77 | &getUserCount &getUserList &getUserDropdown
|
---|
[375] | 78 | &addLoc &updateLoc &delLoc &getLoc
|
---|
[370] | 79 | &getLocCount &getLocList &getLocDropdown
|
---|
[495] | 80 | &getSOA &updateSOA &getRecLine &getRecList &getRecCount
|
---|
[22] | 81 | &addRec &updateRec &delRec
|
---|
[323] | 82 | &getLogCount &getLogEntries
|
---|
[452] | 83 | &getRevPattern
|
---|
[225] | 84 | &getTypelist
|
---|
[254] | 85 | &parentID
|
---|
[117] | 86 | &isParent
|
---|
[452] | 87 | &zoneStatus &getZonesByCIDR &importAXFR
|
---|
[103] | 88 | &export
|
---|
[197] | 89 | &mailNotify
|
---|
[517] | 90 | %typemap %reverse_typemap
|
---|
[489] | 91 | @permtypes $permlist %permchains
|
---|
[2] | 92 | )]
|
---|
| 93 | );
|
---|
| 94 |
|
---|
| 95 | our $errstr = '';
|
---|
[283] | 96 | our $resultstr = '';
|
---|
[2] | 97 |
|
---|
[66] | 98 | # Arguably defined wholly in the db, but little reason to change without supporting code changes
|
---|
[370] | 99 | # group_view, user_view permissions? separate rDNS permission(s)?
|
---|
[66] | 100 | our @permtypes = qw (
|
---|
| 101 | group_edit group_create group_delete
|
---|
| 102 | user_edit user_create user_delete
|
---|
| 103 | domain_edit domain_create domain_delete
|
---|
[387] | 104 | record_edit record_create record_delete record_locchg
|
---|
[370] | 105 | location_edit location_create location_delete location_view
|
---|
[66] | 106 | self_edit admin
|
---|
| 107 | );
|
---|
| 108 | our $permlist = join(',',@permtypes);
|
---|
| 109 |
|
---|
[390] | 110 | # Some permissions more or less require certain others.
|
---|
| 111 | our %permchains = (
|
---|
| 112 | user_edit => 'self_edit',
|
---|
| 113 | location_edit => 'location_view',
|
---|
| 114 | location_create => 'location_view',
|
---|
| 115 | location_delete => 'location_view',
|
---|
| 116 | record_locchg => 'location_view',
|
---|
| 117 | );
|
---|
| 118 |
|
---|
[2] | 119 | # DNS record type map and reverse map.
|
---|
| 120 | # loaded from the database, from http://www.iana.org/assignments/dns-parameters
|
---|
| 121 | our %typemap;
|
---|
| 122 | our %reverse_typemap;
|
---|
| 123 |
|
---|
[228] | 124 | ## (Semi)private variables
|
---|
[278] | 125 |
|
---|
[228] | 126 | # Hash of functions for validating record types. Filled in initGlobals() since
|
---|
| 127 | # it relies on visibility flags from the rectypes table in the DB
|
---|
| 128 | my %validators;
|
---|
[128] | 129 |
|
---|
[295] | 130 | # Entity-relationship reference hashes.
|
---|
| 131 | my %par_tbl = (
|
---|
| 132 | group => 'groups',
|
---|
| 133 | user => 'users',
|
---|
| 134 | defrec => 'default_records',
|
---|
| 135 | defrevrec => 'default_rev_records',
|
---|
| 136 | domain => 'domains',
|
---|
| 137 | revzone => 'revzones',
|
---|
| 138 | record => 'records'
|
---|
| 139 | );
|
---|
| 140 | my %id_col = (
|
---|
| 141 | group => 'group_id',
|
---|
| 142 | user => 'user_id',
|
---|
| 143 | defrec => 'record_id',
|
---|
| 144 | defrevrec => 'record_id',
|
---|
| 145 | domain => 'domain_id',
|
---|
| 146 | revzone => 'rdns_id',
|
---|
| 147 | record => 'record_id'
|
---|
| 148 | );
|
---|
| 149 | my %par_col = (
|
---|
| 150 | group => 'parent_group_id',
|
---|
| 151 | user => 'group_id',
|
---|
| 152 | defrec => 'group_id',
|
---|
| 153 | defrevrec => 'group_id',
|
---|
| 154 | domain => 'group_id',
|
---|
| 155 | revzone => 'group_id',
|
---|
| 156 | record => 'domain_id'
|
---|
| 157 | );
|
---|
| 158 | my %par_type = (
|
---|
| 159 | group => 'group',
|
---|
| 160 | user => 'group',
|
---|
| 161 | defrec => 'group',
|
---|
| 162 | defrevrec => 'group',
|
---|
| 163 | domain => 'group',
|
---|
| 164 | revzone => 'group',
|
---|
| 165 | record => 'domain'
|
---|
| 166 | );
|
---|
[278] | 167 |
|
---|
[2] | 168 | ##
|
---|
[465] | 169 | ## Constructor and destructor
|
---|
| 170 | ##
|
---|
| 171 |
|
---|
| 172 | sub new {
|
---|
| 173 | my $this = shift;
|
---|
| 174 | my $class = ref($this) || $this;
|
---|
| 175 | my %args = @_;
|
---|
[517] | 176 |
|
---|
| 177 | # Prepopulate a basic config. Note some of these *will* cause errors if left unset.
|
---|
| 178 | # note: add appropriate stanzas in __cfgload() to parse these
|
---|
| 179 | my %defconfig = (
|
---|
[529] | 180 | # The only configuration options not loadable from a config file.
|
---|
| 181 | configfile => "/etc/dnsdb/dnsdb.conf", ##CFG_LEAF##
|
---|
[517] | 182 |
|
---|
| 183 | # Database connection info
|
---|
| 184 | dbname => 'dnsdb',
|
---|
| 185 | dbuser => 'dnsdb',
|
---|
| 186 | dbpass => 'secret',
|
---|
| 187 | dbhost => '',
|
---|
| 188 |
|
---|
| 189 | # Email notice settings
|
---|
| 190 | mailhost => 'smtp.example.com',
|
---|
| 191 | mailnotify => 'dnsdb@example.com', # to
|
---|
| 192 | mailsender => 'dnsdb@example.com', # from
|
---|
| 193 | mailname => 'DNS Administration',
|
---|
| 194 | orgname => 'Example Corp',
|
---|
| 195 | domain => 'example.com',
|
---|
| 196 |
|
---|
| 197 | # Template directory
|
---|
| 198 | templatedir => 'templates/',
|
---|
| 199 | # fmeh. this is a real web path, not a logical internal one. hm..
|
---|
| 200 | # cssdir => 'templates/',
|
---|
| 201 | sessiondir => 'session/',
|
---|
| 202 | exportcache => 'cache/',
|
---|
| 203 |
|
---|
| 204 | # Session params
|
---|
| 205 | timeout => '1h', # passed as-is to CGI::Session
|
---|
| 206 |
|
---|
| 207 | # Other miscellanea
|
---|
| 208 | log_failures => 1, # log all evarthing by default
|
---|
| 209 | perpage => 15,
|
---|
| 210 | max_fcgi_requests => 100, # reasonable default?
|
---|
[524] | 211 | force_refresh => 1,
|
---|
[542] | 212 | lowercase => 0, # mangle as little as possible by default
|
---|
[517] | 213 | );
|
---|
| 214 |
|
---|
| 215 | # Config file parse calls.
|
---|
| 216 | # If we are passed a blank argument for $args{configfile},
|
---|
| 217 | # we should NOT parse the default config file - we will
|
---|
| 218 | # rely on hardcoded defaults OR caller-specified values.
|
---|
| 219 | # If we are passed a non-blank argument, parse that file.
|
---|
| 220 | # If no config file is specified, parse the default one.
|
---|
| 221 | my %siteconfig;
|
---|
| 222 | if (defined($args{configfile})) {
|
---|
| 223 | if ($args{configfile}) {
|
---|
| 224 | return if !__cfgload($args{configfile}, \%siteconfig);
|
---|
| 225 | }
|
---|
| 226 | } else {
|
---|
| 227 | return if !__cfgload($defconfig{configfile}, \%siteconfig);
|
---|
[465] | 228 | }
|
---|
[517] | 229 |
|
---|
| 230 | # Assemble the object. Apply configuration hashes in order of precedence.
|
---|
| 231 | my $self = {
|
---|
| 232 | # Hardcoded defaults
|
---|
| 233 | %defconfig,
|
---|
| 234 | # Default config file OR caller-specified one, loaded above
|
---|
| 235 | %siteconfig,
|
---|
| 236 | # Caller-specified arguments
|
---|
| 237 | %args
|
---|
| 238 | };
|
---|
[465] | 239 | bless $self, $class;
|
---|
[517] | 240 |
|
---|
[524] | 241 | # Several settings are booleans. Handle multiple possible ways of setting them.
|
---|
[542] | 242 | for my $boolopt ('log_failures', 'force_refresh', 'lowercase') {
|
---|
[524] | 243 | if ($self->{$boolopt} ne '1' && $self->{$boolopt} ne '0') {
|
---|
| 244 | # true/false, on/off, yes/no all valid.
|
---|
| 245 | if ($self->{$boolopt} =~ /^(?:true|false|t|f|on|off|yes|no)$/) {
|
---|
| 246 | if ($self->{$boolopt} =~ /(?:true|t|on|yes)/) {
|
---|
| 247 | $self->{$boolopt} = 1;
|
---|
| 248 | } else {
|
---|
| 249 | $self->{$boolopt} = 0;
|
---|
| 250 | }
|
---|
| 251 | } else {
|
---|
| 252 | warn "Bad $boolopt setting $self->{$boolopt}\n";
|
---|
| 253 | $self->{$boolopt} = 1;
|
---|
| 254 | }
|
---|
| 255 | }
|
---|
| 256 | }
|
---|
| 257 |
|
---|
[517] | 258 | # Try to connect to the DB, and initialize a number of handy globals.
|
---|
[465] | 259 | $self->{dbh} = connectDB($self->{dbname}, $self->{dbuser}, $self->{dbpass}, $self->{dbhost}) or return;
|
---|
| 260 | $self->initGlobals();
|
---|
| 261 |
|
---|
| 262 | return $self;
|
---|
| 263 | }
|
---|
| 264 |
|
---|
| 265 | sub DESTROY {
|
---|
| 266 | my $self = shift;
|
---|
[517] | 267 | $self->{dbh}->disconnect if $self->{dbh};
|
---|
[465] | 268 | }
|
---|
| 269 |
|
---|
[495] | 270 | sub errstr { $DNSDB::errstr; }
|
---|
| 271 |
|
---|
[465] | 272 | ##
|
---|
[225] | 273 | ## utility functions
|
---|
[281] | 274 | ##
|
---|
| 275 |
|
---|
| 276 | ## DNSDB::_rectable()
|
---|
[224] | 277 | # Takes default+rdns flags, returns appropriate table name
|
---|
| 278 | sub _rectable {
|
---|
| 279 | my $def = shift;
|
---|
| 280 | my $rev = shift;
|
---|
| 281 |
|
---|
| 282 | return 'records' if $def ne 'y';
|
---|
| 283 | return 'default_records' if $rev ne 'y';
|
---|
| 284 | return 'default_rev_records';
|
---|
| 285 | } # end _rectable()
|
---|
| 286 |
|
---|
[281] | 287 | ## DNSDB::_recparent()
|
---|
[224] | 288 | # Takes default+rdns flags, returns appropriate parent-id column name
|
---|
| 289 | sub _recparent {
|
---|
| 290 | my $def = shift;
|
---|
| 291 | my $rev = shift;
|
---|
| 292 |
|
---|
| 293 | return 'group_id' if $def eq 'y';
|
---|
| 294 | return 'rdns_id' if $rev eq 'y';
|
---|
| 295 | return 'domain_id';
|
---|
| 296 | } # end _recparent()
|
---|
| 297 |
|
---|
[281] | 298 | ## DNSDB::_ipparent()
|
---|
[226] | 299 | # Check an IP to be added in a reverse zone to see if it's really in the requested parent.
|
---|
[466] | 300 | # Takes default and reverse flags, IP (fragment) to check, parent zone ID,
|
---|
[226] | 301 | # and a reference to a NetAddr::IP object (also used to pass back a fully-reconstructed IP for
|
---|
| 302 | # database insertion)
|
---|
| 303 | sub _ipparent {
|
---|
[466] | 304 | my $self = shift;
|
---|
| 305 | my $dbh = $self->{dbh};
|
---|
[226] | 306 | my $defrec = shift;
|
---|
| 307 | my $revrec = shift;
|
---|
| 308 | my $val = shift;
|
---|
| 309 | my $id = shift;
|
---|
| 310 | my $addr = shift;
|
---|
[224] | 311 |
|
---|
[232] | 312 | return if $revrec ne 'y'; # this sub not useful in forward zones
|
---|
| 313 |
|
---|
| 314 | $$addr = NetAddr::IP->new($$val); #necessary?
|
---|
| 315 |
|
---|
[226] | 316 | # subsub to split, reverse, and overlay an IP fragment on a netblock
|
---|
| 317 | sub __rev_overlay {
|
---|
| 318 | my $splitme = shift; # ':' or '.', m'lud?
|
---|
| 319 | my $parnet = shift;
|
---|
| 320 | my $val = shift;
|
---|
| 321 | my $addr = shift;
|
---|
| 322 |
|
---|
| 323 | my $joinme = $splitme;
|
---|
| 324 | $splitme = '\.' if $splitme eq '.';
|
---|
[232] | 325 | my @working = reverse(split($splitme, $parnet->addr));
|
---|
| 326 | my @parts = reverse(split($splitme, $$val));
|
---|
[226] | 327 | for (my $i = 0; $i <= $#parts; $i++) {
|
---|
| 328 | $working[$i] = $parts[$i];
|
---|
| 329 | }
|
---|
[232] | 330 | my $checkme = NetAddr::IP->new(join($joinme, reverse(@working))) or return 0;
|
---|
| 331 | return 0 unless $checkme->within($parnet);
|
---|
[226] | 332 | $$addr = $checkme; # force "correct" IP to be recorded.
|
---|
| 333 | return 1;
|
---|
| 334 | }
|
---|
| 335 |
|
---|
| 336 | my ($parstr) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id = ?", undef, ($id));
|
---|
| 337 | my $parnet = NetAddr::IP->new($parstr);
|
---|
| 338 |
|
---|
| 339 | # Fail early on v6-in-v4 or v4-in-v6. We're not accepting these ATM.
|
---|
[232] | 340 | return 0 if $parnet->addr =~ /\./ && $$val =~ /:/;
|
---|
| 341 | return 0 if $parnet->addr =~ /:/ && $$val =~ /\./;
|
---|
[226] | 342 |
|
---|
[340] | 343 | if ($$addr && ($$val =~ /^[\da-fA-F][\da-fA-F:]+[\da-fA-F]$/ || $$val =~ m|/\d+$|)) {
|
---|
| 344 | # the only case where NetAddr::IP's acceptance of legitimate IPs is "correct" is for a proper IPv6 address,
|
---|
| 345 | # or a netblock (only expected on templates)
|
---|
[232] | 346 | # the rest we have to restructure before fiddling. *sigh*
|
---|
| 347 | return 1 if $$addr->within($parnet);
|
---|
| 348 | } else {
|
---|
[340] | 349 | # We don't have a complete IP in $$val (yet)... unless we have a netblock
|
---|
[232] | 350 | if ($parnet->addr =~ /:/) {
|
---|
| 351 | $$val =~ s/^:+//; # gotta strip'em all...
|
---|
[226] | 352 | return __rev_overlay(':', $parnet, $val, $addr);
|
---|
| 353 | }
|
---|
[232] | 354 | if ($parnet->addr =~ /\./) {
|
---|
| 355 | $$val =~ s/^\.+//;
|
---|
| 356 | return __rev_overlay('.', $parnet, $val, $addr);
|
---|
| 357 | }
|
---|
[226] | 358 | # should be impossible to get here...
|
---|
| 359 | }
|
---|
| 360 | # ... and here.
|
---|
| 361 | # can't do nuttin' in forward zones
|
---|
| 362 | } # end _ipparent()
|
---|
| 363 |
|
---|
[281] | 364 | ## DNSDB::_hostparent()
|
---|
[232] | 365 | # A little different than _ipparent above; this tries to *find* the parent zone of a hostname
|
---|
[466] | 366 | # Takes a hostname.
|
---|
[281] | 367 | # Returns the domain ID of the parent domain if one was found.
|
---|
[232] | 368 | sub _hostparent {
|
---|
[466] | 369 | my $self = shift;
|
---|
| 370 | my $dbh = $self->{dbh};
|
---|
[232] | 371 | my $hname = shift;
|
---|
[347] | 372 |
|
---|
| 373 | $hname =~ s/^\*\.//; # this should be impossible to find in the domains table.
|
---|
[232] | 374 | my @hostbits = split /\./, $hname;
|
---|
[349] | 375 | my $sth = $dbh->prepare("SELECT count(*),domain_id FROM domains WHERE lower(domain) = lower(?) GROUP BY domain_id");
|
---|
[232] | 376 | foreach (@hostbits) {
|
---|
| 377 | $sth->execute($hname);
|
---|
| 378 | my ($found, $parid) = $sth->fetchrow_array;
|
---|
| 379 | if ($found) {
|
---|
| 380 | return $parid;
|
---|
| 381 | }
|
---|
| 382 | $hname =~ s/^$_\.//;
|
---|
| 383 | }
|
---|
| 384 | } # end _hostparent()
|
---|
[228] | 385 |
|
---|
[281] | 386 | ## DNSDB::_log()
|
---|
| 387 | # Log an action
|
---|
[466] | 388 | # Takes a log entry hash containing at least:
|
---|
[282] | 389 | # group_id, log entry
|
---|
[281] | 390 | # and optionally one or more of:
|
---|
| 391 | # domain_id, rdns_id
|
---|
[282] | 392 | # The %userdata hash provides the user ID, username, and fullname
|
---|
[281] | 393 | sub _log {
|
---|
[466] | 394 | my $self = shift;
|
---|
| 395 | my $dbh = $self->{dbh};
|
---|
[281] | 396 |
|
---|
| 397 | my %args = @_;
|
---|
| 398 |
|
---|
| 399 | $args{rdns_id} = 0 if !$args{rdns_id};
|
---|
| 400 | $args{domain_id} = 0 if !$args{domain_id};
|
---|
| 401 |
|
---|
| 402 | ##fixme: farm out the actual logging to different subs for file, syslog, internal, etc based on config
|
---|
[517] | 403 | # if ($self->{log_channel} eq 'sql') {
|
---|
[281] | 404 | $dbh->do("INSERT INTO log (domain_id,rdns_id,group_id,entry,user_id,email,name) VALUES (?,?,?,?,?,?,?)",
|
---|
| 405 | undef,
|
---|
| 406 | ($args{domain_id}, $args{rdns_id}, $args{group_id}, $args{entry},
|
---|
[488] | 407 | $self->{loguserid}, $self->{logusername}, $self->{logfullname}) );
|
---|
[517] | 408 | # } elsif ($self->{log_channel} eq 'file') {
|
---|
| 409 | # } elsif ($self->{log_channel} eq 'syslog') {
|
---|
[281] | 410 | # }
|
---|
| 411 | } # end _log
|
---|
| 412 |
|
---|
| 413 |
|
---|
[224] | 414 | ##
|
---|
[228] | 415 | ## Record validation subs.
|
---|
| 416 | ##
|
---|
| 417 |
|
---|
[281] | 418 | ## All of these subs take substantially the same arguments:
|
---|
| 419 | # a hash containing at least the following keys:
|
---|
| 420 | # - defrec (default/live flag)
|
---|
| 421 | # - revrec (forward/reverse flag)
|
---|
| 422 | # - id (parent entity ID)
|
---|
| 423 | # - host (hostname)
|
---|
| 424 | # - rectype
|
---|
| 425 | # - val (IP, hostname [CNAME/MX/SRV] or text)
|
---|
| 426 | # - addr (NetAddr::IP object from val. May be undef.)
|
---|
| 427 | # MX and SRV record validation also expect distance, and SRV records expect weight and port as well.
|
---|
| 428 | # host, rectype, and addr should be references as these may be modified in validation
|
---|
| 429 |
|
---|
[228] | 430 | # A record
|
---|
| 431 | sub _validate_1 {
|
---|
[467] | 432 | my $self = shift;
|
---|
| 433 | my $dbh = $self->{dbh};
|
---|
[229] | 434 |
|
---|
[230] | 435 | my %args = @_;
|
---|
[229] | 436 |
|
---|
[230] | 437 | return ('FAIL', 'Reverse zones cannot contain A records') if $args{revrec} eq 'y';
|
---|
[229] | 438 |
|
---|
| 439 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 440 | # or the intended parent domain for live records.
|
---|
[467] | 441 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[531] | 442 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/);
|
---|
[229] | 443 |
|
---|
| 444 | # Check IP is well-formed, and that it's a v4 address
|
---|
[234] | 445 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
|
---|
[232] | 446 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
[234] | 447 | unless ${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/;
|
---|
| 448 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
[230] | 449 | unless $args{addr} && !$args{addr}->{isv6};
|
---|
[229] | 450 | # coerce IP/value to normalized form for storage
|
---|
[230] | 451 | ${$args{val}} = $args{addr}->addr;
|
---|
[229] | 452 |
|
---|
[228] | 453 | return ('OK','OK');
|
---|
| 454 | } # done A record
|
---|
| 455 |
|
---|
| 456 | # NS record
|
---|
| 457 | sub _validate_2 {
|
---|
[467] | 458 | my $self = shift;
|
---|
| 459 | my $dbh = $self->{dbh};
|
---|
[230] | 460 |
|
---|
| 461 | my %args = @_;
|
---|
| 462 |
|
---|
[328] | 463 | # Check that the target of the record is within the parent.
|
---|
| 464 | # Yes, host<->val are mixed up here; can't see a way to avoid it. :(
|
---|
| 465 | if ($args{defrec} eq 'n') {
|
---|
| 466 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
| 467 | if ($args{revrec} eq 'y') {
|
---|
| 468 | my $tmpip = NetAddr::IP->new(${$args{val}});
|
---|
[467] | 469 | my $pname = $self->revName($args{id});
|
---|
[328] | 470 | return ('FAIL',"${$args{val}} not within $pname")
|
---|
[467] | 471 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$tmpip);
|
---|
[328] | 472 | # Sub the returned thing for ZONE? This could get stupid if you have typos...
|
---|
| 473 | ${$args{val}} =~ s/ZONE/$tmpip->address/;
|
---|
| 474 | } else {
|
---|
[467] | 475 | my $pname = $self->domainName($args{id});
|
---|
[328] | 476 | ${$args{host}} = $pname if ${$args{host}} !~ /\.$pname$/;
|
---|
| 477 | }
|
---|
[230] | 478 | } else {
|
---|
[328] | 479 | # Default reverse NS records should always refer to the implied parent
|
---|
| 480 | ${$args{host}} = 'DOMAIN' if $args{revrec} eq 'n';
|
---|
| 481 | ${$args{val}} = 'ZONE' if $args{revrec} eq 'y';
|
---|
[230] | 482 | }
|
---|
| 483 |
|
---|
| 484 | # Let this lie for now. Needs more magic.
|
---|
| 485 | # # Check IP is well-formed, and that it's a v4 address
|
---|
| 486 | # return ('FAIL',"A record must be a valid IPv4 address")
|
---|
| 487 | # unless $addr && !$addr->{isv6};
|
---|
| 488 | # # coerce IP/value to normalized form for storage
|
---|
| 489 | # $$val = $addr->addr;
|
---|
| 490 |
|
---|
[228] | 491 | return ('OK','OK');
|
---|
| 492 | } # done NS record
|
---|
| 493 |
|
---|
| 494 | # CNAME record
|
---|
| 495 | sub _validate_5 {
|
---|
[467] | 496 | my $self = shift;
|
---|
| 497 | my $dbh = $self->{dbh};
|
---|
[230] | 498 |
|
---|
| 499 | my %args = @_;
|
---|
| 500 |
|
---|
| 501 | # Not really true, but these are only useful for delegating smaller-than-/24 IP blocks.
|
---|
| 502 | # This is fundamentally a messy operation and should really just be taken care of by the
|
---|
| 503 | # export process, not manual maintenance of the necessary records.
|
---|
| 504 | return ('FAIL', 'Reverse zones cannot contain CNAME records') if $args{revrec} eq 'y';
|
---|
| 505 |
|
---|
| 506 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 507 | # or the intended parent domain for live records.
|
---|
[467] | 508 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[230] | 509 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 510 |
|
---|
[228] | 511 | return ('OK','OK');
|
---|
| 512 | } # done CNAME record
|
---|
| 513 |
|
---|
| 514 | # SOA record
|
---|
| 515 | sub _validate_6 {
|
---|
[230] | 516 | # Smart monkeys won't stick their fingers in here; we have
|
---|
| 517 | # separate dedicated routines to deal with SOA records.
|
---|
[228] | 518 | return ('OK','OK');
|
---|
| 519 | } # done SOA record
|
---|
| 520 |
|
---|
| 521 | # PTR record
|
---|
| 522 | sub _validate_12 {
|
---|
[467] | 523 | my $self = shift;
|
---|
| 524 | my $dbh = $self->{dbh};
|
---|
[232] | 525 |
|
---|
| 526 | my %args = @_;
|
---|
| 527 |
|
---|
| 528 | if ($args{revrec} eq 'y') {
|
---|
| 529 | if ($args{defrec} eq 'n') {
|
---|
[467] | 530 | return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
| 531 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
[232] | 532 | ${$args{val}} = $args{addr}->addr;
|
---|
| 533 | } else {
|
---|
[234] | 534 | if (${$args{val}} =~ /\./) {
|
---|
| 535 | # looks like a v4 or fragment
|
---|
| 536 | if (${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/) {
|
---|
| 537 | # woo! a complete IP! validate it and normalize, or fail.
|
---|
| 538 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
| 539 | or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
|
---|
| 540 | ${$args{val}} = $args{addr}->addr;
|
---|
| 541 | } else {
|
---|
[249] | 542 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
[234] | 543 | }
|
---|
| 544 | } elsif (${$args{val}} =~ /[a-f:]/) {
|
---|
| 545 | # looks like a v6 or fragment
|
---|
[251] | 546 | ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
|
---|
[234] | 547 | if ($args{addr}) {
|
---|
| 548 | if ($args{addr}->addr =~ /^0/) {
|
---|
[251] | 549 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
[234] | 550 | } else {
|
---|
| 551 | ${$args{val}} = $args{addr}->addr;
|
---|
| 552 | }
|
---|
| 553 | }
|
---|
| 554 | } else {
|
---|
| 555 | # bare number (probably). These could be v4 or v6, so we'll
|
---|
| 556 | # expand on these on creation of a reverse zone.
|
---|
[251] | 557 | ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
|
---|
[234] | 558 | }
|
---|
[517] | 559 | ${$args{host}} =~ s/\.*$/\.$self->{domain}/ if ${$args{host}} !~ /(?:$self->{domain}|ADMINDOMAIN)$/;
|
---|
[232] | 560 | }
|
---|
| 561 |
|
---|
| 562 | # Multiple PTR records do NOT generally do what most people believe they do,
|
---|
| 563 | # and tend to fail in the most awkward way possible. Check and warn.
|
---|
| 564 | # We use $val instead of $addr->addr since we may be in a defrec, and may have eg "ZONE::42" or "ZONE.12"
|
---|
[249] | 565 |
|
---|
| 566 | my @checkvals = (${$args{val}});
|
---|
| 567 | if (${$args{val}} =~ /,/) {
|
---|
| 568 | # push . and :: variants into checkvals if val has ,
|
---|
| 569 | my $tmp;
|
---|
| 570 | ($tmp = ${$args{val}}) =~ s/,/./;
|
---|
| 571 | push @checkvals, $tmp;
|
---|
| 572 | ($tmp = ${$args{val}}) =~ s/,/::/;
|
---|
| 573 | push @checkvals, $tmp;
|
---|
| 574 | }
|
---|
| 575 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ?");
|
---|
| 576 | foreach my $checkme (@checkvals) {
|
---|
[272] | 577 | if ($args{update}) {
|
---|
| 578 | # Record update. There should usually be an existing PTR (the record being updated)
|
---|
| 579 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 580 | " WHERE val = ?", undef, ($checkme)) };
|
---|
| 581 | return ('WARN', "PTR record for $checkme already exists; adding another will probably not do what you want")
|
---|
[273] | 582 | if @ptrs && (!grep /^$args{update}$/, @ptrs);
|
---|
[272] | 583 | } else {
|
---|
| 584 | # New record. Always warn if a PTR exists
|
---|
| 585 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 586 | " WHERE val = ?", undef, ($checkme));
|
---|
| 587 | return ('WARN', "PTR record for $checkme already exists; adding another will probably not do what you want")
|
---|
| 588 | if $ptrcount;
|
---|
| 589 | }
|
---|
[249] | 590 | }
|
---|
[272] | 591 |
|
---|
[232] | 592 | } else {
|
---|
| 593 | # Not absolutely true but only useful if you hack things up for sub-/24 v4 reverse delegations
|
---|
| 594 | # Simpler to just create the reverse zone and grant access for the customer to edit it, and create direct
|
---|
| 595 | # PTR records on export
|
---|
| 596 | return ('FAIL',"Forward zones cannot contain PTR records");
|
---|
| 597 | }
|
---|
| 598 |
|
---|
[228] | 599 | return ('OK','OK');
|
---|
| 600 | } # done PTR record
|
---|
| 601 |
|
---|
| 602 | # MX record
|
---|
| 603 | sub _validate_15 {
|
---|
[467] | 604 | my $self = shift;
|
---|
| 605 | my $dbh = $self->{dbh};
|
---|
[230] | 606 |
|
---|
| 607 | my %args = @_;
|
---|
| 608 |
|
---|
| 609 | # Not absolutely true but WTF use is an MX record for a reverse zone?
|
---|
| 610 | return ('FAIL', 'Reverse zones cannot contain MX records') if $args{revrec} eq 'y';
|
---|
| 611 |
|
---|
| 612 | return ('FAIL', "Distance is required for MX records") unless defined(${$args{dist}});
|
---|
| 613 | ${$args{dist}} =~ s/\s*//g;
|
---|
| 614 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
|
---|
| 615 |
|
---|
| 616 | ${$args{fields}} = "distance,";
|
---|
| 617 | push @{$args{vallist}}, ${$args{dist}};
|
---|
| 618 |
|
---|
| 619 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 620 | # or the intended parent domain for live records.
|
---|
[467] | 621 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[230] | 622 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 623 |
|
---|
[273] | 624 | # hmm.. this might work. except possibly for something pointing to "deadbeef.ca". <g>
|
---|
| 625 | # if ($type == $reverse_typemap{NS} || $type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
|
---|
| 626 | # if ($val =~ /^\s*[\da-f:.]+\s*$/) {
|
---|
| 627 | # return ('FAIL',"$val is not a valid IP address") if !$addr;
|
---|
| 628 | # }
|
---|
| 629 | # }
|
---|
| 630 |
|
---|
[228] | 631 | return ('OK','OK');
|
---|
| 632 | } # done MX record
|
---|
| 633 |
|
---|
| 634 | # TXT record
|
---|
| 635 | sub _validate_16 {
|
---|
[231] | 636 | # Could arguably put a WARN return here on very long (>512) records
|
---|
[228] | 637 | return ('OK','OK');
|
---|
| 638 | } # done TXT record
|
---|
| 639 |
|
---|
| 640 | # RP record
|
---|
| 641 | sub _validate_17 {
|
---|
[231] | 642 | # Probably have to validate these some day
|
---|
[228] | 643 | return ('OK','OK');
|
---|
| 644 | } # done RP record
|
---|
| 645 |
|
---|
| 646 | # AAAA record
|
---|
| 647 | sub _validate_28 {
|
---|
[467] | 648 | my $self = shift;
|
---|
| 649 | my $dbh = $self->{dbh};
|
---|
[229] | 650 |
|
---|
[230] | 651 | my %args = @_;
|
---|
[229] | 652 |
|
---|
[230] | 653 | return ('FAIL', 'Reverse zones cannot contain AAAA records') if $args{revrec} eq 'y';
|
---|
[229] | 654 |
|
---|
| 655 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 656 | # or the intended parent domain for live records.
|
---|
[467] | 657 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[230] | 658 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
[229] | 659 |
|
---|
| 660 | # Check IP is well-formed, and that it's a v6 address
|
---|
[232] | 661 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
|
---|
[230] | 662 | unless $args{addr} && $args{addr}->{isv6};
|
---|
[229] | 663 | # coerce IP/value to normalized form for storage
|
---|
[230] | 664 | ${$args{val}} = $args{addr}->addr;
|
---|
[229] | 665 |
|
---|
[228] | 666 | return ('OK','OK');
|
---|
| 667 | } # done AAAA record
|
---|
| 668 |
|
---|
| 669 | # SRV record
|
---|
| 670 | sub _validate_33 {
|
---|
[467] | 671 | my $self = shift;
|
---|
| 672 | my $dbh = $self->{dbh};
|
---|
[231] | 673 |
|
---|
| 674 | my %args = @_;
|
---|
| 675 |
|
---|
| 676 | # Not absolutely true but WTF use is an SRV record for a reverse zone?
|
---|
| 677 | return ('FAIL', 'Reverse zones cannot contain SRV records') if $args{revrec} eq 'y';
|
---|
| 678 |
|
---|
| 679 | return ('FAIL', "Distance is required for SRV records") unless defined(${$args{dist}});
|
---|
| 680 | ${$args{dist}} =~ s/\s*//g;
|
---|
| 681 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
|
---|
| 682 |
|
---|
| 683 | return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]")
|
---|
| 684 | unless ${$args{host}} =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/;
|
---|
| 685 | return ('FAIL',"Port and weight are required for SRV records")
|
---|
| 686 | unless defined(${$args{weight}}) && defined(${$args{port}});
|
---|
| 687 | ${$args{weight}} =~ s/\s*//g;
|
---|
| 688 | ${$args{port}} =~ s/\s*//g;
|
---|
| 689 |
|
---|
| 690 | return ('FAIL',"Port and weight are required, and must be numeric")
|
---|
| 691 | unless ${$args{weight}} =~ /^\d+$/ && ${$args{port}} =~ /^\d+$/;
|
---|
| 692 |
|
---|
| 693 | ${$args{fields}} = "distance,weight,port,";
|
---|
| 694 | push @{$args{vallist}}, (${$args{dist}}, ${$args{weight}}, ${$args{port}});
|
---|
| 695 |
|
---|
| 696 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 697 | # or the intended parent domain for live records.
|
---|
[467] | 698 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[231] | 699 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 700 |
|
---|
[228] | 701 | return ('OK','OK');
|
---|
| 702 | } # done SRV record
|
---|
| 703 |
|
---|
| 704 | # Now the custom types
|
---|
| 705 |
|
---|
[232] | 706 | # A+PTR record. With a very little bit of magic we can also use this sub to validate AAAA+PTR. Whee!
|
---|
[228] | 707 | sub _validate_65280 {
|
---|
[467] | 708 | my $self = shift;
|
---|
| 709 | my $dbh = $self->{dbh};
|
---|
[232] | 710 |
|
---|
| 711 | my %args = @_;
|
---|
| 712 |
|
---|
| 713 | my $code = 'OK';
|
---|
| 714 | my $msg = 'OK';
|
---|
| 715 |
|
---|
| 716 | if ($args{defrec} eq 'n') {
|
---|
| 717 | # live record; revrec determines whether we validate the PTR or A component first.
|
---|
[233] | 718 |
|
---|
[232] | 719 | if ($args{revrec} eq 'y') {
|
---|
[467] | 720 | ($code,$msg) = $self->_validate_12(%args);
|
---|
[232] | 721 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 722 |
|
---|
[467] | 723 | # check A+PTR is really v4
|
---|
| 724 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
| 725 | if ${$args{rectype}} == 65280 && $args{addr}->{isv6};
|
---|
| 726 | # check AAAA+PTR is really v6
|
---|
| 727 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
|
---|
| 728 | if ${$args{rectype}} == 65281 && !$args{addr}->{isv6};
|
---|
| 729 |
|
---|
[232] | 730 | # Check if the reqested domain exists. If not, coerce the type down to PTR and warn.
|
---|
[467] | 731 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) {
|
---|
[272] | 732 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
| 733 | " as PTR instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
[232] | 734 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
| 735 | $msg = $addmsg if $code eq 'OK';
|
---|
| 736 | ${$args{rectype}} = $reverse_typemap{PTR};
|
---|
| 737 | return ('WARN', $msg);
|
---|
| 738 | }
|
---|
| 739 |
|
---|
[242] | 740 | # Add domain ID to field list and values
|
---|
| 741 | ${$args{fields}} .= "domain_id,";
|
---|
| 742 | push @{$args{vallist}}, ${$args{domid}};
|
---|
| 743 |
|
---|
[232] | 744 | } else {
|
---|
[467] | 745 | ($code,$msg) = $self->_validate_1(%args) if ${$args{rectype}} == 65280;
|
---|
| 746 | ($code,$msg) = $self->_validate_28(%args) if ${$args{rectype}} == 65281;
|
---|
[232] | 747 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 748 |
|
---|
| 749 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
| 750 | # work here since we don't *know* which parent to put it in.
|
---|
[233] | 751 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
[232] | 752 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
| 753 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
| 754 | if (!$revid) {
|
---|
[272] | 755 | $msg = "Record ".($args{update} ? 'updated' : 'added')." as ".(${$args{rectype}} == 65280 ? 'A' : 'AAAA').
|
---|
[232] | 756 | " instead of $typemap{${$args{rectype}}}; reverse zone not found for ${$args{val}}";
|
---|
| 757 | ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
| 758 | return ('WARN', $msg);
|
---|
| 759 | }
|
---|
| 760 |
|
---|
| 761 | # Check for duplicate PTRs. Note we don't have to play games with $code and $msg, because
|
---|
| 762 | # by definition there can't be duplicate PTRs if the reverse zone isn't managed here.
|
---|
[272] | 763 | if ($args{update}) {
|
---|
| 764 | # Record update. There should usually be an existing PTR (the record being updated)
|
---|
| 765 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 766 | " WHERE val = ?", undef, (${$args{val}})) };
|
---|
[273] | 767 | if (@ptrs && (!grep /^$args{update}$/, @ptrs)) {
|
---|
[272] | 768 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
|
---|
| 769 | $code = 'WARN';
|
---|
| 770 | }
|
---|
| 771 | } else {
|
---|
| 772 | # New record. Always warn if a PTR exists
|
---|
| 773 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 774 | " WHERE val = ?", undef, (${$args{val}}));
|
---|
| 775 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want"
|
---|
| 776 | if $ptrcount;
|
---|
| 777 | $code = 'WARN' if $ptrcount;
|
---|
[232] | 778 | }
|
---|
| 779 |
|
---|
[272] | 780 | # my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 781 | # " WHERE val = ?", undef, ${$args{val}});
|
---|
| 782 | # if ($ptrcount) {
|
---|
| 783 | # my $curid = $dbh->selectrow_array("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 784 | # " WHERE val = ?
|
---|
| 785 | # $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
|
---|
| 786 | # $code = 'WARN';
|
---|
| 787 | # }
|
---|
| 788 |
|
---|
[232] | 789 | ${$args{fields}} .= "rdns_id,";
|
---|
| 790 | push @{$args{vallist}}, $revid;
|
---|
| 791 | }
|
---|
| 792 |
|
---|
[233] | 793 | } else { # defrec eq 'y'
|
---|
| 794 | if ($args{revrec} eq 'y') {
|
---|
[467] | 795 | ($code,$msg) = $self->_validate_12(%args);
|
---|
[233] | 796 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 797 | if (${$args{rectype}} == 65280) {
|
---|
| 798 | return ('FAIL',"A+PTR record must be a valid IPv4 address or fragment")
|
---|
| 799 | if ${$args{val}} =~ /:/;
|
---|
[234] | 800 | ${$args{val}} =~ s/^ZONE,/ZONE./; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
[233] | 801 | } elsif (${$args{rectype}} == 65281) {
|
---|
| 802 | return ('FAIL',"AAAA+PTR record must be a valid IPv6 address or fragment")
|
---|
| 803 | if ${$args{val}} =~ /\./;
|
---|
[234] | 804 | ${$args{val}} =~ s/^ZONE,/ZONE::/; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
[233] | 805 | }
|
---|
| 806 | } else {
|
---|
| 807 | # This is easy. I also can't see a real use-case for A/AAAA+PTR in *all* forward
|
---|
| 808 | # domains, since you wouldn't be able to substitute both domain and reverse zone
|
---|
| 809 | # sanely, and you'd end up with guaranteed over-replicated PTR records that would
|
---|
| 810 | # confuse the hell out of pretty much anything that uses them.
|
---|
[234] | 811 | ##fixme: make this a config flag?
|
---|
[233] | 812 | return ('FAIL', "$typemap{${$args{rectype}}} records not allowed in default domains");
|
---|
| 813 | }
|
---|
[232] | 814 | }
|
---|
| 815 |
|
---|
| 816 | return ($code, $msg);
|
---|
[228] | 817 | } # done A+PTR record
|
---|
| 818 |
|
---|
| 819 | # AAAA+PTR record
|
---|
[232] | 820 | # A+PTR above has been magicked to handle AAAA+PTR as well.
|
---|
[228] | 821 | sub _validate_65281 {
|
---|
[232] | 822 | return _validate_65280(@_);
|
---|
[228] | 823 | } # done AAAA+PTR record
|
---|
| 824 |
|
---|
| 825 | # PTR template record
|
---|
| 826 | sub _validate_65282 {
|
---|
[467] | 827 | my $self = shift;
|
---|
| 828 | my $dbh = $self->{dbh};
|
---|
[340] | 829 |
|
---|
| 830 | my %args = @_;
|
---|
| 831 |
|
---|
| 832 | # we're *this* >.< close to being able to just call _validate_12... unfortunately we can't, quite.
|
---|
| 833 | if ($args{revrec} eq 'y') {
|
---|
| 834 | if ($args{defrec} eq 'n') {
|
---|
[467] | 835 | return ('FAIL', "Template block ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
| 836 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
[340] | 837 | ##fixme: warn if $args{val} is not /31 or larger block?
|
---|
| 838 | ${$args{val}} = "$args{addr}";
|
---|
| 839 | } else {
|
---|
| 840 | if (${$args{val}} =~ /\./) {
|
---|
| 841 | # looks like a v4 or fragment
|
---|
| 842 | if (${$args{val}} =~ m|^\d+\.\d+\.\d+\.\d+(?:/\d+)?$|) {
|
---|
| 843 | # woo! a complete IP! validate it and normalize, or fail.
|
---|
| 844 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
| 845 | or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
|
---|
| 846 | ${$args{val}} = "$args{addr}";
|
---|
| 847 | } else {
|
---|
| 848 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
| 849 | }
|
---|
| 850 | } elsif (${$args{val}} =~ /[a-f:]/) {
|
---|
| 851 | # looks like a v6 or fragment
|
---|
| 852 | ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
|
---|
| 853 | if ($args{addr}) {
|
---|
| 854 | if ($args{addr}->addr =~ /^0/) {
|
---|
| 855 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
| 856 | } else {
|
---|
| 857 | ${$args{val}} = "$args{addr}";
|
---|
| 858 | }
|
---|
| 859 | }
|
---|
| 860 | } else {
|
---|
| 861 | # bare number (probably). These could be v4 or v6, so we'll
|
---|
| 862 | # expand on these on creation of a reverse zone.
|
---|
| 863 | ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
|
---|
| 864 | }
|
---|
| 865 | }
|
---|
| 866 | ##fixme: validate %-patterns?
|
---|
| 867 |
|
---|
| 868 | # Unlike single PTR records, there is absolutely no way to sanely support multiple
|
---|
| 869 | # PTR templates for the same block, since they expect to expand to all the individual
|
---|
| 870 | # IPs on export. Nested templates should be supported though.
|
---|
| 871 |
|
---|
| 872 | my @checkvals = (${$args{val}});
|
---|
| 873 | if (${$args{val}} =~ /,/) {
|
---|
| 874 | # push . and :: variants into checkvals if val has ,
|
---|
| 875 | my $tmp;
|
---|
| 876 | ($tmp = ${$args{val}}) =~ s/,/./;
|
---|
| 877 | push @checkvals, $tmp;
|
---|
| 878 | ($tmp = ${$args{val}}) =~ s/,/::/;
|
---|
| 879 | push @checkvals, $tmp;
|
---|
| 880 | }
|
---|
| 881 | ##fixme: this feels wrong still - need to restrict template pseudorecords to One Of Each
|
---|
| 882 | # Per Netblock such that they don't conflict on export
|
---|
| 883 | my $typeck;
|
---|
| 884 | # type 65282 -> ptr template -> look for any of 65282, 65283, 65284
|
---|
| 885 | $typeck = 'type=65283 OR type=65284' if ${$args{rectype}} == 65282;
|
---|
| 886 | # type 65283 -> a+ptr template -> v4 -> look for 65282 or 65283
|
---|
| 887 | $typeck = 'type=65283' if ${$args{rectype}} == 65282;
|
---|
| 888 | # type 65284 -> aaaa+ptr template -> v6 -> look for 65282 or 65284
|
---|
| 889 | $typeck = 'type=65284' if ${$args{rectype}} == 65282;
|
---|
| 890 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ? ".
|
---|
| 891 | "AND (type=65282 OR $typeck)");
|
---|
| 892 | foreach my $checkme (@checkvals) {
|
---|
| 893 | $pcsth->execute($checkme);
|
---|
| 894 | my ($rc) = $pcsth->fetchrow_array;
|
---|
[442] | 895 | return ('FAIL', "Only one template pseudorecord may exist for a given IP block") if $rc > 1;
|
---|
[340] | 896 | }
|
---|
| 897 |
|
---|
| 898 | } else {
|
---|
| 899 | return ('FAIL', "Forward zones cannot contain PTR records");
|
---|
| 900 | }
|
---|
| 901 |
|
---|
[228] | 902 | return ('OK','OK');
|
---|
| 903 | } # done PTR template record
|
---|
| 904 |
|
---|
| 905 | # A+PTR template record
|
---|
| 906 | sub _validate_65283 {
|
---|
[467] | 907 | my $self = shift;
|
---|
| 908 | my $dbh = $self->{dbh};
|
---|
[340] | 909 |
|
---|
| 910 | my %args = @_;
|
---|
| 911 |
|
---|
| 912 | my ($code,$msg) = ('OK','OK');
|
---|
| 913 |
|
---|
| 914 | ##fixme: need to fiddle things since A+PTR templates are acceptable in live
|
---|
| 915 | # forward zones but not default records
|
---|
| 916 | if ($args{defrec} eq 'n') {
|
---|
| 917 | if ($args{revrec} eq 'n') {
|
---|
[467] | 918 | ($code,$msg) = $self->_validate_1(%args) if ${$args{rectype}} == 65280;
|
---|
| 919 | ($code,$msg) = $self->_validate_28(%args) if ${$args{rectype}} == 65281;
|
---|
[340] | 920 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 921 |
|
---|
| 922 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
| 923 | # work here since we don't *know* which parent to put it in.
|
---|
| 924 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
| 925 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
| 926 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
| 927 | # Fail if no match; we can't coerce a PTR-template type down to not include the PTR bit currently.
|
---|
| 928 | if (!$revid) {
|
---|
| 929 | $msg = "Can't ".($args{update} ? 'update' : 'add')." ${$args{host}}/${$args{val}} as ".
|
---|
| 930 | "$typemap{${$args{rectype}}}: reverse zone not found for ${$args{val}}";
|
---|
| 931 | ##fixme: add A template, AAAA template types?
|
---|
| 932 | # ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
| 933 | return ('FAIL', $msg);
|
---|
| 934 | }
|
---|
| 935 |
|
---|
| 936 | # Add reverse zone ID to field list and values
|
---|
| 937 | ${$args{fields}} .= "rdns_id,";
|
---|
| 938 | push @{$args{vallist}}, $revid;
|
---|
| 939 |
|
---|
| 940 | } else {
|
---|
[467] | 941 | return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
| 942 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
[340] | 943 | ${$args{val}} = "$args{addr}";
|
---|
| 944 |
|
---|
[467] | 945 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) {
|
---|
[340] | 946 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
| 947 | " as PTR template instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
| 948 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
| 949 | $msg = $addmsg if $code eq 'OK';
|
---|
| 950 | ${$args{rectype}} = 65282;
|
---|
| 951 | return ('WARN', $msg);
|
---|
| 952 | }
|
---|
| 953 |
|
---|
| 954 | # Add domain ID to field list and values
|
---|
| 955 | ${$args{fields}} .= "domain_id,";
|
---|
| 956 | push @{$args{vallist}}, ${$args{domid}};
|
---|
| 957 | }
|
---|
| 958 |
|
---|
| 959 | } else {
|
---|
[467] | 960 | my ($code,$msg) = $self->_validate_65282(%args);
|
---|
[340] | 961 | return ($code, $msg) if $code eq 'FAIL';
|
---|
| 962 | # get domain, check against ${$args{name}}
|
---|
| 963 | }
|
---|
| 964 |
|
---|
[228] | 965 | return ('OK','OK');
|
---|
| 966 | } # done AAAA+PTR template record
|
---|
| 967 |
|
---|
| 968 | # AAAA+PTR template record
|
---|
| 969 | sub _validate_65284 {
|
---|
| 970 | return ('OK','OK');
|
---|
| 971 | } # done AAAA+PTR template record
|
---|
| 972 |
|
---|
[342] | 973 | # Delegation record
|
---|
[345] | 974 | # This is essentially a specialized clone of the NS record, primarily useful
|
---|
| 975 | # for delegating IPv4 sub-/24 reverse blocks
|
---|
[342] | 976 | sub _validate_65285 {
|
---|
[467] | 977 | my $self = shift;
|
---|
| 978 | my $dbh = $self->{dbh};
|
---|
[345] | 979 |
|
---|
| 980 | my %args = @_;
|
---|
| 981 |
|
---|
| 982 | # Almost, but not quite, identical to NS record validation.
|
---|
| 983 |
|
---|
| 984 | # Check that the target of the record is within the parent.
|
---|
| 985 | # Yes, host<->val are mixed up here; can't see a way to avoid it. :(
|
---|
| 986 | if ($args{defrec} eq 'n') {
|
---|
| 987 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
| 988 | if ($args{revrec} eq 'y') {
|
---|
| 989 | my $tmpip = NetAddr::IP->new(${$args{val}});
|
---|
[467] | 990 | my $pname = $self->revName($args{id});
|
---|
[345] | 991 | return ('FAIL',"${$args{val}} not within $pname")
|
---|
[467] | 992 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$tmpip);
|
---|
[345] | 993 | # Normalize
|
---|
| 994 | ${$args{val}} = "$tmpip";
|
---|
| 995 | } else {
|
---|
[467] | 996 | my $pname = $self->domainName($args{id});
|
---|
[345] | 997 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 998 | }
|
---|
| 999 | } else {
|
---|
| 1000 | return ('FAIL',"Delegation records are not permitted in default record sets");
|
---|
| 1001 | }
|
---|
[342] | 1002 | return ('OK','OK');
|
---|
| 1003 | }
|
---|
[228] | 1004 |
|
---|
[342] | 1005 |
|
---|
[265] | 1006 | ##
|
---|
| 1007 | ## Record data substitution subs
|
---|
| 1008 | ##
|
---|
[228] | 1009 |
|
---|
[298] | 1010 | # Replace ZONE in hostname, or create (most of) the actual proper zone name
|
---|
[265] | 1011 | sub _ZONE {
|
---|
| 1012 | my $zone = shift;
|
---|
| 1013 | my $string = shift;
|
---|
| 1014 | my $fr = shift || 'f'; # flag for forward/reverse order? nb: ignored for IP
|
---|
[298] | 1015 | my $sep = shift || '-'; # Separator character - unlikely we'll ever need more than . or -
|
---|
[265] | 1016 |
|
---|
[298] | 1017 | my $prefix;
|
---|
[265] | 1018 |
|
---|
| 1019 | $string =~ s/,/./ if !$zone->{isv6};
|
---|
| 1020 | $string =~ s/,/::/ if $zone->{isv6};
|
---|
| 1021 |
|
---|
[298] | 1022 | # Subbing ZONE in the host. We need to properly ID the netblock range
|
---|
| 1023 | # The subbed text should have "network IP with trailing zeros stripped" for
|
---|
| 1024 | # blocks lined up on octet (for v4) or hex-quad (for v6) boundaries
|
---|
| 1025 | # For blocks that do NOT line up on these boundaries, we take the most
|
---|
| 1026 | # significant octet or 16-bit chunk of the "broadcast" IP and append it
|
---|
| 1027 | # after a double-dash
|
---|
| 1028 | # ie:
|
---|
| 1029 | # 8.0.0.0/6 -> 8.0.0.0 -> 11.255.255.255; sub should be 8--11
|
---|
| 1030 | # 10.0.0.0/12 -> 10.0.0.0 -> 10.0.0.0 -> 10.15.255.255; sub should be 10-0--15
|
---|
| 1031 | # 192.168.4.0/22 -> 192.168.4.0 -> 192.168.7.255; sub should be 192-168-4--7
|
---|
| 1032 | # 192.168.0.8/29 -> 192.168.0.8 -> 192.168.0.15; sub should be 192-168-0-8--15
|
---|
| 1033 | # Similar for v6
|
---|
[265] | 1034 |
|
---|
[298] | 1035 | if (!$zone->{isv6}) { # IPv4
|
---|
| 1036 |
|
---|
| 1037 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
| 1038 | # a funky subnet that had host bits set.
|
---|
| 1039 | my $bc = $zone->broadcast->addr;
|
---|
| 1040 |
|
---|
| 1041 | if ($zone->masklen > 24) {
|
---|
| 1042 | $bc =~ s/^\d+\.\d+\.\d+\.//;
|
---|
| 1043 | } elsif ($zone->masklen > 16) {
|
---|
| 1044 | $prefix =~ s/\.0$//;
|
---|
| 1045 | $bc =~ s/^\d+\.\d+\.//;
|
---|
| 1046 | } elsif ($zone->masklen > 8) {
|
---|
| 1047 | $bc =~ s/^\d+\.//;
|
---|
| 1048 | $prefix =~ s/\.0\.0$//;
|
---|
| 1049 | } else {
|
---|
| 1050 | $prefix =~ s/\.0\.0\.0$//;
|
---|
| 1051 | }
|
---|
| 1052 | if ($zone->masklen % 8) {
|
---|
| 1053 | $bc =~ s/(\.255)+$//;
|
---|
| 1054 | $prefix .= "--$bc"; #"--".zone->masklen; # use range or mask length?
|
---|
| 1055 | }
|
---|
| 1056 | if ($fr eq 'f') {
|
---|
| 1057 | $prefix =~ s/\.+/$sep/g;
|
---|
| 1058 | } else {
|
---|
| 1059 | $prefix = join($sep, reverse(split(/\./, $prefix)));
|
---|
| 1060 | }
|
---|
| 1061 |
|
---|
| 1062 | } else { # IPv6
|
---|
| 1063 |
|
---|
| 1064 | if ($fr eq 'f') {
|
---|
| 1065 |
|
---|
| 1066 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
| 1067 | # a funky subnet that had host bits set.
|
---|
[265] | 1068 | my $bc = $zone->broadcast->addr;
|
---|
| 1069 | if (($zone->masklen % 16) != 0) {
|
---|
[298] | 1070 | # Strip trailing :0 off $prefix, and :ffff off the broadcast IP
|
---|
| 1071 | for (my $i=0; $i<(7-int($zone->masklen / 16)); $i++) {
|
---|
| 1072 | $prefix =~ s/:0$//;
|
---|
| 1073 | $bc =~ s/:ffff$//;
|
---|
| 1074 | }
|
---|
| 1075 | # Strip the leading 16-bit chunks off the front of the broadcast IP
|
---|
| 1076 | $bc =~ s/^([a-f0-9]+:)+//;
|
---|
| 1077 | # Append the remaining 16-bit chunk to the prefix after "--"
|
---|
| 1078 | $prefix .= "--$bc";
|
---|
[265] | 1079 | } else {
|
---|
[298] | 1080 | # Strip off :0 from the end until we reach the netblock length.
|
---|
| 1081 | for (my $i=0; $i<(8-$zone->masklen / 16); $i++) {
|
---|
[265] | 1082 | $prefix =~ s/:0$//;
|
---|
[298] | 1083 | }
|
---|
[265] | 1084 | }
|
---|
[298] | 1085 | # Actually deal with the separator
|
---|
| 1086 | $prefix =~ s/:/$sep/g;
|
---|
| 1087 |
|
---|
| 1088 | } else { # $fr eq 'f'
|
---|
| 1089 |
|
---|
| 1090 | $prefix = $zone->network->full; # Just In Case someone managed to slip in
|
---|
| 1091 | # a funky subnet that had host bits set.
|
---|
| 1092 | my $bc = $zone->broadcast->full;
|
---|
| 1093 | $prefix =~ s/://g; # clean these out since they're not spaced right for this case
|
---|
| 1094 | $bc =~ s/://g;
|
---|
| 1095 | # Strip trailing 0 off $prefix, and f off the broadcast IP, to match the mask length
|
---|
| 1096 | for (my $i=0; $i<(31-int($zone->masklen / 4)); $i++) {
|
---|
| 1097 | $prefix =~ s/0$//;
|
---|
| 1098 | $bc =~ s/f$//;
|
---|
| 1099 | }
|
---|
| 1100 | # Split and reverse the order of the nibbles in the network/broadcast IPs
|
---|
[332] | 1101 | # trim another 0 for nibble-aligned blocks first, but only if we really have a block, not an IP
|
---|
| 1102 | $prefix =~ s/0$// if $zone->masklen % 4 == 0 && $zone->masklen != 128;
|
---|
[298] | 1103 | my @nbits = reverse split //, $prefix;
|
---|
| 1104 | my @bbits = reverse split //, $bc;
|
---|
| 1105 | # Handle the sub-nibble case. Eww. I feel dirty supporting this...
|
---|
| 1106 | $nbits[0] = "$nbits[0]-$bbits[0]" if ($zone->masklen % 4) != 0;
|
---|
| 1107 | # Glue it back together
|
---|
| 1108 | $prefix = join($sep, @nbits);
|
---|
| 1109 |
|
---|
| 1110 | } # $fr ne 'f'
|
---|
| 1111 |
|
---|
| 1112 | } # $zone->{isv6}
|
---|
| 1113 |
|
---|
| 1114 | # Do the substitution, finally
|
---|
| 1115 | $string =~ s/ZONE/$prefix/;
|
---|
| 1116 | $string =~ s/--/-/ if $sep ne '-'; # - as separator needs extra help for sub-octet v4 netblocks
|
---|
| 1117 | return $string;
|
---|
| 1118 | } # done _ZONE()
|
---|
| 1119 |
|
---|
| 1120 | # Not quite a substitution sub, but placed here as it's basically the inverse of above;
|
---|
| 1121 | # given the .arpa zone name, return the CIDR netblock the zone is for.
|
---|
[304] | 1122 | # Supports v4 non-octet/non-classful netblocks as per the method outlined in the Grasshopper Book (2nd Ed p217-218)
|
---|
[298] | 1123 | # Does NOT support non-quad v6 netblocks via the same scheme; it shouldn't ever be necessary.
|
---|
| 1124 | # Takes a nominal .arpa zone name, returns a success code and NetAddr::IP, or a fail code and message
|
---|
| 1125 | sub _zone2cidr {
|
---|
| 1126 | my $zone = shift;
|
---|
| 1127 |
|
---|
| 1128 | my $cidr;
|
---|
[301] | 1129 | my $tmpcidr;
|
---|
| 1130 | my $warnmsg = '';
|
---|
[298] | 1131 |
|
---|
| 1132 | if ($zone =~ /\.in-addr\.arpa\.?$/) {
|
---|
| 1133 | # v4 revzone, formal zone name type
|
---|
| 1134 | my $tmpzone = $zone;
|
---|
| 1135 | $tmpzone =~ s/\.in-addr\.arpa\.?//;
|
---|
[301] | 1136 | return ('FAIL', "Non-numerics in apparent IPv4 reverse zone name") if $tmpzone !~ /^(?:\d+-)?[\d\.]+$/;
|
---|
[298] | 1137 |
|
---|
| 1138 | # Snag the octet pieces
|
---|
| 1139 | my @octs = split /\./, $tmpzone;
|
---|
| 1140 |
|
---|
| 1141 | # Map result of a range manipulation to a mask length change. Cheaper than finding the 2-root of $octets[0]+1.
|
---|
[304] | 1142 | # Note we will not support /31 blocks, mostly due to issues telling "24-31" -> .24/29 apart from
|
---|
| 1143 | # "24-31" -> .24/31", with a litte bit of "/31 is icky".
|
---|
| 1144 | my %maskmap = ( 3 => 2, 7 => 3, 15 => 4, 31 => 5, 63 => 6, 127 => 7,
|
---|
| 1145 | 30 => 2, 29 => 3, 28 => 4, 27 => 5, 26 => 6, 25 => 7
|
---|
| 1146 | );
|
---|
[298] | 1147 |
|
---|
| 1148 | # Handle "range" blocks, eg, 80-83.168.192.in-addr.arpa (192.168.80.0/22)
|
---|
| 1149 | # Need to take the size of the range to offset the basic octet-based mask length,
|
---|
| 1150 | # and make sure the first number in the range gets used as the network address for the block
|
---|
[304] | 1151 | # Alternate form: The second number is actually the real netmask, not the end of the range.
|
---|
[298] | 1152 | my $masklen = 0;
|
---|
[307] | 1153 | if ($octs[0] =~ /^((\d+)-(\d+))$/) { # take the range...
|
---|
| 1154 | if (24 < $3 && $3 < 31) {
|
---|
[304] | 1155 | # we have a real netmask
|
---|
[307] | 1156 | $masklen = -$maskmap{$3};
|
---|
[304] | 1157 | } else {
|
---|
| 1158 | # we have a range. NB: only real CIDR ranges are supported
|
---|
[307] | 1159 | $masklen -= $maskmap{-(eval $1)}; # find the mask base...
|
---|
[304] | 1160 | }
|
---|
[307] | 1161 | $octs[0] = $2; # set the base octet of the range...
|
---|
[265] | 1162 | }
|
---|
[298] | 1163 | @octs = reverse @octs; # We can reverse the octet pieces now that we've extracted and munged any ranges
|
---|
[265] | 1164 |
|
---|
[304] | 1165 | # arguably we should only allow sub-octet range/mask in-addr.arpa
|
---|
| 1166 | # specifications in the least significant octet, but the code is
|
---|
| 1167 | # simpler if we deal with sub-octet delegations at any level.
|
---|
| 1168 |
|
---|
[298] | 1169 | # Now we find the "true" mask with the aid of the "base" calculated above
|
---|
| 1170 | if ($#octs == 0) {
|
---|
| 1171 | $masklen += 8;
|
---|
| 1172 | $tmpcidr = "$octs[0].0.0.0/$masklen"; # really hope we don't see one of these very often.
|
---|
| 1173 | } elsif ($#octs == 1) {
|
---|
| 1174 | $masklen += 16;
|
---|
| 1175 | $tmpcidr = "$octs[0].$octs[1].0.0/$masklen";
|
---|
| 1176 | } elsif ($#octs == 2) {
|
---|
| 1177 | $masklen += 24;
|
---|
| 1178 | $tmpcidr = "$octs[0].$octs[1].$octs[2].0/$masklen";
|
---|
[265] | 1179 | } else {
|
---|
[298] | 1180 | $masklen += 32;
|
---|
| 1181 | $tmpcidr = "$octs[0].$octs[1].$octs[2].$octs[3]/$masklen";
|
---|
[265] | 1182 | }
|
---|
| 1183 |
|
---|
[298] | 1184 | } elsif ($zone =~ /\.ip6\.arpa$/) {
|
---|
| 1185 | # v6 revzone, formal zone name type
|
---|
| 1186 | my $tmpzone = $zone;
|
---|
| 1187 | $tmpzone =~ s/\.ip6\.arpa\.?//;
|
---|
[301] | 1188 | ##fixme: if-n-when we decide we can support sub-nibble v6 zone names, we'll need to change this segment
|
---|
| 1189 | return ('FAIL', "Non-hexadecimals in apparent IPv6 reverse zone name") if $tmpzone !~ /^[a-fA-F\d\.]+$/;
|
---|
[298] | 1190 | my @quads = reverse(split(/\./, $tmpzone));
|
---|
| 1191 | $warnmsg .= "Apparent sub-/64 IPv6 reverse zone\n" if $#quads > 15;
|
---|
| 1192 | my $nc;
|
---|
| 1193 | foreach (@quads) {
|
---|
[301] | 1194 | $tmpcidr .= $_;
|
---|
| 1195 | $tmpcidr .= ":" if ++$nc % 4 == 0;
|
---|
[298] | 1196 | }
|
---|
| 1197 | my $nq = 1 if $nc % 4 != 0;
|
---|
| 1198 | my $mask = $nc * 4; # need to do this here because we probably increment it below
|
---|
| 1199 | while ($nc++ % 4 != 0) {
|
---|
[301] | 1200 | $tmpcidr .= "0";
|
---|
[298] | 1201 | }
|
---|
[301] | 1202 | $tmpcidr .= ($nq ? '::' : ':')."/$mask";
|
---|
[298] | 1203 | }
|
---|
[301] | 1204 |
|
---|
| 1205 | # Just to be sure, use NetAddr::IP to validate. Saves a lot of nasty regex watching for valid octet values.
|
---|
| 1206 | return ('FAIL', "Invalid zone $zone (apparent netblock $tmpcidr)")
|
---|
| 1207 | unless $cidr = NetAddr::IP->new($tmpcidr);
|
---|
| 1208 |
|
---|
| 1209 | if ($warnmsg) {
|
---|
| 1210 | $errstr = $warnmsg;
|
---|
| 1211 | return ('WARN', $cidr);
|
---|
| 1212 | }
|
---|
| 1213 | return ('OK', $cidr);
|
---|
[298] | 1214 | } # done _zone2cidr()
|
---|
[265] | 1215 |
|
---|
[337] | 1216 | # Record template %-parameter expansion, IPv4. Note that IPv6 doesn't
|
---|
| 1217 | # really have a sane way to handle this type of expansion at the moment
|
---|
| 1218 | # due to the size of the address space.
|
---|
| 1219 | # Takes a reference to a template string to be expanded, and an IP to use in the replacement.
|
---|
| 1220 | sub _template4_expand {
|
---|
| 1221 | my $tmpl = shift;
|
---|
| 1222 | my $ip = shift;
|
---|
[298] | 1223 |
|
---|
[337] | 1224 | my @ipparts = split /\./, $ip;
|
---|
| 1225 | my @iphex;
|
---|
| 1226 | my @ippad;
|
---|
| 1227 | for (@ipparts) {
|
---|
| 1228 | push @iphex, sprintf("%x", $_);
|
---|
[443] | 1229 | push @ippad, sprintf("%0.3u", $_);
|
---|
[337] | 1230 | }
|
---|
| 1231 |
|
---|
| 1232 | # IP substitutions in template records:
|
---|
| 1233 | #major patterns:
|
---|
| 1234 | #dashed IP, forward and reverse
|
---|
[532] | 1235 | #underscoreed IP, forward and reverse
|
---|
[337] | 1236 | #dotted IP, forward and reverse (even if forward is... dumb)
|
---|
[532] | 1237 | # -> %r for reverse, %i for forward, leading -, _, or . to indicate separator, defaults to -
|
---|
[337] | 1238 | # %r or %-r => %4d-%3d-%2d-%1d
|
---|
[532] | 1239 | # %_r => %4d_%3d_%2d_%1d
|
---|
[337] | 1240 | # %.r => %4d.%3d.%2d.%1d
|
---|
| 1241 | # %i or %-i => %1d-%2d-%3d-%4d
|
---|
[532] | 1242 | # %_i => %1d_%2d_%3d_%4d
|
---|
[337] | 1243 | # %.i => %1d.%2d.%3d.%4d
|
---|
| 1244 | $$tmpl =~ s/\%r/\%4d-\%3d-\%2d-\%1d/g;
|
---|
[532] | 1245 | $$tmpl =~ s/\%([-._])r/\%4d$1\%3d$1\%2d$1\%1d/g;
|
---|
[337] | 1246 | $$tmpl =~ s/\%i/\%1d-\%2d-\%3d-\%4d/g;
|
---|
[532] | 1247 | $$tmpl =~ s/\%([-._])i/\%1d$1\%2d$1\%3d$1\%4d/g;
|
---|
[337] | 1248 |
|
---|
| 1249 | #hex-coded IP
|
---|
| 1250 | # %h
|
---|
| 1251 | $$tmpl =~ s/\%h/$iphex[0]$iphex[1]$iphex[2]$iphex[3]/g;
|
---|
| 1252 |
|
---|
| 1253 | #IP as decimal-coded 32-bit value
|
---|
| 1254 | # %d
|
---|
| 1255 | my $iptmp = $ipparts[0]*256*256*256 + $ipparts[1]*256*256 + $ipparts[2]*256 + $ipparts[3];
|
---|
| 1256 | $$tmpl =~ s/\%d/$iptmp/g;
|
---|
| 1257 |
|
---|
| 1258 | #minor patterns (per-octet)
|
---|
| 1259 | # %[1234][dh0]
|
---|
| 1260 | #octet
|
---|
| 1261 | #hex-coded octet
|
---|
| 1262 | #0-padded octet
|
---|
| 1263 | $$tmpl =~ s/\%([1234])d/$ipparts[$1-1]/g;
|
---|
| 1264 | $$tmpl =~ s/\%([1234])h/$iphex[$1-1]/g;
|
---|
[443] | 1265 | $$tmpl =~ s/\%([1234])0/$ippad[$1-1]/g;
|
---|
[337] | 1266 | } # _template4_expand()
|
---|
| 1267 |
|
---|
[532] | 1268 | # Broad syntactic check on the hostname. Checks for valid characters, correctly-expandable template patterns.
|
---|
| 1269 | # Takes the hostname, type, and live/default and forward/reverse flags
|
---|
| 1270 | # Returns true/false, sets errstr on failures
|
---|
| 1271 | sub _check_hostname_form {
|
---|
| 1272 | my ($hname,$rectype,$defrec,$revrec) = @_;
|
---|
[337] | 1273 |
|
---|
[532] | 1274 | if ($hname =~ /\%/ && ($rectype == 65282 || $rectype == 65283) ) {
|
---|
| 1275 | my $tmphost = $hname;
|
---|
| 1276 | # we don't actually need to test with the real IP passed; that saves a bit of fiddling.
|
---|
| 1277 | _template4_expand(\$tmphost, '10.10.10.10');
|
---|
| 1278 | if ($tmphost =~ /\%/) {
|
---|
| 1279 | $errstr = "Invalid template $hname";
|
---|
| 1280 | return;
|
---|
| 1281 | }
|
---|
| 1282 | } elsif ($revrec eq 'y') {
|
---|
| 1283 | # Reverse zones don't support @ in hostnames
|
---|
| 1284 | # Also skip failure on revzone TXT records; the hostname contains the TXT content in that case.
|
---|
| 1285 | if ($rectype != $reverse_typemap{TXT} && lc($hname) !~ /^[0-9a-z_.-]+$/) {
|
---|
| 1286 | $errstr = "Hostnames may not contain anything other than (0-9 a-z . _)";
|
---|
| 1287 | return;
|
---|
| 1288 | }
|
---|
| 1289 | } else {
|
---|
| 1290 | if (lc($hname) !~ /^(?:[0-9a-z_.-]+|@)$/) {
|
---|
| 1291 | # Don't mention @, because it would be far too wordy to explain the nuance of @
|
---|
| 1292 | $errstr = "Hostnames may not contain anything other than (0-9 a-z . _)";
|
---|
| 1293 | return;
|
---|
| 1294 | }
|
---|
| 1295 | }
|
---|
| 1296 | return 1;
|
---|
| 1297 | } # _check_hostname_form()
|
---|
| 1298 |
|
---|
| 1299 |
|
---|
[228] | 1300 | ##
|
---|
[2] | 1301 | ## Initialization and cleanup subs
|
---|
| 1302 | ##
|
---|
| 1303 |
|
---|
[128] | 1304 | ## DNSDB::__cfgload()
|
---|
| 1305 | # Private sub to parse a config file and load it into %config
|
---|
[517] | 1306 | # Takes a filename and a hashref to put the parsed entries in
|
---|
[128] | 1307 | sub __cfgload {
|
---|
| 1308 | $errstr = '';
|
---|
| 1309 | my $cfgfile = shift;
|
---|
[517] | 1310 | my $cfg = shift;
|
---|
[131] | 1311 |
|
---|
[128] | 1312 | if (open CFG, "<$cfgfile") {
|
---|
| 1313 | while (<CFG>) {
|
---|
| 1314 | chomp;
|
---|
| 1315 | s/^\s*//;
|
---|
| 1316 | next if /^#/;
|
---|
| 1317 | next if /^$/;
|
---|
| 1318 | # hmm. more complex bits in this file might require [heading] headers, maybe?
|
---|
| 1319 | # $mode = $1 if /^\[(a-z)+]/;
|
---|
| 1320 | # DB connect info
|
---|
[517] | 1321 | $cfg->{dbname} = $1 if /^dbname\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1322 | $cfg->{dbuser} = $1 if /^dbuser\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1323 | $cfg->{dbpass} = $1 if /^dbpass\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1324 | $cfg->{dbhost} = $1 if /^dbhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
[128] | 1325 | # Mail settings
|
---|
[517] | 1326 | $cfg->{mailhost} = $1 if /^mailhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1327 | $cfg->{mailnotify} = $1 if /^mailnotify\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
| 1328 | $cfg->{mailsender} = $1 if /^mailsender\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
| 1329 | $cfg->{mailname} = $1 if /^mailname\s*=\s*([a-z0-9\s_.-]+)/i;
|
---|
| 1330 | $cfg->{orgname} = $1 if /^orgname\s*=\s*([a-z0-9\s_.,'-]+)/i;
|
---|
| 1331 | $cfg->{domain} = $1 if /^domain\s*=\s*([a-z0-9_.-]+)/i;
|
---|
[163] | 1332 | # session - note this is fed directly to CGI::Session
|
---|
[517] | 1333 | $cfg->{timeout} = $1 if /^[tT][iI][mM][eE][oO][uU][tT]\s*=\s*(\d+[smhdwMy]?)/;
|
---|
| 1334 | $cfg->{sessiondir} = $1 if m{^sessiondir\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
[201] | 1335 | # misc
|
---|
[517] | 1336 | $cfg->{log_failures} = $1 if /^log_failures\s*=\s*([a-z01]+)/i;
|
---|
| 1337 | $cfg->{perpage} = $1 if /^perpage\s*=\s*(\d+)/i;
|
---|
| 1338 | $cfg->{exportcache} = $1 if m{^exportcache\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
[542] | 1339 | $cfg->{lowercase} = $1 if /^lowercase\s*=\s*([a-z01]+)/i;
|
---|
[517] | 1340 | # not supported in dns.cgi yet
|
---|
| 1341 | # $cfg->{templatedir} = $1 if m{^templatedir\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
| 1342 | # $cfg->{templateoverride} = $1 if m{^templateoverride\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
[400] | 1343 | # RPC options
|
---|
[517] | 1344 | $cfg->{rpcmode} = $1 if /^rpc_mode\s*=\s*(socket|HTTP|XMLRPC)\s*$/i;
|
---|
| 1345 | $cfg->{maxfcgi} = $1 if /^max_fcgi_requests\s*=\s*(\d+)\s*$/i;
|
---|
[524] | 1346 | $cfg->{force_refresh} = $1 if /^force_refresh\s*=\s*([a-z01]+)/i;
|
---|
[465] | 1347 | if (my ($tmp) = /^rpc_iplist\s*=\s*(.+)/i) {
|
---|
| 1348 | my @ips = split /[,\s]+/, $tmp;
|
---|
| 1349 | my $rpcsys = shift @ips;
|
---|
[517] | 1350 | push @{$cfg->{rpcacl}{$rpcsys}}, @ips;
|
---|
[400] | 1351 | }
|
---|
[128] | 1352 | }
|
---|
| 1353 | close CFG;
|
---|
| 1354 | } else {
|
---|
[517] | 1355 | $errstr = "Couldn't load configuration file $cfgfile: $!";
|
---|
[128] | 1356 | return;
|
---|
| 1357 | }
|
---|
| 1358 | return 1;
|
---|
| 1359 | } # end __cfgload()
|
---|
| 1360 |
|
---|
| 1361 |
|
---|
[2] | 1362 | ## DNSDB::connectDB()
|
---|
| 1363 | # Creates connection to DNS database.
|
---|
| 1364 | # Requires the database name, username, and password.
|
---|
[465] | 1365 | # Returns a handle to the db or undef on failure.
|
---|
[2] | 1366 | # Set up for a PostgreSQL db; could be any transactional DBMS with the
|
---|
| 1367 | # right changes.
|
---|
[465] | 1368 | # Called by new(); not intended to be called publicly.
|
---|
[2] | 1369 | sub connectDB {
|
---|
| 1370 | $errstr = '';
|
---|
[15] | 1371 | my $dbname = shift;
|
---|
| 1372 | my $user = shift;
|
---|
| 1373 | my $pass = shift;
|
---|
[2] | 1374 | my $dbh;
|
---|
| 1375 | my $DSN = "DBI:Pg:dbname=$dbname";
|
---|
| 1376 |
|
---|
| 1377 | my $host = shift;
|
---|
| 1378 | $DSN .= ";host=$host" if $host;
|
---|
| 1379 |
|
---|
| 1380 | # Note that we want to autocommit by default, and we will turn it off locally as necessary.
|
---|
| 1381 | # We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
|
---|
| 1382 | $dbh = DBI->connect($DSN, $user, $pass, {
|
---|
| 1383 | AutoCommit => 1,
|
---|
| 1384 | PrintError => 0
|
---|
[465] | 1385 | });
|
---|
| 1386 | if (!$dbh) {
|
---|
| 1387 | $errstr = $DBI::errstr;
|
---|
| 1388 | return;
|
---|
| 1389 | }
|
---|
| 1390 | #) if(!$dbh);
|
---|
[2] | 1391 |
|
---|
[465] | 1392 | local $dbh->{RaiseError} = 1;
|
---|
| 1393 |
|
---|
| 1394 | eval {
|
---|
[212] | 1395 | ##fixme: initialize the DB if we can't find the table (since, by definition, there's
|
---|
| 1396 | # nothing there if we can't select from it...)
|
---|
[465] | 1397 | my $tblsth = $dbh->prepare("SELECT count(*) FROM pg_catalog.pg_class WHERE relkind='r' AND relname=?");
|
---|
| 1398 | my ($tblcount) = $dbh->selectrow_array($tblsth, undef, ('misc'));
|
---|
| 1399 | # return (undef,$DBI::errstr) if $dbh->err;
|
---|
[212] | 1400 |
|
---|
| 1401 | #if ($tblcount == 0) {
|
---|
| 1402 | # # create tables one at a time, checking for each.
|
---|
| 1403 | # return (undef, "check table misc missing");
|
---|
| 1404 | #}
|
---|
| 1405 |
|
---|
| 1406 | # Return here if we can't select.
|
---|
| 1407 | # This should retrieve the dbversion key.
|
---|
[465] | 1408 | my $sth = $dbh->prepare("SELECT key,value FROM misc WHERE misc_id=1");
|
---|
| 1409 | $sth->execute();
|
---|
| 1410 | # return (undef,$DBI::errstr) if ($sth->err);
|
---|
[2] | 1411 |
|
---|
[212] | 1412 | ##fixme: do stuff to the DB on version mismatch
|
---|
| 1413 | # x.y series should upgrade on $DNSDB::VERSION > misc(key=>version)
|
---|
| 1414 | # DB should be downward-compatible; column defaults should give sane (if possibly
|
---|
| 1415 | # useless-and-needs-help) values in columns an older software stack doesn't know about.
|
---|
| 1416 |
|
---|
[2] | 1417 | # See if the select returned anything (or null data). This should
|
---|
| 1418 | # succeed if the select executed, but...
|
---|
[465] | 1419 | $sth->fetchrow();
|
---|
| 1420 | # return (undef,$DBI::errstr) if ($sth->err);
|
---|
[2] | 1421 |
|
---|
[465] | 1422 | $sth->finish;
|
---|
[2] | 1423 |
|
---|
[465] | 1424 | }; # wrapped DB checks
|
---|
| 1425 | if ($@) {
|
---|
| 1426 | $errstr = $@;
|
---|
| 1427 | return;
|
---|
| 1428 | }
|
---|
| 1429 |
|
---|
[2] | 1430 | # If we get here, we should be OK.
|
---|
[465] | 1431 | return $dbh;
|
---|
[2] | 1432 | } # end connectDB
|
---|
| 1433 |
|
---|
| 1434 |
|
---|
| 1435 | ## DNSDB::finish()
|
---|
| 1436 | # Cleans up after database handles and so on.
|
---|
| 1437 | # Requires a database handle
|
---|
| 1438 | sub finish {
|
---|
[465] | 1439 | my $self = shift;
|
---|
| 1440 | $self->{dbh}->disconnect;
|
---|
[2] | 1441 | } # end finish
|
---|
| 1442 |
|
---|
| 1443 |
|
---|
| 1444 | ## DNSDB::initGlobals()
|
---|
| 1445 | # Initialize global variables
|
---|
| 1446 | # NB: this does NOT include web-specific session variables!
|
---|
| 1447 | sub initGlobals {
|
---|
[465] | 1448 | my $self = shift;
|
---|
| 1449 | my $dbh = $self->{dbh};
|
---|
[2] | 1450 |
|
---|
[208] | 1451 | # load record types from database
|
---|
[228] | 1452 | my $sth = $dbh->prepare("SELECT val,name,stdflag FROM rectypes");
|
---|
[2] | 1453 | $sth->execute;
|
---|
[228] | 1454 | while (my ($recval,$recname,$stdflag) = $sth->fetchrow_array()) {
|
---|
[2] | 1455 | $typemap{$recval} = $recname;
|
---|
| 1456 | $reverse_typemap{$recname} = $recval;
|
---|
[228] | 1457 | # now we fill the record validation function hash
|
---|
| 1458 | if ($stdflag < 5) {
|
---|
| 1459 | my $fn = "_validate_$recval";
|
---|
| 1460 | $validators{$recval} = \&$fn;
|
---|
| 1461 | } else {
|
---|
| 1462 | my $fn = "sub { return ('FAIL','Type $recval ($recname) not supported'); }";
|
---|
| 1463 | $validators{$recval} = eval $fn;
|
---|
| 1464 | }
|
---|
[2] | 1465 | }
|
---|
| 1466 | } # end initGlobals
|
---|
| 1467 |
|
---|
| 1468 |
|
---|
[401] | 1469 | ## DNSDB::initRPC()
|
---|
[469] | 1470 | # Takes a remote username and remote fullname.
|
---|
[401] | 1471 | # Sets up the RPC logging-pseudouser if needed.
|
---|
| 1472 | # Sets the %userdata hash for logging.
|
---|
| 1473 | # Returns undef on failure
|
---|
| 1474 | sub initRPC {
|
---|
[469] | 1475 | my $self = shift;
|
---|
| 1476 | my $dbh = $self->{dbh};
|
---|
[401] | 1477 | my %args = @_;
|
---|
| 1478 |
|
---|
| 1479 | return if !$args{username};
|
---|
| 1480 | return if !$args{fullname};
|
---|
| 1481 |
|
---|
[406] | 1482 | $args{username} = "$args{username}/$args{rpcsys}";
|
---|
| 1483 |
|
---|
| 1484 | my $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
|
---|
[404] | 1485 | " FROM users WHERE username=?", undef, ($args{username}) );
|
---|
[406] | 1486 | if (!$tmpuser) {
|
---|
[401] | 1487 | $dbh->do("INSERT INTO users (username,password,firstname,type) VALUES (?,'RPC',?,'R')", undef,
|
---|
| 1488 | ($args{username}, $args{fullname}) );
|
---|
[406] | 1489 | $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
|
---|
[404] | 1490 | " FROM users WHERE username=?", undef, ($args{username}) );
|
---|
[401] | 1491 | }
|
---|
[488] | 1492 | $tmpuser->{lastname} = '' if !$tmpuser->{lastname};
|
---|
| 1493 | $self->{loguserid} = $tmpuser->{userid};
|
---|
| 1494 | $self->{logusername} = $tmpuser->{username};
|
---|
| 1495 | $self->{logfullname} = "$tmpuser->{firstname} $tmpuser->{lastname} ($args{rpcsys})";
|
---|
[406] | 1496 | return 1 if $tmpuser;
|
---|
[401] | 1497 | } # end initRPC()
|
---|
| 1498 |
|
---|
| 1499 |
|
---|
[278] | 1500 | ## DNSDB::login()
|
---|
| 1501 | # Takes a database handle, username and password
|
---|
[316] | 1502 | # Returns a userdata hash (UID, GID, username, fullname parts) if username exists,
|
---|
| 1503 | # password matches the one on file, and account is not disabled
|
---|
[278] | 1504 | # Returns undef otherwise
|
---|
| 1505 | sub login {
|
---|
[469] | 1506 | my $self = shift;
|
---|
| 1507 | my $dbh = $self->{dbh};
|
---|
[278] | 1508 | my $user = shift;
|
---|
| 1509 | my $pass = shift;
|
---|
| 1510 |
|
---|
[316] | 1511 | my $userinfo = $dbh->selectrow_hashref("SELECT user_id,group_id,password,firstname,lastname,status".
|
---|
| 1512 | " FROM users WHERE username=?",
|
---|
[279] | 1513 | undef, ($user) );
|
---|
| 1514 | return if !$userinfo;
|
---|
[316] | 1515 | return if !$userinfo->{status};
|
---|
[278] | 1516 |
|
---|
[279] | 1517 | if ($userinfo->{password} =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
|
---|
[278] | 1518 | # native passwords (crypt-md5)
|
---|
[279] | 1519 | return if $userinfo->{password} ne unix_md5_crypt($pass,$1);
|
---|
| 1520 | } elsif ($userinfo->{password} =~ /^[0-9a-f]{32}$/) {
|
---|
[278] | 1521 | # VegaDNS import (hex-coded MD5)
|
---|
[279] | 1522 | return if $userinfo->{password} ne md5_hex($pass);
|
---|
[278] | 1523 | } else {
|
---|
| 1524 | # plaintext (convenient now and then)
|
---|
[279] | 1525 | return if $userinfo->{password} ne $pass;
|
---|
[278] | 1526 | }
|
---|
| 1527 |
|
---|
[279] | 1528 | return $userinfo;
|
---|
[278] | 1529 | } # end login()
|
---|
| 1530 |
|
---|
| 1531 |
|
---|
[279] | 1532 | ## DNSDB::initActionLog()
|
---|
| 1533 | # Set up action logging. Takes a database handle and user ID
|
---|
| 1534 | # Sets some internal globals and Does The Right Thing to set up a logging channel.
|
---|
| 1535 | # This sets up _log() to spew out log entries to the defined channel without worrying
|
---|
| 1536 | # about having to open a file or a syslog channel
|
---|
| 1537 | ##fixme Need to call _initActionLog_blah() for various logging channels, configured
|
---|
[517] | 1538 | # via dnsdb.conf, in $self->{log_channel} or something
|
---|
[279] | 1539 | # See https://secure.deepnet.cx/trac/dnsadmin/ticket/21
|
---|
| 1540 | sub initActionLog {
|
---|
[469] | 1541 | my $self = shift;
|
---|
| 1542 | my $dbh = $self->{dbh};
|
---|
[279] | 1543 | my $uid = shift;
|
---|
| 1544 |
|
---|
| 1545 | return if !$uid;
|
---|
| 1546 |
|
---|
| 1547 | # snag user info for logging. there's got to be a way to not have to pass this back
|
---|
| 1548 | # and forth from a caller, but web usage means no persistence we can rely on from
|
---|
| 1549 | # the server side.
|
---|
| 1550 | my ($username,$fullname) = $dbh->selectrow_array("SELECT username, firstname || ' ' || lastname".
|
---|
| 1551 | " FROM users WHERE user_id=?", undef, ($uid));
|
---|
| 1552 | ##fixme: errors are unpossible!
|
---|
| 1553 |
|
---|
[488] | 1554 | $self->{logusername} = $username;
|
---|
| 1555 | $self->{loguserid} = $uid;
|
---|
| 1556 | $self->{logfullname} = $fullname;
|
---|
[279] | 1557 |
|
---|
| 1558 | # convert to real check once we have other logging channels
|
---|
[517] | 1559 | # if ($self->{log_channel} eq 'sql') {
|
---|
[279] | 1560 | # Open Log, Sez Me!
|
---|
| 1561 | # }
|
---|
| 1562 |
|
---|
| 1563 | } # end initActionLog
|
---|
| 1564 |
|
---|
| 1565 |
|
---|
[65] | 1566 | ## DNSDB::getPermissions()
|
---|
| 1567 | # Get permissions from DB
|
---|
| 1568 | # Requires DB handle, group or user flag, ID, and hashref.
|
---|
| 1569 | sub getPermissions {
|
---|
[469] | 1570 | my $self = shift;
|
---|
| 1571 | my $dbh = $self->{dbh};
|
---|
| 1572 |
|
---|
[65] | 1573 | my $type = shift;
|
---|
| 1574 | my $id = shift;
|
---|
| 1575 | my $hash = shift;
|
---|
| 1576 |
|
---|
| 1577 | my $sql = qq(
|
---|
| 1578 | SELECT
|
---|
| 1579 | p.admin,p.self_edit,
|
---|
| 1580 | p.group_create,p.group_edit,p.group_delete,
|
---|
| 1581 | p.user_create,p.user_edit,p.user_delete,
|
---|
| 1582 | p.domain_create,p.domain_edit,p.domain_delete,
|
---|
[387] | 1583 | p.record_create,p.record_edit,p.record_delete,p.record_locchg,
|
---|
[382] | 1584 | p.location_create,p.location_edit,p.location_delete,p.location_view
|
---|
[65] | 1585 | FROM permissions p
|
---|
| 1586 | );
|
---|
| 1587 | if ($type eq 'group') {
|
---|
| 1588 | $sql .= qq(
|
---|
| 1589 | JOIN groups g ON g.permission_id=p.permission_id
|
---|
| 1590 | WHERE g.group_id=?
|
---|
| 1591 | );
|
---|
| 1592 | } else {
|
---|
| 1593 | $sql .= qq(
|
---|
| 1594 | JOIN users u ON u.permission_id=p.permission_id
|
---|
| 1595 | WHERE u.user_id=?
|
---|
| 1596 | );
|
---|
| 1597 | }
|
---|
| 1598 |
|
---|
| 1599 | my $sth = $dbh->prepare($sql);
|
---|
| 1600 |
|
---|
[514] | 1601 | ##fixme? we don't trap other plain SELECT errors
|
---|
| 1602 | $sth->execute($id);
|
---|
[65] | 1603 |
|
---|
| 1604 | # my $permref = $sth->fetchrow_hashref;
|
---|
| 1605 | # return $permref;
|
---|
| 1606 | # $hash = $permref;
|
---|
| 1607 | # Eww. Need to learn how to forcibly drop a hashref onto an existing hash.
|
---|
| 1608 | ($hash->{admin},$hash->{self_edit},
|
---|
| 1609 | $hash->{group_create},$hash->{group_edit},$hash->{group_delete},
|
---|
| 1610 | $hash->{user_create},$hash->{user_edit},$hash->{user_delete},
|
---|
| 1611 | $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete},
|
---|
[387] | 1612 | $hash->{record_create},$hash->{record_edit},$hash->{record_delete},$hash->{record_locchg},
|
---|
[382] | 1613 | $hash->{location_create},$hash->{location_edit},$hash->{location_delete},$hash->{location_view}
|
---|
| 1614 | ) = $sth->fetchrow_array;
|
---|
[65] | 1615 |
|
---|
| 1616 | } # end getPermissions()
|
---|
| 1617 |
|
---|
| 1618 |
|
---|
| 1619 | ## DNSDB::changePermissions()
|
---|
| 1620 | # Update an ACL entry
|
---|
| 1621 | # Takes a db handle, type, owner-id, and hashref for the changed permissions.
|
---|
| 1622 | sub changePermissions {
|
---|
[474] | 1623 | my $self = shift;
|
---|
| 1624 | my $dbh = $self->{dbh};
|
---|
[65] | 1625 | my $type = shift;
|
---|
| 1626 | my $id = shift;
|
---|
| 1627 | my $newperms = shift;
|
---|
[87] | 1628 | my $inherit = shift || 0;
|
---|
[65] | 1629 |
|
---|
[294] | 1630 | my $resultmsg = '';
|
---|
[66] | 1631 |
|
---|
[87] | 1632 | # see if we're switching from inherited to custom. for bonus points,
|
---|
| 1633 | # snag the permid and parent permid anyway, since we'll need the permid
|
---|
| 1634 | # to set/alter custom perms, and both if we're switching from custom to
|
---|
| 1635 | # inherited.
|
---|
[294] | 1636 | my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id,".
|
---|
| 1637 | ($type eq 'user' ? 'u.group_id,u.username' : 'u.parent_group_id,u.group_name').
|
---|
[65] | 1638 | " FROM ".($type eq 'user' ? 'users' : 'groups')." u ".
|
---|
[66] | 1639 | " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ".
|
---|
[65] | 1640 | " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?");
|
---|
| 1641 | $sth->execute($id);
|
---|
| 1642 |
|
---|
[294] | 1643 | my ($wasinherited,$permid,$parpermid,$parid,$name) = $sth->fetchrow_array;
|
---|
[66] | 1644 |
|
---|
[78] | 1645 | # hack phtoui
|
---|
| 1646 | # group id 1 is "special" in that it's it's own parent (err... possibly.)
|
---|
| 1647 | # may make its parent id 0 which doesn't exist, and as a bonus is Perl-false.
|
---|
| 1648 | $wasinherited = 0 if ($type eq 'group' && $id == 1);
|
---|
| 1649 |
|
---|
[66] | 1650 | local $dbh->{AutoCommit} = 0;
|
---|
| 1651 | local $dbh->{RaiseError} = 1;
|
---|
| 1652 |
|
---|
| 1653 | # Wrap all the SQL in a transaction
|
---|
| 1654 | eval {
|
---|
[87] | 1655 | if ($inherit) {
|
---|
| 1656 |
|
---|
| 1657 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ".
|
---|
| 1658 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) );
|
---|
| 1659 | $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) );
|
---|
| 1660 |
|
---|
| 1661 | } else {
|
---|
| 1662 |
|
---|
| 1663 | if ($wasinherited) { # munge new permission entry in if we're switching from inherited perms
|
---|
[66] | 1664 | ##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users
|
---|
[87] | 1665 | # ... if'n'when we have groups with fully inherited permissions.
|
---|
| 1666 | # SQL is coo
|
---|
| 1667 | $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ".
|
---|
| 1668 | "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) );
|
---|
| 1669 | ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ".
|
---|
| 1670 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) );
|
---|
| 1671 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ".
|
---|
| 1672 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) );
|
---|
[66] | 1673 | }
|
---|
[78] | 1674 |
|
---|
[87] | 1675 | # and now set the permissions we were passed
|
---|
| 1676 | foreach (@permtypes) {
|
---|
| 1677 | if (defined ($newperms->{$_})) {
|
---|
| 1678 | $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) );
|
---|
| 1679 | }
|
---|
| 1680 | }
|
---|
| 1681 |
|
---|
| 1682 | } # (inherited->)? custom
|
---|
| 1683 |
|
---|
[294] | 1684 | if ($type eq 'user') {
|
---|
| 1685 | $resultmsg = "Updated permissions for user $name";
|
---|
| 1686 | } else {
|
---|
| 1687 | $resultmsg = "Updated default permissions for group $name";
|
---|
| 1688 | }
|
---|
[487] | 1689 | $self->_log(group_id => ($type eq 'user' ? $parid : $id), entry => $resultmsg);
|
---|
[66] | 1690 | $dbh->commit;
|
---|
| 1691 | }; # end eval
|
---|
| 1692 | if ($@) {
|
---|
| 1693 | my $msg = $@;
|
---|
| 1694 | eval { $dbh->rollback; };
|
---|
[294] | 1695 | return ('FAIL',"Error changing permissions: $msg");
|
---|
[66] | 1696 | }
|
---|
| 1697 |
|
---|
[294] | 1698 | return ('OK',$resultmsg);
|
---|
[65] | 1699 | } # end changePermissions()
|
---|
| 1700 |
|
---|
| 1701 |
|
---|
[67] | 1702 | ## DNSDB::comparePermissions()
|
---|
| 1703 | # Compare two permission hashes
|
---|
| 1704 | # Returns '>', '<', '=', '!'
|
---|
| 1705 | sub comparePermissions {
|
---|
| 1706 | my $p1 = shift;
|
---|
| 1707 | my $p2 = shift;
|
---|
| 1708 |
|
---|
| 1709 | my $retval = '='; # assume equality until proven otherwise
|
---|
| 1710 |
|
---|
| 1711 | no warnings "uninitialized";
|
---|
| 1712 |
|
---|
| 1713 | foreach (@permtypes) {
|
---|
| 1714 | next if $p1->{$_} == $p2->{$_}; # equal is good
|
---|
| 1715 | if ($p1->{$_} && !$p2->{$_}) {
|
---|
| 1716 | if ($retval eq '<') { # if we've already found an unequal pair where
|
---|
| 1717 | $retval = '!'; # $p2 has more access, and we now find a pair
|
---|
| 1718 | last; # where $p1 has more access, the overall access
|
---|
| 1719 | } # is neither greater or lesser, it's unequal.
|
---|
| 1720 | $retval = '>';
|
---|
| 1721 | }
|
---|
| 1722 | if (!$p1->{$_} && $p2->{$_}) {
|
---|
| 1723 | if ($retval eq '>') { # if we've already found an unequal pair where
|
---|
| 1724 | $retval = '!'; # $p1 has more access, and we now find a pair
|
---|
| 1725 | last; # where $p2 has more access, the overall access
|
---|
| 1726 | } # is neither greater or lesser, it's unequal.
|
---|
| 1727 | $retval = '<';
|
---|
| 1728 | }
|
---|
| 1729 | }
|
---|
| 1730 | return $retval;
|
---|
| 1731 | } # end comparePermissions()
|
---|
| 1732 |
|
---|
| 1733 |
|
---|
[112] | 1734 | ## DNSDB::changeGroup()
|
---|
| 1735 | # Change group ID of an entity
|
---|
| 1736 | # Takes a database handle, entity type, entity ID, and new group ID
|
---|
| 1737 | sub changeGroup {
|
---|
[476] | 1738 | my $self = shift;
|
---|
| 1739 | my $dbh = $self->{dbh};
|
---|
[112] | 1740 | my $type = shift;
|
---|
| 1741 | my $id = shift;
|
---|
| 1742 | my $newgrp = shift;
|
---|
| 1743 |
|
---|
| 1744 | ##fixme: fail on not enough args
|
---|
| 1745 | #return ('FAIL', "Missing
|
---|
| 1746 |
|
---|
[295] | 1747 | return ('FAIL', "Can't change the group of a $type")
|
---|
| 1748 | unless grep /^$type$/, ('domain','revzone','user','group'); # could be extended for defrecs?
|
---|
| 1749 |
|
---|
| 1750 | # Collect some names for logging and messages
|
---|
| 1751 | my $entname;
|
---|
[112] | 1752 | if ($type eq 'domain') {
|
---|
[473] | 1753 | $entname = $self->domainName($id);
|
---|
[295] | 1754 | } elsif ($type eq 'revzone') {
|
---|
[473] | 1755 | $entname = $self->revName($id);
|
---|
[112] | 1756 | } elsif ($type eq 'user') {
|
---|
[473] | 1757 | $entname = $self->userFullName($id, '%u');
|
---|
[112] | 1758 | } elsif ($type eq 'group') {
|
---|
[473] | 1759 | $entname = $self->groupName($id);
|
---|
[112] | 1760 | }
|
---|
[295] | 1761 |
|
---|
| 1762 | my ($oldgid) = $dbh->selectrow_array("SELECT group_id FROM $par_tbl{$type} WHERE $id_col{$type}=?",
|
---|
| 1763 | undef, ($id));
|
---|
[473] | 1764 | my $oldgname = $self->groupName($oldgid);
|
---|
| 1765 | my $newgname = $self->groupName($newgrp);
|
---|
[295] | 1766 |
|
---|
| 1767 | return ('FAIL', "Can't move things into a group that doesn't exist") if !$newgname;
|
---|
| 1768 |
|
---|
| 1769 | return ('WARN', "Nothing to do, new group is the same as the old group") if $oldgid == $newgrp;
|
---|
| 1770 |
|
---|
| 1771 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 1772 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 1773 | local $dbh->{AutoCommit} = 0;
|
---|
| 1774 | local $dbh->{RaiseError} = 1;
|
---|
| 1775 |
|
---|
| 1776 | eval {
|
---|
| 1777 | $dbh->do("UPDATE $par_tbl{$type} SET group_id=? WHERE $id_col{$type}=?", undef, ($newgrp, $id));
|
---|
| 1778 | # Log the change in both the old and new groups
|
---|
[487] | 1779 | $self->_log(group_id => $oldgid, entry => "Moved $type $entname from $oldgname to $newgname");
|
---|
| 1780 | $self->_log(group_id => $newgrp, entry => "Moved $type $entname from $oldgname to $newgname");
|
---|
[295] | 1781 | $dbh->commit;
|
---|
| 1782 | };
|
---|
| 1783 | if ($@) {
|
---|
| 1784 | my $msg = $@;
|
---|
| 1785 | eval { $dbh->rollback; };
|
---|
[517] | 1786 | if ($self->{log_failures}) {
|
---|
[487] | 1787 | $self->_log(group_id => $oldgid, entry => "Error moving $type $entname to $newgname: $msg");
|
---|
[295] | 1788 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 1789 | }
|
---|
| 1790 | return ('FAIL',"Error moving $type $entname to $newgname: $msg");
|
---|
| 1791 | }
|
---|
| 1792 |
|
---|
| 1793 | return ('OK',"Moved $type $entname from $oldgname to $newgname");
|
---|
[112] | 1794 | } # end changeGroup()
|
---|
| 1795 |
|
---|
| 1796 |
|
---|
[2] | 1797 | ##
|
---|
| 1798 | ## Processing subs
|
---|
| 1799 | ##
|
---|
| 1800 |
|
---|
| 1801 | ## DNSDB::addDomain()
|
---|
| 1802 | # Add a domain
|
---|
[190] | 1803 | # Takes a database handle, domain name, numeric group, boolean(ish) state (active/inactive),
|
---|
| 1804 | # and user info hash (for logging).
|
---|
[2] | 1805 | # Returns a status code and message
|
---|
| 1806 | sub addDomain {
|
---|
| 1807 | $errstr = '';
|
---|
[477] | 1808 | my $self = shift;
|
---|
| 1809 | my $dbh = $self->{dbh};
|
---|
[2] | 1810 | my $domain = shift;
|
---|
[497] | 1811 | return ('FAIL',"Domain must not be blank\n") if !$domain;
|
---|
[2] | 1812 | my $group = shift;
|
---|
[497] | 1813 | return ('FAIL',"Group must be specified\n") if !defined($group);
|
---|
[2] | 1814 | my $state = shift;
|
---|
[497] | 1815 | return ('FAIL',"Domain status must be specified\n") if !defined($state);
|
---|
[516] | 1816 | my $defloc = shift || '';
|
---|
[2] | 1817 |
|
---|
[116] | 1818 | $state = 1 if $state =~ /^active$/;
|
---|
| 1819 | $state = 1 if $state =~ /^on$/;
|
---|
| 1820 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 1821 | $state = 0 if $state =~ /^off$/;
|
---|
| 1822 |
|
---|
| 1823 | return ('FAIL',"Invalid domain status") if $state !~ /^\d+$/;
|
---|
| 1824 |
|
---|
[542] | 1825 | $domain = lc($domain) if $self->{lowercase};
|
---|
| 1826 |
|
---|
[190] | 1827 | return ('FAIL', "Invalid characters in domain") if $domain !~ /^[a-zA-Z0-9_.-]+$/;
|
---|
| 1828 |
|
---|
[349] | 1829 | my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)");
|
---|
[3] | 1830 | my $dom_id;
|
---|
| 1831 |
|
---|
[38] | 1832 | # quick check to start to see if we've already got one
|
---|
| 1833 | $sth->execute($domain);
|
---|
| 1834 | ($dom_id) = $sth->fetchrow_array;
|
---|
| 1835 |
|
---|
| 1836 | return ('FAIL', "Domain already exists") if $dom_id;
|
---|
| 1837 |
|
---|
[2] | 1838 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 1839 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 1840 | local $dbh->{AutoCommit} = 0;
|
---|
| 1841 | local $dbh->{RaiseError} = 1;
|
---|
| 1842 |
|
---|
| 1843 | # Wrap all the SQL in a transaction
|
---|
| 1844 | eval {
|
---|
| 1845 | # insert the domain...
|
---|
[516] | 1846 | $dbh->do("INSERT INTO domains (domain,group_id,status,default_location) VALUES (?,?,?,?)", undef,
|
---|
| 1847 | ($domain, $group, $state, $defloc));
|
---|
[2] | 1848 |
|
---|
| 1849 | # get the ID...
|
---|
[349] | 1850 | ($dom_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
| 1851 | undef, ($domain));
|
---|
[2] | 1852 |
|
---|
[487] | 1853 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
| 1854 | entry => "Added ".($state ? 'active' : 'inactive')." domain $domain");
|
---|
[190] | 1855 |
|
---|
[2] | 1856 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
[190] | 1857 | my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
[516] | 1858 | my $sth_in = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,distance,weight,port,ttl,location)".
|
---|
| 1859 | " VALUES ($dom_id,?,?,?,?,?,?,?,?)");
|
---|
[190] | 1860 | $sth->execute($group);
|
---|
[516] | 1861 | while (my ($host, $type, $val, $dist, $weight, $port, $ttl) = $sth->fetchrow_array()) {
|
---|
[2] | 1862 | $host =~ s/DOMAIN/$domain/g;
|
---|
[37] | 1863 | $val =~ s/DOMAIN/$domain/g;
|
---|
[516] | 1864 | $sth_in->execute($host, $type, $val, $dist, $weight, $port, $ttl, $defloc);
|
---|
[190] | 1865 | if ($typemap{$type} eq 'SOA') {
|
---|
| 1866 | my @tmp1 = split /:/, $host;
|
---|
| 1867 | my @tmp2 = split /:/, $val;
|
---|
[487] | 1868 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
[284] | 1869 | entry => "[new $domain] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
[487] | 1870 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl");
|
---|
[190] | 1871 | } else {
|
---|
| 1872 | my $logentry = "[new $domain] Added record '$host $typemap{$type}";
|
---|
| 1873 | $logentry .= " [distance $dist]" if $typemap{$type} eq 'MX';
|
---|
| 1874 | $logentry .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$type} eq 'SRV';
|
---|
[487] | 1875 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
| 1876 | entry => $logentry." $val', TTL $ttl");
|
---|
[190] | 1877 | }
|
---|
[2] | 1878 | }
|
---|
| 1879 |
|
---|
| 1880 | # once we get here, we should have suceeded.
|
---|
| 1881 | $dbh->commit;
|
---|
| 1882 | }; # end eval
|
---|
| 1883 |
|
---|
| 1884 | if ($@) {
|
---|
| 1885 | my $msg = $@;
|
---|
| 1886 | eval { $dbh->rollback; };
|
---|
[487] | 1887 | $self->_log(group_id => $group, entry => "Failed adding domain $domain ($msg)")
|
---|
[517] | 1888 | if $self->{log_failures};
|
---|
[284] | 1889 | $dbh->commit; # since we enabled transactions earlier
|
---|
[193] | 1890 | return ('FAIL',$msg);
|
---|
[2] | 1891 | } else {
|
---|
[3] | 1892 | return ('OK',$dom_id);
|
---|
[2] | 1893 | }
|
---|
| 1894 | } # end addDomain
|
---|
| 1895 |
|
---|
| 1896 |
|
---|
[274] | 1897 | ## DNSDB::delZone()
|
---|
| 1898 | # Delete a forward or reverse zone.
|
---|
| 1899 | # Takes a database handle, zone ID, and forward/reverse flag.
|
---|
[3] | 1900 | # for now, just delete the records, then the domain.
|
---|
| 1901 | # later we may want to archive it in some way instead (status code 2, for example?)
|
---|
[274] | 1902 | sub delZone {
|
---|
[477] | 1903 | my $self = shift;
|
---|
| 1904 | my $dbh = $self->{dbh};
|
---|
[274] | 1905 | my $zoneid = shift;
|
---|
| 1906 | my $revrec = shift;
|
---|
[3] | 1907 |
|
---|
| 1908 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 1909 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 1910 | local $dbh->{AutoCommit} = 0;
|
---|
| 1911 | local $dbh->{RaiseError} = 1;
|
---|
| 1912 |
|
---|
[285] | 1913 | my $msg = '';
|
---|
[23] | 1914 | my $failmsg = '';
|
---|
[473] | 1915 | my $zone = ($revrec eq 'n' ? $self->domainName($zoneid) : $self->revName($zoneid));
|
---|
[23] | 1916 |
|
---|
[343] | 1917 | return ('FAIL', ($revrec eq 'n' ? 'Domain' : 'Reverse zone')." ID $zoneid doesn't exist") if !$zone;
|
---|
| 1918 |
|
---|
[517] | 1919 | # Set this up here since we may use if if $self->{log_failures} is enabled
|
---|
[285] | 1920 | my %loghash;
|
---|
| 1921 | $loghash{domain_id} = $zoneid if $revrec eq 'n';
|
---|
| 1922 | $loghash{rdns_id} = $zoneid if $revrec eq 'y';
|
---|
[473] | 1923 | $loghash{group_id} = $self->parentID(
|
---|
| 1924 | id => $zoneid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec);
|
---|
[285] | 1925 |
|
---|
[3] | 1926 | # Wrap all the SQL in a transaction
|
---|
| 1927 | eval {
|
---|
[274] | 1928 | # Disentangle custom record types before removing the
|
---|
| 1929 | # ones that are only in the zone to be deleted
|
---|
| 1930 | if ($revrec eq 'n') {
|
---|
| 1931 | my $sth = $dbh->prepare("UPDATE records SET type=?,domain_id=0 WHERE domain_id=? AND type=?");
|
---|
| 1932 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
| 1933 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65280);
|
---|
| 1934 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65281);
|
---|
| 1935 | $sth->execute(65282, $zoneid, 65283);
|
---|
| 1936 | $sth->execute(65282, $zoneid, 65284);
|
---|
| 1937 | $failmsg = "Failure removing domain records";
|
---|
| 1938 | $dbh->do("DELETE FROM records WHERE domain_id=?", undef, ($zoneid));
|
---|
| 1939 | $failmsg = "Failure removing domain";
|
---|
| 1940 | $dbh->do("DELETE FROM domains WHERE domain_id=?", undef, ($zoneid));
|
---|
| 1941 | } else {
|
---|
| 1942 | my $sth = $dbh->prepare("UPDATE records SET type=?,rdns_id=0 WHERE rdns_id=? AND type=?");
|
---|
| 1943 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
| 1944 | $sth->execute($reverse_typemap{A}, $zoneid, 65280);
|
---|
| 1945 | $sth->execute($reverse_typemap{AAAA}, $zoneid, 65281);
|
---|
| 1946 | # We don't have an "A template" or "AAAA template" type, although it might be useful for symmetry.
|
---|
[345] | 1947 | # $sth->execute(65286?, $zoneid, 65283);
|
---|
| 1948 | # $sth->execute(65286?, $zoneid, 65284);
|
---|
[274] | 1949 | $failmsg = "Failure removing reverse records";
|
---|
| 1950 | $dbh->do("DELETE FROM records WHERE rdns_id=?", undef, ($zoneid));
|
---|
| 1951 | $failmsg = "Failure removing reverse zone";
|
---|
| 1952 | $dbh->do("DELETE FROM revzones WHERE rdns_id=?", undef, ($zoneid));
|
---|
| 1953 | }
|
---|
[3] | 1954 |
|
---|
[285] | 1955 | $msg = "Deleted ".($revrec eq 'n' ? 'domain' : 'reverse zone')." $zone";
|
---|
| 1956 | $loghash{entry} = $msg;
|
---|
[487] | 1957 | $self->_log(%loghash);
|
---|
[285] | 1958 |
|
---|
[3] | 1959 | # once we get here, we should have suceeded.
|
---|
[23] | 1960 | $dbh->commit;
|
---|
[3] | 1961 | }; # end eval
|
---|
| 1962 |
|
---|
| 1963 | if ($@) {
|
---|
[285] | 1964 | $msg = $@;
|
---|
[3] | 1965 | eval { $dbh->rollback; };
|
---|
[295] | 1966 | $loghash{entry} = "Error deleting $zone: $msg ($failmsg)";
|
---|
[517] | 1967 | if ($self->{log_failures}) {
|
---|
[487] | 1968 | $self->_log(%loghash);
|
---|
[295] | 1969 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 1970 | }
|
---|
| 1971 | return ('FAIL', $loghash{entry});
|
---|
[3] | 1972 | } else {
|
---|
[295] | 1973 | return ('OK', $msg);
|
---|
[3] | 1974 | }
|
---|
| 1975 |
|
---|
[274] | 1976 | } # end delZone()
|
---|
[3] | 1977 |
|
---|
| 1978 |
|
---|
[2] | 1979 | ## DNSDB::domainName()
|
---|
| 1980 | # Return the domain name based on a domain ID
|
---|
| 1981 | # Takes a database handle and the domain ID
|
---|
| 1982 | # Returns the domain name or undef on failure
|
---|
| 1983 | sub domainName {
|
---|
| 1984 | $errstr = '';
|
---|
[473] | 1985 | my $self = shift;
|
---|
| 1986 | my $dbh = $self->{dbh};
|
---|
[2] | 1987 | my $domid = shift;
|
---|
[91] | 1988 | my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
|
---|
[2] | 1989 | $errstr = $DBI::errstr if !$domname;
|
---|
| 1990 | return $domname if $domname;
|
---|
[91] | 1991 | } # end domainName()
|
---|
[2] | 1992 |
|
---|
| 1993 |
|
---|
[224] | 1994 | ## DNSDB::revName()
|
---|
| 1995 | # Return the reverse zone name based on an rDNS ID
|
---|
| 1996 | # Takes a database handle and the rDNS ID
|
---|
| 1997 | # Returns the reverse zone name or undef on failure
|
---|
| 1998 | sub revName {
|
---|
| 1999 | $errstr = '';
|
---|
[473] | 2000 | my $self = shift;
|
---|
| 2001 | my $dbh = $self->{dbh};
|
---|
[224] | 2002 | my $revid = shift;
|
---|
| 2003 | my ($revname) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id=?", undef, ($revid) );
|
---|
| 2004 | $errstr = $DBI::errstr if !$revname;
|
---|
| 2005 | return $revname if $revname;
|
---|
| 2006 | } # end revName()
|
---|
| 2007 |
|
---|
| 2008 |
|
---|
[91] | 2009 | ## DNSDB::domainID()
|
---|
| 2010 | # Takes a database handle and domain name
|
---|
| 2011 | # Returns the domain ID number
|
---|
| 2012 | sub domainID {
|
---|
| 2013 | $errstr = '';
|
---|
[473] | 2014 | my $self = shift;
|
---|
| 2015 | my $dbh = $self->{dbh};
|
---|
[91] | 2016 | my $domain = shift;
|
---|
[349] | 2017 | my ($domid) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
| 2018 | undef, ($domain) );
|
---|
[501] | 2019 | if (!$domid) {
|
---|
| 2020 | if ($dbh->err) {
|
---|
| 2021 | $errstr = $DBI::errstr;
|
---|
| 2022 | } else {
|
---|
| 2023 | $errstr = "Domain $domain not present";
|
---|
| 2024 | }
|
---|
| 2025 | }
|
---|
[91] | 2026 | return $domid if $domid;
|
---|
| 2027 | } # end domainID()
|
---|
| 2028 |
|
---|
| 2029 |
|
---|
[276] | 2030 | ## DNSDB::revID()
|
---|
| 2031 | # Takes a database handle and reverse zone name
|
---|
| 2032 | # Returns the rDNS ID number
|
---|
| 2033 | sub revID {
|
---|
| 2034 | $errstr = '';
|
---|
[473] | 2035 | my $self = shift;
|
---|
| 2036 | my $dbh = $self->{dbh};
|
---|
[276] | 2037 | my $revzone = shift;
|
---|
| 2038 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ($revzone) );
|
---|
[501] | 2039 | if (!$revid) {
|
---|
| 2040 | if ($dbh->err) {
|
---|
| 2041 | $errstr = $DBI::errstr;
|
---|
| 2042 | } else {
|
---|
| 2043 | $errstr = "Reverse zone $revzone not present";
|
---|
| 2044 | }
|
---|
| 2045 | }
|
---|
[276] | 2046 | return $revid if $revid;
|
---|
| 2047 | } # end revID()
|
---|
| 2048 |
|
---|
| 2049 |
|
---|
[260] | 2050 | ## DNSDB::addRDNS
|
---|
| 2051 | # Adds a reverse DNS zone
|
---|
[286] | 2052 | # Takes a database handle, CIDR block, reverse DNS pattern, numeric group,
|
---|
| 2053 | # and boolean(ish) state (active/inactive)
|
---|
[260] | 2054 | # Returns a status code and message
|
---|
| 2055 | sub addRDNS {
|
---|
[477] | 2056 | my $self = shift;
|
---|
| 2057 | my $dbh = $self->{dbh};
|
---|
[260] | 2058 | my $zone = NetAddr::IP->new(shift);
|
---|
[446] | 2059 |
|
---|
[260] | 2060 | return ('FAIL',"Zone name must be a valid CIDR netblock") unless ($zone && $zone->addr !~ /^0/);
|
---|
[270] | 2061 | my $revpatt = shift; # construct a custom (A/AAAA+)? PTR template record
|
---|
[260] | 2062 | my $group = shift;
|
---|
| 2063 | my $state = shift;
|
---|
[446] | 2064 | my $defloc = shift || '';
|
---|
[260] | 2065 |
|
---|
| 2066 | $state = 1 if $state =~ /^active$/;
|
---|
| 2067 | $state = 1 if $state =~ /^on$/;
|
---|
| 2068 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 2069 | $state = 0 if $state =~ /^off$/;
|
---|
| 2070 |
|
---|
| 2071 | return ('FAIL',"Invalid zone status") if $state !~ /^\d+$/;
|
---|
| 2072 |
|
---|
| 2073 | # quick check to start to see if we've already got one
|
---|
[299] | 2074 | my ($rdns_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ("$zone"));
|
---|
[260] | 2075 |
|
---|
| 2076 | return ('FAIL', "Zone already exists") if $rdns_id;
|
---|
| 2077 |
|
---|
| 2078 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2079 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2080 | local $dbh->{AutoCommit} = 0;
|
---|
| 2081 | local $dbh->{RaiseError} = 1;
|
---|
| 2082 |
|
---|
[264] | 2083 | my $warnstr = '';
|
---|
[270] | 2084 | my $defttl = 3600; # 1 hour should be reasonable. And unless things have gone horribly
|
---|
| 2085 | # wrong, we should have a value to override this anyway.
|
---|
[264] | 2086 |
|
---|
[260] | 2087 | # Wrap all the SQL in a transaction
|
---|
| 2088 | eval {
|
---|
[446] | 2089 | # insert the zone...
|
---|
| 2090 | $dbh->do("INSERT INTO revzones (revnet,group_id,status,default_location) VALUES (?,?,?,?)", undef,
|
---|
| 2091 | ($zone, $group, $state, $defloc) );
|
---|
[260] | 2092 |
|
---|
| 2093 | # get the ID...
|
---|
| 2094 | ($rdns_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
| 2095 |
|
---|
[487] | 2096 | $self->_log(rdns_id => $rdns_id, group_id => $group,
|
---|
| 2097 | entry => "Added ".($state ? 'active' : 'inactive')." reverse zone $zone");
|
---|
[260] | 2098 |
|
---|
| 2099 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
| 2100 | my $sth = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
[446] | 2101 | my $sth_in = $dbh->prepare("INSERT INTO records (rdns_id,domain_id,host,type,val,ttl,location)".
|
---|
| 2102 | " VALUES ($rdns_id,?,?,?,?,?,?)");
|
---|
[260] | 2103 | $sth->execute($group);
|
---|
| 2104 | while (my ($host,$type,$val,$ttl) = $sth->fetchrow_array()) {
|
---|
[264] | 2105 | # Silently skip v4/v6 mismatches. This is not an error, this is expected.
|
---|
| 2106 | if ($zone->{isv6}) {
|
---|
| 2107 | next if ($type == 65280 || $type == 65283);
|
---|
| 2108 | } else {
|
---|
| 2109 | next if ($type == 65281 || $type == 65284);
|
---|
| 2110 | }
|
---|
[269] | 2111 |
|
---|
[517] | 2112 | $host =~ s/ADMINDOMAIN/$self->{domain}/g;
|
---|
[264] | 2113 |
|
---|
[265] | 2114 | # Check to make sure the IP stubs will fit in the zone. Under most usage failures here should be rare.
|
---|
| 2115 | # On failure, tack a note on to a warning string and continue without adding this record.
|
---|
| 2116 | # While we're at it, we substitute $zone for ZONE in the value.
|
---|
| 2117 | if ($val eq 'ZONE') {
|
---|
[444] | 2118 | # If we've got a pattern, we skip the default record version on (A+)PTR-template types
|
---|
| 2119 | next if $revpatt && ($type == 65282 || $type == 65283);
|
---|
[269] | 2120 | ##fixme? do we care if we have multiple whole-zone templates?
|
---|
[265] | 2121 | $val = $zone->network;
|
---|
| 2122 | } elsif ($val =~ /ZONE/) {
|
---|
| 2123 | my $tmpval = $val;
|
---|
| 2124 | $tmpval =~ s/ZONE//;
|
---|
[269] | 2125 | # Bend the rules and allow single-trailing-number PTR or PTR template records to be inserted
|
---|
| 2126 | # as either v4 or v6. May make this an off-by-default config flag
|
---|
| 2127 | # Note that the origin records that may trigger this **SHOULD** already have ZONE,\d
|
---|
| 2128 | if ($type == 12 || $type == 65282) {
|
---|
| 2129 | $tmpval =~ s/[,.]/::/ if ($tmpval =~ /^[,.]\d+$/ && $zone->{isv6});
|
---|
| 2130 | $tmpval =~ s/[,:]+/./ if ($tmpval =~ /^(?:,|::)\d+$/ && !$zone->{isv6});
|
---|
| 2131 | }
|
---|
[265] | 2132 | my $addr;
|
---|
[471] | 2133 | if ($self->_ipparent('n', 'y', \$tmpval, $rdns_id, \$addr)) {
|
---|
[265] | 2134 | $val = $addr->addr;
|
---|
| 2135 | } else {
|
---|
[269] | 2136 | $warnstr .= "\nDefault record '$val $typemap{$type} $host' doesn't fit in $zone, skipping";
|
---|
[264] | 2137 | next;
|
---|
| 2138 | }
|
---|
| 2139 | }
|
---|
| 2140 |
|
---|
[328] | 2141 | # Substitute $zone for ZONE in the hostname, but only for non-NS records.
|
---|
| 2142 | # NS records get this substitution on the value instead.
|
---|
| 2143 | $host = _ZONE($zone, $host) if $type != 2;
|
---|
[265] | 2144 |
|
---|
[269] | 2145 | # Fill in the forward domain ID if we can find it, otherwise:
|
---|
| 2146 | # Coerce type down to PTR or PTR template if we can't
|
---|
| 2147 | my $domid = 0;
|
---|
| 2148 | if ($type >= 65280) {
|
---|
[471] | 2149 | if (!($domid = $self->_hostparent($host))) {
|
---|
[269] | 2150 | $warnstr .= "\nRecord added as PTR instead of $typemap{$type}; domain not found for $host";
|
---|
| 2151 | $type = $reverse_typemap{PTR};
|
---|
| 2152 | $domid = 0; # just to be explicit.
|
---|
| 2153 | }
|
---|
| 2154 | }
|
---|
| 2155 |
|
---|
[446] | 2156 | $sth_in->execute($domid,$host,$type,$val,$ttl,$defloc);
|
---|
[269] | 2157 |
|
---|
[260] | 2158 | if ($typemap{$type} eq 'SOA') {
|
---|
| 2159 | my @tmp1 = split /:/, $host;
|
---|
| 2160 | my @tmp2 = split /:/, $val;
|
---|
[487] | 2161 | $self->_log(rdns_id => $rdns_id, group_id => $group,
|
---|
[286] | 2162 | entry => "[new $zone] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
[487] | 2163 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl");
|
---|
[270] | 2164 | $defttl = $tmp2[3];
|
---|
[260] | 2165 | } else {
|
---|
[446] | 2166 | my $logentry = "[new $zone] Added record '$host $typemap{$type} $val', TTL $ttl";
|
---|
[480] | 2167 | $logentry .= ", default location ".$self->getLoc($defloc)->{description} if $defloc;
|
---|
[487] | 2168 | $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group, entry => $logentry);
|
---|
[260] | 2169 | }
|
---|
| 2170 | }
|
---|
| 2171 |
|
---|
[270] | 2172 | # Generate record based on provided pattern.
|
---|
| 2173 | if ($revpatt) {
|
---|
| 2174 | my $host;
|
---|
| 2175 | my $type = ($zone->{isv6} ? 65284 : 65283);
|
---|
| 2176 | my $val = $zone->network;
|
---|
[269] | 2177 |
|
---|
[270] | 2178 | # Substitute $zone for ZONE in the hostname.
|
---|
| 2179 | $host = _ZONE($zone, $revpatt);
|
---|
| 2180 |
|
---|
| 2181 | my $domid = 0;
|
---|
[471] | 2182 | if (!($domid = $self->_hostparent($host))) {
|
---|
[270] | 2183 | $warnstr .= "\nDefault pattern added as PTR template instead of $typemap{$type}; domain not found for $host";
|
---|
| 2184 | $type = 65282;
|
---|
| 2185 | $domid = 0; # just to be explicit.
|
---|
| 2186 | }
|
---|
| 2187 |
|
---|
[446] | 2188 | $sth_in->execute($domid,$host,$type,$val,$defttl,$defloc);
|
---|
[286] | 2189 | my $logentry = "[new $zone] Added record '$host $typemap{$type}";
|
---|
[487] | 2190 | $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group,
|
---|
| 2191 | entry => $logentry." $val', TTL $defttl from pattern");
|
---|
[270] | 2192 | }
|
---|
| 2193 |
|
---|
[264] | 2194 | # If there are warnings (presumably about default records skipped for cause) log them
|
---|
[487] | 2195 | $self->_log(rdns_id => $rdns_id, group_id => $group, entry => "Warning(s) adding $zone:$warnstr")
|
---|
[264] | 2196 | if $warnstr;
|
---|
[269] | 2197 |
|
---|
[260] | 2198 | # once we get here, we should have suceeded.
|
---|
| 2199 | $dbh->commit;
|
---|
| 2200 | }; # end eval
|
---|
| 2201 |
|
---|
| 2202 | if ($@) {
|
---|
| 2203 | my $msg = $@;
|
---|
| 2204 | eval { $dbh->rollback; };
|
---|
[487] | 2205 | $self->_log(group_id => $group, entry => "Failed adding reverse zone $zone ($msg)")
|
---|
[517] | 2206 | if $self->{log_failures};
|
---|
[286] | 2207 | $dbh->commit; # since we enabled transactions earlier
|
---|
[260] | 2208 | return ('FAIL',$msg);
|
---|
| 2209 | } else {
|
---|
[286] | 2210 | my $retcode = 'OK';
|
---|
| 2211 | if ($warnstr) {
|
---|
| 2212 | $resultstr = $warnstr;
|
---|
| 2213 | $retcode = 'WARN';
|
---|
| 2214 | }
|
---|
| 2215 | return ($retcode, $rdns_id);
|
---|
[260] | 2216 | }
|
---|
| 2217 |
|
---|
| 2218 | } # end addRDNS()
|
---|
| 2219 |
|
---|
| 2220 |
|
---|
[237] | 2221 | ## DNSDB::getZoneCount
|
---|
| 2222 | # Get count of zones in group or groups
|
---|
| 2223 | # Takes a database handle and hash containing:
|
---|
| 2224 | # - the "current" group
|
---|
| 2225 | # - an array of "acceptable" groups
|
---|
| 2226 | # - a flag for forward/reverse zones
|
---|
| 2227 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
| 2228 | # Returns an integer count of the resulting zone list.
|
---|
| 2229 | sub getZoneCount {
|
---|
[477] | 2230 | my $self = shift;
|
---|
| 2231 | my $dbh = $self->{dbh};
|
---|
[237] | 2232 |
|
---|
| 2233 | my %args = @_;
|
---|
| 2234 |
|
---|
[509] | 2235 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 2236 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 2237 | $errstr = "Bad or missing curgroup argument";
|
---|
| 2238 | return;
|
---|
| 2239 | }
|
---|
| 2240 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 2241 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 2242 | $errstr = "Bad childlist argument";
|
---|
| 2243 | return;
|
---|
| 2244 | }
|
---|
| 2245 |
|
---|
[237] | 2246 | my @filterargs;
|
---|
[239] | 2247 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2248 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2249 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
[237] | 2250 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2251 |
|
---|
| 2252 | my $sql;
|
---|
| 2253 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
| 2254 | if ($args{revrec} eq 'n') {
|
---|
| 2255 | $sql = "SELECT count(*) FROM domains".
|
---|
| 2256 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2257 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
| 2258 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
| 2259 | } else {
|
---|
| 2260 | $sql = "SELECT count(*) FROM revzones".
|
---|
| 2261 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2262 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
|
---|
| 2263 | ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2264 | }
|
---|
| 2265 | my ($count) = $dbh->selectrow_array($sql, undef, @filterargs);
|
---|
| 2266 | return $count;
|
---|
| 2267 | } # end getZoneCount()
|
---|
| 2268 |
|
---|
| 2269 |
|
---|
| 2270 | ## DNSDB::getZoneList()
|
---|
| 2271 | # Get a list of zones in the specified group(s)
|
---|
| 2272 | # Takes the same arguments as getZoneCount() above
|
---|
| 2273 | # Returns a reference to an array of hashrefs suitable for feeding to HTML::Template
|
---|
| 2274 | sub getZoneList {
|
---|
[477] | 2275 | my $self = shift;
|
---|
| 2276 | my $dbh = $self->{dbh};
|
---|
[237] | 2277 |
|
---|
| 2278 | my %args = @_;
|
---|
| 2279 |
|
---|
| 2280 | my @zonelist;
|
---|
| 2281 |
|
---|
[475] | 2282 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
[239] | 2283 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[237] | 2284 |
|
---|
[509] | 2285 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 2286 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 2287 | $errstr = "Bad or missing curgroup argument";
|
---|
| 2288 | return;
|
---|
| 2289 | }
|
---|
| 2290 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 2291 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 2292 | $errstr = "Bad childlist argument";
|
---|
| 2293 | return;
|
---|
| 2294 | }
|
---|
| 2295 |
|
---|
[237] | 2296 | my @filterargs;
|
---|
[239] | 2297 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2298 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2299 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
[237] | 2300 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2301 |
|
---|
| 2302 | my $sql;
|
---|
| 2303 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
| 2304 | if ($args{revrec} eq 'n') {
|
---|
[475] | 2305 | $args{sortby} = 'domain' if !$args{sortby} || !grep /^$args{sortby}$/, ('domain','group','status');
|
---|
[237] | 2306 | $sql = "SELECT domain_id,domain,status,groups.group_name AS group FROM domains".
|
---|
| 2307 | " INNER JOIN groups ON domains.group_id=groups.group_id".
|
---|
| 2308 | " WHERE domains.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2309 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
| 2310 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
| 2311 | } else {
|
---|
[239] | 2312 | ##fixme: arguably startwith here is irrelevant. depends on the UI though.
|
---|
[475] | 2313 | $args{sortby} = 'revnet' if !$args{sortby} || !grep /^$args{sortby}$/, ('revnet','group','status');
|
---|
[237] | 2314 | $sql = "SELECT rdns_id,revnet,status,groups.group_name AS group FROM revzones".
|
---|
| 2315 | " INNER JOIN groups ON revzones.group_id=groups.group_id".
|
---|
| 2316 | " WHERE revzones.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2317 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
|
---|
| 2318 | ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2319 | }
|
---|
| 2320 | # A common tail.
|
---|
[239] | 2321 | $sql .= " ORDER BY ".($args{sortby} eq 'group' ? 'groups.group_name' : $args{sortby})." $args{sortorder} ".
|
---|
[517] | 2322 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage}".
|
---|
| 2323 | " OFFSET ".$args{offset}*$self->{perpage});
|
---|
[402] | 2324 | my $sth = $dbh->prepare($sql);
|
---|
| 2325 | $sth->execute(@filterargs);
|
---|
| 2326 | my $rownum = 0;
|
---|
[237] | 2327 |
|
---|
[402] | 2328 | while (my @data = $sth->fetchrow_array) {
|
---|
| 2329 | my %row;
|
---|
| 2330 | $row{domain_id} = $data[0];
|
---|
| 2331 | $row{domain} = $data[1];
|
---|
| 2332 | $row{status} = $data[2];
|
---|
| 2333 | $row{group} = $data[3];
|
---|
| 2334 | push @zonelist, \%row;
|
---|
| 2335 | }
|
---|
| 2336 |
|
---|
| 2337 | return \@zonelist;
|
---|
[237] | 2338 | } # end getZoneList()
|
---|
| 2339 |
|
---|
| 2340 |
|
---|
[383] | 2341 | ## DNSDB::getZoneLocation()
|
---|
[387] | 2342 | # Retrieve the default location for a zone.
|
---|
[383] | 2343 | # Takes a database handle, forward/reverse flag, and zone ID
|
---|
| 2344 | sub getZoneLocation {
|
---|
[477] | 2345 | my $self = shift;
|
---|
| 2346 | my $dbh = $self->{dbh};
|
---|
[383] | 2347 | my $revrec = shift;
|
---|
| 2348 | my $zoneid = shift;
|
---|
| 2349 |
|
---|
| 2350 | my ($loc) = $dbh->selectrow_array("SELECT default_location FROM ".
|
---|
| 2351 | ($revrec eq 'n' ? 'domains WHERE domain_id = ?' : 'revzones WHERE rdns_id = ?'),
|
---|
| 2352 | undef, ($zoneid));
|
---|
| 2353 | return $loc;
|
---|
| 2354 | } # end getZoneLocation()
|
---|
| 2355 |
|
---|
| 2356 |
|
---|
[18] | 2357 | ## DNSDB::addGroup()
|
---|
| 2358 | # Add a group
|
---|
[66] | 2359 | # Takes a database handle, group name, parent group, hashref for permissions,
|
---|
[292] | 2360 | # and optional template-vs-cloneme flag for the default records
|
---|
[18] | 2361 | # Returns a status code and message
|
---|
| 2362 | sub addGroup {
|
---|
| 2363 | $errstr = '';
|
---|
[476] | 2364 | my $self = shift;
|
---|
| 2365 | my $dbh = $self->{dbh};
|
---|
[20] | 2366 | my $groupname = shift;
|
---|
| 2367 | my $pargroup = shift;
|
---|
[66] | 2368 | my $permissions = shift;
|
---|
[18] | 2369 |
|
---|
[66] | 2370 | # 0 indicates "custom", hardcoded.
|
---|
[18] | 2371 | # Any other value clones that group's default records, if it exists.
|
---|
[66] | 2372 | my $inherit = shift || 0;
|
---|
| 2373 | ##fixme: need a flag to indicate clone records or <?> ?
|
---|
[18] | 2374 |
|
---|
| 2375 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2376 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2377 | local $dbh->{AutoCommit} = 0;
|
---|
| 2378 | local $dbh->{RaiseError} = 1;
|
---|
| 2379 |
|
---|
[292] | 2380 | my ($group_id) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($groupname));
|
---|
[38] | 2381 |
|
---|
| 2382 | return ('FAIL', "Group already exists") if $group_id;
|
---|
| 2383 |
|
---|
[18] | 2384 | # Wrap all the SQL in a transaction
|
---|
| 2385 | eval {
|
---|
[292] | 2386 | $dbh->do("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)", undef, ($pargroup, $groupname) );
|
---|
[18] | 2387 |
|
---|
[292] | 2388 | my ($groupid) = $dbh->selectrow_array("SELECT currval('groups_group_id_seq')");
|
---|
[18] | 2389 |
|
---|
[292] | 2390 | # We work through the whole set of permissions instead of specifying them so
|
---|
| 2391 | # that when we add a new permission, we don't have to change the code anywhere
|
---|
| 2392 | # that doesn't explicitly deal with that specific permission.
|
---|
| 2393 | my @permvals;
|
---|
| 2394 | foreach (@permtypes) {
|
---|
| 2395 | if (!defined ($permissions->{$_})) {
|
---|
| 2396 | push @permvals, 0;
|
---|
| 2397 | } else {
|
---|
| 2398 | push @permvals, $permissions->{$_};
|
---|
[66] | 2399 | }
|
---|
[292] | 2400 | }
|
---|
| 2401 | $dbh->do("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")",
|
---|
| 2402 | undef, ($groupid, @permvals) );
|
---|
| 2403 | my ($permid) = $dbh->selectrow_array("SELECT currval('permissions_permission_id_seq')");
|
---|
| 2404 | $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
|
---|
[66] | 2405 |
|
---|
[292] | 2406 | # Default records
|
---|
[255] | 2407 | my $sthf = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
|
---|
[20] | 2408 | "VALUES ($groupid,?,?,?,?,?,?,?)");
|
---|
[255] | 2409 | my $sthr = $dbh->prepare("INSERT INTO default_rev_records (group_id,host,type,val,ttl) ".
|
---|
| 2410 | "VALUES ($groupid,?,?,?,?)");
|
---|
[66] | 2411 | if ($inherit) {
|
---|
[87] | 2412 | # Duplicate records from parent. Actually relying on inherited records feels
|
---|
| 2413 | # very fragile, and it would be problematic to roll over at a later time.
|
---|
[18] | 2414 | my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
[87] | 2415 | $sth2->execute($pargroup);
|
---|
[18] | 2416 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
[255] | 2417 | $sthf->execute(@clonedata);
|
---|
[18] | 2418 | }
|
---|
[255] | 2419 | # And now the reverse records
|
---|
[292] | 2420 | $sth2 = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
[255] | 2421 | $sth2->execute($pargroup);
|
---|
| 2422 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
| 2423 | $sthr->execute(@clonedata);
|
---|
| 2424 | }
|
---|
[18] | 2425 | } else {
|
---|
[66] | 2426 | ##fixme: Hardcoding is Bad, mmmmkaaaay?
|
---|
[18] | 2427 | # reasonable basic defaults for SOA, MX, NS, and minimal hosting
|
---|
| 2428 | # could load from a config file, but somewhere along the line we need hardcoded bits.
|
---|
[255] | 2429 | $sthf->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
|
---|
| 2430 | $sthf->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
|
---|
| 2431 | $sthf->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
|
---|
| 2432 | $sthf->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
|
---|
| 2433 | $sthf->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
|
---|
| 2434 | $sthf->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
|
---|
| 2435 | # reasonable basic defaults for generic reverse zone. Same as initial SQL tabledef.
|
---|
| 2436 | $sthr->execute('hostmaster.ADMINDOMAIN:ns1.ADMINDOMAIN', 6, '10800:3600:604800:10800', 86400);
|
---|
| 2437 | $sthr->execute('unused-%r.ADMINDOMAIN', 65283, 'ZONE', 3600);
|
---|
[18] | 2438 | }
|
---|
| 2439 |
|
---|
[487] | 2440 | $self->_log(group_id => $pargroup, entry => "Added group $groupname");
|
---|
[292] | 2441 |
|
---|
[18] | 2442 | # once we get here, we should have suceeded.
|
---|
| 2443 | $dbh->commit;
|
---|
| 2444 | }; # end eval
|
---|
| 2445 |
|
---|
| 2446 | if ($@) {
|
---|
| 2447 | my $msg = $@;
|
---|
| 2448 | eval { $dbh->rollback; };
|
---|
[517] | 2449 | if ($self->{log_failures}) {
|
---|
[487] | 2450 | $self->_log(group_id => $pargroup, entry => "Failed to add group $groupname: $msg");
|
---|
[292] | 2451 | $dbh->commit;
|
---|
| 2452 | }
|
---|
[18] | 2453 | return ('FAIL',$msg);
|
---|
| 2454 | }
|
---|
| 2455 |
|
---|
[292] | 2456 | return ('OK','OK');
|
---|
[18] | 2457 | } # end addGroup()
|
---|
| 2458 |
|
---|
| 2459 |
|
---|
[22] | 2460 | ## DNSDB::delGroup()
|
---|
| 2461 | # Delete a group.
|
---|
| 2462 | # Takes a group ID
|
---|
| 2463 | # Returns a status code and message
|
---|
| 2464 | sub delGroup {
|
---|
[476] | 2465 | my $self = shift;
|
---|
| 2466 | my $dbh = $self->{dbh};
|
---|
[22] | 2467 | my $groupid = shift;
|
---|
| 2468 |
|
---|
| 2469 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2470 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2471 | local $dbh->{AutoCommit} = 0;
|
---|
| 2472 | local $dbh->{RaiseError} = 1;
|
---|
| 2473 |
|
---|
| 2474 | ##fixme: locate "knowable" error conditions and deal with them before the eval
|
---|
[23] | 2475 | # ... or inside, whatever.
|
---|
[22] | 2476 | # -> domains still exist in group
|
---|
| 2477 | # -> ...
|
---|
[23] | 2478 | my $failmsg = '';
|
---|
[293] | 2479 | my $resultmsg = '';
|
---|
[22] | 2480 |
|
---|
[293] | 2481 | # collect some pieces for logging and error messages
|
---|
[473] | 2482 | my $groupname = $self->groupName($groupid);
|
---|
| 2483 | my $parid = $self->parentID(id => $groupid, type => 'group');
|
---|
[293] | 2484 |
|
---|
[22] | 2485 | # Wrap all the SQL in a transaction
|
---|
| 2486 | eval {
|
---|
[293] | 2487 | # Check for Things in the group
|
---|
| 2488 | $failmsg = "Can't remove group $groupname";
|
---|
| 2489 | my ($grpcnt) = $dbh->selectrow_array("SELECT count(*) FROM groups WHERE parent_group_id=?", undef, ($groupid));
|
---|
| 2490 | die "$grpcnt groups still in group\n" if $grpcnt;
|
---|
| 2491 | my ($domcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($groupid));
|
---|
[23] | 2492 | die "$domcnt domains still in group\n" if $domcnt;
|
---|
[512] | 2493 | my ($revcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($groupid));
|
---|
| 2494 | die "$revcnt reverse zones still in group\n" if $revcnt;
|
---|
[293] | 2495 | my ($usercnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($groupid));
|
---|
| 2496 | die "$usercnt users still in group\n" if $usercnt;
|
---|
[23] | 2497 |
|
---|
[293] | 2498 | $failmsg = "Failed to delete default records for $groupname";
|
---|
| 2499 | $dbh->do("DELETE from default_records WHERE group_id=?", undef, ($groupid));
|
---|
| 2500 | $failmsg = "Failed to delete default reverse records for $groupname";
|
---|
| 2501 | $dbh->do("DELETE from default_rev_records WHERE group_id=?", undef, ($groupid));
|
---|
| 2502 | $failmsg = "Failed to remove group $groupname";
|
---|
| 2503 | $dbh->do("DELETE from groups WHERE group_id=?", undef, ($groupid));
|
---|
[22] | 2504 |
|
---|
[487] | 2505 | $self->_log(group_id => $parid, entry => "Deleted group $groupname");
|
---|
[293] | 2506 | $resultmsg = "Deleted group $groupname";
|
---|
| 2507 |
|
---|
[22] | 2508 | # once we get here, we should have suceeded.
|
---|
| 2509 | $dbh->commit;
|
---|
| 2510 | }; # end eval
|
---|
| 2511 |
|
---|
| 2512 | if ($@) {
|
---|
| 2513 | my $msg = $@;
|
---|
| 2514 | eval { $dbh->rollback; };
|
---|
[517] | 2515 | if ($self->{log_failures}) {
|
---|
[487] | 2516 | $self->_log(group_id => $parid, entry => "$failmsg: $msg");
|
---|
[293] | 2517 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2518 | }
|
---|
[23] | 2519 | return ('FAIL',"$failmsg: $msg");
|
---|
[22] | 2520 | }
|
---|
[293] | 2521 |
|
---|
| 2522 | return ('OK',$resultmsg);
|
---|
[22] | 2523 | } # end delGroup()
|
---|
| 2524 |
|
---|
| 2525 |
|
---|
[19] | 2526 | ## DNSDB::getChildren()
|
---|
| 2527 | # Get a list of all groups whose parent^n is group <n>
|
---|
[24] | 2528 | # Takes a database handle, group ID, reference to an array to put the group IDs in,
|
---|
| 2529 | # and an optional flag to return only immediate children or all children-of-children
|
---|
| 2530 | # default to returning all children
|
---|
[19] | 2531 | # Calls itself
|
---|
| 2532 | sub getChildren {
|
---|
| 2533 | $errstr = '';
|
---|
[476] | 2534 | my $self = shift;
|
---|
| 2535 | my $dbh = $self->{dbh};
|
---|
[20] | 2536 | my $rootgroup = shift;
|
---|
| 2537 | my $groupdest = shift;
|
---|
[24] | 2538 | my $immed = shift || 'all';
|
---|
[19] | 2539 |
|
---|
| 2540 | # special break for default group; otherwise we get stuck.
|
---|
[20] | 2541 | if ($rootgroup == 1) {
|
---|
[19] | 2542 | # by definition, group 1 is the Root Of All Groups
|
---|
[24] | 2543 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
|
---|
[331] | 2544 | ($immed ne 'all' ? " AND parent_group_id=1" : '')." ORDER BY group_name");
|
---|
[19] | 2545 | $sth->execute;
|
---|
| 2546 | while (my @this = $sth->fetchrow_array) {
|
---|
[20] | 2547 | push @$groupdest, @this;
|
---|
[19] | 2548 | }
|
---|
| 2549 | } else {
|
---|
[331] | 2550 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=? ORDER BY group_name");
|
---|
[20] | 2551 | $sth->execute($rootgroup);
|
---|
[19] | 2552 | return if $sth->rows == 0;
|
---|
[20] | 2553 | my @grouplist;
|
---|
| 2554 | while (my ($group) = $sth->fetchrow_array) {
|
---|
| 2555 | push @$groupdest, $group;
|
---|
[476] | 2556 | $self->getChildren($group, $groupdest) if $immed eq 'all';
|
---|
[19] | 2557 | }
|
---|
| 2558 | }
|
---|
| 2559 | } # end getChildren()
|
---|
| 2560 |
|
---|
| 2561 |
|
---|
[20] | 2562 | ## DNSDB::groupName()
|
---|
[17] | 2563 | # Return the group name based on a group ID
|
---|
| 2564 | # Takes a database handle and the group ID
|
---|
| 2565 | # Returns the group name or undef on failure
|
---|
[20] | 2566 | sub groupName {
|
---|
[13] | 2567 | $errstr = '';
|
---|
[473] | 2568 | my $self = shift;
|
---|
| 2569 | my $dbh = $self->{dbh};
|
---|
[20] | 2570 | my $groupid = shift;
|
---|
| 2571 | my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
|
---|
| 2572 | $sth->execute($groupid);
|
---|
| 2573 | my ($groupname) = $sth->fetchrow_array();
|
---|
| 2574 | $errstr = $DBI::errstr if !$groupname;
|
---|
| 2575 | return $groupname if $groupname;
|
---|
| 2576 | } # end groupName
|
---|
[13] | 2577 |
|
---|
| 2578 |
|
---|
[314] | 2579 | ## DNSDB::getGroupCount()
|
---|
| 2580 | # Get count of subgroups in group or groups
|
---|
| 2581 | # Takes a database handle and hash containing:
|
---|
| 2582 | # - the "current" group
|
---|
| 2583 | # - an array of "acceptable" groups
|
---|
| 2584 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
| 2585 | # Returns an integer count of the resulting group list.
|
---|
| 2586 | sub getGroupCount {
|
---|
[476] | 2587 | my $self = shift;
|
---|
| 2588 | my $dbh = $self->{dbh};
|
---|
[314] | 2589 |
|
---|
| 2590 | my %args = @_;
|
---|
| 2591 |
|
---|
[509] | 2592 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 2593 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 2594 | $errstr = "Bad or missing curgroup argument";
|
---|
| 2595 | return;
|
---|
| 2596 | }
|
---|
| 2597 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 2598 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 2599 | $errstr = "Bad childlist argument";
|
---|
| 2600 | return;
|
---|
| 2601 | }
|
---|
| 2602 |
|
---|
[314] | 2603 | my @filterargs;
|
---|
| 2604 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2605 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2606 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2607 |
|
---|
| 2608 | my $sql = "SELECT count(*) FROM groups ".
|
---|
| 2609 | "WHERE parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2610 | ($args{startwith} ? " AND group_name ~* ?" : '').
|
---|
| 2611 | ($args{filter} ? " AND group_name ~* ?" : '');
|
---|
| 2612 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 2613 | $errstr = $dbh->errstr if !$count;
|
---|
| 2614 | return $count;
|
---|
| 2615 | } # end getGroupCount
|
---|
| 2616 |
|
---|
| 2617 |
|
---|
| 2618 | ## DNSDB::getGroupList()
|
---|
| 2619 | # Get a list of sub^n-groups in the specified group(s)
|
---|
| 2620 | # Takes the same arguments as getGroupCount() above
|
---|
| 2621 | # Returns an arrayref containing hashrefs suitable for feeding straight to HTML::Template
|
---|
| 2622 | sub getGroupList {
|
---|
[476] | 2623 | my $self = shift;
|
---|
| 2624 | my $dbh = $self->{dbh};
|
---|
[314] | 2625 |
|
---|
| 2626 | my %args = @_;
|
---|
| 2627 |
|
---|
[509] | 2628 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 2629 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 2630 | $errstr = "Bad or missing curgroup argument";
|
---|
| 2631 | return;
|
---|
| 2632 | }
|
---|
| 2633 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 2634 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 2635 | $errstr = "Bad childlist argument";
|
---|
| 2636 | return;
|
---|
| 2637 | }
|
---|
| 2638 |
|
---|
[314] | 2639 | my @filterargs;
|
---|
| 2640 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2641 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2642 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2643 |
|
---|
| 2644 | # protection against bad or missing arguments
|
---|
[508] | 2645 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
| 2646 | $args{sortby} = 'group' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
[397] | 2647 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[314] | 2648 |
|
---|
| 2649 | # munge sortby for columns in database
|
---|
| 2650 | $args{sortby} = 'g.group_name' if $args{sortby} eq 'group';
|
---|
| 2651 | $args{sortby} = 'g2.group_name' if $args{sortby} eq 'parent';
|
---|
| 2652 |
|
---|
[385] | 2653 | my $sql = q(SELECT g.group_id AS groupid, g.group_name AS groupname, g2.group_name AS pgroup
|
---|
[314] | 2654 | FROM groups g
|
---|
| 2655 | INNER JOIN groups g2 ON g2.group_id=g.parent_group_id
|
---|
| 2656 | ).
|
---|
[385] | 2657 | " WHERE g.parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
[314] | 2658 | ($args{startwith} ? " AND g.group_name ~* ?" : '').
|
---|
| 2659 | ($args{filter} ? " AND g.group_name ~* ?" : '').
|
---|
| 2660 | " GROUP BY g.group_id, g.group_name, g2.group_name ".
|
---|
| 2661 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
[517] | 2662 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
[314] | 2663 | my $glist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 2664 | $errstr = $dbh->errstr if !$glist;
|
---|
[385] | 2665 |
|
---|
| 2666 | # LEFT JOINs make the result set balloon beyond sanity just to include counts;
|
---|
| 2667 | # this means there's lots of crunching needed to trim the result set back down.
|
---|
| 2668 | # So instead we track the order of the groups, and push the counts into the
|
---|
| 2669 | # arrayref result separately.
|
---|
| 2670 | ##fixme: put this whole sub in a transaction? might be
|
---|
| 2671 | # needed for accurate results on very busy systems.
|
---|
[386] | 2672 | ##fixme: large group lists need prepared statements?
|
---|
| 2673 | #my $ucsth = $dbh->prepare("SELECT count(*) FROM users WHERE group_id=?");
|
---|
| 2674 | #my $dcsth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
|
---|
| 2675 | #my $rcsth = $dbh->prepare("SELECT count(*) FROM revzones WHERE group_id=?");
|
---|
[385] | 2676 | foreach (@{$glist}) {
|
---|
[386] | 2677 | my ($ucnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 2678 | $$_{nusers} = $ucnt;
|
---|
| 2679 | my ($dcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 2680 | $$_{ndomains} = $dcnt;
|
---|
| 2681 | my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 2682 | $$_{nrevzones} = $rcnt;
|
---|
[385] | 2683 | }
|
---|
| 2684 |
|
---|
[314] | 2685 | return $glist;
|
---|
| 2686 | } # end getGroupList
|
---|
| 2687 |
|
---|
| 2688 |
|
---|
[118] | 2689 | ## DNSDB::groupID()
|
---|
| 2690 | # Return the group ID based on the group name
|
---|
| 2691 | # Takes a database handle and the group name
|
---|
| 2692 | # Returns the group ID or undef on failure
|
---|
| 2693 | sub groupID {
|
---|
| 2694 | $errstr = '';
|
---|
[473] | 2695 | my $self = shift;
|
---|
| 2696 | my $dbh = $self->{dbh};
|
---|
[118] | 2697 | my $group = shift;
|
---|
[406] | 2698 | my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($group) );
|
---|
[118] | 2699 | $errstr = $DBI::errstr if !$grpid;
|
---|
| 2700 | return $grpid if $grpid;
|
---|
| 2701 | } # end groupID()
|
---|
| 2702 |
|
---|
| 2703 |
|
---|
[24] | 2704 | ## DNSDB::addUser()
|
---|
[87] | 2705 | # Add a user.
|
---|
| 2706 | # Takes a DB handle, username, group ID, password, state (active/inactive).
|
---|
| 2707 | # Optionally accepts:
|
---|
| 2708 | # user type (user/admin) - defaults to user
|
---|
| 2709 | # permissions string - defaults to inherit from group
|
---|
| 2710 | # three valid forms:
|
---|
| 2711 | # i - Inherit permissions
|
---|
| 2712 | # c:<user_id> - Clone permissions from <user_id>
|
---|
| 2713 | # C:<permission list> - Set these specific permissions
|
---|
| 2714 | # first name - defaults to username
|
---|
| 2715 | # last name - defaults to blank
|
---|
| 2716 | # phone - defaults to blank (could put other data within column def)
|
---|
[90] | 2717 | # Returns (OK,<uid>) on success, (FAIL,<message>) on failure
|
---|
[24] | 2718 | sub addUser {
|
---|
| 2719 | $errstr = '';
|
---|
[479] | 2720 | my $self = shift;
|
---|
| 2721 | my $dbh = $self->{dbh};
|
---|
[24] | 2722 | my $username = shift;
|
---|
| 2723 | my $group = shift;
|
---|
| 2724 | my $pass = shift;
|
---|
| 2725 | my $state = shift;
|
---|
[25] | 2726 |
|
---|
[90] | 2727 | return ('FAIL', "Missing one or more required entries") if !defined($state);
|
---|
| 2728 | return ('FAIL', "Username must not be blank") if !$username;
|
---|
[87] | 2729 |
|
---|
[408] | 2730 | # Munge in some alternate state values
|
---|
| 2731 | $state = 1 if $state =~ /^active$/;
|
---|
| 2732 | $state = 1 if $state =~ /^on$/;
|
---|
| 2733 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 2734 | $state = 0 if $state =~ /^off$/;
|
---|
| 2735 |
|
---|
[25] | 2736 | my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
|
---|
| 2737 |
|
---|
[67] | 2738 | my $permstring = shift || 'i'; # default is to inhert permissions from group
|
---|
| 2739 |
|
---|
[25] | 2740 | my $fname = shift || $username;
|
---|
[24] | 2741 | my $lname = shift || '';
|
---|
[25] | 2742 | my $phone = shift || ''; # not going format-check
|
---|
[24] | 2743 |
|
---|
[38] | 2744 | my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
|
---|
[24] | 2745 | my $user_id;
|
---|
| 2746 |
|
---|
[38] | 2747 | # quick check to start to see if we've already got one
|
---|
| 2748 | $sth->execute($username);
|
---|
| 2749 | ($user_id) = $sth->fetchrow_array;
|
---|
| 2750 |
|
---|
| 2751 | return ('FAIL', "User already exists") if $user_id;
|
---|
| 2752 |
|
---|
[24] | 2753 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2754 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2755 | local $dbh->{AutoCommit} = 0;
|
---|
| 2756 | local $dbh->{RaiseError} = 1;
|
---|
| 2757 |
|
---|
| 2758 | # Wrap all the SQL in a transaction
|
---|
| 2759 | eval {
|
---|
[87] | 2760 | # insert the user... note we set inherited perms by default since
|
---|
| 2761 | # it's simple and cleans up some other bits of state
|
---|
| 2762 | my $sth = $dbh->prepare("INSERT INTO users ".
|
---|
| 2763 | "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
|
---|
| 2764 | "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
|
---|
| 2765 | $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);
|
---|
[24] | 2766 |
|
---|
| 2767 | # get the ID...
|
---|
[94] | 2768 | ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");
|
---|
[24] | 2769 |
|
---|
[87] | 2770 | # Permissions! Gotta set'em all!
|
---|
[401] | 2771 | die "Invalid permission string $permstring\n"
|
---|
[87] | 2772 | if $permstring !~ /^(?:
|
---|
| 2773 | i # inherit
|
---|
| 2774 | |c:\d+ # clone
|
---|
| 2775 | # custom. no, the leading , is not a typo
|
---|
[391] | 2776 | |C:(?:,(?:group|user|domain|record|location|self)_(?:edit|create|delete|locchg|view))*
|
---|
[87] | 2777 | )$/x;
|
---|
| 2778 | # bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
|
---|
| 2779 | if ($permstring ne 'i') {
|
---|
| 2780 | # for cloned or custom permissions, we have to create a new permissions entry.
|
---|
| 2781 | my $clonesrc = $group;
|
---|
| 2782 | if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
|
---|
| 2783 | $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
|
---|
| 2784 | "SELECT $permlist,? FROM permissions WHERE permission_id=".
|
---|
| 2785 | "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
|
---|
| 2786 | undef, ($user_id,$clonesrc) );
|
---|
| 2787 | $dbh->do("UPDATE users SET permission_id=".
|
---|
| 2788 | "(SELECT permission_id FROM permissions WHERE user_id=?) ".
|
---|
| 2789 | "WHERE user_id=?", undef, ($user_id, $user_id) );
|
---|
| 2790 | }
|
---|
| 2791 | if ($permstring =~ /^C:/) {
|
---|
| 2792 | # finally for custom permissions, we set the passed-in permissions (and unset
|
---|
| 2793 | # any that might have been brought in by the clone operation above)
|
---|
| 2794 | my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
|
---|
| 2795 | undef, ($user_id) );
|
---|
| 2796 | foreach (@permtypes) {
|
---|
| 2797 | if ($permstring =~ /,$_/) {
|
---|
| 2798 | $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
|
---|
| 2799 | } else {
|
---|
| 2800 | $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
|
---|
| 2801 | }
|
---|
| 2802 | }
|
---|
| 2803 | }
|
---|
| 2804 |
|
---|
| 2805 | $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
|
---|
| 2806 |
|
---|
[25] | 2807 | ##fixme: add another table to hold name/email for log table?
|
---|
| 2808 |
|
---|
[487] | 2809 | $self->_log(group_id => $group, entry => "Added user $username ($fname $lname)");
|
---|
[24] | 2810 | # once we get here, we should have suceeded.
|
---|
| 2811 | $dbh->commit;
|
---|
| 2812 | }; # end eval
|
---|
| 2813 |
|
---|
| 2814 | if ($@) {
|
---|
| 2815 | my $msg = $@;
|
---|
| 2816 | eval { $dbh->rollback; };
|
---|
[517] | 2817 | if ($self->{log_failures}) {
|
---|
[487] | 2818 | $self->_log(group_id => $group, entry => "Error adding user $username: $msg");
|
---|
[294] | 2819 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2820 | }
|
---|
| 2821 | return ('FAIL',"Error adding user $username: $msg");
|
---|
[24] | 2822 | }
|
---|
[294] | 2823 |
|
---|
| 2824 | return ('OK',"User $username ($fname $lname) added");
|
---|
[24] | 2825 | } # end addUser
|
---|
| 2826 |
|
---|
| 2827 |
|
---|
[325] | 2828 | ## DNSDB::getUserCount()
|
---|
| 2829 | # Get count of users in group
|
---|
| 2830 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
| 2831 | # - a reference list of secondary groups
|
---|
| 2832 | # - a filter string
|
---|
| 2833 | # - a "Starts with" string
|
---|
| 2834 | sub getUserCount {
|
---|
[479] | 2835 | my $self = shift;
|
---|
| 2836 | my $dbh = $self->{dbh};
|
---|
[325] | 2837 |
|
---|
| 2838 | my %args = @_;
|
---|
| 2839 |
|
---|
[509] | 2840 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 2841 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 2842 | $errstr = "Bad or missing curgroup argument";
|
---|
| 2843 | return;
|
---|
| 2844 | }
|
---|
| 2845 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 2846 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 2847 | $errstr = "Bad childlist argument";
|
---|
| 2848 | return;
|
---|
| 2849 | }
|
---|
| 2850 |
|
---|
[325] | 2851 | my @filterargs;
|
---|
| 2852 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2853 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2854 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2855 |
|
---|
| 2856 | my $sql = "SELECT count(*) FROM users ".
|
---|
| 2857 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2858 | ($args{startwith} ? " AND username ~* ?" : '').
|
---|
| 2859 | ($args{filter} ? " AND username ~* ?" : '');
|
---|
| 2860 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 2861 | $errstr = $dbh->errstr if !$count;
|
---|
| 2862 | return $count;
|
---|
| 2863 | } # end getUserCount()
|
---|
| 2864 |
|
---|
| 2865 |
|
---|
| 2866 | ## DNSDB::getUserList()
|
---|
| 2867 | # Get list of users
|
---|
| 2868 | # Takes the same arguments as getUserCount() above, plus optional:
|
---|
| 2869 | # - sort field
|
---|
| 2870 | # - sort order
|
---|
| 2871 | # - offset/return-all-everything flag (defaults to $perpage records)
|
---|
| 2872 | sub getUserList {
|
---|
[479] | 2873 | my $self = shift;
|
---|
| 2874 | my $dbh = $self->{dbh};
|
---|
[325] | 2875 |
|
---|
| 2876 | my %args = @_;
|
---|
| 2877 |
|
---|
[509] | 2878 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 2879 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 2880 | $errstr = "Bad or missing curgroup argument";
|
---|
| 2881 | return;
|
---|
| 2882 | }
|
---|
| 2883 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 2884 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 2885 | $errstr = "Bad childlist argument";
|
---|
| 2886 | return;
|
---|
| 2887 | }
|
---|
| 2888 |
|
---|
[325] | 2889 | my @filterargs;
|
---|
| 2890 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2891 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2892 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2893 |
|
---|
| 2894 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
| 2895 | my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
| 2896 | fname => 'fname');
|
---|
| 2897 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 2898 |
|
---|
| 2899 | # protection against bad or missing arguments
|
---|
[508] | 2900 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
| 2901 | $args{sortby} = 'u.username' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
[397] | 2902 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[325] | 2903 |
|
---|
| 2904 | my $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ".
|
---|
| 2905 | "FROM users u ".
|
---|
| 2906 | "INNER JOIN groups g ON u.group_id=g.group_id ".
|
---|
| 2907 | "WHERE u.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2908 | ($args{startwith} ? " AND u.username ~* ?" : '').
|
---|
| 2909 | ($args{filter} ? " AND u.username ~* ?" : '').
|
---|
[401] | 2910 | " AND NOT u.type = 'R' ".
|
---|
[325] | 2911 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
[517] | 2912 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
[325] | 2913 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 2914 | $errstr = $dbh->errstr if !$ulist;
|
---|
| 2915 | return $ulist;
|
---|
| 2916 | } # end getUserList()
|
---|
| 2917 |
|
---|
| 2918 |
|
---|
[326] | 2919 | ## DNSDB::getUserDropdown()
|
---|
| 2920 | # Get a list of usernames for use in a dropdown menu.
|
---|
| 2921 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
| 2922 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
| 2923 | sub getUserDropdown {
|
---|
[479] | 2924 | my $self = shift;
|
---|
| 2925 | my $dbh = $self->{dbh};
|
---|
[326] | 2926 | my $grp = shift;
|
---|
| 2927 | my $sel = shift || 0;
|
---|
| 2928 |
|
---|
| 2929 | my $sth = $dbh->prepare("SELECT username,user_id FROM users WHERE group_id=?");
|
---|
| 2930 | $sth->execute($grp);
|
---|
| 2931 |
|
---|
| 2932 | my @userlist;
|
---|
| 2933 | while (my ($username,$uid) = $sth->fetchrow_array) {
|
---|
| 2934 | my %row = (
|
---|
| 2935 | username => $username,
|
---|
| 2936 | uid => $uid,
|
---|
| 2937 | selected => ($sel == $uid ? 1 : 0)
|
---|
| 2938 | );
|
---|
| 2939 | push @userlist, \%row;
|
---|
| 2940 | }
|
---|
| 2941 | return \@userlist;
|
---|
| 2942 | } # end getUserDropdown()
|
---|
| 2943 |
|
---|
| 2944 |
|
---|
[83] | 2945 | ## DNSDB:: updateUser()
|
---|
[90] | 2946 | # Update general data about user
|
---|
[83] | 2947 | sub updateUser {
|
---|
[479] | 2948 | my $self = shift;
|
---|
| 2949 | my $dbh = $self->{dbh};
|
---|
[118] | 2950 |
|
---|
| 2951 | ##fixme: tweak calling convention so that we can update any given bit of data
|
---|
[83] | 2952 | my $uid = shift;
|
---|
| 2953 | my $username = shift;
|
---|
| 2954 | my $group = shift;
|
---|
| 2955 | my $pass = shift;
|
---|
| 2956 | my $state = shift;
|
---|
[87] | 2957 | my $type = shift || 'u';
|
---|
[83] | 2958 | my $fname = shift || $username;
|
---|
| 2959 | my $lname = shift || '';
|
---|
| 2960 | my $phone = shift || ''; # not going format-check
|
---|
| 2961 |
|
---|
[294] | 2962 | my $resultmsg = '';
|
---|
[83] | 2963 |
|
---|
[411] | 2964 | # Munge in some alternate state values
|
---|
| 2965 | $state = 1 if $state =~ /^active$/;
|
---|
| 2966 | $state = 1 if $state =~ /^on$/;
|
---|
| 2967 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 2968 | $state = 0 if $state =~ /^off$/;
|
---|
| 2969 |
|
---|
[83] | 2970 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2971 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2972 | local $dbh->{AutoCommit} = 0;
|
---|
| 2973 | local $dbh->{RaiseError} = 1;
|
---|
| 2974 |
|
---|
| 2975 | my $sth;
|
---|
| 2976 |
|
---|
| 2977 | # Password can be left blank; if so we assume there's one on file.
|
---|
| 2978 | # Actual blank passwords are bad, mm'kay?
|
---|
| 2979 | if (!$pass) {
|
---|
[294] | 2980 | ($pass) = $dbh->selectrow_array("SELECT password FROM users WHERE user_id=?", undef, ($uid));
|
---|
[83] | 2981 | } else {
|
---|
| 2982 | $pass = unix_md5_crypt($pass);
|
---|
| 2983 | }
|
---|
| 2984 |
|
---|
| 2985 | eval {
|
---|
[294] | 2986 | $dbh->do("UPDATE users SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?".
|
---|
| 2987 | " WHERE user_id=?", undef, ($username, $pass, $fname, $lname, $phone, $type, $state, $uid));
|
---|
| 2988 | $resultmsg = "Updated user info for $username ($fname $lname)";
|
---|
[487] | 2989 | $self->_log(group_id => $group, entry => $resultmsg);
|
---|
[83] | 2990 | $dbh->commit;
|
---|
| 2991 | };
|
---|
| 2992 | if ($@) {
|
---|
| 2993 | my $msg = $@;
|
---|
| 2994 | eval { $dbh->rollback; };
|
---|
[517] | 2995 | if ($self->{log_failures}) {
|
---|
[487] | 2996 | $self->_log(group_id => $group, entry => "Error updating user $username: $msg");
|
---|
[294] | 2997 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2998 | }
|
---|
| 2999 | return ('FAIL',"Error updating user $username: $msg");
|
---|
[83] | 3000 | }
|
---|
[294] | 3001 |
|
---|
| 3002 | return ('OK',$resultmsg);
|
---|
[83] | 3003 | } # end updateUser()
|
---|
| 3004 |
|
---|
| 3005 |
|
---|
[24] | 3006 | ## DNSDB::delUser()
|
---|
[297] | 3007 | # Delete a user.
|
---|
| 3008 | # Takes a database handle and user ID
|
---|
| 3009 | # Returns a success/failure code and matching message
|
---|
[24] | 3010 | sub delUser {
|
---|
[479] | 3011 | my $self = shift;
|
---|
| 3012 | my $dbh = $self->{dbh};
|
---|
[25] | 3013 | my $userid = shift;
|
---|
| 3014 |
|
---|
[297] | 3015 | return ('FAIL',"Bad userid") if !defined($userid);
|
---|
[25] | 3016 |
|
---|
[479] | 3017 | my $userdata = $self->getUserData($userid);
|
---|
[25] | 3018 |
|
---|
[297] | 3019 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3020 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3021 | local $dbh->{AutoCommit} = 0;
|
---|
| 3022 | local $dbh->{RaiseError} = 1;
|
---|
[25] | 3023 |
|
---|
[297] | 3024 | eval {
|
---|
| 3025 | $dbh->do("DELETE FROM users WHERE user_id=?", undef, ($userid));
|
---|
[487] | 3026 | $self->_log(group_id => $userdata->{group_id},
|
---|
[297] | 3027 | entry => "Deleted user ID $userid/".$userdata->{username}.
|
---|
[487] | 3028 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")");
|
---|
[297] | 3029 | $dbh->commit;
|
---|
| 3030 | };
|
---|
| 3031 | if ($@) {
|
---|
| 3032 | my $msg = $@;
|
---|
| 3033 | eval { $dbh->rollback; };
|
---|
[517] | 3034 | if ($self->{log_failures}) {
|
---|
[487] | 3035 | $self->_log(group_id => $userdata->{group_id}, entry => "Error deleting user ID ".
|
---|
| 3036 | "$userid/".$userdata->{username}.": $msg");
|
---|
[297] | 3037 | $dbh->commit;
|
---|
| 3038 | }
|
---|
| 3039 | return ('FAIL',"Error deleting user $userid/".$userdata->{username}.": $msg");
|
---|
| 3040 | }
|
---|
| 3041 |
|
---|
| 3042 | return ('OK',"Deleted user ".$userdata->{username}." (".$userdata->{firstname}." ".$userdata->{lastname}.")");
|
---|
[24] | 3043 | } # end delUser
|
---|
| 3044 |
|
---|
| 3045 |
|
---|
[25] | 3046 | ## DNSDB::userFullName()
|
---|
| 3047 | # Return a pretty string!
|
---|
| 3048 | # Takes a user_id and optional printf-ish string to indicate which pieces where:
|
---|
| 3049 | # %u for the username
|
---|
| 3050 | # %f for the first name
|
---|
| 3051 | # %l for the last name
|
---|
| 3052 | # All other text in the passed string will be left as-is.
|
---|
| 3053 | ##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
|
---|
| 3054 | sub userFullName {
|
---|
| 3055 | $errstr = '';
|
---|
[473] | 3056 | my $self = shift;
|
---|
| 3057 | my $dbh = $self->{dbh};
|
---|
[25] | 3058 | my $userid = shift;
|
---|
| 3059 | my $fullformat = shift || '%f %l (%u)';
|
---|
| 3060 | my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
|
---|
| 3061 | $sth->execute($userid);
|
---|
| 3062 | my ($uname,$fname,$lname) = $sth->fetchrow_array();
|
---|
| 3063 | $errstr = $DBI::errstr if !$uname;
|
---|
| 3064 |
|
---|
| 3065 | $fullformat =~ s/\%u/$uname/g;
|
---|
| 3066 | $fullformat =~ s/\%f/$fname/g;
|
---|
| 3067 | $fullformat =~ s/\%l/$lname/g;
|
---|
| 3068 |
|
---|
| 3069 | return $fullformat;
|
---|
| 3070 | } # end userFullName
|
---|
| 3071 |
|
---|
| 3072 |
|
---|
[51] | 3073 | ## DNSDB::userStatus()
|
---|
| 3074 | # Sets and/or returns a user's status
|
---|
| 3075 | # Takes a database handle, user ID and optionally a status argument
|
---|
| 3076 | # Returns undef on errors.
|
---|
| 3077 | sub userStatus {
|
---|
[479] | 3078 | my $self = shift;
|
---|
| 3079 | my $dbh = $self->{dbh};
|
---|
[51] | 3080 | my $id = shift;
|
---|
[296] | 3081 | my $newstatus = shift || 'mu';
|
---|
[51] | 3082 |
|
---|
| 3083 | return undef if $id !~ /^\d+$/;
|
---|
| 3084 |
|
---|
[479] | 3085 | my $userdata = $self->getUserData($id);
|
---|
[51] | 3086 |
|
---|
[296] | 3087 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3088 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3089 | local $dbh->{AutoCommit} = 0;
|
---|
| 3090 | local $dbh->{RaiseError} = 1;
|
---|
| 3091 |
|
---|
| 3092 | if ($newstatus ne 'mu') {
|
---|
| 3093 | # ooo, fun! let's see what we were passed for status
|
---|
| 3094 | eval {
|
---|
| 3095 | $newstatus = 0 if $newstatus eq 'useroff';
|
---|
| 3096 | $newstatus = 1 if $newstatus eq 'useron';
|
---|
| 3097 | $dbh->do("UPDATE users SET status=? WHERE user_id=?", undef, ($newstatus, $id));
|
---|
| 3098 |
|
---|
[297] | 3099 | $resultstr = ($newstatus ? 'Enabled' : 'Disabled')." user ".$userdata->{username}.
|
---|
| 3100 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")";
|
---|
[296] | 3101 |
|
---|
| 3102 | my %loghash;
|
---|
[473] | 3103 | $loghash{group_id} = $self->parentID(id => $id, type => 'user');
|
---|
[296] | 3104 | $loghash{entry} = $resultstr;
|
---|
[487] | 3105 | $self->_log(%loghash);
|
---|
[296] | 3106 |
|
---|
| 3107 | $dbh->commit;
|
---|
| 3108 | };
|
---|
| 3109 | if ($@) {
|
---|
| 3110 | my $msg = $@;
|
---|
| 3111 | eval { $dbh->rollback; };
|
---|
| 3112 | $resultstr = '';
|
---|
| 3113 | $errstr = $msg;
|
---|
| 3114 | ##fixme: failure logging?
|
---|
| 3115 | return;
|
---|
[51] | 3116 | }
|
---|
| 3117 | }
|
---|
| 3118 |
|
---|
[296] | 3119 | my ($status) = $dbh->selectrow_array("SELECT status FROM users WHERE user_id=?", undef, ($id));
|
---|
[51] | 3120 | return $status;
|
---|
| 3121 | } # end userStatus()
|
---|
| 3122 |
|
---|
| 3123 |
|
---|
[83] | 3124 | ## DNSDB::getUserData()
|
---|
| 3125 | # Get misc user data for display
|
---|
| 3126 | sub getUserData {
|
---|
[479] | 3127 | my $self = shift;
|
---|
| 3128 | my $dbh = $self->{dbh};
|
---|
[83] | 3129 | my $uid = shift;
|
---|
| 3130 |
|
---|
| 3131 | my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
|
---|
| 3132 | "FROM users WHERE user_id=?");
|
---|
| 3133 | $sth->execute($uid);
|
---|
| 3134 | return $sth->fetchrow_hashref();
|
---|
| 3135 | } # end getUserData()
|
---|
| 3136 |
|
---|
| 3137 |
|
---|
[370] | 3138 | ## DNSDB::addLoc()
|
---|
[375] | 3139 | # Add a new location.
|
---|
| 3140 | # Takes a database handle, group ID, short and long description, and a comma-separated
|
---|
| 3141 | # list of IP addresses.
|
---|
| 3142 | # Returns ('OK',<location>) on success, ('FAIL',<failmsg>) on failure
|
---|
| 3143 | sub addLoc {
|
---|
[480] | 3144 | my $self = shift;
|
---|
| 3145 | my $dbh = $self->{dbh};
|
---|
[375] | 3146 | my $grp = shift;
|
---|
| 3147 | my $shdesc = shift;
|
---|
| 3148 | my $comments = shift;
|
---|
| 3149 | my $iplist = shift;
|
---|
[370] | 3150 |
|
---|
[375] | 3151 | # $shdesc gets set to the generated location ID if possible, but these can be de-undefined here.
|
---|
| 3152 | $comments = '' if !$comments;
|
---|
| 3153 | $iplist = '' if !$iplist;
|
---|
| 3154 |
|
---|
| 3155 | my $loc;
|
---|
| 3156 |
|
---|
| 3157 | # Generate a location ID. This is, by spec, a two-character widget. We'll use [a-z][a-z]
|
---|
| 3158 | # for now; 676 locations should satisfy all but the largest of the huge networks.
|
---|
| 3159 | # Not sure whether these are case-sensitive, or what other rules might apply - in any case
|
---|
| 3160 | # the absolute maximum is 16K (256*256) since it's parsed by tinydns as a two-character field.
|
---|
| 3161 |
|
---|
| 3162 | # add just after "my $origloc = $loc;":
|
---|
| 3163 | # # These expand the possible space from 26^2 to 52^2 [* note in testing only 2052 were achieved],
|
---|
| 3164 | # # and wrap it around.
|
---|
| 3165 | # # Yes, they skip a couple of possibles. No, I don't care.
|
---|
| 3166 | # $loc = 'aA' if $loc eq 'zz';
|
---|
| 3167 | # $loc = 'Aa' if $loc eq 'zZ';
|
---|
| 3168 | # $loc = 'ZA' if $loc eq 'Zz';
|
---|
| 3169 | # $loc = 'aa' if $loc eq 'ZZ';
|
---|
| 3170 |
|
---|
| 3171 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3172 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3173 | local $dbh->{AutoCommit} = 0;
|
---|
| 3174 | local $dbh->{RaiseError} = 1;
|
---|
| 3175 |
|
---|
| 3176 | ##fixme: There is probably a far better way to do this. Sequential increments
|
---|
| 3177 | # are marginally less stupid that pure random generation though, and the existence
|
---|
| 3178 | # check makes sure we don't stomp on an imported one.
|
---|
| 3179 |
|
---|
| 3180 | eval {
|
---|
| 3181 | # Get the "last" location. Note this is the only use for loc_id, because selecting on location Does Funky Things
|
---|
| 3182 | ($loc) = $dbh->selectrow_array("SELECT location FROM locations ORDER BY loc_id DESC LIMIT 1");
|
---|
[478] | 3183 | ($loc) = ($loc =~ /^(..)/) if $loc;
|
---|
[375] | 3184 | my $origloc = $loc;
|
---|
[446] | 3185 | $loc = 'aa' if !$loc;
|
---|
[375] | 3186 | # Make a change...
|
---|
| 3187 | $loc++;
|
---|
| 3188 | # ... and keep changing if it exists
|
---|
| 3189 | while ($dbh->selectrow_array("SELECT count(*) FROM locations WHERE location LIKE ?", undef, ($loc.'%'))) {
|
---|
| 3190 | $loc++;
|
---|
| 3191 | ($loc) = ($loc =~ /^(..)/);
|
---|
| 3192 | die "too many locations in use, can't add another one\n" if $loc eq $origloc;
|
---|
| 3193 | ##fixme: really need to handle this case faster somehow
|
---|
| 3194 | #if $loc eq $origloc die "<thwap> bad admin: all locations used, your network is too fragmented";
|
---|
| 3195 | }
|
---|
| 3196 | # And now we should have a unique location. tinydns fundamentally limits the
|
---|
| 3197 | # number of these but there's no doc on what characters are valid.
|
---|
| 3198 | $shdesc = $loc if !$shdesc;
|
---|
| 3199 | $dbh->do("INSERT INTO locations (location, group_id, iplist, description, comments) VALUES (?,?,?,?,?)",
|
---|
| 3200 | undef, ($loc, $grp, $iplist, $shdesc, $comments) );
|
---|
[487] | 3201 | $self->_log(entry => "Added location ($shdesc, '$iplist')");
|
---|
[377] | 3202 | $dbh->commit;
|
---|
[375] | 3203 | };
|
---|
| 3204 | if ($@) {
|
---|
| 3205 | my $msg = $@;
|
---|
| 3206 | eval { $dbh->rollback; };
|
---|
[517] | 3207 | if ($self->{log_failures}) {
|
---|
[375] | 3208 | $shdesc = $loc if !$shdesc;
|
---|
[487] | 3209 | $self->_log(entry => "Failed adding location ($shdesc, '$iplist'): $msg");
|
---|
[375] | 3210 | $dbh->commit;
|
---|
| 3211 | }
|
---|
| 3212 | return ('FAIL',$msg);
|
---|
| 3213 | }
|
---|
| 3214 |
|
---|
| 3215 | return ('OK',$loc);
|
---|
[377] | 3216 | } # end addLoc()
|
---|
[375] | 3217 |
|
---|
| 3218 |
|
---|
[370] | 3219 | ## DNSDB::updateLoc()
|
---|
[428] | 3220 | # Update details of a location.
|
---|
| 3221 | # Takes a database handle, location ID, group ID, short description,
|
---|
| 3222 | # long comments/notes, and comma/space-separated IP list
|
---|
| 3223 | # Returns a result code and message
|
---|
[377] | 3224 | sub updateLoc {
|
---|
[480] | 3225 | my $self = shift;
|
---|
| 3226 | my $dbh = $self->{dbh};
|
---|
[377] | 3227 | my $loc = shift;
|
---|
| 3228 | my $grp = shift;
|
---|
| 3229 | my $shdesc = shift;
|
---|
| 3230 | my $comments = shift;
|
---|
| 3231 | my $iplist = shift;
|
---|
[370] | 3232 |
|
---|
[377] | 3233 | $shdesc = '' if !$shdesc;
|
---|
| 3234 | $comments = '' if !$comments;
|
---|
| 3235 | $iplist = '' if !$iplist;
|
---|
| 3236 |
|
---|
| 3237 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3238 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3239 | local $dbh->{AutoCommit} = 0;
|
---|
| 3240 | local $dbh->{RaiseError} = 1;
|
---|
| 3241 |
|
---|
[480] | 3242 | my $oldloc = $self->getLoc($loc);
|
---|
[377] | 3243 | my $okmsg = "Updated location (".$oldloc->{description}.", '".$oldloc->{iplist}."') to ($shdesc, '$iplist')";
|
---|
| 3244 |
|
---|
| 3245 | eval {
|
---|
| 3246 | $dbh->do("UPDATE locations SET group_id=?,iplist=?,description=?,comments=? WHERE location=?",
|
---|
| 3247 | undef, ($grp, $iplist, $shdesc, $comments, $loc) );
|
---|
[487] | 3248 | $self->_log(entry => $okmsg);
|
---|
[377] | 3249 | $dbh->commit;
|
---|
| 3250 | };
|
---|
| 3251 | if ($@) {
|
---|
| 3252 | my $msg = $@;
|
---|
| 3253 | eval { $dbh->rollback; };
|
---|
[517] | 3254 | if ($self->{log_failures}) {
|
---|
[377] | 3255 | $shdesc = $loc if !$shdesc;
|
---|
[487] | 3256 | $self->_log(entry => "Failed updating location ($shdesc, '$iplist'): $msg");
|
---|
[377] | 3257 | $dbh->commit;
|
---|
| 3258 | }
|
---|
| 3259 | return ('FAIL',$msg);
|
---|
| 3260 | }
|
---|
| 3261 |
|
---|
| 3262 | return ('OK',$okmsg);
|
---|
| 3263 | } # end updateLoc()
|
---|
| 3264 |
|
---|
| 3265 |
|
---|
[370] | 3266 | ## DNSDB::delLoc()
|
---|
[428] | 3267 | sub delLoc {
|
---|
[480] | 3268 | my $self = shift;
|
---|
| 3269 | my $dbh = $self->{dbh};
|
---|
[428] | 3270 | my $loc = shift;
|
---|
[370] | 3271 |
|
---|
[428] | 3272 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3273 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3274 | local $dbh->{AutoCommit} = 0;
|
---|
| 3275 | local $dbh->{RaiseError} = 1;
|
---|
[370] | 3276 |
|
---|
[480] | 3277 | my $oldloc = $self->getLoc($loc);
|
---|
[428] | 3278 | my $olddesc = ($oldloc->{description} ? $oldloc->{description} : $loc);
|
---|
| 3279 | my $okmsg = "Deleted location ($olddesc, '".$oldloc->{iplist}."')";
|
---|
| 3280 |
|
---|
| 3281 | eval {
|
---|
| 3282 | # Check for records with this location first. Deleting a location without deleting records
|
---|
| 3283 | # tagged for that location will render them unpublished without other warning.
|
---|
| 3284 | my ($r) = $dbh->selectrow_array("SELECT record_id FROM records WHERE location=? LIMIT 1", undef, ($loc) );
|
---|
| 3285 | die "Records still exist in location $olddesc\n" if $r;
|
---|
| 3286 | $dbh->do("DELETE FROM locations WHERE location=?", undef, ($loc) );
|
---|
[487] | 3287 | $self->_log(entry => $okmsg);
|
---|
[428] | 3288 | $dbh->commit;
|
---|
| 3289 | };
|
---|
| 3290 | if ($@) {
|
---|
| 3291 | my $msg = $@;
|
---|
| 3292 | eval { $dbh->rollback; };
|
---|
[517] | 3293 | if ($self->{log_failures}) {
|
---|
[487] | 3294 | $self->_log(entry => "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
|
---|
[428] | 3295 | $dbh->commit;
|
---|
| 3296 | }
|
---|
| 3297 | return ('FAIL', "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
|
---|
| 3298 | }
|
---|
| 3299 |
|
---|
| 3300 | return ('OK',$okmsg);
|
---|
| 3301 | } # end delLoc()
|
---|
| 3302 |
|
---|
| 3303 |
|
---|
[375] | 3304 | ## DNSDB::getLoc()
|
---|
[428] | 3305 | # Get details about a location/view
|
---|
| 3306 | # Takes a database handle and location ID.
|
---|
| 3307 | # Returns a reference to a hash containing the group ID, IP list, description, and comments/notes
|
---|
[375] | 3308 | sub getLoc {
|
---|
[480] | 3309 | my $self = shift;
|
---|
| 3310 | my $dbh = $self->{dbh};
|
---|
[375] | 3311 | my $loc = shift;
|
---|
| 3312 |
|
---|
| 3313 | my $sth = $dbh->prepare("SELECT group_id,iplist,description,comments FROM locations WHERE location=?");
|
---|
| 3314 | $sth->execute($loc);
|
---|
| 3315 | return $sth->fetchrow_hashref();
|
---|
| 3316 | } # end getLoc()
|
---|
| 3317 |
|
---|
| 3318 |
|
---|
[370] | 3319 | ## DNSDB::getLocCount()
|
---|
| 3320 | # Get count of locations/views
|
---|
| 3321 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
| 3322 | # - a reference list of secondary groups
|
---|
| 3323 | # - a filter string
|
---|
| 3324 | # - a "Starts with" string
|
---|
| 3325 | sub getLocCount {
|
---|
[480] | 3326 | my $self = shift;
|
---|
| 3327 | my $dbh = $self->{dbh};
|
---|
[370] | 3328 |
|
---|
| 3329 | my %args = @_;
|
---|
| 3330 |
|
---|
[509] | 3331 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 3332 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 3333 | $errstr = "Bad or missing curgroup argument";
|
---|
| 3334 | return;
|
---|
| 3335 | }
|
---|
| 3336 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 3337 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 3338 | $errstr = "Bad childlist argument";
|
---|
| 3339 | return;
|
---|
| 3340 | }
|
---|
| 3341 |
|
---|
[370] | 3342 | my @filterargs;
|
---|
| 3343 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3344 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3345 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3346 |
|
---|
| 3347 | my $sql = "SELECT count(*) FROM locations ".
|
---|
| 3348 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3349 | ($args{startwith} ? " AND description ~* ?" : '').
|
---|
| 3350 | ($args{filter} ? " AND description ~* ?" : '');
|
---|
| 3351 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 3352 | $errstr = $dbh->errstr if !$count;
|
---|
| 3353 | return $count;
|
---|
| 3354 | } # end getLocCount()
|
---|
| 3355 |
|
---|
| 3356 |
|
---|
| 3357 | ## DNSDB::getLocList()
|
---|
| 3358 | sub getLocList {
|
---|
[480] | 3359 | my $self = shift;
|
---|
| 3360 | my $dbh = $self->{dbh};
|
---|
[370] | 3361 |
|
---|
| 3362 | my %args = @_;
|
---|
| 3363 |
|
---|
[509] | 3364 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
| 3365 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
| 3366 | $errstr = "Bad or missing curgroup argument";
|
---|
| 3367 | return;
|
---|
| 3368 | }
|
---|
| 3369 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
| 3370 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
| 3371 | $errstr = "Bad childlist argument";
|
---|
| 3372 | return;
|
---|
| 3373 | }
|
---|
| 3374 |
|
---|
[370] | 3375 | my @filterargs;
|
---|
| 3376 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3377 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3378 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3379 |
|
---|
| 3380 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
| 3381 | # my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
| 3382 | # fname => 'fname');
|
---|
| 3383 | # $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 3384 |
|
---|
| 3385 | # protection against bad or missing arguments
|
---|
[508] | 3386 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
| 3387 | $args{sortby} = 'l.description' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
[397] | 3388 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[370] | 3389 |
|
---|
| 3390 | my $sql = "SELECT l.location, l.description, l.iplist, g.group_name ".
|
---|
| 3391 | "FROM locations l ".
|
---|
| 3392 | "INNER JOIN groups g ON l.group_id=g.group_id ".
|
---|
| 3393 | "WHERE l.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3394 | ($args{startwith} ? " AND l.description ~* ?" : '').
|
---|
| 3395 | ($args{filter} ? " AND l.description ~* ?" : '').
|
---|
| 3396 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
[517] | 3397 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
[370] | 3398 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 3399 | $errstr = $dbh->errstr if !$ulist;
|
---|
| 3400 | return $ulist;
|
---|
| 3401 | } # end getLocList()
|
---|
| 3402 |
|
---|
| 3403 |
|
---|
| 3404 | ## DNSDB::getLocDropdown()
|
---|
[383] | 3405 | # Get a list of location names for use in a dropdown menu.
|
---|
| 3406 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
| 3407 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
| 3408 | sub getLocDropdown {
|
---|
[480] | 3409 | my $self = shift;
|
---|
| 3410 | my $dbh = $self->{dbh};
|
---|
[383] | 3411 | my $grp = shift;
|
---|
| 3412 | my $sel = shift || '';
|
---|
[370] | 3413 |
|
---|
[383] | 3414 | my $sth = $dbh->prepare(qq(
|
---|
| 3415 | SELECT description,location FROM locations
|
---|
| 3416 | WHERE group_id=?
|
---|
| 3417 | ORDER BY description
|
---|
| 3418 | ) );
|
---|
| 3419 | $sth->execute($grp);
|
---|
[370] | 3420 |
|
---|
[383] | 3421 | my @loclist;
|
---|
[446] | 3422 | push @loclist, { locname => "(Default/All)", loc => '', selected => ($sel ? 0 : ($sel eq '' ? 1 : 0)) };
|
---|
[383] | 3423 | while (my ($locname, $loc) = $sth->fetchrow_array) {
|
---|
| 3424 | my %row = (
|
---|
| 3425 | locname => $locname,
|
---|
| 3426 | loc => $loc,
|
---|
| 3427 | selected => ($sel eq $loc ? 1 : 0)
|
---|
| 3428 | );
|
---|
| 3429 | push @loclist, \%row;
|
---|
| 3430 | }
|
---|
| 3431 | return \@loclist;
|
---|
| 3432 | } # end getLocDropdown()
|
---|
| 3433 |
|
---|
| 3434 |
|
---|
[2] | 3435 | ## DNSDB::getSOA()
|
---|
| 3436 | # Return all suitable fields from an SOA record in separate elements of a hash
|
---|
[224] | 3437 | # Takes a database handle, default/live flag, domain/reverse flag, and parent ID
|
---|
[2] | 3438 | sub getSOA {
|
---|
| 3439 | $errstr = '';
|
---|
[481] | 3440 | my $self = shift;
|
---|
| 3441 | my $dbh = $self->{dbh};
|
---|
[2] | 3442 | my $def = shift;
|
---|
[224] | 3443 | my $rev = shift;
|
---|
[2] | 3444 | my $id = shift;
|
---|
| 3445 |
|
---|
[224] | 3446 | # (ab)use distance and weight columns to store SOA data? can't for default_rev_records...
|
---|
| 3447 | # - should really attach serial to the zone parent somewhere
|
---|
[101] | 3448 |
|
---|
[224] | 3449 | my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev).
|
---|
| 3450 | " WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}";
|
---|
[311] | 3451 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
| 3452 | return if !$ret;
|
---|
[246] | 3453 | ##fixme: stick a flag somewhere if the record doesn't exist. by the API, this is an impossible case, but...
|
---|
[2] | 3454 |
|
---|
[311] | 3455 | ($ret->{contact},$ret->{prins}) = split /:/, $ret->{host};
|
---|
| 3456 | delete $ret->{host};
|
---|
| 3457 | ($ret->{refresh},$ret->{retry},$ret->{expire},$ret->{minttl}) = split /:/, $ret->{val};
|
---|
| 3458 | delete $ret->{val};
|
---|
[2] | 3459 |
|
---|
[311] | 3460 | return $ret;
|
---|
[2] | 3461 | } # end getSOA()
|
---|
| 3462 |
|
---|
| 3463 |
|
---|
[246] | 3464 | ## DNSDB::updateSOA()
|
---|
| 3465 | # Update the specified SOA record
|
---|
| 3466 | # Takes a database handle, default/live flag, forward/reverse flag, and SOA data hash
|
---|
[277] | 3467 | # Returns a two-element list with a result code and message
|
---|
[246] | 3468 | sub updateSOA {
|
---|
[473] | 3469 | my $self = shift;
|
---|
| 3470 | my $dbh = $self->{dbh};
|
---|
[246] | 3471 | my $defrec = shift;
|
---|
[248] | 3472 | my $revrec = shift;
|
---|
[246] | 3473 |
|
---|
| 3474 | my %soa = @_;
|
---|
| 3475 |
|
---|
[473] | 3476 | my $oldsoa = $self->getSOA($defrec, $revrec, $soa{id});
|
---|
[277] | 3477 |
|
---|
[311] | 3478 | my $msg;
|
---|
| 3479 | my %logdata;
|
---|
| 3480 | if ($defrec eq 'n') {
|
---|
| 3481 | $logdata{domain_id} = $soa{id} if $revrec eq 'n';
|
---|
| 3482 | $logdata{rdns_id} = $soa{id} if $revrec eq 'y';
|
---|
[473] | 3483 | $logdata{group_id} = $self->parentID(id => $soa{id}, revrec => $revrec,
|
---|
| 3484 | type => ($revrec eq 'n' ? 'domain' : 'revzone') );
|
---|
[311] | 3485 | } else {
|
---|
| 3486 | $logdata{group_id} = $soa{id};
|
---|
| 3487 | }
|
---|
[473] | 3488 | my $parname = ($defrec eq 'y' ? $self->groupName($soa{id}) :
|
---|
| 3489 | ($revrec eq 'n' ? $self->domainName($soa{id}) : $self->revName($soa{id})) );
|
---|
[311] | 3490 |
|
---|
[277] | 3491 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3492 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3493 | local $dbh->{AutoCommit} = 0;
|
---|
| 3494 | local $dbh->{RaiseError} = 1;
|
---|
| 3495 |
|
---|
| 3496 | eval {
|
---|
| 3497 | my $sql = "UPDATE "._rectable($defrec, $revrec)." SET host=?, val=?, ttl=? WHERE record_id=? AND type=6";
|
---|
| 3498 | $dbh->do($sql, undef, ("$soa{contact}:$soa{prins}", "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}",
|
---|
[311] | 3499 | $soa{ttl}, $oldsoa->{record_id}) );
|
---|
| 3500 | $msg = "Updated ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse ' : 'default ') : '').
|
---|
| 3501 | "SOA for $parname: ".
|
---|
| 3502 | "(ns $oldsoa->{prins}, contact $oldsoa->{contact}, refresh $oldsoa->{refresh},".
|
---|
| 3503 | " retry $oldsoa->{retry}, expire $oldsoa->{expire}, minTTL $oldsoa->{minttl}, TTL $oldsoa->{ttl}) to ".
|
---|
[277] | 3504 | "(ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
|
---|
| 3505 | " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})";
|
---|
| 3506 |
|
---|
[311] | 3507 | $logdata{entry} = $msg;
|
---|
[487] | 3508 | $self->_log(%logdata);
|
---|
[277] | 3509 |
|
---|
| 3510 | $dbh->commit;
|
---|
| 3511 | };
|
---|
| 3512 | if ($@) {
|
---|
| 3513 | $msg = $@;
|
---|
| 3514 | eval { $dbh->rollback; };
|
---|
[311] | 3515 | $logdata{entry} = "Error updating ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse zone ' : 'default ') : '').
|
---|
| 3516 | "SOA record for $parname: $msg";
|
---|
[517] | 3517 | if ($self->{log_failures}) {
|
---|
[487] | 3518 | $self->_log(%logdata);
|
---|
[311] | 3519 | $dbh->commit;
|
---|
| 3520 | }
|
---|
| 3521 | return ('FAIL', $logdata{entry});
|
---|
[277] | 3522 | } else {
|
---|
| 3523 | return ('OK', $msg);
|
---|
| 3524 | }
|
---|
[246] | 3525 | } # end updateSOA()
|
---|
| 3526 |
|
---|
| 3527 |
|
---|
[2] | 3528 | ## DNSDB::getRecLine()
|
---|
| 3529 | # Return all data fields for a zone record in separate elements of a hash
|
---|
[243] | 3530 | # Takes a database handle, default/live flag, forward/reverse flag, and record ID
|
---|
[2] | 3531 | sub getRecLine {
|
---|
| 3532 | $errstr = '';
|
---|
[481] | 3533 | my $self = shift;
|
---|
| 3534 | my $dbh = $self->{dbh};
|
---|
[243] | 3535 | my $defrec = shift;
|
---|
| 3536 | my $revrec = shift;
|
---|
[2] | 3537 | my $id = shift;
|
---|
| 3538 |
|
---|
[543] | 3539 | ##fixme: do we need a knob to twist to switch between unix epoch and postgres time string?
|
---|
[429] | 3540 | my $sql = "SELECT record_id,host,type,val,ttl".
|
---|
| 3541 | ($defrec eq 'n' ? ',location' : '').
|
---|
| 3542 | ($revrec eq 'n' ? ',distance,weight,port' : '').
|
---|
[543] | 3543 | (($defrec eq 'y') ? ',group_id FROM ' : ',domain_id,rdns_id,stamp,stamp < now() AS ispast,expires,stampactive FROM ').
|
---|
[243] | 3544 | _rectable($defrec,$revrec)." WHERE record_id=?";
|
---|
[123] | 3545 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
[2] | 3546 |
|
---|
[90] | 3547 | if ($dbh->err) {
|
---|
[2] | 3548 | $errstr = $DBI::errstr;
|
---|
| 3549 | return undef;
|
---|
| 3550 | }
|
---|
| 3551 |
|
---|
[123] | 3552 | if (!$ret) {
|
---|
| 3553 | $errstr = "No such record";
|
---|
| 3554 | return undef;
|
---|
| 3555 | }
|
---|
| 3556 |
|
---|
[243] | 3557 | # explicitly set a parent id
|
---|
| 3558 | if ($defrec eq 'y') {
|
---|
| 3559 | $ret->{parid} = $ret->{group_id};
|
---|
| 3560 | } else {
|
---|
| 3561 | $ret->{parid} = (($revrec eq 'n') ? $ret->{domain_id} : $ret->{rdns_id});
|
---|
| 3562 | # and a secondary if we have a custom type that lives in both a forward and reverse zone
|
---|
| 3563 | $ret->{secid} = (($revrec eq 'y') ? $ret->{domain_id} : $ret->{rdns_id}) if $ret->{type} > 65279;
|
---|
| 3564 | }
|
---|
[451] | 3565 | $ret->{address} = $ret->{val}; # because.
|
---|
[90] | 3566 |
|
---|
| 3567 | return $ret;
|
---|
[2] | 3568 | }
|
---|
| 3569 |
|
---|
| 3570 |
|
---|
| 3571 | ##fixme: should use above (getRecLine()) to get lines for below?
|
---|
[495] | 3572 | ## DNSDB::getRecList()
|
---|
| 3573 | # Return records for a group or zone
|
---|
| 3574 | # Takes a default/live flag, group or zone ID, start,
|
---|
[2] | 3575 | # number of records, sort field, and sort order
|
---|
| 3576 | # Returns a reference to an array of hashes
|
---|
[495] | 3577 | sub getRecList {
|
---|
[2] | 3578 | $errstr = '';
|
---|
[481] | 3579 | my $self = shift;
|
---|
| 3580 | my $dbh = $self->{dbh};
|
---|
[2] | 3581 |
|
---|
[397] | 3582 | my %args = @_;
|
---|
[4] | 3583 |
|
---|
[397] | 3584 | my @filterargs;
|
---|
[135] | 3585 |
|
---|
[397] | 3586 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3587 |
|
---|
| 3588 | # protection against bad or missing arguments
|
---|
[508] | 3589 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
[510] | 3590 | my $defsort;
|
---|
| 3591 | $defsort = 'host' if $args{revrec} eq 'n'; # default sort by host on domain record list
|
---|
| 3592 | $defsort = 'val' if $args{revrec} eq 'y'; # default sort by IP on revzone record list
|
---|
[513] | 3593 | $args{sortby} = '' if !$args{sortby};
|
---|
[508] | 3594 | $args{sortby} = $defsort if !$args{revrec};
|
---|
[512] | 3595 | $args{sortby} = $defsort if $args{sortby} !~ /^[\w_,.]+$/;
|
---|
[397] | 3596 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[517] | 3597 | my $perpage = ($args{nrecs} ? $args{nrecs} : $self->{perpage});
|
---|
[397] | 3598 |
|
---|
[352] | 3599 | # sort reverse zones on IP, correctly
|
---|
[397] | 3600 | # do other fiddling with $args{sortby} while we're at it.
|
---|
[420] | 3601 | # whee! multisort means just passing comma-separated fields in sortby!
|
---|
| 3602 | my $newsort = '';
|
---|
| 3603 | foreach my $sf (split /,/, $args{sortby}) {
|
---|
| 3604 | $sf = "r.$sf";
|
---|
| 3605 | $sf =~ s/r\.val/CAST (r.val AS inet)/
|
---|
| 3606 | if $args{revrec} eq 'y' && $args{defrec} eq 'n';
|
---|
| 3607 | $sf =~ s/r\.type/t.alphaorder/;
|
---|
| 3608 | $newsort .= ",$sf";
|
---|
| 3609 | }
|
---|
| 3610 | $newsort =~ s/^,//;
|
---|
[352] | 3611 |
|
---|
[543] | 3612 | ##fixme: do we need a knob to twist to switch from unix epoch to postgres time string?
|
---|
[224] | 3613 | my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.ttl";
|
---|
[543] | 3614 | $sql .= ",l.description AS locname,stamp,r.stamp < now() AS ispast,r.expires,r.stampactive"
|
---|
| 3615 | if $args{defrec} eq 'n';
|
---|
[397] | 3616 | $sql .= ",r.distance,r.weight,r.port" if $args{revrec} eq 'n';
|
---|
| 3617 | $sql .= " FROM "._rectable($args{defrec},$args{revrec})." r ";
|
---|
[104] | 3618 | $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
|
---|
[397] | 3619 | $sql .= "LEFT JOIN locations l ON r.location=l.location " if $args{defrec} eq 'n';
|
---|
| 3620 | $sql .= "WHERE "._recparent($args{defrec},$args{revrec})." = ?";
|
---|
[104] | 3621 | $sql .= " AND NOT r.type=$reverse_typemap{SOA}";
|
---|
[439] | 3622 | $sql .= " AND (r.host ~* ? OR r.val ~* ?)" if $args{filter};
|
---|
[420] | 3623 | $sql .= " ORDER BY $newsort $args{sortorder}";
|
---|
[324] | 3624 | # ensure consistent ordering by sorting on record_id too
|
---|
[397] | 3625 | $sql .= ", record_id $args{sortorder}";
|
---|
[501] | 3626 | $sql .= ($args{offset} eq 'all' ? '' : " LIMIT $perpage OFFSET ".$args{offset}*$perpage);
|
---|
[4] | 3627 |
|
---|
[397] | 3628 | my @bindvars = ($args{id});
|
---|
[439] | 3629 | push @bindvars, ($args{filter},$args{filter}) if $args{filter};
|
---|
[224] | 3630 |
|
---|
[397] | 3631 | my $ret = $dbh->selectall_arrayref($sql, { Slice => {} }, (@bindvars) );
|
---|
[495] | 3632 | $errstr = "Error retrieving records: ".$dbh->errstr if !$ret;
|
---|
[543] | 3633 |
|
---|
[2] | 3634 | return $ret;
|
---|
[495] | 3635 | } # end getRecList()
|
---|
[2] | 3636 |
|
---|
| 3637 |
|
---|
[91] | 3638 | ## DNSDB::getRecCount()
|
---|
[224] | 3639 | # Return count of non-SOA records in zone (or default records in a group)
|
---|
| 3640 | # Takes a database handle, default/live flag, reverse/forward flag, group/domain ID,
|
---|
| 3641 | # and optional filtering modifier
|
---|
[91] | 3642 | # Returns the count
|
---|
| 3643 | sub getRecCount {
|
---|
[481] | 3644 | my $self = shift;
|
---|
| 3645 | my $dbh = $self->{dbh};
|
---|
[91] | 3646 | my $defrec = shift;
|
---|
[224] | 3647 | my $revrec = shift;
|
---|
[91] | 3648 | my $id = shift;
|
---|
[135] | 3649 | my $filter = shift || '';
|
---|
[91] | 3650 |
|
---|
[135] | 3651 | # keep the nasties down, since we can't ?-sub this bit. :/
|
---|
| 3652 | # note this is chars allowed in DNS hostnames
|
---|
| 3653 | $filter =~ s/[^a-zA-Z0-9_.:-]//g;
|
---|
| 3654 |
|
---|
[222] | 3655 | my @bindvars = ($id);
|
---|
| 3656 | push @bindvars, $filter if $filter;
|
---|
[224] | 3657 | my $sql = "SELECT count(*) FROM ".
|
---|
| 3658 | _rectable($defrec,$revrec).
|
---|
| 3659 | " WHERE "._recparent($defrec,$revrec)."=? ".
|
---|
| 3660 | "AND NOT type=$reverse_typemap{SOA}".
|
---|
| 3661 | ($filter ? " AND host ~* ?" : '');
|
---|
| 3662 | my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) );
|
---|
[91] | 3663 |
|
---|
| 3664 | return $count;
|
---|
| 3665 |
|
---|
| 3666 | } # end getRecCount()
|
---|
| 3667 |
|
---|
| 3668 |
|
---|
[3] | 3669 | ## DNSDB::addRec()
|
---|
[2] | 3670 | # Add a new record to a domain or a group's default records
|
---|
| 3671 | # Takes a database handle, default/live flag, group/domain ID,
|
---|
| 3672 | # host, type, value, and TTL
|
---|
| 3673 | # Some types require additional detail: "distance" for MX and SRV,
|
---|
| 3674 | # and weight/port for SRV
|
---|
| 3675 | # Returns a status code and detail message in case of error
|
---|
[234] | 3676 | ##fixme: pass a hash with the record data, not a series of separate values
|
---|
[2] | 3677 | sub addRec {
|
---|
| 3678 | $errstr = '';
|
---|
[481] | 3679 | my $self = shift;
|
---|
| 3680 | my $dbh = $self->{dbh};
|
---|
[2] | 3681 | my $defrec = shift;
|
---|
[226] | 3682 | my $revrec = shift;
|
---|
| 3683 | my $id = shift; # parent (group_id for defrecs, rdns_id for reverse records,
|
---|
| 3684 | # domain_id for domain records)
|
---|
[2] | 3685 |
|
---|
| 3686 | my $host = shift;
|
---|
[234] | 3687 | my $rectype = shift; # reference so we can coerce it if "+"-types can't find both zones
|
---|
[2] | 3688 | my $val = shift;
|
---|
| 3689 | my $ttl = shift;
|
---|
[389] | 3690 | my $location = shift;
|
---|
| 3691 | $location = '' if !$location;
|
---|
[2] | 3692 |
|
---|
[543] | 3693 | my $expires = shift;
|
---|
| 3694 | $expires = 1 if $expires eq 'until'; # Turn some special values into the appropriate booleans.
|
---|
| 3695 | $expires = 0 if $expires eq 'after';
|
---|
| 3696 | my $stamp = shift;
|
---|
| 3697 | $stamp = '' if !$stamp; # Timestamp should be a string at this point.
|
---|
| 3698 |
|
---|
[417] | 3699 | # Spaces are evil.
|
---|
| 3700 | $$host =~ s/^\s+//;
|
---|
| 3701 | $$host =~ s/\s+$//;
|
---|
[418] | 3702 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
[417] | 3703 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 3704 | $$val =~ s/^\s+//;
|
---|
| 3705 | $$val =~ s/\s+$//;
|
---|
| 3706 | }
|
---|
| 3707 |
|
---|
[542] | 3708 | if ($self->{lowercase}) {
|
---|
| 3709 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
| 3710 | $$host = lc($$host);
|
---|
| 3711 | $$val = lc($$val);
|
---|
| 3712 | } else {
|
---|
| 3713 | # TXT records should preserve user entry in the string.
|
---|
| 3714 | if ($revrec eq 'n') {
|
---|
| 3715 | $$host = lc($$host);
|
---|
| 3716 | } else {
|
---|
| 3717 | $$val = lc($$val);
|
---|
| 3718 | }
|
---|
| 3719 | }
|
---|
| 3720 | }
|
---|
| 3721 |
|
---|
[226] | 3722 | # prep for validation
|
---|
[252] | 3723 | my $addr = NetAddr::IP->new($$val);
|
---|
| 3724 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
[226] | 3725 |
|
---|
| 3726 | my $domid = 0;
|
---|
| 3727 | my $revid = 0;
|
---|
| 3728 |
|
---|
| 3729 | my $retcode = 'OK'; # assume everything will go OK
|
---|
| 3730 | my $retmsg = '';
|
---|
| 3731 |
|
---|
| 3732 | # do simple validation first
|
---|
| 3733 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
|
---|
| 3734 |
|
---|
[532] | 3735 | # Quick check on hostname parts. There are enough variations to justify a sub now.
|
---|
| 3736 | return ('FAIL', $errstr) if ! _check_hostname_form($$host, $$rectype, $defrec, $revrec);
|
---|
[226] | 3737 |
|
---|
[234] | 3738 | # Collect these even if we're only doing a simple A record so we can call *any* validation sub
|
---|
| 3739 | my $dist = shift;
|
---|
[281] | 3740 | my $weight = shift;
|
---|
[234] | 3741 | my $port = shift;
|
---|
[226] | 3742 |
|
---|
[234] | 3743 | my $fields;
|
---|
| 3744 | my @vallist;
|
---|
[226] | 3745 |
|
---|
[234] | 3746 | # Call the validation sub for the type requested.
|
---|
[481] | 3747 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec, id => $id,
|
---|
[249] | 3748 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
[234] | 3749 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
[481] | 3750 | fields => \$fields, vallist => \@vallist);
|
---|
[129] | 3751 |
|
---|
[234] | 3752 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
[209] | 3753 |
|
---|
[234] | 3754 | # Set up database fields and bind parameters
|
---|
[481] | 3755 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
| 3756 | push @vallist, ($$host,$$rectype,$$val,$ttl,$id);
|
---|
| 3757 |
|
---|
| 3758 | if ($defrec eq 'n') {
|
---|
[543] | 3759 | # locations are not for default records, silly coder!
|
---|
[481] | 3760 | $fields .= ",location";
|
---|
| 3761 | push @vallist, $location;
|
---|
[543] | 3762 | # timestamps are rare.
|
---|
| 3763 | if ($stamp) {
|
---|
| 3764 | $fields .= ",stamp,expires,stampactive";
|
---|
| 3765 | push @vallist, $stamp, $expires, 'y';
|
---|
| 3766 | } else {
|
---|
| 3767 | $fields .= ",stampactive";
|
---|
| 3768 | push @vallist, 'n';
|
---|
| 3769 | }
|
---|
[481] | 3770 | }
|
---|
[543] | 3771 |
|
---|
| 3772 | # a little magic to get the right number of ? placeholders based on how many values we're providing
|
---|
[234] | 3773 | my $vallen = '?'.(',?'x$#vallist);
|
---|
[2] | 3774 |
|
---|
[287] | 3775 | # Put together the success log entry. We have to use this horrible kludge
|
---|
| 3776 | # because domain_id and rdns_id may or may not be present, and if they are,
|
---|
| 3777 | # they're not at a guaranteed consistent index in the array. wheee!
|
---|
| 3778 | my %logdata;
|
---|
| 3779 | my @ftmp = split /,/, $fields;
|
---|
| 3780 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
| 3781 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
| 3782 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
| 3783 | }
|
---|
| 3784 | $logdata{group_id} = $id if $defrec eq 'y';
|
---|
[473] | 3785 | $logdata{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec)
|
---|
[287] | 3786 | if $defrec eq 'n';
|
---|
[328] | 3787 | $logdata{entry} = "Added ".($defrec eq 'y' ? 'default record' : 'record');
|
---|
| 3788 | # NS records for revzones get special treatment
|
---|
| 3789 | if ($revrec eq 'y' && $$rectype == 2) {
|
---|
| 3790 | $logdata{entry} .= " '$$val $typemap{$$rectype} $$host";
|
---|
| 3791 | } else {
|
---|
| 3792 | $logdata{entry} .= " '$$host $typemap{$$rectype} $$val";
|
---|
| 3793 | }
|
---|
| 3794 |
|
---|
[287] | 3795 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
| 3796 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]"
|
---|
| 3797 | if $typemap{$$rectype} eq 'SRV';
|
---|
[425] | 3798 | $logdata{entry} .= "', TTL $ttl";
|
---|
[480] | 3799 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location;
|
---|
[543] | 3800 | $logdata{entry} .= ($expires eq 'after' ? ', valid after ' : ', expires at ').$stamp if $stamp;
|
---|
[287] | 3801 |
|
---|
[90] | 3802 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3803 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3804 | local $dbh->{AutoCommit} = 0;
|
---|
| 3805 | local $dbh->{RaiseError} = 1;
|
---|
[2] | 3806 |
|
---|
[90] | 3807 | eval {
|
---|
[236] | 3808 | $dbh->do("INSERT INTO "._rectable($defrec, $revrec)." ($fields) VALUES ($vallen)",
|
---|
[90] | 3809 | undef, @vallist);
|
---|
[487] | 3810 | $self->_log(%logdata);
|
---|
[90] | 3811 | $dbh->commit;
|
---|
| 3812 | };
|
---|
| 3813 | if ($@) {
|
---|
| 3814 | my $msg = $@;
|
---|
| 3815 | eval { $dbh->rollback; };
|
---|
[517] | 3816 | if ($self->{log_failures}) {
|
---|
[289] | 3817 | $logdata{entry} = "Failed adding ".($defrec eq 'y' ? 'default ' : '').
|
---|
| 3818 | "record '$$host $typemap{$$rectype} $$val', TTL $ttl ($msg)";
|
---|
[487] | 3819 | $self->_log(%logdata);
|
---|
[289] | 3820 | $dbh->commit;
|
---|
| 3821 | }
|
---|
[90] | 3822 | return ('FAIL',$msg);
|
---|
| 3823 | }
|
---|
[2] | 3824 |
|
---|
[287] | 3825 | $resultstr = $logdata{entry};
|
---|
[226] | 3826 | return ($retcode, $retmsg);
|
---|
[90] | 3827 |
|
---|
[2] | 3828 | } # end addRec()
|
---|
| 3829 |
|
---|
| 3830 |
|
---|
[16] | 3831 | ## DNSDB::updateRec()
|
---|
| 3832 | # Update a record
|
---|
[273] | 3833 | # Takes a database handle, default and reverse flags, record ID, immediate parent ID, and new record data.
|
---|
| 3834 | # Returns a status code and message
|
---|
[16] | 3835 | sub updateRec {
|
---|
| 3836 | $errstr = '';
|
---|
[17] | 3837 |
|
---|
[481] | 3838 | my $self = shift;
|
---|
| 3839 | my $dbh = $self->{dbh};
|
---|
[16] | 3840 | my $defrec = shift;
|
---|
[272] | 3841 | my $revrec = shift;
|
---|
[16] | 3842 | my $id = shift;
|
---|
[272] | 3843 | my $parid = shift; # immediate parent entity that we're descending from to update the record
|
---|
[16] | 3844 |
|
---|
[273] | 3845 | # all records have these
|
---|
[16] | 3846 | my $host = shift;
|
---|
[272] | 3847 | my $hostbk = $$host; # Keep a backup copy of the original, so we can WARN if the update mangles the domain
|
---|
| 3848 | my $rectype = shift;
|
---|
[16] | 3849 | my $val = shift;
|
---|
| 3850 | my $ttl = shift;
|
---|
[389] | 3851 | my $location = shift; # may be empty/null/undef depending on caller
|
---|
| 3852 | $location = '' if !$location;
|
---|
[16] | 3853 |
|
---|
[543] | 3854 | my $expires = shift;
|
---|
| 3855 | $expires = 1 if $expires eq 'until'; # Turn some special values into the appropriate booleans.
|
---|
| 3856 | $expires = 0 if $expires eq 'after';
|
---|
| 3857 | my $stamp = shift;
|
---|
| 3858 | $stamp = '' if !$stamp; # Timestamp should be a string at this point.
|
---|
| 3859 |
|
---|
[510] | 3860 | # just set it to an empty string; failures will be caught later.
|
---|
| 3861 | $$host = '' if !$$host;
|
---|
| 3862 |
|
---|
[417] | 3863 | # Spaces are evil.
|
---|
| 3864 | $$host =~ s/^\s+//;
|
---|
| 3865 | $$host =~ s/\s+$//;
|
---|
[418] | 3866 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
[417] | 3867 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 3868 | $$val =~ s/^\s+//;
|
---|
| 3869 | $$val =~ s/\s+$//;
|
---|
| 3870 | }
|
---|
| 3871 |
|
---|
[542] | 3872 | if ($self->{lowercase}) {
|
---|
| 3873 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
| 3874 | $$host = lc($$host);
|
---|
| 3875 | $$val = lc($$val);
|
---|
| 3876 | } else {
|
---|
| 3877 | # TXT records should preserve user entry in the string.
|
---|
| 3878 | if ($revrec eq 'n') {
|
---|
| 3879 | $$host = lc($$host);
|
---|
| 3880 | } else {
|
---|
| 3881 | $$val = lc($$val);
|
---|
| 3882 | }
|
---|
| 3883 | }
|
---|
| 3884 | }
|
---|
| 3885 |
|
---|
[272] | 3886 | # prep for validation
|
---|
| 3887 | my $addr = NetAddr::IP->new($$val);
|
---|
| 3888 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
[16] | 3889 |
|
---|
[272] | 3890 | my $domid = 0;
|
---|
| 3891 | my $revid = 0;
|
---|
| 3892 |
|
---|
| 3893 | my $retcode = 'OK'; # assume everything will go OK
|
---|
| 3894 | my $retmsg = '';
|
---|
| 3895 |
|
---|
[273] | 3896 | # do simple validation first
|
---|
[272] | 3897 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
|
---|
| 3898 |
|
---|
[532] | 3899 | # Quick check on hostname parts. There are enough variations to justify a sub now.
|
---|
| 3900 | return ('FAIL', $errstr) if ! _check_hostname_form($$host, $$rectype, $defrec, $revrec);
|
---|
[272] | 3901 |
|
---|
[273] | 3902 | # only MX and SRV will use these
|
---|
[288] | 3903 | my $dist = shift || 0;
|
---|
| 3904 | my $weight = shift || 0;
|
---|
| 3905 | my $port = shift || 0;
|
---|
[16] | 3906 |
|
---|
[272] | 3907 | my $fields;
|
---|
| 3908 | my @vallist;
|
---|
[16] | 3909 |
|
---|
[273] | 3910 | # get old record data so we have the right parent ID
|
---|
| 3911 | # and for logging (eventually)
|
---|
[481] | 3912 | my $oldrec = $self->getRecLine($defrec, $revrec, $id);
|
---|
[223] | 3913 |
|
---|
[272] | 3914 | # Call the validation sub for the type requested.
|
---|
| 3915 | # Note the ID to pass here is the *parent*, not the record
|
---|
[481] | 3916 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec,
|
---|
[272] | 3917 | id => ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})),
|
---|
| 3918 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
| 3919 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
| 3920 | fields => \$fields, vallist => \@vallist,
|
---|
[481] | 3921 | update => $id);
|
---|
[272] | 3922 |
|
---|
| 3923 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
| 3924 |
|
---|
[273] | 3925 | # Set up database fields and bind parameters. Note only the optional fields
|
---|
| 3926 | # (distance, weight, port, secondary parent ID) are added in the validation call above
|
---|
[448] | 3927 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
| 3928 | push @vallist, ($$host,$$rectype,$$val,$ttl,
|
---|
[273] | 3929 | ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})) );
|
---|
[272] | 3930 |
|
---|
[448] | 3931 | if ($defrec eq 'n') {
|
---|
[543] | 3932 | # locations are not for default records, silly coder!
|
---|
[448] | 3933 | $fields .= ",location";
|
---|
| 3934 | push @vallist, $location;
|
---|
[543] | 3935 | # timestamps are rare.
|
---|
| 3936 | if ($stamp) {
|
---|
| 3937 | $fields .= ",stamp,expires,stampactive";
|
---|
| 3938 | push @vallist, $stamp, $expires, 'y';
|
---|
| 3939 | } else {
|
---|
| 3940 | $fields .= ",stampactive";
|
---|
| 3941 | push @vallist, 'n';
|
---|
| 3942 | }
|
---|
[448] | 3943 | }
|
---|
| 3944 |
|
---|
[273] | 3945 | # hack hack PTHUI
|
---|
| 3946 | # need to forcibly make sure we disassociate a record with a parent it's no longer related to.
|
---|
| 3947 | # eg, PTR records may not have a domain parent, or A/AAAA records may not have a revzone parent.
|
---|
| 3948 | # mainly needed for crossover types that got coerced down to "standard" types
|
---|
| 3949 | if ($defrec eq 'n') {
|
---|
| 3950 | if ($$rectype == $reverse_typemap{PTR}) {
|
---|
| 3951 | $fields .= ",domain_id";
|
---|
| 3952 | push @vallist, 0;
|
---|
| 3953 | }
|
---|
| 3954 | if ($$rectype == $reverse_typemap{A} || $$rectype == $reverse_typemap{AAAA}) {
|
---|
| 3955 | $fields .= ",rdns_id";
|
---|
| 3956 | push @vallist, 0;
|
---|
| 3957 | }
|
---|
| 3958 | }
|
---|
[345] | 3959 | # fix fat-finger-originated record type changes
|
---|
| 3960 | if ($$rectype == 65285) {
|
---|
| 3961 | $fields .= ",rdns_id" if $revrec eq 'n';
|
---|
| 3962 | $fields .= ",domain_id" if $revrec eq 'y';
|
---|
| 3963 | push @vallist, 0;
|
---|
| 3964 | }
|
---|
[341] | 3965 | if ($defrec eq 'n') {
|
---|
| 3966 | $domid = $parid if $revrec eq 'n';
|
---|
| 3967 | $revid = $parid if $revrec eq 'y';
|
---|
| 3968 | }
|
---|
[272] | 3969 |
|
---|
[288] | 3970 | # Put together the success log entry. Horrible kludge from addRec() copied as-is since
|
---|
| 3971 | # we don't know whether the passed arguments or retrieved values for domain_id and rdns_id
|
---|
| 3972 | # will be maintained (due to "not-in-zone" validation changes)
|
---|
| 3973 | my %logdata;
|
---|
[341] | 3974 | $logdata{domain_id} = $domid;
|
---|
| 3975 | $logdata{rdns_id} = $revid;
|
---|
[288] | 3976 | my @ftmp = split /,/, $fields;
|
---|
| 3977 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
| 3978 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
| 3979 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
| 3980 | }
|
---|
| 3981 | $logdata{group_id} = $parid if $defrec eq 'y';
|
---|
[473] | 3982 | $logdata{group_id} = $self->parentID(id => $parid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec)
|
---|
[288] | 3983 | if $defrec eq 'n';
|
---|
[328] | 3984 | $logdata{entry} = "Updated ".($defrec eq 'y' ? 'default record' : 'record')." from\n";
|
---|
| 3985 | # NS records for revzones get special treatment
|
---|
| 3986 | if ($revrec eq 'y' && $$rectype == 2) {
|
---|
| 3987 | $logdata{entry} .= " '$oldrec->{val} $typemap{$oldrec->{type}} $oldrec->{host}";
|
---|
| 3988 | } else {
|
---|
| 3989 | $logdata{entry} .= " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
| 3990 | }
|
---|
[288] | 3991 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
| 3992 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
| 3993 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
[425] | 3994 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
[480] | 3995 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location};
|
---|
[543] | 3996 | $logdata{entry} .= ($oldrec->{expires} ? ', expires at ' : ', valid after ').$oldrec->{stamp}
|
---|
| 3997 | if $oldrec->{stampactive};
|
---|
[425] | 3998 | $logdata{entry} .= "\nto\n";
|
---|
[328] | 3999 | # More NS special
|
---|
| 4000 | if ($revrec eq 'y' && $$rectype == 2) {
|
---|
| 4001 | $logdata{entry} .= "'$$val $typemap{$$rectype} $$host";
|
---|
| 4002 | } else {
|
---|
| 4003 | $logdata{entry} .= "'$$host $typemap{$$rectype} $$val";
|
---|
| 4004 | }
|
---|
[288] | 4005 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
| 4006 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$$rectype} eq 'SRV';
|
---|
[425] | 4007 | $logdata{entry} .= "', TTL $ttl";
|
---|
[480] | 4008 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location;
|
---|
[543] | 4009 | $logdata{entry} .= ($expires eq 'after' ? ', valid after ' : ', expires at ').$stamp if $stamp;
|
---|
[288] | 4010 |
|
---|
[90] | 4011 | local $dbh->{AutoCommit} = 0;
|
---|
| 4012 | local $dbh->{RaiseError} = 1;
|
---|
| 4013 |
|
---|
[341] | 4014 | # Fiddle the field list into something suitable for updates
|
---|
| 4015 | $fields =~ s/,/=?,/g;
|
---|
| 4016 | $fields .= "=?";
|
---|
| 4017 |
|
---|
[90] | 4018 | eval {
|
---|
[273] | 4019 | $dbh->do("UPDATE "._rectable($defrec,$revrec)." SET $fields WHERE record_id=?", undef, (@vallist, $id) );
|
---|
[487] | 4020 | $self->_log(%logdata);
|
---|
[130] | 4021 | $dbh->commit;
|
---|
[90] | 4022 | };
|
---|
| 4023 | if ($@) {
|
---|
| 4024 | my $msg = $@;
|
---|
[288] | 4025 | eval { $dbh->rollback; };
|
---|
[517] | 4026 | if ($self->{log_failures}) {
|
---|
[289] | 4027 | $logdata{entry} = "Failed updating ".($defrec eq 'y' ? 'default ' : '').
|
---|
| 4028 | "record '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
[487] | 4029 | $self->_log(%logdata);
|
---|
[289] | 4030 | $dbh->commit;
|
---|
| 4031 | }
|
---|
[90] | 4032 | return ('FAIL', $msg);
|
---|
| 4033 | }
|
---|
| 4034 |
|
---|
[288] | 4035 | $resultstr = $logdata{entry};
|
---|
[272] | 4036 | return ($retcode, $retmsg);
|
---|
[16] | 4037 | } # end updateRec()
|
---|
| 4038 |
|
---|
| 4039 |
|
---|
[459] | 4040 | ## DNSDB::downconvert()
|
---|
| 4041 | # A mostly internal (not exported) semiutilty sub to downconvert from pseudotype <x>
|
---|
| 4042 | # to a compatible component type. Only a handful of operations are valid, anything
|
---|
| 4043 | # else is a null-op.
|
---|
| 4044 | # Takes the record ID and the new type. Returns boolean.
|
---|
| 4045 | sub downconvert {
|
---|
[481] | 4046 | my $self = shift;
|
---|
| 4047 | my $dbh = $self->{dbh};
|
---|
[459] | 4048 | my $recid = shift;
|
---|
| 4049 | my $newtype = shift;
|
---|
| 4050 |
|
---|
| 4051 | # also, only work on live records; little to no value trying to do this on default records.
|
---|
[481] | 4052 | my $rec = $self->getRecLine('n', 'y', $recid);
|
---|
[459] | 4053 |
|
---|
| 4054 | # hm?
|
---|
| 4055 | #return 1 if !$rec;
|
---|
| 4056 |
|
---|
| 4057 | return 1 if $rec->{type} < 65000; # Only the reverse-record pseudotypes can be downconverted
|
---|
| 4058 | return 1 if $rec->{type} == 65282; # Nowhere to go
|
---|
| 4059 |
|
---|
| 4060 | my $delpar;
|
---|
| 4061 | my @sqlargs;
|
---|
| 4062 | if ($rec->{type} == 65280) {
|
---|
| 4063 | return 1 if $newtype != 1 && $newtype != 12;
|
---|
| 4064 | $delpar = ($newtype == 1 ? 'rdns_id' : 'domain_id');
|
---|
| 4065 | push @sqlargs, 0, $newtype, $recid;
|
---|
| 4066 | } elsif ($rec->{type} == 65281) {
|
---|
| 4067 | return 1 if $newtype != 28 && $newtype != 12;
|
---|
| 4068 | $delpar = ($newtype == 28 ? 'rdns_id' : 'domain_id');
|
---|
| 4069 | push @sqlargs, 0, $newtype, $recid;
|
---|
| 4070 | } elsif ($rec->{type} == 65283) {
|
---|
| 4071 | return 1 if $newtype != 65282;
|
---|
| 4072 | $delpar = 'rdns_id';
|
---|
| 4073 | } elsif ($rec->{type} == 65284) {
|
---|
| 4074 | return 1 if $newtype != 65282;
|
---|
| 4075 | $delpar = 'rdns_id';
|
---|
| 4076 | } else {
|
---|
| 4077 | # Your llama is on fire.
|
---|
| 4078 | }
|
---|
| 4079 |
|
---|
| 4080 | local $dbh->{AutoCommit} = 0;
|
---|
| 4081 | local $dbh->{RaiseError} = 1;
|
---|
| 4082 |
|
---|
| 4083 | eval {
|
---|
| 4084 | $dbh->do("UPDATE records SET $delpar = ?, type = ? WHERE record_id = ?", undef, @sqlargs);
|
---|
| 4085 | $dbh->commit;
|
---|
| 4086 | };
|
---|
| 4087 | if ($@) {
|
---|
| 4088 | $errstr = $@;
|
---|
| 4089 | eval { $dbh->rollback; };
|
---|
| 4090 | return 0;
|
---|
| 4091 | }
|
---|
| 4092 | return 1;
|
---|
| 4093 | } # end downconvert()
|
---|
| 4094 |
|
---|
| 4095 |
|
---|
[3] | 4096 | ## DNSDB::delRec()
|
---|
| 4097 | # Delete a record.
|
---|
| 4098 | sub delRec {
|
---|
| 4099 | $errstr = '';
|
---|
[481] | 4100 | my $self = shift;
|
---|
| 4101 | my $dbh = $self->{dbh};
|
---|
[3] | 4102 | my $defrec = shift;
|
---|
[243] | 4103 | my $revrec = shift;
|
---|
[3] | 4104 | my $id = shift;
|
---|
| 4105 |
|
---|
[481] | 4106 | my $oldrec = $self->getRecLine($defrec, $revrec, $id);
|
---|
[3] | 4107 |
|
---|
[290] | 4108 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4109 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4110 | local $dbh->{AutoCommit} = 0;
|
---|
| 4111 | local $dbh->{RaiseError} = 1;
|
---|
[3] | 4112 |
|
---|
[290] | 4113 | # Put together the log entry
|
---|
| 4114 | my %logdata;
|
---|
| 4115 | $logdata{domain_id} = $oldrec->{domain_id};
|
---|
| 4116 | $logdata{rdns_id} = $oldrec->{rdns_id};
|
---|
| 4117 | $logdata{group_id} = $oldrec->{group_id} if $defrec eq 'y';
|
---|
[473] | 4118 | $logdata{group_id} = $self->parentID(id => $oldrec->{domain_id}, type => ($revrec eq 'n' ? 'domain' : 'revzone'),
|
---|
| 4119 | revrec => $revrec)
|
---|
[290] | 4120 | if $defrec eq 'n';
|
---|
| 4121 | $logdata{entry} = "Deleted ".($defrec eq 'y' ? 'default record ' : 'record ').
|
---|
| 4122 | "'$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
| 4123 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
| 4124 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
| 4125 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
[425] | 4126 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
[480] | 4127 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location};
|
---|
[290] | 4128 |
|
---|
| 4129 | eval {
|
---|
| 4130 | my $sth = $dbh->do("DELETE FROM "._rectable($defrec,$revrec)." WHERE record_id=?", undef, ($id));
|
---|
[487] | 4131 | $self->_log(%logdata);
|
---|
[290] | 4132 | $dbh->commit;
|
---|
| 4133 | };
|
---|
| 4134 | if ($@) {
|
---|
| 4135 | my $msg = $@;
|
---|
| 4136 | eval { $dbh->rollback; };
|
---|
[517] | 4137 | if ($self->{log_failures}) {
|
---|
[290] | 4138 | $logdata{entry} = "Error deleting ".($defrec eq 'y' ? 'default record' : 'record').
|
---|
| 4139 | " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
[487] | 4140 | $self->_log(%logdata);
|
---|
[290] | 4141 | $dbh->commit;
|
---|
| 4142 | }
|
---|
| 4143 | return ('FAIL', $msg);
|
---|
| 4144 | }
|
---|
| 4145 |
|
---|
| 4146 | return ('OK',$logdata{entry});
|
---|
[3] | 4147 | } # end delRec()
|
---|
| 4148 |
|
---|
| 4149 |
|
---|
[323] | 4150 | ## DNSDB::getLogCount()
|
---|
| 4151 | # Get a count of log entries
|
---|
| 4152 | # Takes a database handle and a hash containing at least:
|
---|
| 4153 | # - Entity ID and entity type as the primary log "slice"
|
---|
| 4154 | sub getLogCount {
|
---|
[483] | 4155 | my $self = shift;
|
---|
| 4156 | my $dbh = $self->{dbh};
|
---|
[323] | 4157 |
|
---|
| 4158 | my %args = @_;
|
---|
| 4159 |
|
---|
| 4160 | my @filterargs;
|
---|
| 4161 | ##fixme: which fields do we want to filter on?
|
---|
| 4162 | # push @filterargs,
|
---|
| 4163 |
|
---|
| 4164 | $errstr = 'Missing primary parent ID and/or type';
|
---|
| 4165 | # fail early if we don't have a "prime" ID to look for log entries for
|
---|
| 4166 | return if !$args{id};
|
---|
| 4167 |
|
---|
| 4168 | # or if the prime id type is missing or invalid
|
---|
| 4169 | return if !$args{logtype};
|
---|
| 4170 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
| 4171 | $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
|
---|
| 4172 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
|
---|
| 4173 |
|
---|
| 4174 | my $sql = "SELECT count(*) FROM log ".
|
---|
| 4175 | "WHERE $id_col{$args{logtype}}=?".
|
---|
| 4176 | ($args{filter} ? " AND entry ~* ?" : '');
|
---|
| 4177 | my ($count) = $dbh->selectrow_array($sql, undef, ($args{id}, @filterargs) );
|
---|
| 4178 | $errstr = $dbh->errstr if !$count;
|
---|
| 4179 | return $count;
|
---|
| 4180 | } # end getLogCount()
|
---|
| 4181 |
|
---|
| 4182 |
|
---|
| 4183 | ## DNSDB::getLogEntries()
|
---|
| 4184 | # Get a list of log entries
|
---|
| 4185 | # Takes arguments as with getLogCount() above, plus optional:
|
---|
| 4186 | # - sort field
|
---|
| 4187 | # - sort order
|
---|
| 4188 | # - offset for pagination
|
---|
| 4189 | sub getLogEntries {
|
---|
[483] | 4190 | my $self = shift;
|
---|
| 4191 | my $dbh = $self->{dbh};
|
---|
[323] | 4192 |
|
---|
| 4193 | my %args = @_;
|
---|
| 4194 |
|
---|
| 4195 | my @filterargs;
|
---|
| 4196 |
|
---|
| 4197 | # fail early if we don't have a "prime" ID to look for log entries for
|
---|
| 4198 | return if !$args{id};
|
---|
| 4199 |
|
---|
| 4200 | # or if the prime id type is missing or invalid
|
---|
| 4201 | return if !$args{logtype};
|
---|
| 4202 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
| 4203 | $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
|
---|
| 4204 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
|
---|
| 4205 |
|
---|
| 4206 | # Sorting defaults
|
---|
[508] | 4207 | $args{sortorder} = 'DESC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
| 4208 | $args{sortby} = 'stamp' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
[397] | 4209 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[323] | 4210 |
|
---|
[324] | 4211 | my %sortmap = (fname => 'name', username => 'email', entry => 'entry', stamp => 'stamp');
|
---|
[323] | 4212 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 4213 |
|
---|
| 4214 | my $sql = "SELECT user_id AS userid, email AS useremail, name AS userfname, entry AS logentry, ".
|
---|
| 4215 | "date_trunc('second',stamp) AS logtime ".
|
---|
| 4216 | "FROM log ".
|
---|
| 4217 | "WHERE $id_col{$args{logtype}}=?".
|
---|
| 4218 | ($args{filter} ? " AND entry ~* ?" : '').
|
---|
[324] | 4219 | " ORDER BY $args{sortby} $args{sortorder}, log_id $args{sortorder}".
|
---|
[517] | 4220 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
[323] | 4221 | my $loglist = $dbh->selectall_arrayref($sql, { Slice => {} }, ($args{id}, @filterargs) );
|
---|
| 4222 | $errstr = $dbh->errstr if !$loglist;
|
---|
| 4223 | return $loglist;
|
---|
| 4224 | } # end getLogEntries()
|
---|
| 4225 |
|
---|
| 4226 |
|
---|
[452] | 4227 | ## IPDB::getRevPattern()
|
---|
| 4228 | # Get the narrowest template pattern applicable to a passed CIDR address (may be a netblock or an IP)
|
---|
| 4229 | sub getRevPattern {
|
---|
[483] | 4230 | my $self = shift;
|
---|
| 4231 | my $dbh = $self->{dbh};
|
---|
[452] | 4232 | my $cidr = shift;
|
---|
| 4233 | my $group = shift || 1; # just in case
|
---|
| 4234 |
|
---|
[462] | 4235 | # for speed! Casting and comparing even ~7K records takes ~2.5s, so narrow it down to one revzone first.
|
---|
| 4236 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >>= ? AND group_id = ?",
|
---|
| 4237 | undef, ($cidr, $group) );
|
---|
| 4238 |
|
---|
| 4239 | ##fixme? may need to narrow things down more by octet-chopping and doing text comparisons before casting.
|
---|
| 4240 | my ($revpatt) = $dbh->selectrow_array("SELECT host FROM records ".
|
---|
| 4241 | "WHERE (type in (12,65280,65281,65282,65283,65284)) AND rdns_id = ? AND CAST (val AS inet) >>= ? ".
|
---|
| 4242 | "ORDER BY CAST (val AS inet) DESC LIMIT 1", undef, ($revid, $cidr) );
|
---|
[452] | 4243 | return $revpatt;
|
---|
| 4244 | } # end getRevPattern()
|
---|
| 4245 |
|
---|
| 4246 |
|
---|
[225] | 4247 | ## DNSDB::getTypelist()
|
---|
| 4248 | # Get a list of record types for various UI dropdowns
|
---|
| 4249 | # Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A)
|
---|
| 4250 | # Returns an arrayref to list of hashrefs perfect for HTML::Template
|
---|
| 4251 | sub getTypelist {
|
---|
[483] | 4252 | my $self = shift;
|
---|
| 4253 | my $dbh = $self->{dbh};
|
---|
[225] | 4254 | my $recgroup = shift;
|
---|
| 4255 | my $type = shift || $reverse_typemap{A};
|
---|
| 4256 |
|
---|
| 4257 | # also accepting $webvar{revrec}!
|
---|
| 4258 | $recgroup = 'f' if $recgroup eq 'n';
|
---|
| 4259 | $recgroup = 'r' if $recgroup eq 'y';
|
---|
| 4260 |
|
---|
| 4261 | my $sql = "SELECT val,name FROM rectypes WHERE ";
|
---|
| 4262 | if ($recgroup eq 'r') {
|
---|
| 4263 | # reverse zone types
|
---|
| 4264 | $sql .= "stdflag=2 OR stdflag=3";
|
---|
| 4265 | } elsif ($recgroup eq 'l') {
|
---|
| 4266 | # DNS lookup types. Note we avoid our custom types >= 65280, since those are entirely internal.
|
---|
| 4267 | $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280";
|
---|
| 4268 | } else {
|
---|
| 4269 | # default; forward zone types. technically $type eq 'f' but not worth the error message.
|
---|
| 4270 | $sql .= "stdflag=1 OR stdflag=2";
|
---|
[506] | 4271 | $sql .= " AND val < 65280" if $recgroup eq 'fo'; # An extra flag to trim off the pseudotypes as well.
|
---|
[225] | 4272 | }
|
---|
| 4273 | $sql .= " ORDER BY listorder";
|
---|
| 4274 |
|
---|
| 4275 | my $sth = $dbh->prepare($sql);
|
---|
| 4276 | $sth->execute;
|
---|
| 4277 | my @typelist;
|
---|
| 4278 | while (my ($rval,$rname) = $sth->fetchrow_array()) {
|
---|
| 4279 | my %row = ( recval => $rval, recname => $rname );
|
---|
| 4280 | $row{tselect} = 1 if $rval == $type;
|
---|
| 4281 | push @typelist, \%row;
|
---|
| 4282 | }
|
---|
| 4283 |
|
---|
| 4284 | # Add SOA on lookups since it's not listed in other dropdowns.
|
---|
| 4285 | if ($recgroup eq 'l') {
|
---|
| 4286 | my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
|
---|
| 4287 | $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
|
---|
| 4288 | push @typelist, \%row;
|
---|
| 4289 | }
|
---|
| 4290 |
|
---|
| 4291 | return \@typelist;
|
---|
| 4292 | } # end getTypelist()
|
---|
| 4293 |
|
---|
| 4294 |
|
---|
[254] | 4295 | ## DNSDB::parentID()
|
---|
| 4296 | # Get ID of entity that is nearest parent to requested id
|
---|
| 4297 | # Takes a database handle and a hash of entity ID, entity type, optional parent type flag
|
---|
| 4298 | # (domain/reverse zone or group), and optional default/live and forward/reverse flags
|
---|
| 4299 | # Returns the ID or undef on failure
|
---|
| 4300 | sub parentID {
|
---|
[473] | 4301 | my $self = shift;
|
---|
| 4302 | my $dbh = $self->{dbh};
|
---|
[116] | 4303 |
|
---|
[254] | 4304 | my %args = @_;
|
---|
[116] | 4305 |
|
---|
[254] | 4306 | # clean up the parent-type. Set it to group if not set; coerce revzone to domain for simpler logic
|
---|
| 4307 | $args{partype} = 'group' if !$args{partype};
|
---|
| 4308 | $args{partype} = 'domain' if $args{partype} eq 'revzone';
|
---|
[116] | 4309 |
|
---|
[254] | 4310 | # clean up defrec and revrec. default to live record, forward zone
|
---|
| 4311 | $args{defrec} = 'n' if !$args{defrec};
|
---|
| 4312 | $args{revrec} = 'n' if !$args{revrec};
|
---|
[116] | 4313 |
|
---|
[254] | 4314 | if ($par_type{$args{partype}} eq 'domain') {
|
---|
| 4315 | # only live records can have a domain/zone parent
|
---|
| 4316 | return unless ($args{type} eq 'record' && $args{defrec} eq 'n');
|
---|
| 4317 | my $result = $dbh->selectrow_hashref("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
| 4318 | " FROM records WHERE record_id = ?",
|
---|
| 4319 | undef, ($args{id}) ) or return;
|
---|
| 4320 | return $result;
|
---|
| 4321 | } else {
|
---|
| 4322 | # snag some arguments that will either fall through or be overwritten to save some code duplication
|
---|
| 4323 | my $tmpid = $args{id};
|
---|
| 4324 | my $type = $args{type};
|
---|
| 4325 | if ($type eq 'record' && $args{defrec} eq 'n') {
|
---|
| 4326 | # Live records go through the records table first.
|
---|
| 4327 | ($tmpid) = $dbh->selectrow_array("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
| 4328 | " FROM records WHERE record_id = ?",
|
---|
| 4329 | undef, ($args{id}) ) or return;
|
---|
| 4330 | $type = ($args{revrec} eq 'n' ? 'domain' : 'revzone');
|
---|
| 4331 | }
|
---|
| 4332 | my ($result) = $dbh->selectrow_array("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
|
---|
| 4333 | undef, ($tmpid) );
|
---|
| 4334 | return $result;
|
---|
| 4335 | }
|
---|
| 4336 | # should be impossible to get here with even remotely sane arguments
|
---|
| 4337 | return;
|
---|
| 4338 | } # end parentID()
|
---|
[116] | 4339 |
|
---|
| 4340 |
|
---|
[117] | 4341 | ## DNSDB::isParent()
|
---|
| 4342 | # Returns true if $id1 is a parent of $id2, false otherwise
|
---|
| 4343 | sub isParent {
|
---|
[470] | 4344 | my $self = shift;
|
---|
| 4345 | my $dbh = $self->{dbh};
|
---|
[117] | 4346 | my $id1 = shift;
|
---|
| 4347 | my $type1 = shift;
|
---|
| 4348 | my $id2 = shift;
|
---|
| 4349 | my $type2 = shift;
|
---|
| 4350 | ##todo: immediate, secondary, full (default)
|
---|
| 4351 |
|
---|
[157] | 4352 | # Return false on invalid types
|
---|
[244] | 4353 | return 0 if !grep /^$type1$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
| 4354 | return 0 if !grep /^$type2$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
[157] | 4355 |
|
---|
[117] | 4356 | # Return false on impossible relations
|
---|
| 4357 | return 0 if $type1 eq 'record'; # nothing may be a child of a record
|
---|
| 4358 | return 0 if $type1 eq 'defrec'; # nothing may be a child of a record
|
---|
[244] | 4359 | return 0 if $type1 eq 'defrevrec'; # nothing may be a child of a record
|
---|
[117] | 4360 | return 0 if $type1 eq 'user'; # nothing may be child of a user
|
---|
| 4361 | return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record
|
---|
[244] | 4362 | return 0 if $type1 eq 'revzone' && $type2 ne 'record';# reverse zone may not be a parent of anything other than a record
|
---|
[117] | 4363 |
|
---|
[186] | 4364 | # ennnhhhh.... if we're passed an id of 0, it will never be found. usual
|
---|
| 4365 | # case would be the UI creating a new <thing>, and so we don't have an ID for
|
---|
| 4366 | # <thing> to look up yet. in that case the UI should check the parent as well.
|
---|
| 4367 | return 0 if $id1 == 0; # nothing can have a parent id of 0
|
---|
| 4368 | return 1 if $id2 == 0; # anything could have a child id of 0 (or "unknown")
|
---|
| 4369 |
|
---|
[117] | 4370 | # group 1 is the ultimate root parent
|
---|
| 4371 | return 1 if $type1 eq 'group' && $id1 == 1;
|
---|
| 4372 |
|
---|
[155] | 4373 | # groups are always (a) parent of themselves
|
---|
| 4374 | return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2;
|
---|
| 4375 |
|
---|
[117] | 4376 | my $id = $id2;
|
---|
| 4377 | my $type = $type2;
|
---|
| 4378 | my $foundparent = 0;
|
---|
[155] | 4379 |
|
---|
[244] | 4380 | # Records are the only entity with two possible parents. We need to split the parent checks on
|
---|
| 4381 | # domain/rdns.
|
---|
| 4382 | if ($type eq 'record') {
|
---|
| 4383 | my ($dom,$rdns) = $dbh->selectrow_array("SELECT domain_id,rdns_id FROM records WHERE record_id=?",
|
---|
| 4384 | undef, ($id));
|
---|
| 4385 | # check immediate parent against request
|
---|
| 4386 | return 1 if $type1 eq 'domain' && $id1 == $dom;
|
---|
| 4387 | return 1 if $type1 eq 'revzone' && $id1 == $rdns;
|
---|
| 4388 | # if request is group, check *both* parents. Only check if the parent is nonzero though.
|
---|
[470] | 4389 | return 1 if $dom && $self->isParent($id1, $type1, $dom, 'domain');
|
---|
| 4390 | return 1 if $rdns && $self->isParent($id1, $type1, $rdns, 'revzone');
|
---|
[244] | 4391 | # exit here since we've executed the loop below by proxy in the above recursive calls.
|
---|
| 4392 | return 0;
|
---|
| 4393 | }
|
---|
| 4394 |
|
---|
| 4395 | # almost the same loop as getParents() above
|
---|
[186] | 4396 | my $limiter = 0;
|
---|
[117] | 4397 | while (1) {
|
---|
[155] | 4398 | my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
|
---|
[117] | 4399 | my $result = $dbh->selectrow_hashref($sql,
|
---|
[157] | 4400 | undef, ($id) );
|
---|
[186] | 4401 | if (!$result) {
|
---|
| 4402 | $limiter++;
|
---|
[244] | 4403 | ##fixme: how often will this happen on a live site? fail at max limiter <n>?
|
---|
[541] | 4404 | # 2013/10/22 only seems to happen when you request an entity that doesn't exist.
|
---|
[186] | 4405 | warn "no results looking for $sql with id $id (depth $limiter)\n";
|
---|
| 4406 | last;
|
---|
| 4407 | }
|
---|
[157] | 4408 | if ($result && $result->{$par_col{$type}} == $id1) {
|
---|
[117] | 4409 | $foundparent = 1;
|
---|
| 4410 | last;
|
---|
[157] | 4411 | } else {
|
---|
| 4412 | ##fixme: do we care about trying to return a "no such record/domain/user/group" error?
|
---|
[244] | 4413 | # should be impossible to create an inconsistent DB just with API calls.
|
---|
[157] | 4414 | warn $dbh->errstr." $sql, $id" if $dbh->errstr;
|
---|
[117] | 4415 | }
|
---|
| 4416 | # group 1 is its own parent. need this here more to break strange loops than for detecting a parent
|
---|
| 4417 | last if $result->{$par_col{$type}} == 1;
|
---|
[152] | 4418 | $id = $result->{$par_col{$type}};
|
---|
[117] | 4419 | $type = $par_type{$type};
|
---|
| 4420 | }
|
---|
| 4421 |
|
---|
| 4422 | return $foundparent;
|
---|
| 4423 | } # end isParent()
|
---|
| 4424 |
|
---|
| 4425 |
|
---|
[275] | 4426 | ## DNSDB::zoneStatus()
|
---|
| 4427 | # Returns and optionally sets a zone's status
|
---|
| 4428 | # Takes a database handle, domain/revzone ID, forward/reverse flag, and optionally a status argument
|
---|
| 4429 | # Returns status, or undef on errors.
|
---|
| 4430 | sub zoneStatus {
|
---|
[477] | 4431 | my $self = shift;
|
---|
| 4432 | my $dbh = $self->{dbh};
|
---|
[3] | 4433 | my $id = shift;
|
---|
[275] | 4434 | my $revrec = shift;
|
---|
| 4435 | my $newstatus = shift || 'mu';
|
---|
[3] | 4436 |
|
---|
| 4437 | return undef if $id !~ /^\d+$/;
|
---|
| 4438 |
|
---|
[283] | 4439 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4440 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4441 | local $dbh->{AutoCommit} = 0;
|
---|
| 4442 | local $dbh->{RaiseError} = 1;
|
---|
| 4443 |
|
---|
[275] | 4444 | if ($newstatus ne 'mu') {
|
---|
[283] | 4445 | # ooo, fun! let's see what we were passed for status
|
---|
| 4446 | eval {
|
---|
| 4447 | $newstatus = 0 if $newstatus eq 'domoff';
|
---|
| 4448 | $newstatus = 1 if $newstatus eq 'domon';
|
---|
| 4449 | $dbh->do("UPDATE ".($revrec eq 'n' ? 'domains' : 'revzones')." SET status=? WHERE ".
|
---|
[275] | 4450 | ($revrec eq 'n' ? 'domain_id' : 'rdns_id')."=?", undef, ($newstatus,$id) );
|
---|
[283] | 4451 |
|
---|
| 4452 | ##fixme switch to more consise "Enabled <domain"/"Disabled <domain>" as with users?
|
---|
[473] | 4453 | $resultstr = "Changed ".($revrec eq 'n' ? $self->domainName($id) : $self->revName($id)).
|
---|
[283] | 4454 | " state to ".($newstatus ? 'active' : 'inactive');
|
---|
| 4455 |
|
---|
| 4456 | my %loghash;
|
---|
| 4457 | $loghash{domain_id} = $id if $revrec eq 'n';
|
---|
| 4458 | $loghash{rdns_id} = $id if $revrec eq 'y';
|
---|
[473] | 4459 | $loghash{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec);
|
---|
[283] | 4460 | $loghash{entry} = $resultstr;
|
---|
[487] | 4461 | $self->_log(%loghash);
|
---|
[283] | 4462 |
|
---|
| 4463 | $dbh->commit;
|
---|
| 4464 | };
|
---|
| 4465 | if ($@) {
|
---|
| 4466 | my $msg = $@;
|
---|
| 4467 | eval { $dbh->rollback; };
|
---|
| 4468 | $resultstr = '';
|
---|
| 4469 | $errstr = $msg;
|
---|
| 4470 | return;
|
---|
| 4471 | }
|
---|
[3] | 4472 | }
|
---|
| 4473 |
|
---|
[275] | 4474 | my ($status) = $dbh->selectrow_array("SELECT status FROM ".
|
---|
| 4475 | ($revrec eq 'n' ? "domains WHERE domain_id=?" : "revzones WHERE rdns_id=?"),
|
---|
| 4476 | undef, ($id) );
|
---|
[3] | 4477 | return $status;
|
---|
[275] | 4478 | } # end zoneStatus()
|
---|
[3] | 4479 |
|
---|
| 4480 |
|
---|
[452] | 4481 | ## DNSDB::getZonesByCIDR()
|
---|
| 4482 | # Get a list of zone names and IDs that records for a passed CIDR block are within.
|
---|
| 4483 | sub getZonesByCIDR {
|
---|
[477] | 4484 | my $self = shift;
|
---|
| 4485 | my $dbh = $self->{dbh};
|
---|
[452] | 4486 | my %args = @_;
|
---|
| 4487 |
|
---|
| 4488 | my $result = $dbh->selectall_arrayref("SELECT rdns_id,revnet FROM revzones WHERE revnet >>= ? OR revnet <<= ?",
|
---|
| 4489 | { Slice => {} }, ($args{cidr}, $args{cidr}) );
|
---|
| 4490 | return $result;
|
---|
| 4491 | } # end getZonesByCIDR()
|
---|
| 4492 |
|
---|
| 4493 |
|
---|
[33] | 4494 | ## DNSDB::importAXFR
|
---|
| 4495 | # Import a domain via AXFR
|
---|
[37] | 4496 | # Takes AXFR host, domain to transfer, group to put the domain in,
|
---|
[484] | 4497 | # and an optional hash containing:
|
---|
| 4498 | # status - active/inactive state flag (defaults to active)
|
---|
| 4499 | # rwsoa - overwrite-SOA flag (defaults to off)
|
---|
| 4500 | # rwns - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
|
---|
| 4501 | # merge - flag to automerge A or AAAA records with matching PTR records
|
---|
[37] | 4502 | # Returns a status code (OK, WARN, or FAIL) and message - message should be blank
|
---|
| 4503 | # if status is OK, but WARN includes conditions that are not fatal but should
|
---|
| 4504 | # really be reported.
|
---|
[33] | 4505 | sub importAXFR {
|
---|
[484] | 4506 | my $self = shift;
|
---|
| 4507 | my $dbh = $self->{dbh};
|
---|
[35] | 4508 | my $ifrom_in = shift;
|
---|
[301] | 4509 | my $zone = shift;
|
---|
[33] | 4510 | my $group = shift;
|
---|
[484] | 4511 |
|
---|
| 4512 | my %args = @_;
|
---|
| 4513 |
|
---|
[33] | 4514 | ##fixme: add mode to delete&replace, merge+overwrite, merge new?
|
---|
| 4515 |
|
---|
[484] | 4516 | $args{status} = (defined($args{status}) ? $args{status} : 0);
|
---|
| 4517 | $args{status} = 1 if $args{status} eq 'on';
|
---|
| 4518 |
|
---|
[37] | 4519 | my $nrecs = 0;
|
---|
| 4520 | my $soaflag = 0;
|
---|
| 4521 | my $nsflag = 0;
|
---|
| 4522 | my $warnmsg = '';
|
---|
| 4523 | my $ifrom;
|
---|
[33] | 4524 |
|
---|
[301] | 4525 | my $rev = 'n';
|
---|
[302] | 4526 | my $code = 'OK';
|
---|
| 4527 | my $msg = 'foobar?';
|
---|
[301] | 4528 |
|
---|
[35] | 4529 | # choke on possible bad setting in ifrom
|
---|
[37] | 4530 | # IPv4 and v6, and valid hostnames!
|
---|
[35] | 4531 | ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
| 4532 | return ('FAIL', "Bad AXFR source host $ifrom")
|
---|
| 4533 | unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
| 4534 |
|
---|
[301] | 4535 | my $errmsg;
|
---|
| 4536 |
|
---|
| 4537 | my $zone_id;
|
---|
| 4538 | my $domain_id = 0;
|
---|
| 4539 | my $rdns_id = 0;
|
---|
| 4540 | my $cidr;
|
---|
| 4541 |
|
---|
| 4542 | # magic happens! detect if we're importing a domain or a reverse zone
|
---|
| 4543 | # while we're at it, figure out what the CIDR netblock is (if we got a .arpa)
|
---|
| 4544 | # or what the formal .arpa zone is (if we got a CIDR netblock)
|
---|
| 4545 | # Handles sub-octet v4 zones in the format specified in the Cricket Book, 2nd Ed, p217-218
|
---|
| 4546 |
|
---|
| 4547 | if ($zone =~ m{(?:\.arpa\.?|/\d+)$}) {
|
---|
| 4548 | # we seem to have a reverse zone
|
---|
| 4549 | $rev = 'y';
|
---|
| 4550 |
|
---|
| 4551 | if ($zone =~ /\.arpa\.?$/) {
|
---|
| 4552 | # we have a formal reverse zone. call _zone2cidr and get the CIDR block.
|
---|
| 4553 | ($code,$msg) = _zone2cidr($zone);
|
---|
| 4554 | return ($code, $msg) if $code eq 'FAIL';
|
---|
| 4555 | $cidr = $msg;
|
---|
| 4556 | } elsif ($zone =~ m|^[\d.]+/\d+$|) {
|
---|
| 4557 | # v4 revzone, CIDR netblock
|
---|
| 4558 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 4559 | $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
| 4560 | } elsif ($zone =~ m|^[a-fA-F\d:]+/\d+$|) {
|
---|
| 4561 | # v6 revzone, CIDR netblock
|
---|
| 4562 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 4563 | return ('FAIL', "$zone is not a nibble-aligned block") if $cidr->masklen % 4 != 0;
|
---|
| 4564 | $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.');
|
---|
| 4565 | } else {
|
---|
| 4566 | # there is. no. else!
|
---|
| 4567 | return ('FAIL', "Unknown zone name format");
|
---|
| 4568 | }
|
---|
| 4569 |
|
---|
| 4570 | # quick check to start to see if we've already got one
|
---|
| 4571 |
|
---|
| 4572 | ($zone_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?",
|
---|
| 4573 | undef, ("$cidr"));
|
---|
| 4574 | $rdns_id = $zone_id;
|
---|
| 4575 | } else {
|
---|
| 4576 | # default to domain
|
---|
[349] | 4577 | ($zone_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
[301] | 4578 | undef, ($zone));
|
---|
| 4579 | $domain_id = $zone_id;
|
---|
| 4580 | }
|
---|
| 4581 |
|
---|
| 4582 | return ('FAIL', ($rev eq 'n' ? 'Domain' : 'Reverse zone')." already exists") if $zone_id;
|
---|
| 4583 |
|
---|
[303] | 4584 | # little local utility sub to swap $val and $host for revzone records.
|
---|
| 4585 | sub _revswap {
|
---|
| 4586 | my $rechost = shift;
|
---|
| 4587 | my $recdata = shift;
|
---|
| 4588 |
|
---|
| 4589 | if ($rechost =~ /\.in-addr\.arpa\.?$/) {
|
---|
| 4590 | $rechost =~ s/\.in-addr\.arpa\.?$//;
|
---|
| 4591 | $rechost = join '.', reverse split /\./, $rechost;
|
---|
| 4592 | } else {
|
---|
| 4593 | $rechost =~ s/\.ip6\.arpa\.?$//;
|
---|
| 4594 | my @nibs = reverse split /\./, $rechost;
|
---|
| 4595 | $rechost = '';
|
---|
| 4596 | my $nc;
|
---|
| 4597 | foreach (@nibs) {
|
---|
| 4598 | $rechost.= $_;
|
---|
| 4599 | $rechost .= ":" if ++$nc % 4 == 0 && $nc < 32;
|
---|
| 4600 | }
|
---|
[307] | 4601 | $rechost .= ":" if $nc < 32 && $rechost !~ /\*$/; # close netblock records?
|
---|
| 4602 | ##fixme: there's a case that ends up with a partial entry here:
|
---|
| 4603 | # ip:add:re:ss::
|
---|
| 4604 | # can't reproduce after letting it sit overnight after discovery. :(
|
---|
| 4605 | #print "$rechost\n";
|
---|
[303] | 4606 | # canonicalize with NetAddr::IP
|
---|
| 4607 | $rechost = NetAddr::IP->new($rechost)->addr unless $rechost =~ /\*$/;
|
---|
| 4608 | }
|
---|
| 4609 | return ($recdata,$rechost)
|
---|
| 4610 | }
|
---|
| 4611 |
|
---|
| 4612 |
|
---|
[33] | 4613 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4614 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4615 | local $dbh->{AutoCommit} = 0;
|
---|
| 4616 | local $dbh->{RaiseError} = 1;
|
---|
| 4617 |
|
---|
[301] | 4618 | my $sth;
|
---|
| 4619 | eval {
|
---|
[34] | 4620 |
|
---|
[301] | 4621 | if ($rev eq 'n') {
|
---|
[33] | 4622 | ##fixme: serial
|
---|
[484] | 4623 | $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef,
|
---|
| 4624 | ($zone, $group, $args{status}) );
|
---|
[301] | 4625 | # get domain id so we can do the records
|
---|
| 4626 | ($zone_id) = $dbh->selectrow_array("SELECT currval('domains_domain_id_seq')");
|
---|
| 4627 | $domain_id = $zone_id;
|
---|
[487] | 4628 | $self->_log(group_id => $group, domain_id => $domain_id,
|
---|
| 4629 | entry => "[Added ".($args{status} ? 'active' : 'inactive')." domain $zone via AXFR]");
|
---|
[301] | 4630 | } else {
|
---|
| 4631 | ##fixme: serial
|
---|
[484] | 4632 | $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef,
|
---|
| 4633 | ($cidr,$group,$args{status}) );
|
---|
[301] | 4634 | # get revzone id so we can do the records
|
---|
| 4635 | ($zone_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
| 4636 | $rdns_id = $zone_id;
|
---|
[487] | 4637 | $self->_log(group_id => $group, rdns_id => $rdns_id,
|
---|
| 4638 | entry => "[Added ".($args{status} ? 'active' : 'inactive')." reverse zone $cidr via AXFR]");
|
---|
[301] | 4639 | }
|
---|
[33] | 4640 |
|
---|
[35] | 4641 | ## bizarre DBI<->Net::DNS interaction bug:
|
---|
| 4642 | ## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
|
---|
[37] | 4643 | ## fixed, apparently I was doing *something* odd, but not certain what it was that
|
---|
| 4644 | ## caused a commit instead of barfing
|
---|
[35] | 4645 |
|
---|
[34] | 4646 | my $res = Net::DNS::Resolver->new;
|
---|
[35] | 4647 | $res->nameservers($ifrom);
|
---|
[301] | 4648 | $res->axfr_start($zone)
|
---|
[35] | 4649 | or die "Couldn't begin AXFR\n";
|
---|
[34] | 4650 |
|
---|
[301] | 4651 | $sth = $dbh->prepare("INSERT INTO records (domain_id,rdns_id,host,type,val,distance,weight,port,ttl)".
|
---|
| 4652 | " VALUES (?,?,?,?,?,?,?,?,?)");
|
---|
| 4653 |
|
---|
[307] | 4654 | # Stash info about sub-octet v4 revzones here so we don't have
|
---|
| 4655 | # to store the CNAMEs used to delegate a suboctet zone
|
---|
| 4656 | # $suboct{zone}{ns}[] -> array of nameservers
|
---|
| 4657 | # $suboct{zone}{cname}[] -> array of extant CNAMEs (Just In Case someone did something bizarre)
|
---|
| 4658 | ## commented pending actual use of this data. for now, we'll just
|
---|
| 4659 | ## auto-(re)create the CNAMEs in revzones on export
|
---|
| 4660 | # my %suboct;
|
---|
| 4661 |
|
---|
[35] | 4662 | while (my $rr = $res->axfr_next()) {
|
---|
[301] | 4663 |
|
---|
| 4664 | my $val;
|
---|
| 4665 | my $distance = 0;
|
---|
| 4666 | my $weight = 0;
|
---|
| 4667 | my $port = 0;
|
---|
[303] | 4668 | my $logfrag = '';
|
---|
[301] | 4669 |
|
---|
[33] | 4670 | my $type = $rr->type;
|
---|
[301] | 4671 | my $host = $rr->name;
|
---|
[484] | 4672 | my $ttl = ($args{newttl} ? $args{newttl} : $rr->ttl); # allow force-override TTLs
|
---|
[35] | 4673 |
|
---|
[37] | 4674 | $soaflag = 1 if $type eq 'SOA';
|
---|
| 4675 | $nsflag = 1 if $type eq 'NS';
|
---|
[35] | 4676 |
|
---|
[34] | 4677 | # "Primary" types:
|
---|
| 4678 | # A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
|
---|
| 4679 | # maybe KEY
|
---|
| 4680 |
|
---|
[302] | 4681 | # BIND supports:
|
---|
| 4682 | # [standard]
|
---|
| 4683 | # A AAAA CNAME MX NS PTR SOA TXT
|
---|
| 4684 | # [variously experimental, obsolete, or obscure]
|
---|
| 4685 | # 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
|
---|
| 4686 | # ... if one can ever find the right magic to format them correctly
|
---|
| 4687 |
|
---|
| 4688 | # Net::DNS supports:
|
---|
| 4689 | # RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
|
---|
| 4690 | # EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
|
---|
| 4691 | # DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
|
---|
| 4692 |
|
---|
[35] | 4693 | # nasty big ugly case-like thing here, since we have to do *some* different
|
---|
| 4694 | # processing depending on the record. le sigh.
|
---|
| 4695 |
|
---|
[105] | 4696 | ##fixme: what record types other than TXT can/will have >255-byte payloads?
|
---|
| 4697 |
|
---|
[34] | 4698 | if ($type eq 'A') {
|
---|
[301] | 4699 | $val = $rr->address;
|
---|
[34] | 4700 | } elsif ($type eq 'NS') {
|
---|
[37] | 4701 | # hmm. should we warn here if subdomain NS'es are left alone?
|
---|
[484] | 4702 | next if ($args{rwns} && ($rr->name eq $zone));
|
---|
[302] | 4703 | if ($rev eq 'y') {
|
---|
| 4704 | # revzones have records more or less reversed from forward zones.
|
---|
| 4705 | my ($tmpcode,$tmpmsg) = _zone2cidr($host);
|
---|
[401] | 4706 | die "Error converting NS record: $tmpmsg\n" if $tmpcode eq 'FAIL'; # hmm. may not make sense...
|
---|
[302] | 4707 | $val = "$tmpmsg";
|
---|
| 4708 | $host = $rr->nsdname;
|
---|
[303] | 4709 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
[307] | 4710 | # Tag and preserve. For now this is commented for a no-op, but we have Ideas for
|
---|
| 4711 | # another custom storage type ("DELEGATE") that will use these subzone-delegation records
|
---|
| 4712 | #if ($val ne "$cidr") {
|
---|
| 4713 | # push @{$suboct{$val}{ns}}, $host;
|
---|
| 4714 | #}
|
---|
[302] | 4715 | } else {
|
---|
| 4716 | $val = $rr->nsdname;
|
---|
| 4717 | }
|
---|
[35] | 4718 | $nsflag = 1;
|
---|
[34] | 4719 | } elsif ($type eq 'CNAME') {
|
---|
[302] | 4720 | if ($rev eq 'y') {
|
---|
[303] | 4721 | # hmm. do we even want to bother with storing these at this level? Sub-octet delegation
|
---|
| 4722 | # by CNAME is essentially a record-publication hack, and we want to just represent the
|
---|
| 4723 | # "true" logical intentions as far down the stack as we can from the UI.
|
---|
| 4724 | ($host,$val) = _revswap($host,$rr->cname);
|
---|
| 4725 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
[307] | 4726 | # Tag and preserve in case we want to commit them as-is later, but mostly we don't care.
|
---|
| 4727 | # Commented pending actually doing something with possibly new type DELEGATE
|
---|
| 4728 | #my $tmprev = $host;
|
---|
| 4729 | #$tmprev =~ s/^\d+\.//;
|
---|
| 4730 | #($code,$tmprev) = _zone2cidr($tmprev);
|
---|
| 4731 | #push @{$suboct{"$tmprev"}{cname}}, $val;
|
---|
| 4732 | # Silently skip CNAMEs in revzones.
|
---|
| 4733 | next;
|
---|
[302] | 4734 | } else {
|
---|
| 4735 | $val = $rr->cname;
|
---|
| 4736 | }
|
---|
[34] | 4737 | } elsif ($type eq 'SOA') {
|
---|
[484] | 4738 | next if $args{rwsoa};
|
---|
[307] | 4739 | $host = $rr->rname.":".$rr->mname;
|
---|
[301] | 4740 | $val = $rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum;
|
---|
[35] | 4741 | $soaflag = 1;
|
---|
[34] | 4742 | } elsif ($type eq 'PTR') {
|
---|
[303] | 4743 | ($host,$val) = _revswap($host,$rr->ptrdname);
|
---|
| 4744 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
[34] | 4745 | # hmm. PTR records should not be in forward zones.
|
---|
| 4746 | } elsif ($type eq 'MX') {
|
---|
[301] | 4747 | $val = $rr->exchange;
|
---|
| 4748 | $distance = $rr->preference;
|
---|
[34] | 4749 | } elsif ($type eq 'TXT') {
|
---|
| 4750 | ##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
|
---|
| 4751 | ## but don't really seem enthusiastic about it.
|
---|
[303] | 4752 | #print "should use rdatastr:\n\t".$rr->rdatastr."\n or char_str_list:\n\t".join(' ',$rr->char_str_list())."\n";
|
---|
| 4753 | # rdatastr returns a BIND-targetted logical string, including opening and closing quotes
|
---|
| 4754 | # char_str_list returns a list of the individual string fragments in the record
|
---|
[307] | 4755 | # txtdata returns the more useful all-in-one form (since we want to push such protocol
|
---|
| 4756 | # details as far down the stack as we can)
|
---|
[303] | 4757 | # NB: this may turn out to be more troublesome if we ever have need of >512-byte TXT records.
|
---|
| 4758 | if ($rev eq 'y') {
|
---|
| 4759 | ($host,$val) = _revswap($host,$rr->txtdata);
|
---|
| 4760 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
| 4761 | } else {
|
---|
| 4762 | $val = $rr->txtdata;
|
---|
| 4763 | }
|
---|
[34] | 4764 | } elsif ($type eq 'SPF') {
|
---|
| 4765 | ##fixme: and the same caveat here, since it is apparently a clone of ::TXT
|
---|
[301] | 4766 | $val = $rr->txtdata;
|
---|
[34] | 4767 | } elsif ($type eq 'AAAA') {
|
---|
[301] | 4768 | $val = $rr->address;
|
---|
[34] | 4769 | } elsif ($type eq 'SRV') {
|
---|
[301] | 4770 | $val = $rr->target;
|
---|
| 4771 | $distance = $rr->priority;
|
---|
| 4772 | $weight = $rr->weight;
|
---|
| 4773 | $port = $rr->port;
|
---|
[34] | 4774 | } elsif ($type eq 'KEY') {
|
---|
[35] | 4775 | # we don't actually know what to do with these...
|
---|
[301] | 4776 | $val = $rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname;
|
---|
[35] | 4777 | } else {
|
---|
[301] | 4778 | $val = $rr->rdatastr;
|
---|
[35] | 4779 | # Finding a different record type is not fatal.... just problematic.
|
---|
[37] | 4780 | # We may not be able to export it correctly.
|
---|
[35] | 4781 | $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
|
---|
[33] | 4782 | }
|
---|
| 4783 |
|
---|
[303] | 4784 | my $logentry = "[AXFR ".($rev eq 'n' ? $zone : $cidr)."] ";
|
---|
[34] | 4785 |
|
---|
[484] | 4786 | if ($args{merge}) {
|
---|
[307] | 4787 | if ($rev eq 'n') {
|
---|
| 4788 | # importing a domain; we have A and AAAA records that could be merged with matching PTR records
|
---|
| 4789 | my $etype;
|
---|
| 4790 | my ($erdns,$erid,$ettl) = $dbh->selectrow_array("SELECT rdns_id,record_id,ttl FROM records ".
|
---|
| 4791 | "WHERE host=? AND val=? AND type=12",
|
---|
| 4792 | undef, ($host, $val) );
|
---|
| 4793 | if ($erid) {
|
---|
| 4794 | if ($type eq 'A') { # PTR -> A+PTR
|
---|
| 4795 | $etype = 65280;
|
---|
| 4796 | $logentry .= "Merged A record with existing PTR record '$host A+PTR $val', TTL $ettl";
|
---|
| 4797 | }
|
---|
| 4798 | if ($type eq 'AAAA') { # PTR -> AAAA+PTR
|
---|
| 4799 | $etype = 65281;
|
---|
| 4800 | $logentry .= "Merged AAAA record with existing PTR record '$host AAAA+PTR $val', TTL $ettl";
|
---|
| 4801 | }
|
---|
| 4802 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
| 4803 | $dbh->do("UPDATE records SET domain_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
| 4804 | ($domain_id, $ettl, $etype, $erid));
|
---|
| 4805 | $nrecs++;
|
---|
[487] | 4806 | $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $erdns, entry => $logentry);
|
---|
[307] | 4807 | next; # while axfr_next
|
---|
| 4808 | }
|
---|
| 4809 | } # $rev eq 'n'
|
---|
| 4810 | else {
|
---|
| 4811 | # importing a revzone, we have PTR records that could be merged with matching A/AAAA records
|
---|
| 4812 | my ($domid,$erid,$ettl,$etype) = $dbh->selectrow_array("SELECT domain_id,record_id,ttl,type FROM records ".
|
---|
| 4813 | "WHERE host=? AND val=? AND (type=1 OR type=28)",
|
---|
| 4814 | undef, ($host, $val) );
|
---|
| 4815 | if ($erid) {
|
---|
| 4816 | if ($etype == 1) { # A -> A+PTR
|
---|
| 4817 | $etype = 65280;
|
---|
| 4818 | $logentry .= "Merged PTR record with existing matching A record '$host A+PTR $val', TTL $ettl";
|
---|
| 4819 | }
|
---|
| 4820 | if ($etype == 28) { # AAAA -> AAAA+PTR
|
---|
| 4821 | $etype = 65281;
|
---|
| 4822 | $logentry .= "Merged PTR record with existing matching AAAA record '$host AAAA+PTR $val', TTL $ettl";
|
---|
| 4823 | }
|
---|
| 4824 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
| 4825 | $dbh->do("UPDATE records SET rdns_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
| 4826 | ($rdns_id, $ettl, $etype, $erid));
|
---|
| 4827 | $nrecs++;
|
---|
[487] | 4828 | $self->_log(group_id => $group, domain_id => $domid, rdns_id => $rdns_id, entry => $logentry);
|
---|
[307] | 4829 | next; # while axfr_next
|
---|
| 4830 | }
|
---|
| 4831 | } # $rev eq 'y'
|
---|
[484] | 4832 | } # if $args{merge}
|
---|
[34] | 4833 |
|
---|
[302] | 4834 | # Insert the new record
|
---|
[301] | 4835 | $sth->execute($domain_id, $rdns_id, $host, $reverse_typemap{$type}, $val,
|
---|
| 4836 | $distance, $weight, $port, $ttl);
|
---|
| 4837 |
|
---|
[37] | 4838 | $nrecs++;
|
---|
[34] | 4839 |
|
---|
[301] | 4840 | if ($type eq 'SOA') {
|
---|
[484] | 4841 | # also !$args{rwsoa}, but if that's set, it should be impossible to get here.
|
---|
[301] | 4842 | my @tmp1 = split /:/, $host;
|
---|
| 4843 | my @tmp2 = split /:/, $val;
|
---|
| 4844 | $logentry .= "Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
| 4845 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl";
|
---|
[303] | 4846 | } elsif ($logfrag) {
|
---|
| 4847 | # special case for log entries we need to meddle with a little.
|
---|
| 4848 | $logentry .= $logfrag;
|
---|
[301] | 4849 | } else {
|
---|
| 4850 | $logentry .= "Added record '$host $type";
|
---|
| 4851 | $logentry .= " [distance $distance]" if $type eq 'MX';
|
---|
| 4852 | $logentry .= " [priority $distance] [weight $weight] [port $port]" if $type eq 'SRV';
|
---|
| 4853 | $logentry .= " $val', TTL $ttl";
|
---|
| 4854 | }
|
---|
[487] | 4855 | $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $rdns_id, entry => $logentry);
|
---|
[301] | 4856 |
|
---|
[37] | 4857 | } # while axfr_next
|
---|
| 4858 |
|
---|
[307] | 4859 | # Detect and handle delegated subzones
|
---|
| 4860 | # Placeholder for when we decide what to actually do with this, see previous comments in NS and CNAME handling.
|
---|
| 4861 | #foreach (keys %suboct) {
|
---|
| 4862 | # print "found ".($suboct{$_}{ns} ? @{$suboct{$_}{ns}} : '0')." NS records and ".
|
---|
| 4863 | # ($suboct{$_}{cname} ? @{$suboct{$_}{cname}} : '0')." CNAMEs for $_\n";
|
---|
| 4864 | #}
|
---|
| 4865 |
|
---|
[37] | 4866 | # Overwrite SOA record
|
---|
[484] | 4867 | if ($args{rwsoa}) {
|
---|
[37] | 4868 | $soaflag = 1;
|
---|
| 4869 | my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
|
---|
| 4870 | my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
| 4871 | $sthgetsoa->execute($group,$reverse_typemap{SOA});
|
---|
| 4872 | while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
|
---|
[301] | 4873 | $host =~ s/DOMAIN/$zone/g;
|
---|
| 4874 | $val =~ s/DOMAIN/$zone/g;
|
---|
| 4875 | $sthputsoa->execute($zone_id,$host,$reverse_typemap{SOA},$val,$ttl);
|
---|
[34] | 4876 | }
|
---|
[37] | 4877 | }
|
---|
[34] | 4878 |
|
---|
[37] | 4879 | # Overwrite NS records
|
---|
[484] | 4880 | if ($args{rwns}) {
|
---|
[37] | 4881 | $nsflag = 1;
|
---|
| 4882 | my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
|
---|
| 4883 | my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
| 4884 | $sthgetns->execute($group,$reverse_typemap{NS});
|
---|
| 4885 | while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
|
---|
[301] | 4886 | $host =~ s/DOMAIN/$zone/g;
|
---|
| 4887 | $val =~ s/DOMAIN/$zone/g;
|
---|
| 4888 | $sthputns->execute($zone_id,$host,$reverse_typemap{NS},$val,$ttl);
|
---|
[37] | 4889 | }
|
---|
| 4890 | }
|
---|
[34] | 4891 |
|
---|
[35] | 4892 | die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
|
---|
| 4893 | die "Bad zone: No SOA record!\n" if !$soaflag;
|
---|
| 4894 | die "Bad zone: No NS records!\n" if !$nsflag;
|
---|
| 4895 |
|
---|
[37] | 4896 | $dbh->commit;
|
---|
[35] | 4897 |
|
---|
[33] | 4898 | };
|
---|
| 4899 |
|
---|
| 4900 | if ($@) {
|
---|
| 4901 | my $msg = $@;
|
---|
| 4902 | eval { $dbh->rollback; };
|
---|
[34] | 4903 | return ('FAIL',$msg." $warnmsg");
|
---|
[33] | 4904 | } else {
|
---|
[35] | 4905 | return ('WARN', $warnmsg) if $warnmsg;
|
---|
[91] | 4906 | return ('OK',"Imported OK");
|
---|
[33] | 4907 | }
|
---|
| 4908 |
|
---|
[37] | 4909 | # it should be impossible to get here.
|
---|
[34] | 4910 | return ('WARN',"OOOK!");
|
---|
[33] | 4911 | } # end importAXFR()
|
---|
| 4912 |
|
---|
| 4913 |
|
---|
[302] | 4914 | ## DNSDB::importBIND()
|
---|
| 4915 | sub importBIND {
|
---|
| 4916 | } # end importBIND()
|
---|
| 4917 |
|
---|
| 4918 |
|
---|
| 4919 | ## DNSDB::import_tinydns()
|
---|
| 4920 | sub import_tinydns {
|
---|
| 4921 | } # end import_tinydns()
|
---|
| 4922 |
|
---|
| 4923 |
|
---|
[103] | 4924 | ## DNSDB::export()
|
---|
| 4925 | # Export the DNS database, or a part of it
|
---|
[485] | 4926 | # Takes a string indicating the export type, plus optional arguments depending on type
|
---|
[103] | 4927 | # Writes zone data to targets as appropriate for type
|
---|
| 4928 | sub export {
|
---|
[485] | 4929 | my $self = shift;
|
---|
[103] | 4930 | my $target = shift;
|
---|
| 4931 |
|
---|
| 4932 | if ($target eq 'tiny') {
|
---|
[485] | 4933 | $self->__export_tiny(@_);
|
---|
[103] | 4934 | }
|
---|
| 4935 | # elsif ($target eq 'foo') {
|
---|
[485] | 4936 | # __export_foo(@_);
|
---|
[103] | 4937 | #}
|
---|
| 4938 | # etc
|
---|
| 4939 |
|
---|
| 4940 | } # end export()
|
---|
| 4941 |
|
---|
| 4942 |
|
---|
| 4943 | ## DNSDB::__export_tiny
|
---|
| 4944 | # Internal sub to implement tinyDNS (compatible) export
|
---|
[485] | 4945 | # Takes filehandle to write export to, optional argument(s)
|
---|
[103] | 4946 | # to determine which data gets exported
|
---|
| 4947 | sub __export_tiny {
|
---|
[485] | 4948 | my $self = shift;
|
---|
| 4949 | my $dbh = $self->{dbh};
|
---|
[103] | 4950 | my $datafile = shift;
|
---|
| 4951 |
|
---|
| 4952 | ##fixme: slurp up further options to specify particular zone(s) to export
|
---|
| 4953 |
|
---|
| 4954 | ##fixme: fail if $datafile isn't an open, writable file
|
---|
| 4955 |
|
---|
| 4956 | # easy case - export all evarything
|
---|
| 4957 | # not-so-easy case - export item(s) specified
|
---|
| 4958 | # todo: figure out what kind of list we use to export items
|
---|
| 4959 |
|
---|
[329] | 4960 | # raw packet in unknown format: first byte indicates length
|
---|
| 4961 | # of remaining data, allows up to 255 raw bytes
|
---|
| 4962 |
|
---|
[372] | 4963 | # Locations/views - worth including in the caching setup?
|
---|
| 4964 | my $lochash = $dbh->selectall_hashref("SELECT location,iplist FROM locations", 'location');
|
---|
| 4965 | foreach my $location (keys %$lochash) {
|
---|
[375] | 4966 | foreach my $ipprefix (split /[,\s]+/, $lochash->{$location}{iplist}) {
|
---|
| 4967 | $ipprefix =~ s/\s+//g;
|
---|
[449] | 4968 | $ipprefix = new NetAddr::IP $ipprefix;
|
---|
| 4969 | ##fixme: how to handle IPv6?
|
---|
| 4970 | next if $ipprefix->{isv6};
|
---|
| 4971 | # have to account for /nn CIDR entries. tinydns only speaks octet-sliced prefix.
|
---|
| 4972 | if ($ipprefix->masklen <= 8) {
|
---|
| 4973 | foreach ($ipprefix->split(8)) {
|
---|
| 4974 | my $tmp = $_->addr;
|
---|
| 4975 | $tmp =~ s/\.\d+\.\d+\.\d+$//;
|
---|
| 4976 | print $datafile "%$location:$tmp\n";
|
---|
| 4977 | }
|
---|
| 4978 | } elsif ($ipprefix->masklen <= 16) {
|
---|
| 4979 | foreach ($ipprefix->split(16)) {
|
---|
| 4980 | my $tmp = $_->addr;
|
---|
| 4981 | $tmp =~ s/\.\d+\.\d+$//;
|
---|
| 4982 | print $datafile "%$location:$tmp\n";
|
---|
| 4983 | }
|
---|
| 4984 | } elsif ($ipprefix->masklen <= 24) {
|
---|
| 4985 | foreach ($ipprefix->split(24)) {
|
---|
| 4986 | my $tmp = $_->addr;
|
---|
| 4987 | $tmp =~ s/\.\d+$//;
|
---|
| 4988 | print $datafile "%$location:$tmp\n";
|
---|
| 4989 | }
|
---|
| 4990 | } else {
|
---|
| 4991 | foreach ($ipprefix->split(32)) {
|
---|
| 4992 | print $datafile "%$location:".$_->addr."\n";
|
---|
| 4993 | }
|
---|
| 4994 | }
|
---|
[372] | 4995 | }
|
---|
| 4996 | print $datafile "%$location\n" if !$lochash->{$location}{iplist};
|
---|
| 4997 | }
|
---|
| 4998 |
|
---|
[329] | 4999 | # tracking hash so we don't double-export A+PTR or AAAA+PTR records.
|
---|
| 5000 | my %recflags;
|
---|
| 5001 |
|
---|
[523] | 5002 | # For reasons unknown, we can't sanely UNION these statements. Feh.
|
---|
| 5003 | # Supposedly it should work though (note last 3 lines):
|
---|
| 5004 | ## PG manual
|
---|
| 5005 | #UNION Clause
|
---|
| 5006 | #
|
---|
| 5007 | #The UNION clause has this general form:
|
---|
| 5008 | #
|
---|
| 5009 | # select_statement UNION [ ALL ] select_statement
|
---|
| 5010 | #
|
---|
| 5011 | #select_statement is any SELECT statement without an ORDER BY, LIMIT, FOR UPDATE, or FOR SHARE clause. (ORDER BY
|
---|
| 5012 | #and LIMIT can be attached to a subexpression if it is enclosed in parentheses. Without parentheses, these
|
---|
| 5013 | #clauses will be taken to apply to the result of the UNION, not to its right-hand input expression.)
|
---|
| 5014 | my $soasth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
| 5015 | "FROM records WHERE rdns_id=? AND type=6");
|
---|
[543] | 5016 | my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location,extract(epoch from stamp),expires,stampactive ".
|
---|
[523] | 5017 | "FROM records WHERE rdns_id=? AND not type=6 ".
|
---|
| 5018 | "ORDER BY masklen(CAST(val AS inet)) DESC, CAST(val AS inet)");
|
---|
| 5019 | my $revsth = $dbh->prepare("SELECT rdns_id,revnet,status,changed FROM revzones WHERE status=1 ".
|
---|
| 5020 | "ORDER BY masklen(revnet) DESC");
|
---|
| 5021 | my $zonesth = $dbh->prepare("UPDATE revzones SET changed='n' WHERE rdns_id=?");
|
---|
| 5022 | $revsth->execute();
|
---|
| 5023 | while (my ($revid,$revzone,$revstat,$changed) = $revsth->fetchrow_array) {
|
---|
[368] | 5024 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
| 5025 | # O_NOFOLLOW
|
---|
| 5026 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
| 5027 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
| 5028 | # still be followed.
|
---|
| 5029 | # but that doesn't help other platforms. :/
|
---|
[523] | 5030 | my $tmpzone = NetAddr::IP->new($revzone);
|
---|
| 5031 | ##fixme: locations/views? subnet mask? need to avoid possible collisions with zone/superzone
|
---|
| 5032 | ## (eg /20 vs /24, starting on .0.0)
|
---|
| 5033 | my $cz = $tmpzone->network->addr."-".$tmpzone->masklen;
|
---|
| 5034 | my $cachefile = "$self->{exportcache}/$cz";
|
---|
| 5035 | my $tmpcache = "$self->{exportcache}/tmp.$cz.$$";
|
---|
[521] | 5036 | eval {
|
---|
[108] | 5037 |
|
---|
[521] | 5038 | # only update the cache file if the zone has changed, or if the cache file has nothing in it.
|
---|
[524] | 5039 | if ($self->{force_refresh} || $changed || !-e $cachefile || -z $cachefile) {
|
---|
[521] | 5040 | open ZONECACHE, ">$tmpcache" or die "Error creating temporary file $tmpcache: $!\n";
|
---|
| 5041 |
|
---|
[523] | 5042 | # need to fetch this separately since the rest of the records all (should) have real IPs in val
|
---|
| 5043 | $soasth->execute($revid);
|
---|
| 5044 | my (@zsoa) = $soasth->fetchrow_array();
|
---|
| 5045 | _printrec_tiny(*ZONECACHE,'y',\%recflags,$revzone,
|
---|
| 5046 | $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],'');
|
---|
| 5047 |
|
---|
| 5048 | $recsth->execute($revid);
|
---|
[543] | 5049 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc,$stamp,$expires,$stampactive) = $recsth->fetchrow_array) {
|
---|
[523] | 5050 | next if $recflags{$recid};
|
---|
[521] | 5051 |
|
---|
[543] | 5052 | # not sure this is necessary for revzones.
|
---|
| 5053 | # # Spaces are evil.
|
---|
| 5054 | # $val =~ s/^\s+//;
|
---|
| 5055 | # $val =~ s/\s+$//;
|
---|
| 5056 | # if ($typemap{$type} ne 'TXT') {
|
---|
| 5057 | # # Leading or trailng spaces could be legit in TXT records.
|
---|
| 5058 | # $host =~ s/^\s+//;
|
---|
| 5059 | # $host =~ s/\s+$//;
|
---|
| 5060 | # }
|
---|
[372] | 5061 |
|
---|
[523] | 5062 | _printrec_tiny(*ZONECACHE, 'y', \%recflags, $revzone,
|
---|
[543] | 5063 | $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp, $expires, $stampactive)
|
---|
[368] | 5064 | if *ZONECACHE;
|
---|
[450] | 5065 |
|
---|
[523] | 5066 | $recflags{$recid} = 1;
|
---|
[368] | 5067 |
|
---|
[521] | 5068 | } # while ($recsth)
|
---|
| 5069 |
|
---|
| 5070 | close ZONECACHE; # force the file to be written
|
---|
| 5071 |
|
---|
| 5072 | # catch obvious write errors that leave an empty temp file
|
---|
| 5073 | if (-s $tmpcache) {
|
---|
| 5074 | rename $tmpcache, $cachefile
|
---|
| 5075 | or die "Error overwriting cache file $cachefile with temporary file: $!\n";
|
---|
| 5076 | }
|
---|
| 5077 |
|
---|
| 5078 | } # if $changed or cache filesize is 0
|
---|
| 5079 |
|
---|
| 5080 | };
|
---|
| 5081 | if ($@) {
|
---|
[523] | 5082 | print "error writing new data for $revzone: $@\n";
|
---|
[521] | 5083 | # error! something borked, and we should be able to fall back on the old cache file
|
---|
| 5084 | # report the error, somehow.
|
---|
| 5085 | } else {
|
---|
[523] | 5086 | # mark zone as unmodified. Only do this if no errors, that way
|
---|
[521] | 5087 | # export failures should recover a little more automatically.
|
---|
[523] | 5088 | $zonesth->execute($revid);
|
---|
[368] | 5089 | }
|
---|
[521] | 5090 | # Always stream the cache (even if stale or obsolete due to errors creating the new cache)
|
---|
| 5091 | open CACHE, "<$cachefile";
|
---|
| 5092 | print $datafile $_ while <CACHE>;
|
---|
| 5093 | close CACHE;
|
---|
| 5094 |
|
---|
[523] | 5095 | } # while ($revsth)
|
---|
[329] | 5096 |
|
---|
[523] | 5097 | my $domsth = $dbh->prepare("SELECT domain_id,domain,status,changed FROM domains WHERE status=1");
|
---|
[543] | 5098 | $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location,extract(epoch from stamp),expires,stampactive ".
|
---|
[523] | 5099 | "FROM records WHERE domain_id=?"); # Just exclude all types relating to rDNS
|
---|
| 5100 | # "FROM records WHERE domain_id=? AND type < 65280"); # Just exclude all types relating to rDNS
|
---|
| 5101 | $zonesth = $dbh->prepare("UPDATE domains SET changed='n' WHERE domain_id=?");
|
---|
| 5102 | $domsth->execute();
|
---|
| 5103 | while (my ($domid,$dom,$domstat,$changed) = $domsth->fetchrow_array) {
|
---|
[368] | 5104 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
| 5105 | # O_NOFOLLOW
|
---|
| 5106 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
| 5107 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
| 5108 | # still be followed.
|
---|
| 5109 | # but that doesn't help other platforms. :/
|
---|
[523] | 5110 | my $cachefile = "$self->{exportcache}/$dom";
|
---|
| 5111 | my $tmpcache = "$self->{exportcache}/tmp.$dom.$$";
|
---|
[521] | 5112 | eval {
|
---|
[344] | 5113 |
|
---|
[521] | 5114 | # only update the cache file if the zone has changed, or if the cache file has nothing in it.
|
---|
[524] | 5115 | if ($self->{force_refresh} || $changed || !-e $cachefile || -z $cachefile) {
|
---|
[521] | 5116 | open ZONECACHE, ">$tmpcache" or die "Error creating temporary file $tmpcache: $!\n";
|
---|
[329] | 5117 |
|
---|
[523] | 5118 | $recsth->execute($domid);
|
---|
[543] | 5119 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc,$stamp,$expires,$stampactive) = $recsth->fetchrow_array) {
|
---|
[523] | 5120 | next if $recflags{$recid};
|
---|
[521] | 5121 |
|
---|
[523] | 5122 | # Spaces are evil.
|
---|
| 5123 | $host =~ s/^\s+//;
|
---|
| 5124 | $host =~ s/\s+$//;
|
---|
| 5125 | if ($typemap{$type} ne 'TXT') {
|
---|
| 5126 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 5127 | $val =~ s/^\s+//;
|
---|
| 5128 | $val =~ s/\s+$//;
|
---|
| 5129 | }
|
---|
| 5130 |
|
---|
| 5131 | _printrec_tiny(*ZONECACHE, 'n', \%recflags,
|
---|
[543] | 5132 | $dom, $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp, $expires, $stampactive)
|
---|
[368] | 5133 | if *ZONECACHE;
|
---|
[329] | 5134 |
|
---|
[523] | 5135 | $recflags{$recid} = 1;
|
---|
[450] | 5136 |
|
---|
[521] | 5137 | } # while ($recsth)
|
---|
| 5138 |
|
---|
| 5139 | close ZONECACHE; # force the file to be written
|
---|
| 5140 |
|
---|
| 5141 | # catch obvious write errors that leave an empty temp file
|
---|
| 5142 | if (-s $tmpcache) {
|
---|
| 5143 | rename $tmpcache, $cachefile
|
---|
| 5144 | or die "Error overwriting cache file $cachefile with temporary file: $!\n";
|
---|
| 5145 | }
|
---|
| 5146 |
|
---|
| 5147 | } # if $changed or cache filesize is 0
|
---|
| 5148 |
|
---|
| 5149 | };
|
---|
| 5150 | if ($@) {
|
---|
[523] | 5151 | print "error writing new data for $dom: $@\n";
|
---|
[521] | 5152 | # error! something borked, and we should be able to fall back on the old cache file
|
---|
| 5153 | # report the error, somehow.
|
---|
| 5154 | } else {
|
---|
[523] | 5155 | # mark domain as unmodified. Only do this if no errors, that way
|
---|
[521] | 5156 | # export failures should recover a little more automatically.
|
---|
[523] | 5157 | $zonesth->execute($domid);
|
---|
[368] | 5158 | }
|
---|
[521] | 5159 | # Always stream the cache (even if stale or obsolete due to errors creating the new cache)
|
---|
| 5160 | open CACHE, "<$cachefile";
|
---|
| 5161 | print $datafile $_ while <CACHE>;
|
---|
| 5162 | close CACHE;
|
---|
| 5163 |
|
---|
[329] | 5164 | } # while ($domsth)
|
---|
| 5165 |
|
---|
| 5166 | } # end __export_tiny()
|
---|
| 5167 |
|
---|
| 5168 |
|
---|
| 5169 | # Utility sub for __export_tiny above
|
---|
| 5170 | sub _printrec_tiny {
|
---|
[543] | 5171 | my ($datafile,$revrec,$recflags,$zone,$host,$type,$val,$dist,$weight,$port,$ttl,$loc,$stamp,$expires,$stampactive) = @_;
|
---|
[329] | 5172 |
|
---|
[543] | 5173 | $loc = '' if !$loc; # de-nullify - just in case
|
---|
| 5174 | ##fixme: handle case of record-with-location-that-doesn't-exist better.
|
---|
| 5175 | # note this currently fails safe (tested) - records with a location that
|
---|
| 5176 | # doesn't exist will not be sent to any client
|
---|
| 5177 | # $loc = '' if !$lochash->{$loc};
|
---|
| 5178 |
|
---|
| 5179 |
|
---|
| 5180 | ## Records that are valid only before or after a set time
|
---|
| 5181 |
|
---|
| 5182 | # record due to expire sometime is the complex case. we don't want to just
|
---|
| 5183 | # rely on tinydns' auto-adjusting TTLs, because the default TTL in that case
|
---|
| 5184 | # is one day instead of the SOA minttl as BIND might do.
|
---|
| 5185 |
|
---|
| 5186 | # consider the case where a record is set to expire a week ahead, but the next
|
---|
| 5187 | # day later you want to change it NOW (or as NOWish as you get with your DNS
|
---|
| 5188 | # management practice). but now you're stuck, because someone, somewhere,
|
---|
| 5189 | # has just done a lookup before your latest change was published, and they'll
|
---|
| 5190 | # be caching that old, broken record for 1 day instead of your zone default
|
---|
| 5191 | # TTL.
|
---|
| 5192 |
|
---|
| 5193 | # $stamp-$ttl is the *latest* we can publish the record with the defined TTL
|
---|
| 5194 | # to still have the expiry happen as scheduled, but we need to find some
|
---|
| 5195 | # *earlier* point. We can maybe guess, and 2x TTL is probably reasonable,
|
---|
| 5196 | # but we need info on the export frequency.
|
---|
| 5197 |
|
---|
| 5198 | # export the normal, non-expiring record up until $stamp-<guesstimate>, then
|
---|
| 5199 | # switch to exporting a record with the TAI64 stamp and a 0 TTL so tinydns
|
---|
| 5200 | # takes over TTL management.
|
---|
| 5201 |
|
---|
| 5202 | if ($stampactive) {
|
---|
| 5203 | if ($expires) {
|
---|
| 5204 | # record expires at $stamp; decide if we need to keep the TTL and ignore
|
---|
| 5205 | # the stamp for a time or if we need to change the TTL to 0 and convert
|
---|
| 5206 | # $stamp to TAI64 so tinydns can use $stamp to autoadjust the TTL on the fly.
|
---|
| 5207 | # extra hack, optimally needs more knowledge of data export frequency
|
---|
| 5208 | # smack the idiot customer who insists on 0 TTLs; they can suck up and
|
---|
| 5209 | # deal with a 10-minute TTL. especially on scheduled changes. note this
|
---|
| 5210 | # should be (export freq * 2), but we don't know the actual export frequency.
|
---|
| 5211 | $ttl = 300 if $ttl == 0; #hack phtui
|
---|
| 5212 | my $ahead = (86400 < $ttl*2 ? 86400 : $ttl*2);
|
---|
| 5213 | if ((time() + $ahead) < $stamp) {
|
---|
| 5214 | # more than 2x TTL OR more than one day (whichever is less) from expiry time; publish normal record
|
---|
| 5215 | $stamp = '';
|
---|
| 5216 | } else {
|
---|
| 5217 | # less than 2x TTL from expiry time, let tinydns take over TTL management and publish the TAI64 stamp.
|
---|
| 5218 | $ttl = 0;
|
---|
| 5219 | $stamp = unixtai64($stamp);
|
---|
| 5220 | $stamp =~ s/\@//;
|
---|
| 5221 | }
|
---|
| 5222 | } else {
|
---|
| 5223 | # record is "active after"; convert epoch from database to TAI64, publish, and collect $200.
|
---|
| 5224 | $stamp = unixtai64($stamp);
|
---|
| 5225 | $stamp =~ s/\@//;
|
---|
| 5226 | }
|
---|
| 5227 | } else {
|
---|
| 5228 | # flag for active timestamp is false; don't actually put a timestamp in the output
|
---|
| 5229 | $stamp = '';
|
---|
| 5230 | }
|
---|
| 5231 |
|
---|
| 5232 | # support tinydns' auto-TTL
|
---|
| 5233 | $ttl = '' if $ttl == -1;
|
---|
| 5234 | # these are WAY FREAKING HIGH - higher even than most TLD registry TTLs!
|
---|
| 5235 | # NS 259200 => 3d
|
---|
| 5236 | # all others 86400 => 1d
|
---|
| 5237 |
|
---|
[531] | 5238 | if ($revrec eq 'y') {
|
---|
| 5239 | $val = $zone if $val eq '@';
|
---|
| 5240 | } else {
|
---|
| 5241 | $host = $zone if $host eq '@';
|
---|
| 5242 | }
|
---|
| 5243 |
|
---|
[329] | 5244 | ## Convert a bare number into an octal-coded pair of octets.
|
---|
| 5245 | # Take optional arg to indicate a decimal or hex input. Defaults to hex.
|
---|
| 5246 | sub octalize {
|
---|
| 5247 | my $tmp = shift;
|
---|
| 5248 | my $srctype = shift || 'h'; # default assumes hex string
|
---|
| 5249 | $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
|
---|
| 5250 | $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
|
---|
| 5251 | my @o = ($tmp =~ /^(..)(..)$/); # split into octets
|
---|
| 5252 | return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);;
|
---|
| 5253 | }
|
---|
| 5254 |
|
---|
[339] | 5255 | ## WARNING: This works to export even the whole Internet's worth of IP space...
|
---|
| 5256 | ## if you have the disk/RAM to handle the dataset, and you call this sub based on /16-sized chunks
|
---|
| 5257 | ## A /16 took ~3 seconds with a handful of separate records; adding a /8 pushed export time out to ~13m:40s
|
---|
| 5258 | ## 0/0 is estimated to take ~54 hours and ~256G of disk
|
---|
| 5259 | ## RAM usage depends on how many non-template entries you have in the set.
|
---|
| 5260 | ## This should probably be done on record addition rather than export; large blocks may need to be done in a
|
---|
| 5261 | ## forked process
|
---|
| 5262 | sub __publish_subnet {
|
---|
| 5263 | my $sub = shift;
|
---|
| 5264 | my $recflags = shift;
|
---|
| 5265 | my $hpat = shift;
|
---|
| 5266 | my $fh = shift;
|
---|
| 5267 | my $ttl = shift;
|
---|
| 5268 | my $stamp = shift;
|
---|
| 5269 | my $loc = shift;
|
---|
| 5270 | my $ptronly = shift || 0;
|
---|
| 5271 |
|
---|
| 5272 | my $iplist = $sub->splitref(32);
|
---|
| 5273 | foreach (@$iplist) {
|
---|
| 5274 | my $ip = $_->addr;
|
---|
| 5275 | # make as if we split the non-octet-aligned block into octet-aligned blocks as with SOA
|
---|
| 5276 | next if $ip =~ /\.(0|255)$/;
|
---|
| 5277 | next if $$recflags{$ip};
|
---|
| 5278 | $$recflags{$ip}++;
|
---|
[463] | 5279 | next if $hpat eq '%blank%'; # Allows blanking a subnet so no records are published.
|
---|
[339] | 5280 | my $rec = $hpat; # start fresh with the template for each IP
|
---|
| 5281 | _template4_expand(\$rec, $ip);
|
---|
| 5282 | print $fh ($ptronly ? "^"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$rec" : "=$rec:$ip").
|
---|
| 5283 | ":$ttl:$stamp:$loc\n";
|
---|
| 5284 | }
|
---|
| 5285 | }
|
---|
| 5286 |
|
---|
[103] | 5287 | ##fixme? append . to all host/val hostnames
|
---|
| 5288 | if ($typemap{$type} eq 'SOA') {
|
---|
| 5289 |
|
---|
| 5290 | # host contains pri-ns:responsible
|
---|
| 5291 | # val is abused to contain refresh:retry:expire:minttl
|
---|
| 5292 | ##fixme: "manual" serial vs tinydns-autoserial
|
---|
[202] | 5293 | # let's be explicit about abusing $host and $val
|
---|
| 5294 | my ($email, $primary) = (split /:/, $host)[0,1];
|
---|
| 5295 | my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
|
---|
[330] | 5296 | if ($revrec eq 'y') {
|
---|
[337] | 5297 | ##fixme: have to publish SOA records for each v4 /24 in sub-/16, and each /16 in sub-/8
|
---|
| 5298 | # what about v6?
|
---|
| 5299 | # -> only need SOA for local chunks offset from reverse delegation boundaries, so v6 is fine
|
---|
[330] | 5300 | $zone = NetAddr::IP->new($zone);
|
---|
[337] | 5301 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
| 5302 | if (!$zone->{isv6} && ($zone->masklen < 24) && ($zone->masklen % 8 != 0)) {
|
---|
| 5303 | foreach my $szone ($zone->split($zone->masklen + (8 - $zone->masklen % 8))) {
|
---|
| 5304 | $szone = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
| 5305 | print $datafile "Z$szone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
|
---|
| 5306 | }
|
---|
| 5307 | return; # skips "default" bits just below
|
---|
| 5308 | }
|
---|
[330] | 5309 | $zone = _ZONE($zone, 'ZONE', 'r', '.').($zone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 5310 | }
|
---|
[329] | 5311 | print $datafile "Z$zone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
|
---|
[103] | 5312 |
|
---|
| 5313 | } elsif ($typemap{$type} eq 'A') {
|
---|
| 5314 |
|
---|
[108] | 5315 | print $datafile "+$host:$val:$ttl:$stamp:$loc\n";
|
---|
[103] | 5316 |
|
---|
| 5317 | } elsif ($typemap{$type} eq 'NS') {
|
---|
| 5318 |
|
---|
[330] | 5319 | if ($revrec eq 'y') {
|
---|
| 5320 | $val = NetAddr::IP->new($val);
|
---|
[345] | 5321 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
| 5322 | if (!$val->{isv6} && ($val->masklen < 24) && ($val->masklen % 8 != 0)) {
|
---|
[346] | 5323 | foreach my $szone ($val->split($val->masklen + (8 - $val->masklen % 8))) {
|
---|
[345] | 5324 | my $szone2 = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
[346] | 5325 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
[345] | 5326 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n";
|
---|
[346] | 5327 | $$recflags{$szone2} = $val->masklen;
|
---|
[345] | 5328 | }
|
---|
[346] | 5329 | } elsif ($val->{isv6} && ($val->masklen < 64) && ($val->masklen % 4 !=0)) {
|
---|
| 5330 | foreach my $szone ($val->split($val->masklen + (4 - $val->masklen % 4))) {
|
---|
| 5331 | my $szone2 = _ZONE($szone, 'ZONE.ip6.arpa', 'r', '.');
|
---|
| 5332 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
| 5333 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n";
|
---|
| 5334 | $$recflags{$szone2} = $val->masklen;
|
---|
| 5335 | }
|
---|
| 5336 | } else {
|
---|
| 5337 | my $val2 = _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 5338 | print $datafile "\&$val2"."::$host:$ttl:$stamp:$loc\n";
|
---|
| 5339 | $$recflags{$val2} = $val->masklen;
|
---|
[345] | 5340 | }
|
---|
[330] | 5341 | } else {
|
---|
| 5342 | print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n";
|
---|
| 5343 | }
|
---|
[103] | 5344 |
|
---|
| 5345 | } elsif ($typemap{$type} eq 'AAAA') {
|
---|
| 5346 |
|
---|
| 5347 | print $datafile ":$host:28:";
|
---|
| 5348 | my $altgrp = 0;
|
---|
| 5349 | my @altconv;
|
---|
[108] | 5350 | # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
|
---|
[103] | 5351 | foreach (split /:/, $val) {
|
---|
| 5352 | if (/^$/) {
|
---|
| 5353 | # flag blank entry; this is a series of 0's of (currently) unknown length
|
---|
| 5354 | $altconv[$altgrp++] = 's';
|
---|
| 5355 | } else {
|
---|
| 5356 | # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
|
---|
| 5357 | $altconv[$altgrp++] = octalize($_)
|
---|
| 5358 | }
|
---|
| 5359 | }
|
---|
| 5360 | foreach my $octet (@altconv) {
|
---|
| 5361 | # if not 's', output
|
---|
| 5362 | print $datafile $octet unless $octet =~ /^s$/;
|
---|
| 5363 | # if 's', output (9-array length)x literal '\000\000'
|
---|
| 5364 | print $datafile '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
|
---|
| 5365 | }
|
---|
[108] | 5366 | print $datafile ":$ttl:$stamp:$loc\n";
|
---|
[103] | 5367 |
|
---|
| 5368 | } elsif ($typemap{$type} eq 'MX') {
|
---|
| 5369 |
|
---|
[108] | 5370 | print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n";
|
---|
[103] | 5371 |
|
---|
| 5372 | } elsif ($typemap{$type} eq 'TXT') {
|
---|
| 5373 |
|
---|
| 5374 | ##fixme: split v-e-r-y long TXT strings? will need to do so for BIND export, at least
|
---|
[350] | 5375 | if ($revrec eq 'n') {
|
---|
| 5376 | $val =~ s/:/\\072/g; # may need to replace other symbols
|
---|
| 5377 | print $datafile "'$host:$val:$ttl:$stamp:$loc\n";
|
---|
| 5378 | } else {
|
---|
| 5379 | $host =~ s/:/\\072/g; # may need to replace other symbols
|
---|
| 5380 | my $val2 = NetAddr::IP->new($val);
|
---|
| 5381 | print $datafile "'"._ZONE($val2, 'ZONE', 'r', '.').($val2->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
| 5382 | ":$host:$ttl:$stamp:$loc\n";
|
---|
| 5383 | }
|
---|
[103] | 5384 |
|
---|
| 5385 | # by-hand TXT
|
---|
| 5386 | #:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
|
---|
| 5387 | #@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
|
---|
| 5388 | #'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
|
---|
| 5389 |
|
---|
| 5390 | #txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
|
---|
| 5391 | #: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
|
---|
| 5392 |
|
---|
| 5393 | # very long TXT record as brought in by axfr-get
|
---|
| 5394 | # note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
|
---|
| 5395 | # also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
|
---|
| 5396 | #:longtxt.deepnet.cx:16:
|
---|
| 5397 | #\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
|
---|
| 5398 | #\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.
|
---|
| 5399 | #\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.
|
---|
| 5400 | #:3600
|
---|
| 5401 |
|
---|
| 5402 | } elsif ($typemap{$type} eq 'CNAME') {
|
---|
| 5403 |
|
---|
[372] | 5404 | if ($revrec eq 'n') {
|
---|
| 5405 | print $datafile "C$host:$val:$ttl:$stamp:$loc\n";
|
---|
| 5406 | } else {
|
---|
| 5407 | my $val2 = NetAddr::IP->new($val);
|
---|
| 5408 | print $datafile "C"._ZONE($val2, 'ZONE', 'r', '.').($val2->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
| 5409 | ":$host:$ttl:$stamp:$loc\n";
|
---|
| 5410 | }
|
---|
[103] | 5411 |
|
---|
| 5412 | } elsif ($typemap{$type} eq 'SRV') {
|
---|
| 5413 |
|
---|
| 5414 | # data is two-byte values for priority, weight, port, in that order,
|
---|
| 5415 | # followed by length/string data
|
---|
| 5416 |
|
---|
| 5417 | print $datafile ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
|
---|
| 5418 |
|
---|
| 5419 | $val .= '.' if $val !~ /\.$/;
|
---|
| 5420 | foreach (split /\./, $val) {
|
---|
| 5421 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
| 5422 | }
|
---|
[108] | 5423 | print $datafile "\\000:$ttl:$stamp:$loc\n";
|
---|
[103] | 5424 |
|
---|
| 5425 | } elsif ($typemap{$type} eq 'RP') {
|
---|
| 5426 |
|
---|
| 5427 | # RP consists of two mostly free-form strings.
|
---|
| 5428 | # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
|
---|
| 5429 | # The second is the "hostname" of a TXT record with more info.
|
---|
| 5430 | print $datafile ":$host:17:";
|
---|
| 5431 | my ($who,$what) = split /\s/, $val;
|
---|
| 5432 | foreach (split /\./, $who) {
|
---|
| 5433 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
| 5434 | }
|
---|
| 5435 | print $datafile '\000';
|
---|
| 5436 | foreach (split /\./, $what) {
|
---|
| 5437 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
| 5438 | }
|
---|
[108] | 5439 | print $datafile "\\000:$ttl:$stamp:$loc\n";
|
---|
[103] | 5440 |
|
---|
| 5441 | } elsif ($typemap{$type} eq 'PTR') {
|
---|
| 5442 |
|
---|
[332] | 5443 | $zone = NetAddr::IP->new($zone);
|
---|
[337] | 5444 | $$recflags{$val}++;
|
---|
[332] | 5445 | if (!$zone->{isv6} && $zone->masklen > 24) {
|
---|
| 5446 | ($val) = ($val =~ /\.(\d+)$/);
|
---|
| 5447 | print $datafile "^$val."._ZONE($zone, 'ZONE', 'r', '.').'.in-addr.arpa'.
|
---|
| 5448 | ":$host:ttl:$stamp:$loc\n";
|
---|
| 5449 | } else {
|
---|
| 5450 | $val = NetAddr::IP->new($val);
|
---|
| 5451 | print $datafile "^".
|
---|
| 5452 | _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
[334] | 5453 | ":$host:$ttl:$stamp:$loc\n";
|
---|
[332] | 5454 | }
|
---|
[103] | 5455 |
|
---|
[333] | 5456 | } elsif ($type == 65280) { # A+PTR
|
---|
[334] | 5457 |
|
---|
[337] | 5458 | $$recflags{$val}++;
|
---|
[334] | 5459 | print $datafile "=$host:$val:$ttl:$stamp:$loc\n";
|
---|
| 5460 |
|
---|
[333] | 5461 | } elsif ($type == 65281) { # AAAA+PTR
|
---|
| 5462 |
|
---|
[526] | 5463 | $$recflags{$val}++;
|
---|
[333] | 5464 | # treat these as two separate records. since tinydns doesn't have
|
---|
| 5465 | # a native combined type, we have to create them separately anyway.
|
---|
[526] | 5466 | # print both; a dangling record is harmless, and impossible via web
|
---|
| 5467 | # UI anyway
|
---|
| 5468 | _printrec_tiny($datafile,$revrec,$recflags,$zone,$host,28,$val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
| 5469 | _printrec_tiny($datafile,$revrec,$recflags,$zone,$host,12,$val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
[335] | 5470 | ##fixme: add a config flag to indicate use of the patch from http://www.fefe.de/dns/
|
---|
| 5471 | # type 6 is for AAAA+PTR, type 3 is for AAAA
|
---|
[333] | 5472 |
|
---|
| 5473 | } elsif ($type == 65282) { # PTR template
|
---|
[335] | 5474 |
|
---|
| 5475 | # only useful for v4 with standard DNS software, since this expands all
|
---|
| 5476 | # IPs in $zone (or possibly $val?) with autogenerated records
|
---|
[337] | 5477 | $val = NetAddr::IP->new($val);
|
---|
| 5478 | return if $val->{isv6};
|
---|
[336] | 5479 |
|
---|
[339] | 5480 | if ($val->masklen <= 16) {
|
---|
| 5481 | foreach my $sub ($val->split(16)) {
|
---|
| 5482 | __publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, 1);
|
---|
| 5483 | }
|
---|
| 5484 | } else {
|
---|
| 5485 | __publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, 1);
|
---|
[337] | 5486 | }
|
---|
[335] | 5487 |
|
---|
[333] | 5488 | } elsif ($type == 65283) { # A+PTR template
|
---|
[335] | 5489 |
|
---|
[337] | 5490 | $val = NetAddr::IP->new($val);
|
---|
| 5491 | # Just In Case. An A+PTR should be impossible to add to a v6 revzone via API.
|
---|
| 5492 | return if $val->{isv6};
|
---|
[339] | 5493 |
|
---|
| 5494 | if ($val->masklen <= 16) {
|
---|
| 5495 | foreach my $sub ($val->split(16)) {
|
---|
| 5496 | __publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, 0);
|
---|
| 5497 | }
|
---|
| 5498 | } else {
|
---|
| 5499 | __publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, 0);
|
---|
[337] | 5500 | }
|
---|
[335] | 5501 |
|
---|
[333] | 5502 | } elsif ($type == 65284) { # AAAA+PTR template
|
---|
[335] | 5503 | # Stub for completeness. Could be exported to DNS software that supports
|
---|
| 5504 | # some degree of internal automagic in generic-record-creation
|
---|
| 5505 | # (eg http://search.cpan.org/dist/AllKnowingDNS/ )
|
---|
[333] | 5506 |
|
---|
[345] | 5507 | } elsif ($type == 65285) { # Delegation
|
---|
| 5508 | # This is intended for reverse zones, but may prove useful in forward zones.
|
---|
| 5509 |
|
---|
[346] | 5510 | # All delegations need to create one or more NS records. The NS record handler knows what to do.
|
---|
| 5511 | _printrec_tiny($datafile,$revrec,$recflags,$zone,$host,$reverse_typemap{'NS'},
|
---|
| 5512 | $val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
| 5513 | if ($revrec eq 'y') {
|
---|
| 5514 | # In the case of a sub-/24 v4 reverse delegation, we need to generate CNAMEs
|
---|
| 5515 | # to redirect all of the individual IP lookups as well.
|
---|
| 5516 | # Not sure how this would actually resolve if a /24 or larger was delegated
|
---|
| 5517 | # one way, and a sub-/24 in that >=/24 was delegated elsewhere...
|
---|
| 5518 | my $dblock = NetAddr::IP->new($val);
|
---|
| 5519 | if (!$dblock->{isv6} && $dblock->masklen > 24) {
|
---|
| 5520 | my @subs = $dblock->split;
|
---|
| 5521 | foreach (@subs) {
|
---|
| 5522 | next if $$recflags{"$_"};
|
---|
| 5523 | my ($oct) = ($_->addr =~ /(\d+)$/);
|
---|
| 5524 | print $datafile "C"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$oct.".
|
---|
| 5525 | _ZONE($dblock, 'ZONE.in-addr.arpa', 'r', '.').":$ttl:$stamp:$loc\n";
|
---|
| 5526 | $$recflags{"$_"}++;
|
---|
| 5527 | }
|
---|
| 5528 | }
|
---|
| 5529 | }
|
---|
[345] | 5530 |
|
---|
[364] | 5531 | ##
|
---|
| 5532 | ## Uncommon types. These will need better UI support Any Day Sometime Maybe(TM).
|
---|
| 5533 | ##
|
---|
| 5534 |
|
---|
| 5535 | } elsif ($type == 44) { # SSHFP
|
---|
| 5536 | my ($algo,$fpt,$fp) = split /\s+/, $val;
|
---|
| 5537 |
|
---|
| 5538 | my $rec = sprintf ":$host:44:\\%0.3o\\%0.3o", $algo, $fpt;
|
---|
| 5539 | while (my ($byte) = ($fp =~ /^(..)/) ) {
|
---|
| 5540 | $rec .= sprintf "\\%0.3o", hex($byte);
|
---|
| 5541 | $fp =~ s/^..//;
|
---|
| 5542 | }
|
---|
| 5543 | print $datafile "$rec:$ttl:$stamp:$loc\n";
|
---|
| 5544 |
|
---|
[345] | 5545 | } else {
|
---|
[108] | 5546 | # raw record. we don't know what's in here, so we ASS-U-ME the user has
|
---|
| 5547 | # put it in correctly, since either the user is messing directly with the
|
---|
| 5548 | # database, or the record was imported via AXFR
|
---|
| 5549 | # <split by char>
|
---|
| 5550 | # convert anything not a-zA-Z0-9.- to octal coding
|
---|
| 5551 |
|
---|
| 5552 | ##fixme: add flag to export "unknown" record types - note we'll probably end up
|
---|
| 5553 | # mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
|
---|
| 5554 | #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
|
---|
| 5555 |
|
---|
[103] | 5556 | } # record type if-else
|
---|
| 5557 |
|
---|
[329] | 5558 | } # end _printrec_tiny()
|
---|
[103] | 5559 |
|
---|
| 5560 |
|
---|
[197] | 5561 | ## DNSDB::mailNotify()
|
---|
[283] | 5562 | # Sends notification mail to recipients regarding a DNSDB operation
|
---|
[197] | 5563 | sub mailNotify {
|
---|
[483] | 5564 | my $self = shift;
|
---|
| 5565 | my $dbh = $self->{dbh};
|
---|
[197] | 5566 | my ($subj,$message) = @_;
|
---|
| 5567 |
|
---|
[517] | 5568 | return if $self->{mailhost} eq 'smtp.example.com'; # do nothing if still using default SMTP host.
|
---|
[197] | 5569 |
|
---|
[517] | 5570 | my $mailer = Net::SMTP->new($self->{mailhost}, Hello => "dnsadmin.$self->{domain}");
|
---|
[197] | 5571 |
|
---|
[517] | 5572 | my $mailsender = ($self->{mailsender} ? $self->{mailsender} : $self->{mailnotify});
|
---|
[197] | 5573 |
|
---|
| 5574 | $mailer->mail($mailsender);
|
---|
[517] | 5575 | $mailer->to($self->{mailnotify});
|
---|
| 5576 | $mailer->data("From: \"$self->{mailname}\" <$mailsender>\n",
|
---|
| 5577 | "To: <$self->{mailnotify}>\n",
|
---|
[197] | 5578 | "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
|
---|
| 5579 | "Subject: $subj\n",
|
---|
[529] | 5580 | "X-Mailer: DNSAdmin v".$DNSDB::VERSION." Notify\n",
|
---|
[517] | 5581 | "Organization: $self->{orgname}\n",
|
---|
[197] | 5582 | "\n$message\n");
|
---|
| 5583 | $mailer->quit;
|
---|
| 5584 | }
|
---|
| 5585 |
|
---|
[2] | 5586 | # shut Perl up
|
---|
| 5587 | 1;
|
---|