[2] | 1 | # dns/trunk/DNSDB.pm
|
---|
| 2 | # Abstraction functions for DNS administration
|
---|
[262] | 3 | ##
|
---|
| 4 | # $Id: DNSDB.pm 490 2013-04-09 19:18:00Z kdeugau $
|
---|
[320] | 5 | # Copyright 2008-2012 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;
|
---|
[226] | 30 | use NetAddr::IP qw(:lower);
|
---|
[198] | 31 | use POSIX;
|
---|
[368] | 32 | use Fcntl qw(:flock);
|
---|
| 33 |
|
---|
[2] | 34 | use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
|
---|
| 35 |
|
---|
[321] | 36 | $VERSION = 1.1; ##VERSION##
|
---|
[2] | 37 | @ISA = qw(Exporter);
|
---|
| 38 | @EXPORT_OK = qw(
|
---|
[279] | 39 | &initGlobals &login &initActionLog
|
---|
[489] | 40 | &getPermissions &changePermissions &comparePermissions
|
---|
[112] | 41 | &changeGroup
|
---|
[128] | 42 | &loadConfig &connectDB &finish
|
---|
[276] | 43 | &addDomain &delZone &domainName &revName &domainID &revID &addRDNS
|
---|
[383] | 44 | &getZoneCount &getZoneList &getZoneLocation
|
---|
[22] | 45 | &addGroup &delGroup &getChildren &groupName
|
---|
[314] | 46 | &getGroupCount &getGroupList
|
---|
[83] | 47 | &addUser &updateUser &delUser &userFullName &userStatus &getUserData
|
---|
[326] | 48 | &getUserCount &getUserList &getUserDropdown
|
---|
[375] | 49 | &addLoc &updateLoc &delLoc &getLoc
|
---|
[370] | 50 | &getLocCount &getLocList &getLocDropdown
|
---|
[277] | 51 | &getSOA &updateSOA &getRecLine &getDomRecs &getRecCount
|
---|
[22] | 52 | &addRec &updateRec &delRec
|
---|
[323] | 53 | &getLogCount &getLogEntries
|
---|
[452] | 54 | &getRevPattern
|
---|
[225] | 55 | &getTypelist
|
---|
[254] | 56 | &parentID
|
---|
[117] | 57 | &isParent
|
---|
[452] | 58 | &zoneStatus &getZonesByCIDR &importAXFR
|
---|
[103] | 59 | &export
|
---|
[197] | 60 | &mailNotify
|
---|
[128] | 61 | %typemap %reverse_typemap %config
|
---|
[489] | 62 | @permtypes $permlist %permchains
|
---|
[2] | 63 | );
|
---|
| 64 |
|
---|
[489] | 65 | @EXPORT = qw(%typemap %reverse_typemap @permtypes $permlist %permchains);
|
---|
[2] | 66 | %EXPORT_TAGS = ( ALL => [qw(
|
---|
[279] | 67 | &initGlobals &login &initActionLog
|
---|
[489] | 68 | &getPermissions &changePermissions &comparePermissions
|
---|
[112] | 69 | &changeGroup
|
---|
[128] | 70 | &loadConfig &connectDB &finish
|
---|
[276] | 71 | &addDomain &delZone &domainName &revName &domainID &revID &addRDNS
|
---|
[383] | 72 | &getZoneCount &getZoneList &getZoneLocation
|
---|
[22] | 73 | &addGroup &delGroup &getChildren &groupName
|
---|
[314] | 74 | &getGroupCount &getGroupList
|
---|
[83] | 75 | &addUser &updateUser &delUser &userFullName &userStatus &getUserData
|
---|
[326] | 76 | &getUserCount &getUserList &getUserDropdown
|
---|
[375] | 77 | &addLoc &updateLoc &delLoc &getLoc
|
---|
[370] | 78 | &getLocCount &getLocList &getLocDropdown
|
---|
[277] | 79 | &getSOA &updateSOA &getRecLine &getDomRecs &getRecCount
|
---|
[22] | 80 | &addRec &updateRec &delRec
|
---|
[323] | 81 | &getLogCount &getLogEntries
|
---|
[452] | 82 | &getRevPattern
|
---|
[225] | 83 | &getTypelist
|
---|
[254] | 84 | &parentID
|
---|
[117] | 85 | &isParent
|
---|
[452] | 86 | &zoneStatus &getZonesByCIDR &importAXFR
|
---|
[103] | 87 | &export
|
---|
[197] | 88 | &mailNotify
|
---|
[128] | 89 | %typemap %reverse_typemap %config
|
---|
[489] | 90 | @permtypes $permlist %permchains
|
---|
[2] | 91 | )]
|
---|
| 92 | );
|
---|
| 93 |
|
---|
| 94 | our $errstr = '';
|
---|
[283] | 95 | our $resultstr = '';
|
---|
[2] | 96 |
|
---|
| 97 | # Halfway sane defaults for SOA, TTL, etc.
|
---|
[101] | 98 | # serial defaults to 0 for convenience.
|
---|
| 99 | # value will be either YYYYMMDDNN for BIND/etc, or auto-internal for tinydns
|
---|
[2] | 100 | our %def = qw (
|
---|
| 101 | contact hostmaster.DOMAIN
|
---|
| 102 | prins ns1.myserver.com
|
---|
[101] | 103 | serial 0
|
---|
[2] | 104 | soattl 86400
|
---|
| 105 | refresh 10800
|
---|
| 106 | retry 3600
|
---|
| 107 | expire 604800
|
---|
| 108 | minttl 10800
|
---|
| 109 | ttl 10800
|
---|
| 110 | );
|
---|
| 111 |
|
---|
[66] | 112 | # Arguably defined wholly in the db, but little reason to change without supporting code changes
|
---|
[370] | 113 | # group_view, user_view permissions? separate rDNS permission(s)?
|
---|
[66] | 114 | our @permtypes = qw (
|
---|
| 115 | group_edit group_create group_delete
|
---|
| 116 | user_edit user_create user_delete
|
---|
| 117 | domain_edit domain_create domain_delete
|
---|
[387] | 118 | record_edit record_create record_delete record_locchg
|
---|
[370] | 119 | location_edit location_create location_delete location_view
|
---|
[66] | 120 | self_edit admin
|
---|
| 121 | );
|
---|
| 122 | our $permlist = join(',',@permtypes);
|
---|
| 123 |
|
---|
[390] | 124 | # Some permissions more or less require certain others.
|
---|
| 125 | our %permchains = (
|
---|
| 126 | user_edit => 'self_edit',
|
---|
| 127 | location_edit => 'location_view',
|
---|
| 128 | location_create => 'location_view',
|
---|
| 129 | location_delete => 'location_view',
|
---|
| 130 | record_locchg => 'location_view',
|
---|
| 131 | );
|
---|
| 132 |
|
---|
[2] | 133 | # DNS record type map and reverse map.
|
---|
| 134 | # loaded from the database, from http://www.iana.org/assignments/dns-parameters
|
---|
| 135 | our %typemap;
|
---|
| 136 | our %reverse_typemap;
|
---|
| 137 |
|
---|
[128] | 138 | # Prepopulate a basic config. Note some of these *will* cause errors if left unset.
|
---|
[195] | 139 | # note: add appropriate stanzas in loadConfig to parse these
|
---|
[128] | 140 | our %config = (
|
---|
| 141 | # Database connection info
|
---|
| 142 | dbname => 'dnsdb',
|
---|
| 143 | dbuser => 'dnsdb',
|
---|
| 144 | dbpass => 'secret',
|
---|
| 145 | dbhost => '',
|
---|
| 146 |
|
---|
| 147 | # Email notice settings
|
---|
| 148 | mailhost => 'smtp.example.com',
|
---|
[195] | 149 | mailnotify => 'dnsdb@example.com', # to
|
---|
| 150 | mailsender => 'dnsdb@example.com', # from
|
---|
[128] | 151 | mailname => 'DNS Administration',
|
---|
[195] | 152 | orgname => 'Example Corp',
|
---|
| 153 | domain => 'example.com',
|
---|
[128] | 154 |
|
---|
| 155 | # Template directory
|
---|
| 156 | templatedir => 'templates/',
|
---|
| 157 | # fmeh. this is a real web path, not a logical internal one. hm..
|
---|
[163] | 158 | # cssdir => 'templates/',
|
---|
[216] | 159 | sessiondir => 'session/',
|
---|
[368] | 160 | exportcache => 'cache/',
|
---|
[163] | 161 |
|
---|
| 162 | # Session params
|
---|
[195] | 163 | timeout => '3600', # 1 hour default
|
---|
| 164 |
|
---|
| 165 | # Other miscellanea
|
---|
| 166 | log_failures => 1, # log all evarthing by default
|
---|
[201] | 167 | perpage => 15,
|
---|
[490] | 168 | maxfcgi => 100, # reasonable default?
|
---|
[128] | 169 | );
|
---|
| 170 |
|
---|
[228] | 171 | ## (Semi)private variables
|
---|
[278] | 172 |
|
---|
[228] | 173 | # Hash of functions for validating record types. Filled in initGlobals() since
|
---|
| 174 | # it relies on visibility flags from the rectypes table in the DB
|
---|
| 175 | my %validators;
|
---|
[128] | 176 |
|
---|
[295] | 177 | # Entity-relationship reference hashes.
|
---|
| 178 | my %par_tbl = (
|
---|
| 179 | group => 'groups',
|
---|
| 180 | user => 'users',
|
---|
| 181 | defrec => 'default_records',
|
---|
| 182 | defrevrec => 'default_rev_records',
|
---|
| 183 | domain => 'domains',
|
---|
| 184 | revzone => 'revzones',
|
---|
| 185 | record => 'records'
|
---|
| 186 | );
|
---|
| 187 | my %id_col = (
|
---|
| 188 | group => 'group_id',
|
---|
| 189 | user => 'user_id',
|
---|
| 190 | defrec => 'record_id',
|
---|
| 191 | defrevrec => 'record_id',
|
---|
| 192 | domain => 'domain_id',
|
---|
| 193 | revzone => 'rdns_id',
|
---|
| 194 | record => 'record_id'
|
---|
| 195 | );
|
---|
| 196 | my %par_col = (
|
---|
| 197 | group => 'parent_group_id',
|
---|
| 198 | user => 'group_id',
|
---|
| 199 | defrec => 'group_id',
|
---|
| 200 | defrevrec => 'group_id',
|
---|
| 201 | domain => 'group_id',
|
---|
| 202 | revzone => 'group_id',
|
---|
| 203 | record => 'domain_id'
|
---|
| 204 | );
|
---|
| 205 | my %par_type = (
|
---|
| 206 | group => 'group',
|
---|
| 207 | user => 'group',
|
---|
| 208 | defrec => 'group',
|
---|
| 209 | defrevrec => 'group',
|
---|
| 210 | domain => 'group',
|
---|
| 211 | revzone => 'group',
|
---|
| 212 | record => 'domain'
|
---|
| 213 | );
|
---|
[278] | 214 |
|
---|
[2] | 215 | ##
|
---|
[465] | 216 | ## Constructor and destructor
|
---|
| 217 | ##
|
---|
| 218 |
|
---|
| 219 | sub new {
|
---|
| 220 | my $this = shift;
|
---|
| 221 | my $class = ref($this) || $this;
|
---|
| 222 | my %args = @_;
|
---|
| 223 | ##fixme? to ponder: do we do some magic if the caller sets eg dbname to prevent parsing of the config file?
|
---|
| 224 | if (!loadConfig(basename => $args{configfile})) {
|
---|
| 225 | warn "Using default configuration; unable to load custom settings: $errstr\n";
|
---|
| 226 | }
|
---|
| 227 | my $self = \%config;
|
---|
| 228 | $self->{configfile} = $args{configfile};
|
---|
| 229 | bless $self, $class;
|
---|
| 230 | $self->{dbh} = connectDB($self->{dbname}, $self->{dbuser}, $self->{dbpass}, $self->{dbhost}) or return;
|
---|
| 231 | $self->initGlobals();
|
---|
| 232 |
|
---|
| 233 | return $self;
|
---|
| 234 | }
|
---|
| 235 |
|
---|
| 236 | sub DESTROY {
|
---|
| 237 | my $self = shift;
|
---|
| 238 | $self->{dbh}->disconnect;
|
---|
| 239 | }
|
---|
| 240 |
|
---|
| 241 | ##
|
---|
[225] | 242 | ## utility functions
|
---|
[281] | 243 | ##
|
---|
| 244 |
|
---|
| 245 | ## DNSDB::_rectable()
|
---|
[224] | 246 | # Takes default+rdns flags, returns appropriate table name
|
---|
| 247 | sub _rectable {
|
---|
| 248 | my $def = shift;
|
---|
| 249 | my $rev = shift;
|
---|
| 250 |
|
---|
| 251 | return 'records' if $def ne 'y';
|
---|
| 252 | return 'default_records' if $rev ne 'y';
|
---|
| 253 | return 'default_rev_records';
|
---|
| 254 | } # end _rectable()
|
---|
| 255 |
|
---|
[281] | 256 | ## DNSDB::_recparent()
|
---|
[224] | 257 | # Takes default+rdns flags, returns appropriate parent-id column name
|
---|
| 258 | sub _recparent {
|
---|
| 259 | my $def = shift;
|
---|
| 260 | my $rev = shift;
|
---|
| 261 |
|
---|
| 262 | return 'group_id' if $def eq 'y';
|
---|
| 263 | return 'rdns_id' if $rev eq 'y';
|
---|
| 264 | return 'domain_id';
|
---|
| 265 | } # end _recparent()
|
---|
| 266 |
|
---|
[281] | 267 | ## DNSDB::_ipparent()
|
---|
[226] | 268 | # Check an IP to be added in a reverse zone to see if it's really in the requested parent.
|
---|
[466] | 269 | # Takes default and reverse flags, IP (fragment) to check, parent zone ID,
|
---|
[226] | 270 | # and a reference to a NetAddr::IP object (also used to pass back a fully-reconstructed IP for
|
---|
| 271 | # database insertion)
|
---|
| 272 | sub _ipparent {
|
---|
[466] | 273 | my $self = shift;
|
---|
| 274 | my $dbh = $self->{dbh};
|
---|
[226] | 275 | my $defrec = shift;
|
---|
| 276 | my $revrec = shift;
|
---|
| 277 | my $val = shift;
|
---|
| 278 | my $id = shift;
|
---|
| 279 | my $addr = shift;
|
---|
[224] | 280 |
|
---|
[232] | 281 | return if $revrec ne 'y'; # this sub not useful in forward zones
|
---|
| 282 |
|
---|
| 283 | $$addr = NetAddr::IP->new($$val); #necessary?
|
---|
| 284 |
|
---|
[226] | 285 | # subsub to split, reverse, and overlay an IP fragment on a netblock
|
---|
| 286 | sub __rev_overlay {
|
---|
| 287 | my $splitme = shift; # ':' or '.', m'lud?
|
---|
| 288 | my $parnet = shift;
|
---|
| 289 | my $val = shift;
|
---|
| 290 | my $addr = shift;
|
---|
| 291 |
|
---|
| 292 | my $joinme = $splitme;
|
---|
| 293 | $splitme = '\.' if $splitme eq '.';
|
---|
[232] | 294 | my @working = reverse(split($splitme, $parnet->addr));
|
---|
| 295 | my @parts = reverse(split($splitme, $$val));
|
---|
[226] | 296 | for (my $i = 0; $i <= $#parts; $i++) {
|
---|
| 297 | $working[$i] = $parts[$i];
|
---|
| 298 | }
|
---|
[232] | 299 | my $checkme = NetAddr::IP->new(join($joinme, reverse(@working))) or return 0;
|
---|
| 300 | return 0 unless $checkme->within($parnet);
|
---|
[226] | 301 | $$addr = $checkme; # force "correct" IP to be recorded.
|
---|
| 302 | return 1;
|
---|
| 303 | }
|
---|
| 304 |
|
---|
| 305 | my ($parstr) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id = ?", undef, ($id));
|
---|
| 306 | my $parnet = NetAddr::IP->new($parstr);
|
---|
| 307 |
|
---|
| 308 | # Fail early on v6-in-v4 or v4-in-v6. We're not accepting these ATM.
|
---|
[232] | 309 | return 0 if $parnet->addr =~ /\./ && $$val =~ /:/;
|
---|
| 310 | return 0 if $parnet->addr =~ /:/ && $$val =~ /\./;
|
---|
[226] | 311 |
|
---|
[340] | 312 | if ($$addr && ($$val =~ /^[\da-fA-F][\da-fA-F:]+[\da-fA-F]$/ || $$val =~ m|/\d+$|)) {
|
---|
| 313 | # the only case where NetAddr::IP's acceptance of legitimate IPs is "correct" is for a proper IPv6 address,
|
---|
| 314 | # or a netblock (only expected on templates)
|
---|
[232] | 315 | # the rest we have to restructure before fiddling. *sigh*
|
---|
| 316 | return 1 if $$addr->within($parnet);
|
---|
| 317 | } else {
|
---|
[340] | 318 | # We don't have a complete IP in $$val (yet)... unless we have a netblock
|
---|
[232] | 319 | if ($parnet->addr =~ /:/) {
|
---|
| 320 | $$val =~ s/^:+//; # gotta strip'em all...
|
---|
[226] | 321 | return __rev_overlay(':', $parnet, $val, $addr);
|
---|
| 322 | }
|
---|
[232] | 323 | if ($parnet->addr =~ /\./) {
|
---|
| 324 | $$val =~ s/^\.+//;
|
---|
| 325 | return __rev_overlay('.', $parnet, $val, $addr);
|
---|
| 326 | }
|
---|
[226] | 327 | # should be impossible to get here...
|
---|
| 328 | }
|
---|
| 329 | # ... and here.
|
---|
| 330 | # can't do nuttin' in forward zones
|
---|
| 331 | } # end _ipparent()
|
---|
| 332 |
|
---|
[281] | 333 | ## DNSDB::_hostparent()
|
---|
[232] | 334 | # A little different than _ipparent above; this tries to *find* the parent zone of a hostname
|
---|
[466] | 335 | # Takes a hostname.
|
---|
[281] | 336 | # Returns the domain ID of the parent domain if one was found.
|
---|
[232] | 337 | sub _hostparent {
|
---|
[466] | 338 | my $self = shift;
|
---|
| 339 | my $dbh = $self->{dbh};
|
---|
[232] | 340 | my $hname = shift;
|
---|
[347] | 341 |
|
---|
| 342 | $hname =~ s/^\*\.//; # this should be impossible to find in the domains table.
|
---|
[232] | 343 | my @hostbits = split /\./, $hname;
|
---|
[349] | 344 | my $sth = $dbh->prepare("SELECT count(*),domain_id FROM domains WHERE lower(domain) = lower(?) GROUP BY domain_id");
|
---|
[232] | 345 | foreach (@hostbits) {
|
---|
| 346 | $sth->execute($hname);
|
---|
| 347 | my ($found, $parid) = $sth->fetchrow_array;
|
---|
| 348 | if ($found) {
|
---|
| 349 | return $parid;
|
---|
| 350 | }
|
---|
| 351 | $hname =~ s/^$_\.//;
|
---|
| 352 | }
|
---|
| 353 | } # end _hostparent()
|
---|
[228] | 354 |
|
---|
[281] | 355 | ## DNSDB::_log()
|
---|
| 356 | # Log an action
|
---|
[466] | 357 | # Takes a log entry hash containing at least:
|
---|
[282] | 358 | # group_id, log entry
|
---|
[281] | 359 | # and optionally one or more of:
|
---|
| 360 | # domain_id, rdns_id
|
---|
[282] | 361 | # The %userdata hash provides the user ID, username, and fullname
|
---|
[281] | 362 | sub _log {
|
---|
[466] | 363 | my $self = shift;
|
---|
| 364 | my $dbh = $self->{dbh};
|
---|
[281] | 365 |
|
---|
| 366 | my %args = @_;
|
---|
| 367 |
|
---|
| 368 | $args{rdns_id} = 0 if !$args{rdns_id};
|
---|
| 369 | $args{domain_id} = 0 if !$args{domain_id};
|
---|
| 370 |
|
---|
| 371 | ##fixme: farm out the actual logging to different subs for file, syslog, internal, etc based on config
|
---|
| 372 | # if ($config{log_channel} eq 'sql') {
|
---|
| 373 | $dbh->do("INSERT INTO log (domain_id,rdns_id,group_id,entry,user_id,email,name) VALUES (?,?,?,?,?,?,?)",
|
---|
| 374 | undef,
|
---|
| 375 | ($args{domain_id}, $args{rdns_id}, $args{group_id}, $args{entry},
|
---|
[488] | 376 | $self->{loguserid}, $self->{logusername}, $self->{logfullname}) );
|
---|
[281] | 377 | # } elsif ($config{log_channel} eq 'file') {
|
---|
| 378 | # } elsif ($config{log_channel} eq 'syslog') {
|
---|
| 379 | # }
|
---|
| 380 | } # end _log
|
---|
| 381 |
|
---|
| 382 |
|
---|
[224] | 383 | ##
|
---|
[228] | 384 | ## Record validation subs.
|
---|
| 385 | ##
|
---|
| 386 |
|
---|
[281] | 387 | ## All of these subs take substantially the same arguments:
|
---|
| 388 | # a hash containing at least the following keys:
|
---|
| 389 | # - defrec (default/live flag)
|
---|
| 390 | # - revrec (forward/reverse flag)
|
---|
| 391 | # - id (parent entity ID)
|
---|
| 392 | # - host (hostname)
|
---|
| 393 | # - rectype
|
---|
| 394 | # - val (IP, hostname [CNAME/MX/SRV] or text)
|
---|
| 395 | # - addr (NetAddr::IP object from val. May be undef.)
|
---|
| 396 | # MX and SRV record validation also expect distance, and SRV records expect weight and port as well.
|
---|
| 397 | # host, rectype, and addr should be references as these may be modified in validation
|
---|
| 398 |
|
---|
[228] | 399 | # A record
|
---|
| 400 | sub _validate_1 {
|
---|
[467] | 401 | my $self = shift;
|
---|
| 402 | my $dbh = $self->{dbh};
|
---|
[229] | 403 |
|
---|
[230] | 404 | my %args = @_;
|
---|
[229] | 405 |
|
---|
[230] | 406 | return ('FAIL', 'Reverse zones cannot contain A records') if $args{revrec} eq 'y';
|
---|
[229] | 407 |
|
---|
| 408 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 409 | # or the intended parent domain for live records.
|
---|
[467] | 410 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[230] | 411 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
[229] | 412 |
|
---|
| 413 | # Check IP is well-formed, and that it's a v4 address
|
---|
[234] | 414 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
|
---|
[232] | 415 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
[234] | 416 | unless ${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/;
|
---|
| 417 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
[230] | 418 | unless $args{addr} && !$args{addr}->{isv6};
|
---|
[229] | 419 | # coerce IP/value to normalized form for storage
|
---|
[230] | 420 | ${$args{val}} = $args{addr}->addr;
|
---|
[229] | 421 |
|
---|
[228] | 422 | return ('OK','OK');
|
---|
| 423 | } # done A record
|
---|
| 424 |
|
---|
| 425 | # NS record
|
---|
| 426 | sub _validate_2 {
|
---|
[467] | 427 | my $self = shift;
|
---|
| 428 | my $dbh = $self->{dbh};
|
---|
[230] | 429 |
|
---|
| 430 | my %args = @_;
|
---|
| 431 |
|
---|
[328] | 432 | # Check that the target of the record is within the parent.
|
---|
| 433 | # Yes, host<->val are mixed up here; can't see a way to avoid it. :(
|
---|
| 434 | if ($args{defrec} eq 'n') {
|
---|
| 435 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
| 436 | if ($args{revrec} eq 'y') {
|
---|
| 437 | my $tmpip = NetAddr::IP->new(${$args{val}});
|
---|
[467] | 438 | my $pname = $self->revName($args{id});
|
---|
[328] | 439 | return ('FAIL',"${$args{val}} not within $pname")
|
---|
[467] | 440 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$tmpip);
|
---|
[328] | 441 | # Sub the returned thing for ZONE? This could get stupid if you have typos...
|
---|
| 442 | ${$args{val}} =~ s/ZONE/$tmpip->address/;
|
---|
| 443 | } else {
|
---|
[467] | 444 | my $pname = $self->domainName($args{id});
|
---|
[328] | 445 | ${$args{host}} = $pname if ${$args{host}} !~ /\.$pname$/;
|
---|
| 446 | }
|
---|
[230] | 447 | } else {
|
---|
[328] | 448 | # Default reverse NS records should always refer to the implied parent
|
---|
| 449 | ${$args{host}} = 'DOMAIN' if $args{revrec} eq 'n';
|
---|
| 450 | ${$args{val}} = 'ZONE' if $args{revrec} eq 'y';
|
---|
[230] | 451 | }
|
---|
| 452 |
|
---|
| 453 | # Let this lie for now. Needs more magic.
|
---|
| 454 | # # Check IP is well-formed, and that it's a v4 address
|
---|
| 455 | # return ('FAIL',"A record must be a valid IPv4 address")
|
---|
| 456 | # unless $addr && !$addr->{isv6};
|
---|
| 457 | # # coerce IP/value to normalized form for storage
|
---|
| 458 | # $$val = $addr->addr;
|
---|
| 459 |
|
---|
[228] | 460 | return ('OK','OK');
|
---|
| 461 | } # done NS record
|
---|
| 462 |
|
---|
| 463 | # CNAME record
|
---|
| 464 | sub _validate_5 {
|
---|
[467] | 465 | my $self = shift;
|
---|
| 466 | my $dbh = $self->{dbh};
|
---|
[230] | 467 |
|
---|
| 468 | my %args = @_;
|
---|
| 469 |
|
---|
| 470 | # Not really true, but these are only useful for delegating smaller-than-/24 IP blocks.
|
---|
| 471 | # This is fundamentally a messy operation and should really just be taken care of by the
|
---|
| 472 | # export process, not manual maintenance of the necessary records.
|
---|
| 473 | return ('FAIL', 'Reverse zones cannot contain CNAME records') if $args{revrec} eq 'y';
|
---|
| 474 |
|
---|
| 475 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 476 | # or the intended parent domain for live records.
|
---|
[467] | 477 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[230] | 478 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 479 |
|
---|
[228] | 480 | return ('OK','OK');
|
---|
| 481 | } # done CNAME record
|
---|
| 482 |
|
---|
| 483 | # SOA record
|
---|
| 484 | sub _validate_6 {
|
---|
[230] | 485 | # Smart monkeys won't stick their fingers in here; we have
|
---|
| 486 | # separate dedicated routines to deal with SOA records.
|
---|
[228] | 487 | return ('OK','OK');
|
---|
| 488 | } # done SOA record
|
---|
| 489 |
|
---|
| 490 | # PTR record
|
---|
| 491 | sub _validate_12 {
|
---|
[467] | 492 | my $self = shift;
|
---|
| 493 | my $dbh = $self->{dbh};
|
---|
[232] | 494 |
|
---|
| 495 | my %args = @_;
|
---|
| 496 |
|
---|
| 497 | if ($args{revrec} eq 'y') {
|
---|
| 498 | if ($args{defrec} eq 'n') {
|
---|
[467] | 499 | return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
| 500 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
[232] | 501 | ${$args{val}} = $args{addr}->addr;
|
---|
| 502 | } else {
|
---|
[234] | 503 | if (${$args{val}} =~ /\./) {
|
---|
| 504 | # looks like a v4 or fragment
|
---|
| 505 | if (${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/) {
|
---|
| 506 | # woo! a complete IP! validate it and normalize, or fail.
|
---|
| 507 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
| 508 | or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
|
---|
| 509 | ${$args{val}} = $args{addr}->addr;
|
---|
| 510 | } else {
|
---|
[249] | 511 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
[234] | 512 | }
|
---|
| 513 | } elsif (${$args{val}} =~ /[a-f:]/) {
|
---|
| 514 | # looks like a v6 or fragment
|
---|
[251] | 515 | ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
|
---|
[234] | 516 | if ($args{addr}) {
|
---|
| 517 | if ($args{addr}->addr =~ /^0/) {
|
---|
[251] | 518 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
[234] | 519 | } else {
|
---|
| 520 | ${$args{val}} = $args{addr}->addr;
|
---|
| 521 | }
|
---|
| 522 | }
|
---|
| 523 | } else {
|
---|
| 524 | # bare number (probably). These could be v4 or v6, so we'll
|
---|
| 525 | # expand on these on creation of a reverse zone.
|
---|
[251] | 526 | ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
|
---|
[234] | 527 | }
|
---|
[249] | 528 | ${$args{host}} =~ s/\.*$/\.$config{domain}/ if ${$args{host}} !~ /(?:$config{domain}|ADMINDOMAIN)$/;
|
---|
[232] | 529 | }
|
---|
| 530 |
|
---|
| 531 | # Multiple PTR records do NOT generally do what most people believe they do,
|
---|
| 532 | # and tend to fail in the most awkward way possible. Check and warn.
|
---|
| 533 | # We use $val instead of $addr->addr since we may be in a defrec, and may have eg "ZONE::42" or "ZONE.12"
|
---|
[249] | 534 |
|
---|
| 535 | my @checkvals = (${$args{val}});
|
---|
| 536 | if (${$args{val}} =~ /,/) {
|
---|
| 537 | # push . and :: variants into checkvals if val has ,
|
---|
| 538 | my $tmp;
|
---|
| 539 | ($tmp = ${$args{val}}) =~ s/,/./;
|
---|
| 540 | push @checkvals, $tmp;
|
---|
| 541 | ($tmp = ${$args{val}}) =~ s/,/::/;
|
---|
| 542 | push @checkvals, $tmp;
|
---|
| 543 | }
|
---|
| 544 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ?");
|
---|
| 545 | foreach my $checkme (@checkvals) {
|
---|
[272] | 546 | if ($args{update}) {
|
---|
| 547 | # Record update. There should usually be an existing PTR (the record being updated)
|
---|
| 548 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 549 | " WHERE val = ?", undef, ($checkme)) };
|
---|
| 550 | return ('WARN', "PTR record for $checkme already exists; adding another will probably not do what you want")
|
---|
[273] | 551 | if @ptrs && (!grep /^$args{update}$/, @ptrs);
|
---|
[272] | 552 | } else {
|
---|
| 553 | # New record. Always warn if a PTR exists
|
---|
| 554 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 555 | " WHERE val = ?", undef, ($checkme));
|
---|
| 556 | return ('WARN', "PTR record for $checkme already exists; adding another will probably not do what you want")
|
---|
| 557 | if $ptrcount;
|
---|
| 558 | }
|
---|
[249] | 559 | }
|
---|
[272] | 560 |
|
---|
[232] | 561 | } else {
|
---|
| 562 | # Not absolutely true but only useful if you hack things up for sub-/24 v4 reverse delegations
|
---|
| 563 | # Simpler to just create the reverse zone and grant access for the customer to edit it, and create direct
|
---|
| 564 | # PTR records on export
|
---|
| 565 | return ('FAIL',"Forward zones cannot contain PTR records");
|
---|
| 566 | }
|
---|
| 567 |
|
---|
[228] | 568 | return ('OK','OK');
|
---|
| 569 | } # done PTR record
|
---|
| 570 |
|
---|
| 571 | # MX record
|
---|
| 572 | sub _validate_15 {
|
---|
[467] | 573 | my $self = shift;
|
---|
| 574 | my $dbh = $self->{dbh};
|
---|
[230] | 575 |
|
---|
| 576 | my %args = @_;
|
---|
| 577 |
|
---|
| 578 | # Not absolutely true but WTF use is an MX record for a reverse zone?
|
---|
| 579 | return ('FAIL', 'Reverse zones cannot contain MX records') if $args{revrec} eq 'y';
|
---|
| 580 |
|
---|
| 581 | return ('FAIL', "Distance is required for MX records") unless defined(${$args{dist}});
|
---|
| 582 | ${$args{dist}} =~ s/\s*//g;
|
---|
| 583 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
|
---|
| 584 |
|
---|
| 585 | ${$args{fields}} = "distance,";
|
---|
| 586 | push @{$args{vallist}}, ${$args{dist}};
|
---|
| 587 |
|
---|
| 588 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 589 | # or the intended parent domain for live records.
|
---|
[467] | 590 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[230] | 591 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 592 |
|
---|
[273] | 593 | # hmm.. this might work. except possibly for something pointing to "deadbeef.ca". <g>
|
---|
| 594 | # if ($type == $reverse_typemap{NS} || $type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
|
---|
| 595 | # if ($val =~ /^\s*[\da-f:.]+\s*$/) {
|
---|
| 596 | # return ('FAIL',"$val is not a valid IP address") if !$addr;
|
---|
| 597 | # }
|
---|
| 598 | # }
|
---|
| 599 |
|
---|
[228] | 600 | return ('OK','OK');
|
---|
| 601 | } # done MX record
|
---|
| 602 |
|
---|
| 603 | # TXT record
|
---|
| 604 | sub _validate_16 {
|
---|
[231] | 605 | # Could arguably put a WARN return here on very long (>512) records
|
---|
[228] | 606 | return ('OK','OK');
|
---|
| 607 | } # done TXT record
|
---|
| 608 |
|
---|
| 609 | # RP record
|
---|
| 610 | sub _validate_17 {
|
---|
[231] | 611 | # Probably have to validate these some day
|
---|
[228] | 612 | return ('OK','OK');
|
---|
| 613 | } # done RP record
|
---|
| 614 |
|
---|
| 615 | # AAAA record
|
---|
| 616 | sub _validate_28 {
|
---|
[467] | 617 | my $self = shift;
|
---|
| 618 | my $dbh = $self->{dbh};
|
---|
[229] | 619 |
|
---|
[230] | 620 | my %args = @_;
|
---|
[229] | 621 |
|
---|
[230] | 622 | return ('FAIL', 'Reverse zones cannot contain AAAA records') if $args{revrec} eq 'y';
|
---|
[229] | 623 |
|
---|
| 624 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 625 | # or the intended parent domain for live records.
|
---|
[467] | 626 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[230] | 627 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
[229] | 628 |
|
---|
| 629 | # Check IP is well-formed, and that it's a v6 address
|
---|
[232] | 630 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
|
---|
[230] | 631 | unless $args{addr} && $args{addr}->{isv6};
|
---|
[229] | 632 | # coerce IP/value to normalized form for storage
|
---|
[230] | 633 | ${$args{val}} = $args{addr}->addr;
|
---|
[229] | 634 |
|
---|
[228] | 635 | return ('OK','OK');
|
---|
| 636 | } # done AAAA record
|
---|
| 637 |
|
---|
| 638 | # SRV record
|
---|
| 639 | sub _validate_33 {
|
---|
[467] | 640 | my $self = shift;
|
---|
| 641 | my $dbh = $self->{dbh};
|
---|
[231] | 642 |
|
---|
| 643 | my %args = @_;
|
---|
| 644 |
|
---|
| 645 | # Not absolutely true but WTF use is an SRV record for a reverse zone?
|
---|
| 646 | return ('FAIL', 'Reverse zones cannot contain SRV records') if $args{revrec} eq 'y';
|
---|
| 647 |
|
---|
| 648 | return ('FAIL', "Distance is required for SRV records") unless defined(${$args{dist}});
|
---|
| 649 | ${$args{dist}} =~ s/\s*//g;
|
---|
| 650 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
|
---|
| 651 |
|
---|
| 652 | return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]")
|
---|
| 653 | unless ${$args{host}} =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/;
|
---|
| 654 | return ('FAIL',"Port and weight are required for SRV records")
|
---|
| 655 | unless defined(${$args{weight}}) && defined(${$args{port}});
|
---|
| 656 | ${$args{weight}} =~ s/\s*//g;
|
---|
| 657 | ${$args{port}} =~ s/\s*//g;
|
---|
| 658 |
|
---|
| 659 | return ('FAIL',"Port and weight are required, and must be numeric")
|
---|
| 660 | unless ${$args{weight}} =~ /^\d+$/ && ${$args{port}} =~ /^\d+$/;
|
---|
| 661 |
|
---|
| 662 | ${$args{fields}} = "distance,weight,port,";
|
---|
| 663 | push @{$args{vallist}}, (${$args{dist}}, ${$args{weight}}, ${$args{port}});
|
---|
| 664 |
|
---|
| 665 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 666 | # or the intended parent domain for live records.
|
---|
[467] | 667 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[231] | 668 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 669 |
|
---|
[228] | 670 | return ('OK','OK');
|
---|
| 671 | } # done SRV record
|
---|
| 672 |
|
---|
| 673 | # Now the custom types
|
---|
| 674 |
|
---|
[232] | 675 | # A+PTR record. With a very little bit of magic we can also use this sub to validate AAAA+PTR. Whee!
|
---|
[228] | 676 | sub _validate_65280 {
|
---|
[467] | 677 | my $self = shift;
|
---|
| 678 | my $dbh = $self->{dbh};
|
---|
[232] | 679 |
|
---|
| 680 | my %args = @_;
|
---|
| 681 |
|
---|
| 682 | my $code = 'OK';
|
---|
| 683 | my $msg = 'OK';
|
---|
| 684 |
|
---|
| 685 | if ($args{defrec} eq 'n') {
|
---|
| 686 | # live record; revrec determines whether we validate the PTR or A component first.
|
---|
[233] | 687 |
|
---|
[232] | 688 | if ($args{revrec} eq 'y') {
|
---|
[467] | 689 | ($code,$msg) = $self->_validate_12(%args);
|
---|
[232] | 690 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 691 |
|
---|
[467] | 692 | # check A+PTR is really v4
|
---|
| 693 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
| 694 | if ${$args{rectype}} == 65280 && $args{addr}->{isv6};
|
---|
| 695 | # check AAAA+PTR is really v6
|
---|
| 696 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
|
---|
| 697 | if ${$args{rectype}} == 65281 && !$args{addr}->{isv6};
|
---|
| 698 |
|
---|
[232] | 699 | # Check if the reqested domain exists. If not, coerce the type down to PTR and warn.
|
---|
[467] | 700 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) {
|
---|
[272] | 701 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
| 702 | " as PTR instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
[232] | 703 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
| 704 | $msg = $addmsg if $code eq 'OK';
|
---|
| 705 | ${$args{rectype}} = $reverse_typemap{PTR};
|
---|
| 706 | return ('WARN', $msg);
|
---|
| 707 | }
|
---|
| 708 |
|
---|
[242] | 709 | # Add domain ID to field list and values
|
---|
| 710 | ${$args{fields}} .= "domain_id,";
|
---|
| 711 | push @{$args{vallist}}, ${$args{domid}};
|
---|
| 712 |
|
---|
[232] | 713 | } else {
|
---|
[467] | 714 | ($code,$msg) = $self->_validate_1(%args) if ${$args{rectype}} == 65280;
|
---|
| 715 | ($code,$msg) = $self->_validate_28(%args) if ${$args{rectype}} == 65281;
|
---|
[232] | 716 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 717 |
|
---|
| 718 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
| 719 | # work here since we don't *know* which parent to put it in.
|
---|
[233] | 720 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
[232] | 721 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
| 722 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
| 723 | if (!$revid) {
|
---|
[272] | 724 | $msg = "Record ".($args{update} ? 'updated' : 'added')." as ".(${$args{rectype}} == 65280 ? 'A' : 'AAAA').
|
---|
[232] | 725 | " instead of $typemap{${$args{rectype}}}; reverse zone not found for ${$args{val}}";
|
---|
| 726 | ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
| 727 | return ('WARN', $msg);
|
---|
| 728 | }
|
---|
| 729 |
|
---|
| 730 | # Check for duplicate PTRs. Note we don't have to play games with $code and $msg, because
|
---|
| 731 | # by definition there can't be duplicate PTRs if the reverse zone isn't managed here.
|
---|
[272] | 732 | if ($args{update}) {
|
---|
| 733 | # Record update. There should usually be an existing PTR (the record being updated)
|
---|
| 734 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 735 | " WHERE val = ?", undef, (${$args{val}})) };
|
---|
[273] | 736 | if (@ptrs && (!grep /^$args{update}$/, @ptrs)) {
|
---|
[272] | 737 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
|
---|
| 738 | $code = 'WARN';
|
---|
| 739 | }
|
---|
| 740 | } else {
|
---|
| 741 | # New record. Always warn if a PTR exists
|
---|
| 742 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 743 | " WHERE val = ?", undef, (${$args{val}}));
|
---|
| 744 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want"
|
---|
| 745 | if $ptrcount;
|
---|
| 746 | $code = 'WARN' if $ptrcount;
|
---|
[232] | 747 | }
|
---|
| 748 |
|
---|
[272] | 749 | # my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 750 | # " WHERE val = ?", undef, ${$args{val}});
|
---|
| 751 | # if ($ptrcount) {
|
---|
| 752 | # my $curid = $dbh->selectrow_array("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 753 | # " WHERE val = ?
|
---|
| 754 | # $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
|
---|
| 755 | # $code = 'WARN';
|
---|
| 756 | # }
|
---|
| 757 |
|
---|
[232] | 758 | ${$args{fields}} .= "rdns_id,";
|
---|
| 759 | push @{$args{vallist}}, $revid;
|
---|
| 760 | }
|
---|
| 761 |
|
---|
[233] | 762 | } else { # defrec eq 'y'
|
---|
| 763 | if ($args{revrec} eq 'y') {
|
---|
[467] | 764 | ($code,$msg) = $self->_validate_12(%args);
|
---|
[233] | 765 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 766 | if (${$args{rectype}} == 65280) {
|
---|
| 767 | return ('FAIL',"A+PTR record must be a valid IPv4 address or fragment")
|
---|
| 768 | if ${$args{val}} =~ /:/;
|
---|
[234] | 769 | ${$args{val}} =~ s/^ZONE,/ZONE./; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
[233] | 770 | } elsif (${$args{rectype}} == 65281) {
|
---|
| 771 | return ('FAIL',"AAAA+PTR record must be a valid IPv6 address or fragment")
|
---|
| 772 | if ${$args{val}} =~ /\./;
|
---|
[234] | 773 | ${$args{val}} =~ s/^ZONE,/ZONE::/; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
[233] | 774 | }
|
---|
| 775 | } else {
|
---|
| 776 | # This is easy. I also can't see a real use-case for A/AAAA+PTR in *all* forward
|
---|
| 777 | # domains, since you wouldn't be able to substitute both domain and reverse zone
|
---|
| 778 | # sanely, and you'd end up with guaranteed over-replicated PTR records that would
|
---|
| 779 | # confuse the hell out of pretty much anything that uses them.
|
---|
[234] | 780 | ##fixme: make this a config flag?
|
---|
[233] | 781 | return ('FAIL', "$typemap{${$args{rectype}}} records not allowed in default domains");
|
---|
| 782 | }
|
---|
[232] | 783 | }
|
---|
| 784 |
|
---|
| 785 | return ($code, $msg);
|
---|
[228] | 786 | } # done A+PTR record
|
---|
| 787 |
|
---|
| 788 | # AAAA+PTR record
|
---|
[232] | 789 | # A+PTR above has been magicked to handle AAAA+PTR as well.
|
---|
[228] | 790 | sub _validate_65281 {
|
---|
[232] | 791 | return _validate_65280(@_);
|
---|
[228] | 792 | } # done AAAA+PTR record
|
---|
| 793 |
|
---|
| 794 | # PTR template record
|
---|
| 795 | sub _validate_65282 {
|
---|
[467] | 796 | my $self = shift;
|
---|
| 797 | my $dbh = $self->{dbh};
|
---|
[340] | 798 |
|
---|
| 799 | my %args = @_;
|
---|
| 800 |
|
---|
| 801 | # we're *this* >.< close to being able to just call _validate_12... unfortunately we can't, quite.
|
---|
| 802 | if ($args{revrec} eq 'y') {
|
---|
| 803 | if ($args{defrec} eq 'n') {
|
---|
[467] | 804 | return ('FAIL', "Template block ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
| 805 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
[340] | 806 | ##fixme: warn if $args{val} is not /31 or larger block?
|
---|
| 807 | ${$args{val}} = "$args{addr}";
|
---|
| 808 | } else {
|
---|
| 809 | if (${$args{val}} =~ /\./) {
|
---|
| 810 | # looks like a v4 or fragment
|
---|
| 811 | if (${$args{val}} =~ m|^\d+\.\d+\.\d+\.\d+(?:/\d+)?$|) {
|
---|
| 812 | # woo! a complete IP! validate it and normalize, or fail.
|
---|
| 813 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
| 814 | or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
|
---|
| 815 | ${$args{val}} = "$args{addr}";
|
---|
| 816 | } else {
|
---|
| 817 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
| 818 | }
|
---|
| 819 | } elsif (${$args{val}} =~ /[a-f:]/) {
|
---|
| 820 | # looks like a v6 or fragment
|
---|
| 821 | ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
|
---|
| 822 | if ($args{addr}) {
|
---|
| 823 | if ($args{addr}->addr =~ /^0/) {
|
---|
| 824 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
| 825 | } else {
|
---|
| 826 | ${$args{val}} = "$args{addr}";
|
---|
| 827 | }
|
---|
| 828 | }
|
---|
| 829 | } else {
|
---|
| 830 | # bare number (probably). These could be v4 or v6, so we'll
|
---|
| 831 | # expand on these on creation of a reverse zone.
|
---|
| 832 | ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
|
---|
| 833 | }
|
---|
| 834 | }
|
---|
| 835 | ##fixme: validate %-patterns?
|
---|
| 836 |
|
---|
| 837 | # Unlike single PTR records, there is absolutely no way to sanely support multiple
|
---|
| 838 | # PTR templates for the same block, since they expect to expand to all the individual
|
---|
| 839 | # IPs on export. Nested templates should be supported though.
|
---|
| 840 |
|
---|
| 841 | my @checkvals = (${$args{val}});
|
---|
| 842 | if (${$args{val}} =~ /,/) {
|
---|
| 843 | # push . and :: variants into checkvals if val has ,
|
---|
| 844 | my $tmp;
|
---|
| 845 | ($tmp = ${$args{val}}) =~ s/,/./;
|
---|
| 846 | push @checkvals, $tmp;
|
---|
| 847 | ($tmp = ${$args{val}}) =~ s/,/::/;
|
---|
| 848 | push @checkvals, $tmp;
|
---|
| 849 | }
|
---|
| 850 | ##fixme: this feels wrong still - need to restrict template pseudorecords to One Of Each
|
---|
| 851 | # Per Netblock such that they don't conflict on export
|
---|
| 852 | my $typeck;
|
---|
| 853 | # type 65282 -> ptr template -> look for any of 65282, 65283, 65284
|
---|
| 854 | $typeck = 'type=65283 OR type=65284' if ${$args{rectype}} == 65282;
|
---|
| 855 | # type 65283 -> a+ptr template -> v4 -> look for 65282 or 65283
|
---|
| 856 | $typeck = 'type=65283' if ${$args{rectype}} == 65282;
|
---|
| 857 | # type 65284 -> aaaa+ptr template -> v6 -> look for 65282 or 65284
|
---|
| 858 | $typeck = 'type=65284' if ${$args{rectype}} == 65282;
|
---|
| 859 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ? ".
|
---|
| 860 | "AND (type=65282 OR $typeck)");
|
---|
| 861 | foreach my $checkme (@checkvals) {
|
---|
| 862 | $pcsth->execute($checkme);
|
---|
| 863 | my ($rc) = $pcsth->fetchrow_array;
|
---|
[442] | 864 | return ('FAIL', "Only one template pseudorecord may exist for a given IP block") if $rc > 1;
|
---|
[340] | 865 | }
|
---|
| 866 |
|
---|
| 867 | } else {
|
---|
| 868 | return ('FAIL', "Forward zones cannot contain PTR records");
|
---|
| 869 | }
|
---|
| 870 |
|
---|
[228] | 871 | return ('OK','OK');
|
---|
| 872 | } # done PTR template record
|
---|
| 873 |
|
---|
| 874 | # A+PTR template record
|
---|
| 875 | sub _validate_65283 {
|
---|
[467] | 876 | my $self = shift;
|
---|
| 877 | my $dbh = $self->{dbh};
|
---|
[340] | 878 |
|
---|
| 879 | my %args = @_;
|
---|
| 880 |
|
---|
| 881 | my ($code,$msg) = ('OK','OK');
|
---|
| 882 |
|
---|
| 883 | ##fixme: need to fiddle things since A+PTR templates are acceptable in live
|
---|
| 884 | # forward zones but not default records
|
---|
| 885 | if ($args{defrec} eq 'n') {
|
---|
| 886 | if ($args{revrec} eq 'n') {
|
---|
[467] | 887 | ($code,$msg) = $self->_validate_1(%args) if ${$args{rectype}} == 65280;
|
---|
| 888 | ($code,$msg) = $self->_validate_28(%args) if ${$args{rectype}} == 65281;
|
---|
[340] | 889 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 890 |
|
---|
| 891 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
| 892 | # work here since we don't *know* which parent to put it in.
|
---|
| 893 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
| 894 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
| 895 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
| 896 | # Fail if no match; we can't coerce a PTR-template type down to not include the PTR bit currently.
|
---|
| 897 | if (!$revid) {
|
---|
| 898 | $msg = "Can't ".($args{update} ? 'update' : 'add')." ${$args{host}}/${$args{val}} as ".
|
---|
| 899 | "$typemap{${$args{rectype}}}: reverse zone not found for ${$args{val}}";
|
---|
| 900 | ##fixme: add A template, AAAA template types?
|
---|
| 901 | # ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
| 902 | return ('FAIL', $msg);
|
---|
| 903 | }
|
---|
| 904 |
|
---|
| 905 | # Add reverse zone ID to field list and values
|
---|
| 906 | ${$args{fields}} .= "rdns_id,";
|
---|
| 907 | push @{$args{vallist}}, $revid;
|
---|
| 908 |
|
---|
| 909 | } else {
|
---|
[467] | 910 | return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
| 911 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
[340] | 912 | ${$args{val}} = "$args{addr}";
|
---|
| 913 |
|
---|
[467] | 914 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) {
|
---|
[340] | 915 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
| 916 | " as PTR template instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
| 917 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
| 918 | $msg = $addmsg if $code eq 'OK';
|
---|
| 919 | ${$args{rectype}} = 65282;
|
---|
| 920 | return ('WARN', $msg);
|
---|
| 921 | }
|
---|
| 922 |
|
---|
| 923 | # Add domain ID to field list and values
|
---|
| 924 | ${$args{fields}} .= "domain_id,";
|
---|
| 925 | push @{$args{vallist}}, ${$args{domid}};
|
---|
| 926 | }
|
---|
| 927 |
|
---|
| 928 | } else {
|
---|
[467] | 929 | my ($code,$msg) = $self->_validate_65282(%args);
|
---|
[340] | 930 | return ($code, $msg) if $code eq 'FAIL';
|
---|
| 931 | # get domain, check against ${$args{name}}
|
---|
| 932 | }
|
---|
| 933 |
|
---|
[228] | 934 | return ('OK','OK');
|
---|
| 935 | } # done AAAA+PTR template record
|
---|
| 936 |
|
---|
| 937 | # AAAA+PTR template record
|
---|
| 938 | sub _validate_65284 {
|
---|
| 939 | return ('OK','OK');
|
---|
| 940 | } # done AAAA+PTR template record
|
---|
| 941 |
|
---|
[342] | 942 | # Delegation record
|
---|
[345] | 943 | # This is essentially a specialized clone of the NS record, primarily useful
|
---|
| 944 | # for delegating IPv4 sub-/24 reverse blocks
|
---|
[342] | 945 | sub _validate_65285 {
|
---|
[467] | 946 | my $self = shift;
|
---|
| 947 | my $dbh = $self->{dbh};
|
---|
[345] | 948 |
|
---|
| 949 | my %args = @_;
|
---|
| 950 |
|
---|
| 951 | # Almost, but not quite, identical to NS record validation.
|
---|
| 952 |
|
---|
| 953 | # Check that the target of the record is within the parent.
|
---|
| 954 | # Yes, host<->val are mixed up here; can't see a way to avoid it. :(
|
---|
| 955 | if ($args{defrec} eq 'n') {
|
---|
| 956 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
| 957 | if ($args{revrec} eq 'y') {
|
---|
| 958 | my $tmpip = NetAddr::IP->new(${$args{val}});
|
---|
[467] | 959 | my $pname = $self->revName($args{id});
|
---|
[345] | 960 | return ('FAIL',"${$args{val}} not within $pname")
|
---|
[467] | 961 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$tmpip);
|
---|
[345] | 962 | # Normalize
|
---|
| 963 | ${$args{val}} = "$tmpip";
|
---|
| 964 | } else {
|
---|
[467] | 965 | my $pname = $self->domainName($args{id});
|
---|
[345] | 966 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 967 | }
|
---|
| 968 | } else {
|
---|
| 969 | return ('FAIL',"Delegation records are not permitted in default record sets");
|
---|
| 970 | }
|
---|
[342] | 971 | return ('OK','OK');
|
---|
| 972 | }
|
---|
[228] | 973 |
|
---|
[342] | 974 |
|
---|
[265] | 975 | ##
|
---|
| 976 | ## Record data substitution subs
|
---|
| 977 | ##
|
---|
[228] | 978 |
|
---|
[298] | 979 | # Replace ZONE in hostname, or create (most of) the actual proper zone name
|
---|
[265] | 980 | sub _ZONE {
|
---|
| 981 | my $zone = shift;
|
---|
| 982 | my $string = shift;
|
---|
| 983 | my $fr = shift || 'f'; # flag for forward/reverse order? nb: ignored for IP
|
---|
[298] | 984 | my $sep = shift || '-'; # Separator character - unlikely we'll ever need more than . or -
|
---|
[265] | 985 |
|
---|
[298] | 986 | my $prefix;
|
---|
[265] | 987 |
|
---|
| 988 | $string =~ s/,/./ if !$zone->{isv6};
|
---|
| 989 | $string =~ s/,/::/ if $zone->{isv6};
|
---|
| 990 |
|
---|
[298] | 991 | # Subbing ZONE in the host. We need to properly ID the netblock range
|
---|
| 992 | # The subbed text should have "network IP with trailing zeros stripped" for
|
---|
| 993 | # blocks lined up on octet (for v4) or hex-quad (for v6) boundaries
|
---|
| 994 | # For blocks that do NOT line up on these boundaries, we take the most
|
---|
| 995 | # significant octet or 16-bit chunk of the "broadcast" IP and append it
|
---|
| 996 | # after a double-dash
|
---|
| 997 | # ie:
|
---|
| 998 | # 8.0.0.0/6 -> 8.0.0.0 -> 11.255.255.255; sub should be 8--11
|
---|
| 999 | # 10.0.0.0/12 -> 10.0.0.0 -> 10.0.0.0 -> 10.15.255.255; sub should be 10-0--15
|
---|
| 1000 | # 192.168.4.0/22 -> 192.168.4.0 -> 192.168.7.255; sub should be 192-168-4--7
|
---|
| 1001 | # 192.168.0.8/29 -> 192.168.0.8 -> 192.168.0.15; sub should be 192-168-0-8--15
|
---|
| 1002 | # Similar for v6
|
---|
[265] | 1003 |
|
---|
[298] | 1004 | if (!$zone->{isv6}) { # IPv4
|
---|
| 1005 |
|
---|
| 1006 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
| 1007 | # a funky subnet that had host bits set.
|
---|
| 1008 | my $bc = $zone->broadcast->addr;
|
---|
| 1009 |
|
---|
| 1010 | if ($zone->masklen > 24) {
|
---|
| 1011 | $bc =~ s/^\d+\.\d+\.\d+\.//;
|
---|
| 1012 | } elsif ($zone->masklen > 16) {
|
---|
| 1013 | $prefix =~ s/\.0$//;
|
---|
| 1014 | $bc =~ s/^\d+\.\d+\.//;
|
---|
| 1015 | } elsif ($zone->masklen > 8) {
|
---|
| 1016 | $bc =~ s/^\d+\.//;
|
---|
| 1017 | $prefix =~ s/\.0\.0$//;
|
---|
| 1018 | } else {
|
---|
| 1019 | $prefix =~ s/\.0\.0\.0$//;
|
---|
| 1020 | }
|
---|
| 1021 | if ($zone->masklen % 8) {
|
---|
| 1022 | $bc =~ s/(\.255)+$//;
|
---|
| 1023 | $prefix .= "--$bc"; #"--".zone->masklen; # use range or mask length?
|
---|
| 1024 | }
|
---|
| 1025 | if ($fr eq 'f') {
|
---|
| 1026 | $prefix =~ s/\.+/$sep/g;
|
---|
| 1027 | } else {
|
---|
| 1028 | $prefix = join($sep, reverse(split(/\./, $prefix)));
|
---|
| 1029 | }
|
---|
| 1030 |
|
---|
| 1031 | } else { # IPv6
|
---|
| 1032 |
|
---|
| 1033 | if ($fr eq 'f') {
|
---|
| 1034 |
|
---|
| 1035 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
| 1036 | # a funky subnet that had host bits set.
|
---|
[265] | 1037 | my $bc = $zone->broadcast->addr;
|
---|
| 1038 | if (($zone->masklen % 16) != 0) {
|
---|
[298] | 1039 | # Strip trailing :0 off $prefix, and :ffff off the broadcast IP
|
---|
| 1040 | for (my $i=0; $i<(7-int($zone->masklen / 16)); $i++) {
|
---|
| 1041 | $prefix =~ s/:0$//;
|
---|
| 1042 | $bc =~ s/:ffff$//;
|
---|
| 1043 | }
|
---|
| 1044 | # Strip the leading 16-bit chunks off the front of the broadcast IP
|
---|
| 1045 | $bc =~ s/^([a-f0-9]+:)+//;
|
---|
| 1046 | # Append the remaining 16-bit chunk to the prefix after "--"
|
---|
| 1047 | $prefix .= "--$bc";
|
---|
[265] | 1048 | } else {
|
---|
[298] | 1049 | # Strip off :0 from the end until we reach the netblock length.
|
---|
| 1050 | for (my $i=0; $i<(8-$zone->masklen / 16); $i++) {
|
---|
[265] | 1051 | $prefix =~ s/:0$//;
|
---|
[298] | 1052 | }
|
---|
[265] | 1053 | }
|
---|
[298] | 1054 | # Actually deal with the separator
|
---|
| 1055 | $prefix =~ s/:/$sep/g;
|
---|
| 1056 |
|
---|
| 1057 | } else { # $fr eq 'f'
|
---|
| 1058 |
|
---|
| 1059 | $prefix = $zone->network->full; # Just In Case someone managed to slip in
|
---|
| 1060 | # a funky subnet that had host bits set.
|
---|
| 1061 | my $bc = $zone->broadcast->full;
|
---|
| 1062 | $prefix =~ s/://g; # clean these out since they're not spaced right for this case
|
---|
| 1063 | $bc =~ s/://g;
|
---|
| 1064 | # Strip trailing 0 off $prefix, and f off the broadcast IP, to match the mask length
|
---|
| 1065 | for (my $i=0; $i<(31-int($zone->masklen / 4)); $i++) {
|
---|
| 1066 | $prefix =~ s/0$//;
|
---|
| 1067 | $bc =~ s/f$//;
|
---|
| 1068 | }
|
---|
| 1069 | # Split and reverse the order of the nibbles in the network/broadcast IPs
|
---|
[332] | 1070 | # trim another 0 for nibble-aligned blocks first, but only if we really have a block, not an IP
|
---|
| 1071 | $prefix =~ s/0$// if $zone->masklen % 4 == 0 && $zone->masklen != 128;
|
---|
[298] | 1072 | my @nbits = reverse split //, $prefix;
|
---|
| 1073 | my @bbits = reverse split //, $bc;
|
---|
| 1074 | # Handle the sub-nibble case. Eww. I feel dirty supporting this...
|
---|
| 1075 | $nbits[0] = "$nbits[0]-$bbits[0]" if ($zone->masklen % 4) != 0;
|
---|
| 1076 | # Glue it back together
|
---|
| 1077 | $prefix = join($sep, @nbits);
|
---|
| 1078 |
|
---|
| 1079 | } # $fr ne 'f'
|
---|
| 1080 |
|
---|
| 1081 | } # $zone->{isv6}
|
---|
| 1082 |
|
---|
| 1083 | # Do the substitution, finally
|
---|
| 1084 | $string =~ s/ZONE/$prefix/;
|
---|
| 1085 | $string =~ s/--/-/ if $sep ne '-'; # - as separator needs extra help for sub-octet v4 netblocks
|
---|
| 1086 | return $string;
|
---|
| 1087 | } # done _ZONE()
|
---|
| 1088 |
|
---|
| 1089 | # Not quite a substitution sub, but placed here as it's basically the inverse of above;
|
---|
| 1090 | # given the .arpa zone name, return the CIDR netblock the zone is for.
|
---|
[304] | 1091 | # Supports v4 non-octet/non-classful netblocks as per the method outlined in the Grasshopper Book (2nd Ed p217-218)
|
---|
[298] | 1092 | # Does NOT support non-quad v6 netblocks via the same scheme; it shouldn't ever be necessary.
|
---|
| 1093 | # Takes a nominal .arpa zone name, returns a success code and NetAddr::IP, or a fail code and message
|
---|
| 1094 | sub _zone2cidr {
|
---|
| 1095 | my $zone = shift;
|
---|
| 1096 |
|
---|
| 1097 | my $cidr;
|
---|
[301] | 1098 | my $tmpcidr;
|
---|
| 1099 | my $warnmsg = '';
|
---|
[298] | 1100 |
|
---|
| 1101 | if ($zone =~ /\.in-addr\.arpa\.?$/) {
|
---|
| 1102 | # v4 revzone, formal zone name type
|
---|
| 1103 | my $tmpzone = $zone;
|
---|
| 1104 | $tmpzone =~ s/\.in-addr\.arpa\.?//;
|
---|
[301] | 1105 | return ('FAIL', "Non-numerics in apparent IPv4 reverse zone name") if $tmpzone !~ /^(?:\d+-)?[\d\.]+$/;
|
---|
[298] | 1106 |
|
---|
| 1107 | # Snag the octet pieces
|
---|
| 1108 | my @octs = split /\./, $tmpzone;
|
---|
| 1109 |
|
---|
| 1110 | # Map result of a range manipulation to a mask length change. Cheaper than finding the 2-root of $octets[0]+1.
|
---|
[304] | 1111 | # Note we will not support /31 blocks, mostly due to issues telling "24-31" -> .24/29 apart from
|
---|
| 1112 | # "24-31" -> .24/31", with a litte bit of "/31 is icky".
|
---|
| 1113 | my %maskmap = ( 3 => 2, 7 => 3, 15 => 4, 31 => 5, 63 => 6, 127 => 7,
|
---|
| 1114 | 30 => 2, 29 => 3, 28 => 4, 27 => 5, 26 => 6, 25 => 7
|
---|
| 1115 | );
|
---|
[298] | 1116 |
|
---|
| 1117 | # Handle "range" blocks, eg, 80-83.168.192.in-addr.arpa (192.168.80.0/22)
|
---|
| 1118 | # Need to take the size of the range to offset the basic octet-based mask length,
|
---|
| 1119 | # and make sure the first number in the range gets used as the network address for the block
|
---|
[304] | 1120 | # Alternate form: The second number is actually the real netmask, not the end of the range.
|
---|
[298] | 1121 | my $masklen = 0;
|
---|
[307] | 1122 | if ($octs[0] =~ /^((\d+)-(\d+))$/) { # take the range...
|
---|
| 1123 | if (24 < $3 && $3 < 31) {
|
---|
[304] | 1124 | # we have a real netmask
|
---|
[307] | 1125 | $masklen = -$maskmap{$3};
|
---|
[304] | 1126 | } else {
|
---|
| 1127 | # we have a range. NB: only real CIDR ranges are supported
|
---|
[307] | 1128 | $masklen -= $maskmap{-(eval $1)}; # find the mask base...
|
---|
[304] | 1129 | }
|
---|
[307] | 1130 | $octs[0] = $2; # set the base octet of the range...
|
---|
[265] | 1131 | }
|
---|
[298] | 1132 | @octs = reverse @octs; # We can reverse the octet pieces now that we've extracted and munged any ranges
|
---|
[265] | 1133 |
|
---|
[304] | 1134 | # arguably we should only allow sub-octet range/mask in-addr.arpa
|
---|
| 1135 | # specifications in the least significant octet, but the code is
|
---|
| 1136 | # simpler if we deal with sub-octet delegations at any level.
|
---|
| 1137 |
|
---|
[298] | 1138 | # Now we find the "true" mask with the aid of the "base" calculated above
|
---|
| 1139 | if ($#octs == 0) {
|
---|
| 1140 | $masklen += 8;
|
---|
| 1141 | $tmpcidr = "$octs[0].0.0.0/$masklen"; # really hope we don't see one of these very often.
|
---|
| 1142 | } elsif ($#octs == 1) {
|
---|
| 1143 | $masklen += 16;
|
---|
| 1144 | $tmpcidr = "$octs[0].$octs[1].0.0/$masklen";
|
---|
| 1145 | } elsif ($#octs == 2) {
|
---|
| 1146 | $masklen += 24;
|
---|
| 1147 | $tmpcidr = "$octs[0].$octs[1].$octs[2].0/$masklen";
|
---|
[265] | 1148 | } else {
|
---|
[298] | 1149 | $masklen += 32;
|
---|
| 1150 | $tmpcidr = "$octs[0].$octs[1].$octs[2].$octs[3]/$masklen";
|
---|
[265] | 1151 | }
|
---|
| 1152 |
|
---|
[298] | 1153 | } elsif ($zone =~ /\.ip6\.arpa$/) {
|
---|
| 1154 | # v6 revzone, formal zone name type
|
---|
| 1155 | my $tmpzone = $zone;
|
---|
| 1156 | $tmpzone =~ s/\.ip6\.arpa\.?//;
|
---|
[301] | 1157 | ##fixme: if-n-when we decide we can support sub-nibble v6 zone names, we'll need to change this segment
|
---|
| 1158 | return ('FAIL', "Non-hexadecimals in apparent IPv6 reverse zone name") if $tmpzone !~ /^[a-fA-F\d\.]+$/;
|
---|
[298] | 1159 | my @quads = reverse(split(/\./, $tmpzone));
|
---|
| 1160 | $warnmsg .= "Apparent sub-/64 IPv6 reverse zone\n" if $#quads > 15;
|
---|
| 1161 | my $nc;
|
---|
| 1162 | foreach (@quads) {
|
---|
[301] | 1163 | $tmpcidr .= $_;
|
---|
| 1164 | $tmpcidr .= ":" if ++$nc % 4 == 0;
|
---|
[298] | 1165 | }
|
---|
| 1166 | my $nq = 1 if $nc % 4 != 0;
|
---|
| 1167 | my $mask = $nc * 4; # need to do this here because we probably increment it below
|
---|
| 1168 | while ($nc++ % 4 != 0) {
|
---|
[301] | 1169 | $tmpcidr .= "0";
|
---|
[298] | 1170 | }
|
---|
[301] | 1171 | $tmpcidr .= ($nq ? '::' : ':')."/$mask";
|
---|
[298] | 1172 | }
|
---|
[301] | 1173 |
|
---|
| 1174 | # Just to be sure, use NetAddr::IP to validate. Saves a lot of nasty regex watching for valid octet values.
|
---|
| 1175 | return ('FAIL', "Invalid zone $zone (apparent netblock $tmpcidr)")
|
---|
| 1176 | unless $cidr = NetAddr::IP->new($tmpcidr);
|
---|
| 1177 |
|
---|
| 1178 | if ($warnmsg) {
|
---|
| 1179 | $errstr = $warnmsg;
|
---|
| 1180 | return ('WARN', $cidr);
|
---|
| 1181 | }
|
---|
| 1182 | return ('OK', $cidr);
|
---|
[298] | 1183 | } # done _zone2cidr()
|
---|
[265] | 1184 |
|
---|
[337] | 1185 | # Record template %-parameter expansion, IPv4. Note that IPv6 doesn't
|
---|
| 1186 | # really have a sane way to handle this type of expansion at the moment
|
---|
| 1187 | # due to the size of the address space.
|
---|
| 1188 | # Takes a reference to a template string to be expanded, and an IP to use in the replacement.
|
---|
| 1189 | sub _template4_expand {
|
---|
| 1190 | my $tmpl = shift;
|
---|
| 1191 | my $ip = shift;
|
---|
[298] | 1192 |
|
---|
[337] | 1193 | my @ipparts = split /\./, $ip;
|
---|
| 1194 | my @iphex;
|
---|
| 1195 | my @ippad;
|
---|
| 1196 | for (@ipparts) {
|
---|
| 1197 | push @iphex, sprintf("%x", $_);
|
---|
[443] | 1198 | push @ippad, sprintf("%0.3u", $_);
|
---|
[337] | 1199 | }
|
---|
| 1200 |
|
---|
| 1201 | # IP substitutions in template records:
|
---|
| 1202 | #major patterns:
|
---|
| 1203 | #dashed IP, forward and reverse
|
---|
| 1204 | #dotted IP, forward and reverse (even if forward is... dumb)
|
---|
| 1205 | # -> %r for reverse, %i for forward, leading - or . to indicate separator, defaults to -
|
---|
| 1206 | # %r or %-r => %4d-%3d-%2d-%1d
|
---|
| 1207 | # %.r => %4d.%3d.%2d.%1d
|
---|
| 1208 | # %i or %-i => %1d-%2d-%3d-%4d
|
---|
| 1209 | # %.i => %1d.%2d.%3d.%4d
|
---|
| 1210 | $$tmpl =~ s/\%r/\%4d-\%3d-\%2d-\%1d/g;
|
---|
| 1211 | $$tmpl =~ s/\%([-.])r/\%4d$1\%3d$1\%2d$1\%1d/g;
|
---|
| 1212 | $$tmpl =~ s/\%i/\%1d-\%2d-\%3d-\%4d/g;
|
---|
| 1213 | $$tmpl =~ s/\%([-.])i/\%1d$1\%2d$1\%3d$1\%4d/g;
|
---|
| 1214 |
|
---|
| 1215 | #hex-coded IP
|
---|
| 1216 | # %h
|
---|
| 1217 | $$tmpl =~ s/\%h/$iphex[0]$iphex[1]$iphex[2]$iphex[3]/g;
|
---|
| 1218 |
|
---|
| 1219 | #IP as decimal-coded 32-bit value
|
---|
| 1220 | # %d
|
---|
| 1221 | my $iptmp = $ipparts[0]*256*256*256 + $ipparts[1]*256*256 + $ipparts[2]*256 + $ipparts[3];
|
---|
| 1222 | $$tmpl =~ s/\%d/$iptmp/g;
|
---|
| 1223 |
|
---|
| 1224 | #minor patterns (per-octet)
|
---|
| 1225 | # %[1234][dh0]
|
---|
| 1226 | #octet
|
---|
| 1227 | #hex-coded octet
|
---|
| 1228 | #0-padded octet
|
---|
| 1229 | $$tmpl =~ s/\%([1234])d/$ipparts[$1-1]/g;
|
---|
| 1230 | $$tmpl =~ s/\%([1234])h/$iphex[$1-1]/g;
|
---|
[443] | 1231 | $$tmpl =~ s/\%([1234])0/$ippad[$1-1]/g;
|
---|
[337] | 1232 | } # _template4_expand()
|
---|
| 1233 |
|
---|
| 1234 |
|
---|
[228] | 1235 | ##
|
---|
[2] | 1236 | ## Initialization and cleanup subs
|
---|
| 1237 | ##
|
---|
| 1238 |
|
---|
[128] | 1239 | ## DNSDB::loadConfig()
|
---|
| 1240 | # Load the minimum required initial state (DB connect info) from a config file
|
---|
| 1241 | # Load misc other bits while we're at it.
|
---|
[400] | 1242 | # Takes an optional hash that may contain:
|
---|
| 1243 | # - basename and config path to look for
|
---|
[128] | 1244 | # Populates the %config and %def hashes
|
---|
| 1245 | sub loadConfig {
|
---|
[400] | 1246 | my %args = @_;
|
---|
[465] | 1247 | $args{configfile} = '' if !$args{configfile};
|
---|
[128] | 1248 |
|
---|
[465] | 1249 | ##fixme this is *intended* to load a system-default config template, and allow
|
---|
| 1250 | # overriding on a per-tool or per-web-UI-instance basis with a secondary config
|
---|
| 1251 | # file. The "default" config file can't be deleted in the current form.
|
---|
| 1252 |
|
---|
[128] | 1253 | my $deferr = ''; # place to put error from default config file in case we can't find either one
|
---|
| 1254 |
|
---|
[219] | 1255 | my $configroot = "/etc/dnsdb"; ##CFG_LEAF##
|
---|
[465] | 1256 | $configroot = '' if $args{configfile} =~ m|^/|; # allow passed siteconfig to specify an arbitrary absolute path
|
---|
| 1257 | $args{configfile} .= ".conf" if $args{configfile} !~ /\.conf$/;
|
---|
[128] | 1258 | my $defconfig = "$configroot/dnsdb.conf";
|
---|
[465] | 1259 | my $siteconfig = "$configroot/$args{configfile}";
|
---|
[128] | 1260 |
|
---|
| 1261 | # System defaults
|
---|
[465] | 1262 | __cfgload("$defconfig") or $deferr = $errstr;
|
---|
[128] | 1263 |
|
---|
[131] | 1264 | # Per-site-ish settings.
|
---|
[465] | 1265 | if ($args{configfile} ne '.conf') {
|
---|
| 1266 | unless (__cfgload("$siteconfig")) {
|
---|
[131] | 1267 | $errstr = ($deferr ? "Error opening default config file $defconfig: $deferr\n" : '').
|
---|
[128] | 1268 | "Error opening site config file $siteconfig";
|
---|
[131] | 1269 | return;
|
---|
| 1270 | }
|
---|
[128] | 1271 | }
|
---|
| 1272 |
|
---|
[195] | 1273 | # Munge log_failures.
|
---|
| 1274 | if ($config{log_failures} ne '1' && $config{log_failures} ne '0') {
|
---|
| 1275 | # true/false, on/off, yes/no all valid.
|
---|
| 1276 | if ($config{log_failures} =~ /^(?:true|false|on|off|yes|no)$/) {
|
---|
| 1277 | if ($config{log_failures} =~ /(?:true|on|yes)/) {
|
---|
| 1278 | $config{log_failures} = 1;
|
---|
| 1279 | } else {
|
---|
| 1280 | $config{log_failures} = 0;
|
---|
| 1281 | }
|
---|
| 1282 | } else {
|
---|
| 1283 | $errstr = "Bad log_failures setting $config{log_failures}";
|
---|
| 1284 | $config{log_failures} = 1;
|
---|
| 1285 | # Bad setting shouldn't be fatal.
|
---|
| 1286 | # return 2;
|
---|
| 1287 | }
|
---|
| 1288 | }
|
---|
| 1289 |
|
---|
[128] | 1290 | # All good, clear the error and go home.
|
---|
| 1291 | $errstr = '';
|
---|
| 1292 | return 1;
|
---|
| 1293 | } # end loadConfig()
|
---|
| 1294 |
|
---|
| 1295 |
|
---|
| 1296 | ## DNSDB::__cfgload()
|
---|
| 1297 | # Private sub to parse a config file and load it into %config
|
---|
[465] | 1298 | # Takes a filename
|
---|
[128] | 1299 | sub __cfgload {
|
---|
| 1300 | $errstr = '';
|
---|
| 1301 | my $cfgfile = shift;
|
---|
[131] | 1302 |
|
---|
[128] | 1303 | if (open CFG, "<$cfgfile") {
|
---|
| 1304 | while (<CFG>) {
|
---|
| 1305 | chomp;
|
---|
| 1306 | s/^\s*//;
|
---|
| 1307 | next if /^#/;
|
---|
| 1308 | next if /^$/;
|
---|
| 1309 | # hmm. more complex bits in this file might require [heading] headers, maybe?
|
---|
| 1310 | # $mode = $1 if /^\[(a-z)+]/;
|
---|
| 1311 | # DB connect info
|
---|
| 1312 | $config{dbname} = $1 if /^dbname\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1313 | $config{dbuser} = $1 if /^dbuser\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1314 | $config{dbpass} = $1 if /^dbpass\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1315 | $config{dbhost} = $1 if /^dbhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1316 | # SOA defaults
|
---|
| 1317 | $def{contact} = $1 if /^contact\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1318 | $def{prins} = $1 if /^prins\s*=\s*([a-z0-9_.-]+)/i;
|
---|
[201] | 1319 | $def{soattl} = $1 if /^soattl\s*=\s*(\d+)/i;
|
---|
| 1320 | $def{refresh} = $1 if /^refresh\s*=\s*(\d+)/i;
|
---|
| 1321 | $def{retry} = $1 if /^retry\s*=\s*(\d+)/i;
|
---|
| 1322 | $def{expire} = $1 if /^expire\s*=\s*(\d+)/i;
|
---|
| 1323 | $def{minttl} = $1 if /^minttl\s*=\s*(\d+)/i;
|
---|
| 1324 | $def{ttl} = $1 if /^ttl\s*=\s*(\d+)/i;
|
---|
[128] | 1325 | # Mail settings
|
---|
| 1326 | $config{mailhost} = $1 if /^mailhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
[198] | 1327 | $config{mailnotify} = $1 if /^mailnotify\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
| 1328 | $config{mailsender} = $1 if /^mailsender\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
[128] | 1329 | $config{mailname} = $1 if /^mailname\s*=\s*([a-z0-9\s_.-]+)/i;
|
---|
[195] | 1330 | $config{orgname} = $1 if /^orgname\s*=\s*([a-z0-9\s_.,'-]+)/i;
|
---|
| 1331 | $config{domain} = $1 if /^domain\s*=\s*([a-z0-9_.-]+)/i;
|
---|
[163] | 1332 | # session - note this is fed directly to CGI::Session
|
---|
[216] | 1333 | $config{timeout} = $1 if /^[tT][iI][mM][eE][oO][uU][tT]\s*=\s*(\d+[smhdwMy]?)/;
|
---|
| 1334 | $config{sessiondir} = $1 if m{^sessiondir\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
[201] | 1335 | # misc
|
---|
[195] | 1336 | $config{log_failures} = $1 if /^log_failures\s*=\s*([a-z01]+)/i;
|
---|
[201] | 1337 | $config{perpage} = $1 if /^perpage\s*=\s*(\d+)/i;
|
---|
[368] | 1338 | $config{exportcache} = $1 if m{^exportcache\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
[400] | 1339 | # RPC options
|
---|
[465] | 1340 | $config{rpcmode} = $1 if /^rpc_mode\s*=\s*(socket|HTTP|XMLRPC)\s*$/i;
|
---|
[490] | 1341 | $config{maxfcgi} = $1 if /^max_fcgi_requests\s*=\s*(\d+)\s*$/i;
|
---|
[465] | 1342 | if (my ($tmp) = /^rpc_iplist\s*=\s*(.+)/i) {
|
---|
| 1343 | my @ips = split /[,\s]+/, $tmp;
|
---|
| 1344 | my $rpcsys = shift @ips;
|
---|
| 1345 | push @{$config{rpcacl}{$rpcsys}}, @ips;
|
---|
[400] | 1346 | }
|
---|
[128] | 1347 | }
|
---|
| 1348 | close CFG;
|
---|
| 1349 | } else {
|
---|
| 1350 | $errstr = $!;
|
---|
| 1351 | return;
|
---|
| 1352 | }
|
---|
| 1353 | return 1;
|
---|
| 1354 | } # end __cfgload()
|
---|
| 1355 |
|
---|
| 1356 |
|
---|
[2] | 1357 | ## DNSDB::connectDB()
|
---|
| 1358 | # Creates connection to DNS database.
|
---|
| 1359 | # Requires the database name, username, and password.
|
---|
[465] | 1360 | # Returns a handle to the db or undef on failure.
|
---|
[2] | 1361 | # Set up for a PostgreSQL db; could be any transactional DBMS with the
|
---|
| 1362 | # right changes.
|
---|
[465] | 1363 | # Called by new(); not intended to be called publicly.
|
---|
[2] | 1364 | sub connectDB {
|
---|
| 1365 | $errstr = '';
|
---|
[15] | 1366 | my $dbname = shift;
|
---|
| 1367 | my $user = shift;
|
---|
| 1368 | my $pass = shift;
|
---|
[2] | 1369 | my $dbh;
|
---|
| 1370 | my $DSN = "DBI:Pg:dbname=$dbname";
|
---|
| 1371 |
|
---|
| 1372 | my $host = shift;
|
---|
| 1373 | $DSN .= ";host=$host" if $host;
|
---|
| 1374 |
|
---|
| 1375 | # Note that we want to autocommit by default, and we will turn it off locally as necessary.
|
---|
| 1376 | # We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
|
---|
| 1377 | $dbh = DBI->connect($DSN, $user, $pass, {
|
---|
| 1378 | AutoCommit => 1,
|
---|
| 1379 | PrintError => 0
|
---|
[465] | 1380 | });
|
---|
| 1381 | if (!$dbh) {
|
---|
| 1382 | $errstr = $DBI::errstr;
|
---|
| 1383 | return;
|
---|
| 1384 | }
|
---|
| 1385 | #) if(!$dbh);
|
---|
[2] | 1386 |
|
---|
[465] | 1387 | local $dbh->{RaiseError} = 1;
|
---|
| 1388 |
|
---|
| 1389 | eval {
|
---|
[212] | 1390 | ##fixme: initialize the DB if we can't find the table (since, by definition, there's
|
---|
| 1391 | # nothing there if we can't select from it...)
|
---|
[465] | 1392 | my $tblsth = $dbh->prepare("SELECT count(*) FROM pg_catalog.pg_class WHERE relkind='r' AND relname=?");
|
---|
| 1393 | my ($tblcount) = $dbh->selectrow_array($tblsth, undef, ('misc'));
|
---|
| 1394 | # return (undef,$DBI::errstr) if $dbh->err;
|
---|
[212] | 1395 |
|
---|
| 1396 | #if ($tblcount == 0) {
|
---|
| 1397 | # # create tables one at a time, checking for each.
|
---|
| 1398 | # return (undef, "check table misc missing");
|
---|
| 1399 | #}
|
---|
| 1400 |
|
---|
| 1401 | # Return here if we can't select.
|
---|
| 1402 | # This should retrieve the dbversion key.
|
---|
[465] | 1403 | my $sth = $dbh->prepare("SELECT key,value FROM misc WHERE misc_id=1");
|
---|
| 1404 | $sth->execute();
|
---|
| 1405 | # return (undef,$DBI::errstr) if ($sth->err);
|
---|
[2] | 1406 |
|
---|
[212] | 1407 | ##fixme: do stuff to the DB on version mismatch
|
---|
| 1408 | # x.y series should upgrade on $DNSDB::VERSION > misc(key=>version)
|
---|
| 1409 | # DB should be downward-compatible; column defaults should give sane (if possibly
|
---|
| 1410 | # useless-and-needs-help) values in columns an older software stack doesn't know about.
|
---|
| 1411 |
|
---|
[2] | 1412 | # See if the select returned anything (or null data). This should
|
---|
| 1413 | # succeed if the select executed, but...
|
---|
[465] | 1414 | $sth->fetchrow();
|
---|
| 1415 | # return (undef,$DBI::errstr) if ($sth->err);
|
---|
[2] | 1416 |
|
---|
[465] | 1417 | $sth->finish;
|
---|
[2] | 1418 |
|
---|
[465] | 1419 | }; # wrapped DB checks
|
---|
| 1420 | if ($@) {
|
---|
| 1421 | $errstr = $@;
|
---|
| 1422 | return;
|
---|
| 1423 | }
|
---|
| 1424 |
|
---|
[2] | 1425 | # If we get here, we should be OK.
|
---|
[465] | 1426 | return $dbh;
|
---|
[2] | 1427 | } # end connectDB
|
---|
| 1428 |
|
---|
| 1429 |
|
---|
| 1430 | ## DNSDB::finish()
|
---|
| 1431 | # Cleans up after database handles and so on.
|
---|
| 1432 | # Requires a database handle
|
---|
| 1433 | sub finish {
|
---|
[465] | 1434 | my $self = shift;
|
---|
| 1435 | $self->{dbh}->disconnect;
|
---|
[2] | 1436 | } # end finish
|
---|
| 1437 |
|
---|
| 1438 |
|
---|
| 1439 | ## DNSDB::initGlobals()
|
---|
| 1440 | # Initialize global variables
|
---|
| 1441 | # NB: this does NOT include web-specific session variables!
|
---|
| 1442 | sub initGlobals {
|
---|
[465] | 1443 | my $self = shift;
|
---|
| 1444 | my $dbh = $self->{dbh};
|
---|
[2] | 1445 |
|
---|
[208] | 1446 | # load record types from database
|
---|
[228] | 1447 | my $sth = $dbh->prepare("SELECT val,name,stdflag FROM rectypes");
|
---|
[2] | 1448 | $sth->execute;
|
---|
[228] | 1449 | while (my ($recval,$recname,$stdflag) = $sth->fetchrow_array()) {
|
---|
[2] | 1450 | $typemap{$recval} = $recname;
|
---|
| 1451 | $reverse_typemap{$recname} = $recval;
|
---|
[228] | 1452 | # now we fill the record validation function hash
|
---|
| 1453 | if ($stdflag < 5) {
|
---|
| 1454 | my $fn = "_validate_$recval";
|
---|
| 1455 | $validators{$recval} = \&$fn;
|
---|
| 1456 | } else {
|
---|
| 1457 | my $fn = "sub { return ('FAIL','Type $recval ($recname) not supported'); }";
|
---|
| 1458 | $validators{$recval} = eval $fn;
|
---|
| 1459 | }
|
---|
[2] | 1460 | }
|
---|
| 1461 | } # end initGlobals
|
---|
| 1462 |
|
---|
| 1463 |
|
---|
[401] | 1464 | ## DNSDB::initRPC()
|
---|
[469] | 1465 | # Takes a remote username and remote fullname.
|
---|
[401] | 1466 | # Sets up the RPC logging-pseudouser if needed.
|
---|
| 1467 | # Sets the %userdata hash for logging.
|
---|
| 1468 | # Returns undef on failure
|
---|
| 1469 | sub initRPC {
|
---|
[469] | 1470 | my $self = shift;
|
---|
| 1471 | my $dbh = $self->{dbh};
|
---|
[401] | 1472 | my %args = @_;
|
---|
| 1473 |
|
---|
| 1474 | return if !$args{username};
|
---|
| 1475 | return if !$args{fullname};
|
---|
| 1476 |
|
---|
[406] | 1477 | $args{username} = "$args{username}/$args{rpcsys}";
|
---|
| 1478 |
|
---|
| 1479 | my $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
|
---|
[404] | 1480 | " FROM users WHERE username=?", undef, ($args{username}) );
|
---|
[406] | 1481 | if (!$tmpuser) {
|
---|
[401] | 1482 | $dbh->do("INSERT INTO users (username,password,firstname,type) VALUES (?,'RPC',?,'R')", undef,
|
---|
| 1483 | ($args{username}, $args{fullname}) );
|
---|
[406] | 1484 | $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
|
---|
[404] | 1485 | " FROM users WHERE username=?", undef, ($args{username}) );
|
---|
[401] | 1486 | }
|
---|
[488] | 1487 | $tmpuser->{lastname} = '' if !$tmpuser->{lastname};
|
---|
| 1488 | $self->{loguserid} = $tmpuser->{userid};
|
---|
| 1489 | $self->{logusername} = $tmpuser->{username};
|
---|
| 1490 | $self->{logfullname} = "$tmpuser->{firstname} $tmpuser->{lastname} ($args{rpcsys})";
|
---|
[406] | 1491 | return 1 if $tmpuser;
|
---|
[401] | 1492 | } # end initRPC()
|
---|
| 1493 |
|
---|
| 1494 |
|
---|
[278] | 1495 | ## DNSDB::login()
|
---|
| 1496 | # Takes a database handle, username and password
|
---|
[316] | 1497 | # Returns a userdata hash (UID, GID, username, fullname parts) if username exists,
|
---|
| 1498 | # password matches the one on file, and account is not disabled
|
---|
[278] | 1499 | # Returns undef otherwise
|
---|
| 1500 | sub login {
|
---|
[469] | 1501 | my $self = shift;
|
---|
| 1502 | my $dbh = $self->{dbh};
|
---|
[278] | 1503 | my $user = shift;
|
---|
| 1504 | my $pass = shift;
|
---|
| 1505 |
|
---|
[316] | 1506 | my $userinfo = $dbh->selectrow_hashref("SELECT user_id,group_id,password,firstname,lastname,status".
|
---|
| 1507 | " FROM users WHERE username=?",
|
---|
[279] | 1508 | undef, ($user) );
|
---|
| 1509 | return if !$userinfo;
|
---|
[316] | 1510 | return if !$userinfo->{status};
|
---|
[278] | 1511 |
|
---|
[279] | 1512 | if ($userinfo->{password} =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
|
---|
[278] | 1513 | # native passwords (crypt-md5)
|
---|
[279] | 1514 | return if $userinfo->{password} ne unix_md5_crypt($pass,$1);
|
---|
| 1515 | } elsif ($userinfo->{password} =~ /^[0-9a-f]{32}$/) {
|
---|
[278] | 1516 | # VegaDNS import (hex-coded MD5)
|
---|
[279] | 1517 | return if $userinfo->{password} ne md5_hex($pass);
|
---|
[278] | 1518 | } else {
|
---|
| 1519 | # plaintext (convenient now and then)
|
---|
[279] | 1520 | return if $userinfo->{password} ne $pass;
|
---|
[278] | 1521 | }
|
---|
| 1522 |
|
---|
[279] | 1523 | return $userinfo;
|
---|
[278] | 1524 | } # end login()
|
---|
| 1525 |
|
---|
| 1526 |
|
---|
[279] | 1527 | ## DNSDB::initActionLog()
|
---|
| 1528 | # Set up action logging. Takes a database handle and user ID
|
---|
| 1529 | # Sets some internal globals and Does The Right Thing to set up a logging channel.
|
---|
| 1530 | # This sets up _log() to spew out log entries to the defined channel without worrying
|
---|
| 1531 | # about having to open a file or a syslog channel
|
---|
| 1532 | ##fixme Need to call _initActionLog_blah() for various logging channels, configured
|
---|
| 1533 | # via dnsdb.conf, in $config{log_channel} or something
|
---|
| 1534 | # See https://secure.deepnet.cx/trac/dnsadmin/ticket/21
|
---|
| 1535 | sub initActionLog {
|
---|
[469] | 1536 | my $self = shift;
|
---|
| 1537 | my $dbh = $self->{dbh};
|
---|
[279] | 1538 | my $uid = shift;
|
---|
| 1539 |
|
---|
| 1540 | return if !$uid;
|
---|
| 1541 |
|
---|
| 1542 | # snag user info for logging. there's got to be a way to not have to pass this back
|
---|
| 1543 | # and forth from a caller, but web usage means no persistence we can rely on from
|
---|
| 1544 | # the server side.
|
---|
| 1545 | my ($username,$fullname) = $dbh->selectrow_array("SELECT username, firstname || ' ' || lastname".
|
---|
| 1546 | " FROM users WHERE user_id=?", undef, ($uid));
|
---|
| 1547 | ##fixme: errors are unpossible!
|
---|
| 1548 |
|
---|
[488] | 1549 | $self->{logusername} = $username;
|
---|
| 1550 | $self->{loguserid} = $uid;
|
---|
| 1551 | $self->{logfullname} = $fullname;
|
---|
[279] | 1552 |
|
---|
| 1553 | # convert to real check once we have other logging channels
|
---|
| 1554 | # if ($config{log_channel} eq 'sql') {
|
---|
| 1555 | # Open Log, Sez Me!
|
---|
| 1556 | # }
|
---|
| 1557 |
|
---|
| 1558 | } # end initActionLog
|
---|
| 1559 |
|
---|
| 1560 |
|
---|
[65] | 1561 | ## DNSDB::getPermissions()
|
---|
| 1562 | # Get permissions from DB
|
---|
| 1563 | # Requires DB handle, group or user flag, ID, and hashref.
|
---|
| 1564 | sub getPermissions {
|
---|
[469] | 1565 | my $self = shift;
|
---|
| 1566 | my $dbh = $self->{dbh};
|
---|
| 1567 |
|
---|
[65] | 1568 | my $type = shift;
|
---|
| 1569 | my $id = shift;
|
---|
| 1570 | my $hash = shift;
|
---|
| 1571 |
|
---|
| 1572 | my $sql = qq(
|
---|
| 1573 | SELECT
|
---|
| 1574 | p.admin,p.self_edit,
|
---|
| 1575 | p.group_create,p.group_edit,p.group_delete,
|
---|
| 1576 | p.user_create,p.user_edit,p.user_delete,
|
---|
| 1577 | p.domain_create,p.domain_edit,p.domain_delete,
|
---|
[387] | 1578 | p.record_create,p.record_edit,p.record_delete,p.record_locchg,
|
---|
[382] | 1579 | p.location_create,p.location_edit,p.location_delete,p.location_view
|
---|
[65] | 1580 | FROM permissions p
|
---|
| 1581 | );
|
---|
| 1582 | if ($type eq 'group') {
|
---|
| 1583 | $sql .= qq(
|
---|
| 1584 | JOIN groups g ON g.permission_id=p.permission_id
|
---|
| 1585 | WHERE g.group_id=?
|
---|
| 1586 | );
|
---|
| 1587 | } else {
|
---|
| 1588 | $sql .= qq(
|
---|
| 1589 | JOIN users u ON u.permission_id=p.permission_id
|
---|
| 1590 | WHERE u.user_id=?
|
---|
| 1591 | );
|
---|
| 1592 | }
|
---|
| 1593 |
|
---|
| 1594 | my $sth = $dbh->prepare($sql);
|
---|
| 1595 |
|
---|
| 1596 | $sth->execute($id) or die "argh: ".$sth->errstr;
|
---|
| 1597 |
|
---|
| 1598 | # my $permref = $sth->fetchrow_hashref;
|
---|
| 1599 | # return $permref;
|
---|
| 1600 | # $hash = $permref;
|
---|
| 1601 | # Eww. Need to learn how to forcibly drop a hashref onto an existing hash.
|
---|
| 1602 | ($hash->{admin},$hash->{self_edit},
|
---|
| 1603 | $hash->{group_create},$hash->{group_edit},$hash->{group_delete},
|
---|
| 1604 | $hash->{user_create},$hash->{user_edit},$hash->{user_delete},
|
---|
| 1605 | $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete},
|
---|
[387] | 1606 | $hash->{record_create},$hash->{record_edit},$hash->{record_delete},$hash->{record_locchg},
|
---|
[382] | 1607 | $hash->{location_create},$hash->{location_edit},$hash->{location_delete},$hash->{location_view}
|
---|
| 1608 | ) = $sth->fetchrow_array;
|
---|
[65] | 1609 |
|
---|
| 1610 | } # end getPermissions()
|
---|
| 1611 |
|
---|
| 1612 |
|
---|
| 1613 | ## DNSDB::changePermissions()
|
---|
| 1614 | # Update an ACL entry
|
---|
| 1615 | # Takes a db handle, type, owner-id, and hashref for the changed permissions.
|
---|
| 1616 | sub changePermissions {
|
---|
[474] | 1617 | my $self = shift;
|
---|
| 1618 | my $dbh = $self->{dbh};
|
---|
[65] | 1619 | my $type = shift;
|
---|
| 1620 | my $id = shift;
|
---|
| 1621 | my $newperms = shift;
|
---|
[87] | 1622 | my $inherit = shift || 0;
|
---|
[65] | 1623 |
|
---|
[294] | 1624 | my $resultmsg = '';
|
---|
[66] | 1625 |
|
---|
[87] | 1626 | # see if we're switching from inherited to custom. for bonus points,
|
---|
| 1627 | # snag the permid and parent permid anyway, since we'll need the permid
|
---|
| 1628 | # to set/alter custom perms, and both if we're switching from custom to
|
---|
| 1629 | # inherited.
|
---|
[294] | 1630 | my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id,".
|
---|
| 1631 | ($type eq 'user' ? 'u.group_id,u.username' : 'u.parent_group_id,u.group_name').
|
---|
[65] | 1632 | " FROM ".($type eq 'user' ? 'users' : 'groups')." u ".
|
---|
[66] | 1633 | " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ".
|
---|
[65] | 1634 | " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?");
|
---|
| 1635 | $sth->execute($id);
|
---|
| 1636 |
|
---|
[294] | 1637 | my ($wasinherited,$permid,$parpermid,$parid,$name) = $sth->fetchrow_array;
|
---|
[66] | 1638 |
|
---|
[78] | 1639 | # hack phtoui
|
---|
| 1640 | # group id 1 is "special" in that it's it's own parent (err... possibly.)
|
---|
| 1641 | # may make its parent id 0 which doesn't exist, and as a bonus is Perl-false.
|
---|
| 1642 | $wasinherited = 0 if ($type eq 'group' && $id == 1);
|
---|
| 1643 |
|
---|
[66] | 1644 | local $dbh->{AutoCommit} = 0;
|
---|
| 1645 | local $dbh->{RaiseError} = 1;
|
---|
| 1646 |
|
---|
| 1647 | # Wrap all the SQL in a transaction
|
---|
| 1648 | eval {
|
---|
[87] | 1649 | if ($inherit) {
|
---|
| 1650 |
|
---|
| 1651 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ".
|
---|
| 1652 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) );
|
---|
| 1653 | $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) );
|
---|
| 1654 |
|
---|
| 1655 | } else {
|
---|
| 1656 |
|
---|
| 1657 | if ($wasinherited) { # munge new permission entry in if we're switching from inherited perms
|
---|
[66] | 1658 | ##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users
|
---|
[87] | 1659 | # ... if'n'when we have groups with fully inherited permissions.
|
---|
| 1660 | # SQL is coo
|
---|
| 1661 | $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ".
|
---|
| 1662 | "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) );
|
---|
| 1663 | ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ".
|
---|
| 1664 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) );
|
---|
| 1665 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ".
|
---|
| 1666 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) );
|
---|
[66] | 1667 | }
|
---|
[78] | 1668 |
|
---|
[87] | 1669 | # and now set the permissions we were passed
|
---|
| 1670 | foreach (@permtypes) {
|
---|
| 1671 | if (defined ($newperms->{$_})) {
|
---|
| 1672 | $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) );
|
---|
| 1673 | }
|
---|
| 1674 | }
|
---|
| 1675 |
|
---|
| 1676 | } # (inherited->)? custom
|
---|
| 1677 |
|
---|
[294] | 1678 | if ($type eq 'user') {
|
---|
| 1679 | $resultmsg = "Updated permissions for user $name";
|
---|
| 1680 | } else {
|
---|
| 1681 | $resultmsg = "Updated default permissions for group $name";
|
---|
| 1682 | }
|
---|
[487] | 1683 | $self->_log(group_id => ($type eq 'user' ? $parid : $id), entry => $resultmsg);
|
---|
[66] | 1684 | $dbh->commit;
|
---|
| 1685 | }; # end eval
|
---|
| 1686 | if ($@) {
|
---|
| 1687 | my $msg = $@;
|
---|
| 1688 | eval { $dbh->rollback; };
|
---|
[294] | 1689 | return ('FAIL',"Error changing permissions: $msg");
|
---|
[66] | 1690 | }
|
---|
| 1691 |
|
---|
[294] | 1692 | return ('OK',$resultmsg);
|
---|
[65] | 1693 | } # end changePermissions()
|
---|
| 1694 |
|
---|
| 1695 |
|
---|
[67] | 1696 | ## DNSDB::comparePermissions()
|
---|
| 1697 | # Compare two permission hashes
|
---|
| 1698 | # Returns '>', '<', '=', '!'
|
---|
| 1699 | sub comparePermissions {
|
---|
| 1700 | my $p1 = shift;
|
---|
| 1701 | my $p2 = shift;
|
---|
| 1702 |
|
---|
| 1703 | my $retval = '='; # assume equality until proven otherwise
|
---|
| 1704 |
|
---|
| 1705 | no warnings "uninitialized";
|
---|
| 1706 |
|
---|
| 1707 | foreach (@permtypes) {
|
---|
| 1708 | next if $p1->{$_} == $p2->{$_}; # equal is good
|
---|
| 1709 | if ($p1->{$_} && !$p2->{$_}) {
|
---|
| 1710 | if ($retval eq '<') { # if we've already found an unequal pair where
|
---|
| 1711 | $retval = '!'; # $p2 has more access, and we now find a pair
|
---|
| 1712 | last; # where $p1 has more access, the overall access
|
---|
| 1713 | } # is neither greater or lesser, it's unequal.
|
---|
| 1714 | $retval = '>';
|
---|
| 1715 | }
|
---|
| 1716 | if (!$p1->{$_} && $p2->{$_}) {
|
---|
| 1717 | if ($retval eq '>') { # if we've already found an unequal pair where
|
---|
| 1718 | $retval = '!'; # $p1 has more access, and we now find a pair
|
---|
| 1719 | last; # where $p2 has more access, the overall access
|
---|
| 1720 | } # is neither greater or lesser, it's unequal.
|
---|
| 1721 | $retval = '<';
|
---|
| 1722 | }
|
---|
| 1723 | }
|
---|
| 1724 | return $retval;
|
---|
| 1725 | } # end comparePermissions()
|
---|
| 1726 |
|
---|
| 1727 |
|
---|
[112] | 1728 | ## DNSDB::changeGroup()
|
---|
| 1729 | # Change group ID of an entity
|
---|
| 1730 | # Takes a database handle, entity type, entity ID, and new group ID
|
---|
| 1731 | sub changeGroup {
|
---|
[476] | 1732 | my $self = shift;
|
---|
| 1733 | my $dbh = $self->{dbh};
|
---|
[112] | 1734 | my $type = shift;
|
---|
| 1735 | my $id = shift;
|
---|
| 1736 | my $newgrp = shift;
|
---|
| 1737 |
|
---|
| 1738 | ##fixme: fail on not enough args
|
---|
| 1739 | #return ('FAIL', "Missing
|
---|
| 1740 |
|
---|
[295] | 1741 | return ('FAIL', "Can't change the group of a $type")
|
---|
| 1742 | unless grep /^$type$/, ('domain','revzone','user','group'); # could be extended for defrecs?
|
---|
| 1743 |
|
---|
| 1744 | # Collect some names for logging and messages
|
---|
| 1745 | my $entname;
|
---|
[112] | 1746 | if ($type eq 'domain') {
|
---|
[473] | 1747 | $entname = $self->domainName($id);
|
---|
[295] | 1748 | } elsif ($type eq 'revzone') {
|
---|
[473] | 1749 | $entname = $self->revName($id);
|
---|
[112] | 1750 | } elsif ($type eq 'user') {
|
---|
[473] | 1751 | $entname = $self->userFullName($id, '%u');
|
---|
[112] | 1752 | } elsif ($type eq 'group') {
|
---|
[473] | 1753 | $entname = $self->groupName($id);
|
---|
[112] | 1754 | }
|
---|
[295] | 1755 |
|
---|
| 1756 | my ($oldgid) = $dbh->selectrow_array("SELECT group_id FROM $par_tbl{$type} WHERE $id_col{$type}=?",
|
---|
| 1757 | undef, ($id));
|
---|
[473] | 1758 | my $oldgname = $self->groupName($oldgid);
|
---|
| 1759 | my $newgname = $self->groupName($newgrp);
|
---|
[295] | 1760 |
|
---|
| 1761 | return ('FAIL', "Can't move things into a group that doesn't exist") if !$newgname;
|
---|
| 1762 |
|
---|
| 1763 | return ('WARN', "Nothing to do, new group is the same as the old group") if $oldgid == $newgrp;
|
---|
| 1764 |
|
---|
| 1765 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 1766 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 1767 | local $dbh->{AutoCommit} = 0;
|
---|
| 1768 | local $dbh->{RaiseError} = 1;
|
---|
| 1769 |
|
---|
| 1770 | eval {
|
---|
| 1771 | $dbh->do("UPDATE $par_tbl{$type} SET group_id=? WHERE $id_col{$type}=?", undef, ($newgrp, $id));
|
---|
| 1772 | # Log the change in both the old and new groups
|
---|
[487] | 1773 | $self->_log(group_id => $oldgid, entry => "Moved $type $entname from $oldgname to $newgname");
|
---|
| 1774 | $self->_log(group_id => $newgrp, entry => "Moved $type $entname from $oldgname to $newgname");
|
---|
[295] | 1775 | $dbh->commit;
|
---|
| 1776 | };
|
---|
| 1777 | if ($@) {
|
---|
| 1778 | my $msg = $@;
|
---|
| 1779 | eval { $dbh->rollback; };
|
---|
| 1780 | if ($config{log_failures}) {
|
---|
[487] | 1781 | $self->_log(group_id => $oldgid, entry => "Error moving $type $entname to $newgname: $msg");
|
---|
[295] | 1782 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 1783 | }
|
---|
| 1784 | return ('FAIL',"Error moving $type $entname to $newgname: $msg");
|
---|
| 1785 | }
|
---|
| 1786 |
|
---|
| 1787 | return ('OK',"Moved $type $entname from $oldgname to $newgname");
|
---|
[112] | 1788 | } # end changeGroup()
|
---|
| 1789 |
|
---|
| 1790 |
|
---|
[2] | 1791 | ##
|
---|
| 1792 | ## Processing subs
|
---|
| 1793 | ##
|
---|
| 1794 |
|
---|
| 1795 | ## DNSDB::addDomain()
|
---|
| 1796 | # Add a domain
|
---|
[190] | 1797 | # Takes a database handle, domain name, numeric group, boolean(ish) state (active/inactive),
|
---|
| 1798 | # and user info hash (for logging).
|
---|
[2] | 1799 | # Returns a status code and message
|
---|
| 1800 | sub addDomain {
|
---|
| 1801 | $errstr = '';
|
---|
[477] | 1802 | my $self = shift;
|
---|
| 1803 | my $dbh = $self->{dbh};
|
---|
[2] | 1804 | return ('FAIL',"Need database handle") if !$dbh;
|
---|
| 1805 | my $domain = shift;
|
---|
[91] | 1806 | return ('FAIL',"Domain must not be blank") if !$domain;
|
---|
[2] | 1807 | my $group = shift;
|
---|
| 1808 | return ('FAIL',"Need group") if !defined($group);
|
---|
| 1809 | my $state = shift;
|
---|
| 1810 | return ('FAIL',"Need domain status") if !defined($state);
|
---|
| 1811 |
|
---|
[116] | 1812 | $state = 1 if $state =~ /^active$/;
|
---|
| 1813 | $state = 1 if $state =~ /^on$/;
|
---|
| 1814 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 1815 | $state = 0 if $state =~ /^off$/;
|
---|
| 1816 |
|
---|
| 1817 | return ('FAIL',"Invalid domain status") if $state !~ /^\d+$/;
|
---|
| 1818 |
|
---|
[190] | 1819 | return ('FAIL', "Invalid characters in domain") if $domain !~ /^[a-zA-Z0-9_.-]+$/;
|
---|
| 1820 |
|
---|
[349] | 1821 | my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)");
|
---|
[3] | 1822 | my $dom_id;
|
---|
| 1823 |
|
---|
[38] | 1824 | # quick check to start to see if we've already got one
|
---|
| 1825 | $sth->execute($domain);
|
---|
| 1826 | ($dom_id) = $sth->fetchrow_array;
|
---|
| 1827 |
|
---|
| 1828 | return ('FAIL', "Domain already exists") if $dom_id;
|
---|
| 1829 |
|
---|
[2] | 1830 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 1831 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 1832 | local $dbh->{AutoCommit} = 0;
|
---|
| 1833 | local $dbh->{RaiseError} = 1;
|
---|
| 1834 |
|
---|
| 1835 | # Wrap all the SQL in a transaction
|
---|
| 1836 | eval {
|
---|
| 1837 | # insert the domain...
|
---|
[190] | 1838 | $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef, ($domain, $group, $state));
|
---|
[2] | 1839 |
|
---|
| 1840 | # get the ID...
|
---|
[349] | 1841 | ($dom_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
| 1842 | undef, ($domain));
|
---|
[2] | 1843 |
|
---|
[487] | 1844 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
| 1845 | entry => "Added ".($state ? 'active' : 'inactive')." domain $domain");
|
---|
[190] | 1846 |
|
---|
[2] | 1847 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
[190] | 1848 | my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
| 1849 | my $sth_in = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,distance,weight,port,ttl)".
|
---|
| 1850 | " VALUES ($dom_id,?,?,?,?,?,?,?)");
|
---|
| 1851 | $sth->execute($group);
|
---|
[3] | 1852 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $sth->fetchrow_array()) {
|
---|
[2] | 1853 | $host =~ s/DOMAIN/$domain/g;
|
---|
[37] | 1854 | $val =~ s/DOMAIN/$domain/g;
|
---|
[3] | 1855 | $sth_in->execute($host,$type,$val,$dist,$weight,$port,$ttl);
|
---|
[190] | 1856 | if ($typemap{$type} eq 'SOA') {
|
---|
| 1857 | my @tmp1 = split /:/, $host;
|
---|
| 1858 | my @tmp2 = split /:/, $val;
|
---|
[487] | 1859 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
[284] | 1860 | entry => "[new $domain] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
[487] | 1861 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl");
|
---|
[190] | 1862 | } else {
|
---|
| 1863 | my $logentry = "[new $domain] Added record '$host $typemap{$type}";
|
---|
| 1864 | $logentry .= " [distance $dist]" if $typemap{$type} eq 'MX';
|
---|
| 1865 | $logentry .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$type} eq 'SRV';
|
---|
[487] | 1866 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
| 1867 | entry => $logentry." $val', TTL $ttl");
|
---|
[190] | 1868 | }
|
---|
[2] | 1869 | }
|
---|
| 1870 |
|
---|
| 1871 | # once we get here, we should have suceeded.
|
---|
| 1872 | $dbh->commit;
|
---|
| 1873 | }; # end eval
|
---|
| 1874 |
|
---|
| 1875 | if ($@) {
|
---|
| 1876 | my $msg = $@;
|
---|
| 1877 | eval { $dbh->rollback; };
|
---|
[487] | 1878 | $self->_log(group_id => $group, entry => "Failed adding domain $domain ($msg)")
|
---|
[284] | 1879 | if $config{log_failures};
|
---|
| 1880 | $dbh->commit; # since we enabled transactions earlier
|
---|
[193] | 1881 | return ('FAIL',$msg);
|
---|
[2] | 1882 | } else {
|
---|
[3] | 1883 | return ('OK',$dom_id);
|
---|
[2] | 1884 | }
|
---|
| 1885 | } # end addDomain
|
---|
| 1886 |
|
---|
| 1887 |
|
---|
[274] | 1888 | ## DNSDB::delZone()
|
---|
| 1889 | # Delete a forward or reverse zone.
|
---|
| 1890 | # Takes a database handle, zone ID, and forward/reverse flag.
|
---|
[3] | 1891 | # for now, just delete the records, then the domain.
|
---|
| 1892 | # later we may want to archive it in some way instead (status code 2, for example?)
|
---|
[274] | 1893 | sub delZone {
|
---|
[477] | 1894 | my $self = shift;
|
---|
| 1895 | my $dbh = $self->{dbh};
|
---|
[274] | 1896 | my $zoneid = shift;
|
---|
| 1897 | my $revrec = shift;
|
---|
[3] | 1898 |
|
---|
| 1899 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 1900 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 1901 | local $dbh->{AutoCommit} = 0;
|
---|
| 1902 | local $dbh->{RaiseError} = 1;
|
---|
| 1903 |
|
---|
[285] | 1904 | my $msg = '';
|
---|
[23] | 1905 | my $failmsg = '';
|
---|
[473] | 1906 | my $zone = ($revrec eq 'n' ? $self->domainName($zoneid) : $self->revName($zoneid));
|
---|
[23] | 1907 |
|
---|
[343] | 1908 | return ('FAIL', ($revrec eq 'n' ? 'Domain' : 'Reverse zone')." ID $zoneid doesn't exist") if !$zone;
|
---|
| 1909 |
|
---|
[285] | 1910 | # Set this up here since we may use if if $config{log_failures} is enabled
|
---|
| 1911 | my %loghash;
|
---|
| 1912 | $loghash{domain_id} = $zoneid if $revrec eq 'n';
|
---|
| 1913 | $loghash{rdns_id} = $zoneid if $revrec eq 'y';
|
---|
[473] | 1914 | $loghash{group_id} = $self->parentID(
|
---|
| 1915 | id => $zoneid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec);
|
---|
[285] | 1916 |
|
---|
[3] | 1917 | # Wrap all the SQL in a transaction
|
---|
| 1918 | eval {
|
---|
[274] | 1919 | # Disentangle custom record types before removing the
|
---|
| 1920 | # ones that are only in the zone to be deleted
|
---|
| 1921 | if ($revrec eq 'n') {
|
---|
| 1922 | my $sth = $dbh->prepare("UPDATE records SET type=?,domain_id=0 WHERE domain_id=? AND type=?");
|
---|
| 1923 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
| 1924 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65280);
|
---|
| 1925 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65281);
|
---|
| 1926 | $sth->execute(65282, $zoneid, 65283);
|
---|
| 1927 | $sth->execute(65282, $zoneid, 65284);
|
---|
| 1928 | $failmsg = "Failure removing domain records";
|
---|
| 1929 | $dbh->do("DELETE FROM records WHERE domain_id=?", undef, ($zoneid));
|
---|
| 1930 | $failmsg = "Failure removing domain";
|
---|
| 1931 | $dbh->do("DELETE FROM domains WHERE domain_id=?", undef, ($zoneid));
|
---|
| 1932 | } else {
|
---|
| 1933 | my $sth = $dbh->prepare("UPDATE records SET type=?,rdns_id=0 WHERE rdns_id=? AND type=?");
|
---|
| 1934 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
| 1935 | $sth->execute($reverse_typemap{A}, $zoneid, 65280);
|
---|
| 1936 | $sth->execute($reverse_typemap{AAAA}, $zoneid, 65281);
|
---|
| 1937 | # We don't have an "A template" or "AAAA template" type, although it might be useful for symmetry.
|
---|
[345] | 1938 | # $sth->execute(65286?, $zoneid, 65283);
|
---|
| 1939 | # $sth->execute(65286?, $zoneid, 65284);
|
---|
[274] | 1940 | $failmsg = "Failure removing reverse records";
|
---|
| 1941 | $dbh->do("DELETE FROM records WHERE rdns_id=?", undef, ($zoneid));
|
---|
| 1942 | $failmsg = "Failure removing reverse zone";
|
---|
| 1943 | $dbh->do("DELETE FROM revzones WHERE rdns_id=?", undef, ($zoneid));
|
---|
| 1944 | }
|
---|
[3] | 1945 |
|
---|
[285] | 1946 | $msg = "Deleted ".($revrec eq 'n' ? 'domain' : 'reverse zone')." $zone";
|
---|
| 1947 | $loghash{entry} = $msg;
|
---|
[487] | 1948 | $self->_log(%loghash);
|
---|
[285] | 1949 |
|
---|
[3] | 1950 | # once we get here, we should have suceeded.
|
---|
[23] | 1951 | $dbh->commit;
|
---|
[3] | 1952 | }; # end eval
|
---|
| 1953 |
|
---|
| 1954 | if ($@) {
|
---|
[285] | 1955 | $msg = $@;
|
---|
[3] | 1956 | eval { $dbh->rollback; };
|
---|
[295] | 1957 | $loghash{entry} = "Error deleting $zone: $msg ($failmsg)";
|
---|
| 1958 | if ($config{log_failures}) {
|
---|
[487] | 1959 | $self->_log(%loghash);
|
---|
[295] | 1960 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 1961 | }
|
---|
| 1962 | return ('FAIL', $loghash{entry});
|
---|
[3] | 1963 | } else {
|
---|
[295] | 1964 | return ('OK', $msg);
|
---|
[3] | 1965 | }
|
---|
| 1966 |
|
---|
[274] | 1967 | } # end delZone()
|
---|
[3] | 1968 |
|
---|
| 1969 |
|
---|
[2] | 1970 | ## DNSDB::domainName()
|
---|
| 1971 | # Return the domain name based on a domain ID
|
---|
| 1972 | # Takes a database handle and the domain ID
|
---|
| 1973 | # Returns the domain name or undef on failure
|
---|
| 1974 | sub domainName {
|
---|
| 1975 | $errstr = '';
|
---|
[473] | 1976 | my $self = shift;
|
---|
| 1977 | my $dbh = $self->{dbh};
|
---|
[2] | 1978 | my $domid = shift;
|
---|
[91] | 1979 | my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
|
---|
[2] | 1980 | $errstr = $DBI::errstr if !$domname;
|
---|
| 1981 | return $domname if $domname;
|
---|
[91] | 1982 | } # end domainName()
|
---|
[2] | 1983 |
|
---|
| 1984 |
|
---|
[224] | 1985 | ## DNSDB::revName()
|
---|
| 1986 | # Return the reverse zone name based on an rDNS ID
|
---|
| 1987 | # Takes a database handle and the rDNS ID
|
---|
| 1988 | # Returns the reverse zone name or undef on failure
|
---|
| 1989 | sub revName {
|
---|
| 1990 | $errstr = '';
|
---|
[473] | 1991 | my $self = shift;
|
---|
| 1992 | my $dbh = $self->{dbh};
|
---|
[224] | 1993 | my $revid = shift;
|
---|
| 1994 | my ($revname) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id=?", undef, ($revid) );
|
---|
| 1995 | $errstr = $DBI::errstr if !$revname;
|
---|
| 1996 | return $revname if $revname;
|
---|
| 1997 | } # end revName()
|
---|
| 1998 |
|
---|
| 1999 |
|
---|
[91] | 2000 | ## DNSDB::domainID()
|
---|
| 2001 | # Takes a database handle and domain name
|
---|
| 2002 | # Returns the domain ID number
|
---|
| 2003 | sub domainID {
|
---|
| 2004 | $errstr = '';
|
---|
[473] | 2005 | my $self = shift;
|
---|
| 2006 | my $dbh = $self->{dbh};
|
---|
[91] | 2007 | my $domain = shift;
|
---|
[349] | 2008 | my ($domid) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
| 2009 | undef, ($domain) );
|
---|
[91] | 2010 | $errstr = $DBI::errstr if !$domid;
|
---|
| 2011 | return $domid if $domid;
|
---|
| 2012 | } # end domainID()
|
---|
| 2013 |
|
---|
| 2014 |
|
---|
[276] | 2015 | ## DNSDB::revID()
|
---|
| 2016 | # Takes a database handle and reverse zone name
|
---|
| 2017 | # Returns the rDNS ID number
|
---|
| 2018 | sub revID {
|
---|
| 2019 | $errstr = '';
|
---|
[473] | 2020 | my $self = shift;
|
---|
| 2021 | my $dbh = $self->{dbh};
|
---|
[276] | 2022 | my $revzone = shift;
|
---|
| 2023 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ($revzone) );
|
---|
| 2024 | $errstr = $DBI::errstr if !$revid;
|
---|
| 2025 | return $revid if $revid;
|
---|
| 2026 | } # end revID()
|
---|
| 2027 |
|
---|
| 2028 |
|
---|
[260] | 2029 | ## DNSDB::addRDNS
|
---|
| 2030 | # Adds a reverse DNS zone
|
---|
[286] | 2031 | # Takes a database handle, CIDR block, reverse DNS pattern, numeric group,
|
---|
| 2032 | # and boolean(ish) state (active/inactive)
|
---|
[260] | 2033 | # Returns a status code and message
|
---|
| 2034 | sub addRDNS {
|
---|
[477] | 2035 | my $self = shift;
|
---|
| 2036 | my $dbh = $self->{dbh};
|
---|
[260] | 2037 | my $zone = NetAddr::IP->new(shift);
|
---|
[446] | 2038 |
|
---|
[260] | 2039 | return ('FAIL',"Zone name must be a valid CIDR netblock") unless ($zone && $zone->addr !~ /^0/);
|
---|
[270] | 2040 | my $revpatt = shift; # construct a custom (A/AAAA+)? PTR template record
|
---|
[260] | 2041 | my $group = shift;
|
---|
| 2042 | my $state = shift;
|
---|
[446] | 2043 | my $defloc = shift || '';
|
---|
[260] | 2044 |
|
---|
| 2045 | $state = 1 if $state =~ /^active$/;
|
---|
| 2046 | $state = 1 if $state =~ /^on$/;
|
---|
| 2047 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 2048 | $state = 0 if $state =~ /^off$/;
|
---|
| 2049 |
|
---|
| 2050 | return ('FAIL',"Invalid zone status") if $state !~ /^\d+$/;
|
---|
| 2051 |
|
---|
| 2052 | # quick check to start to see if we've already got one
|
---|
[299] | 2053 | my ($rdns_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ("$zone"));
|
---|
[260] | 2054 |
|
---|
| 2055 | return ('FAIL', "Zone already exists") if $rdns_id;
|
---|
| 2056 |
|
---|
| 2057 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2058 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2059 | local $dbh->{AutoCommit} = 0;
|
---|
| 2060 | local $dbh->{RaiseError} = 1;
|
---|
| 2061 |
|
---|
[264] | 2062 | my $warnstr = '';
|
---|
[270] | 2063 | my $defttl = 3600; # 1 hour should be reasonable. And unless things have gone horribly
|
---|
| 2064 | # wrong, we should have a value to override this anyway.
|
---|
[264] | 2065 |
|
---|
[260] | 2066 | # Wrap all the SQL in a transaction
|
---|
| 2067 | eval {
|
---|
[446] | 2068 | # insert the zone...
|
---|
| 2069 | $dbh->do("INSERT INTO revzones (revnet,group_id,status,default_location) VALUES (?,?,?,?)", undef,
|
---|
| 2070 | ($zone, $group, $state, $defloc) );
|
---|
[260] | 2071 |
|
---|
| 2072 | # get the ID...
|
---|
| 2073 | ($rdns_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
| 2074 |
|
---|
[487] | 2075 | $self->_log(rdns_id => $rdns_id, group_id => $group,
|
---|
| 2076 | entry => "Added ".($state ? 'active' : 'inactive')." reverse zone $zone");
|
---|
[260] | 2077 |
|
---|
| 2078 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
| 2079 | my $sth = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
[446] | 2080 | my $sth_in = $dbh->prepare("INSERT INTO records (rdns_id,domain_id,host,type,val,ttl,location)".
|
---|
| 2081 | " VALUES ($rdns_id,?,?,?,?,?,?)");
|
---|
[260] | 2082 | $sth->execute($group);
|
---|
| 2083 | while (my ($host,$type,$val,$ttl) = $sth->fetchrow_array()) {
|
---|
[264] | 2084 | # Silently skip v4/v6 mismatches. This is not an error, this is expected.
|
---|
| 2085 | if ($zone->{isv6}) {
|
---|
| 2086 | next if ($type == 65280 || $type == 65283);
|
---|
| 2087 | } else {
|
---|
| 2088 | next if ($type == 65281 || $type == 65284);
|
---|
| 2089 | }
|
---|
[269] | 2090 |
|
---|
[260] | 2091 | $host =~ s/ADMINDOMAIN/$config{domain}/g;
|
---|
[264] | 2092 |
|
---|
[265] | 2093 | # Check to make sure the IP stubs will fit in the zone. Under most usage failures here should be rare.
|
---|
| 2094 | # On failure, tack a note on to a warning string and continue without adding this record.
|
---|
| 2095 | # While we're at it, we substitute $zone for ZONE in the value.
|
---|
| 2096 | if ($val eq 'ZONE') {
|
---|
[444] | 2097 | # If we've got a pattern, we skip the default record version on (A+)PTR-template types
|
---|
| 2098 | next if $revpatt && ($type == 65282 || $type == 65283);
|
---|
[269] | 2099 | ##fixme? do we care if we have multiple whole-zone templates?
|
---|
[265] | 2100 | $val = $zone->network;
|
---|
| 2101 | } elsif ($val =~ /ZONE/) {
|
---|
| 2102 | my $tmpval = $val;
|
---|
| 2103 | $tmpval =~ s/ZONE//;
|
---|
[269] | 2104 | # Bend the rules and allow single-trailing-number PTR or PTR template records to be inserted
|
---|
| 2105 | # as either v4 or v6. May make this an off-by-default config flag
|
---|
| 2106 | # Note that the origin records that may trigger this **SHOULD** already have ZONE,\d
|
---|
| 2107 | if ($type == 12 || $type == 65282) {
|
---|
| 2108 | $tmpval =~ s/[,.]/::/ if ($tmpval =~ /^[,.]\d+$/ && $zone->{isv6});
|
---|
| 2109 | $tmpval =~ s/[,:]+/./ if ($tmpval =~ /^(?:,|::)\d+$/ && !$zone->{isv6});
|
---|
| 2110 | }
|
---|
[265] | 2111 | my $addr;
|
---|
[471] | 2112 | if ($self->_ipparent('n', 'y', \$tmpval, $rdns_id, \$addr)) {
|
---|
[265] | 2113 | $val = $addr->addr;
|
---|
| 2114 | } else {
|
---|
[269] | 2115 | $warnstr .= "\nDefault record '$val $typemap{$type} $host' doesn't fit in $zone, skipping";
|
---|
[264] | 2116 | next;
|
---|
| 2117 | }
|
---|
| 2118 | }
|
---|
| 2119 |
|
---|
[328] | 2120 | # Substitute $zone for ZONE in the hostname, but only for non-NS records.
|
---|
| 2121 | # NS records get this substitution on the value instead.
|
---|
| 2122 | $host = _ZONE($zone, $host) if $type != 2;
|
---|
[265] | 2123 |
|
---|
[269] | 2124 | # Fill in the forward domain ID if we can find it, otherwise:
|
---|
| 2125 | # Coerce type down to PTR or PTR template if we can't
|
---|
| 2126 | my $domid = 0;
|
---|
| 2127 | if ($type >= 65280) {
|
---|
[471] | 2128 | if (!($domid = $self->_hostparent($host))) {
|
---|
[269] | 2129 | $warnstr .= "\nRecord added as PTR instead of $typemap{$type}; domain not found for $host";
|
---|
| 2130 | $type = $reverse_typemap{PTR};
|
---|
| 2131 | $domid = 0; # just to be explicit.
|
---|
| 2132 | }
|
---|
| 2133 | }
|
---|
| 2134 |
|
---|
[446] | 2135 | $sth_in->execute($domid,$host,$type,$val,$ttl,$defloc);
|
---|
[269] | 2136 |
|
---|
[260] | 2137 | if ($typemap{$type} eq 'SOA') {
|
---|
| 2138 | my @tmp1 = split /:/, $host;
|
---|
| 2139 | my @tmp2 = split /:/, $val;
|
---|
[487] | 2140 | $self->_log(rdns_id => $rdns_id, group_id => $group,
|
---|
[286] | 2141 | entry => "[new $zone] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
[487] | 2142 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl");
|
---|
[270] | 2143 | $defttl = $tmp2[3];
|
---|
[260] | 2144 | } else {
|
---|
[446] | 2145 | my $logentry = "[new $zone] Added record '$host $typemap{$type} $val', TTL $ttl";
|
---|
[480] | 2146 | $logentry .= ", default location ".$self->getLoc($defloc)->{description} if $defloc;
|
---|
[487] | 2147 | $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group, entry => $logentry);
|
---|
[260] | 2148 | }
|
---|
| 2149 | }
|
---|
| 2150 |
|
---|
[270] | 2151 | # Generate record based on provided pattern.
|
---|
| 2152 | if ($revpatt) {
|
---|
| 2153 | my $host;
|
---|
| 2154 | my $type = ($zone->{isv6} ? 65284 : 65283);
|
---|
| 2155 | my $val = $zone->network;
|
---|
[269] | 2156 |
|
---|
[270] | 2157 | # Substitute $zone for ZONE in the hostname.
|
---|
| 2158 | $host = _ZONE($zone, $revpatt);
|
---|
| 2159 |
|
---|
| 2160 | my $domid = 0;
|
---|
[471] | 2161 | if (!($domid = $self->_hostparent($host))) {
|
---|
[270] | 2162 | $warnstr .= "\nDefault pattern added as PTR template instead of $typemap{$type}; domain not found for $host";
|
---|
| 2163 | $type = 65282;
|
---|
| 2164 | $domid = 0; # just to be explicit.
|
---|
| 2165 | }
|
---|
| 2166 |
|
---|
[446] | 2167 | $sth_in->execute($domid,$host,$type,$val,$defttl,$defloc);
|
---|
[286] | 2168 | my $logentry = "[new $zone] Added record '$host $typemap{$type}";
|
---|
[487] | 2169 | $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group,
|
---|
| 2170 | entry => $logentry." $val', TTL $defttl from pattern");
|
---|
[270] | 2171 | }
|
---|
| 2172 |
|
---|
[264] | 2173 | # If there are warnings (presumably about default records skipped for cause) log them
|
---|
[487] | 2174 | $self->_log(rdns_id => $rdns_id, group_id => $group, entry => "Warning(s) adding $zone:$warnstr")
|
---|
[264] | 2175 | if $warnstr;
|
---|
[269] | 2176 |
|
---|
[260] | 2177 | # once we get here, we should have suceeded.
|
---|
| 2178 | $dbh->commit;
|
---|
| 2179 | }; # end eval
|
---|
| 2180 |
|
---|
| 2181 | if ($@) {
|
---|
| 2182 | my $msg = $@;
|
---|
| 2183 | eval { $dbh->rollback; };
|
---|
[487] | 2184 | $self->_log(group_id => $group, entry => "Failed adding reverse zone $zone ($msg)")
|
---|
[286] | 2185 | if $config{log_failures};
|
---|
| 2186 | $dbh->commit; # since we enabled transactions earlier
|
---|
[260] | 2187 | return ('FAIL',$msg);
|
---|
| 2188 | } else {
|
---|
[286] | 2189 | my $retcode = 'OK';
|
---|
| 2190 | if ($warnstr) {
|
---|
| 2191 | $resultstr = $warnstr;
|
---|
| 2192 | $retcode = 'WARN';
|
---|
| 2193 | }
|
---|
| 2194 | return ($retcode, $rdns_id);
|
---|
[260] | 2195 | }
|
---|
| 2196 |
|
---|
| 2197 | } # end addRDNS()
|
---|
| 2198 |
|
---|
| 2199 |
|
---|
[237] | 2200 | ## DNSDB::getZoneCount
|
---|
| 2201 | # Get count of zones in group or groups
|
---|
| 2202 | # Takes a database handle and hash containing:
|
---|
| 2203 | # - the "current" group
|
---|
| 2204 | # - an array of "acceptable" groups
|
---|
| 2205 | # - a flag for forward/reverse zones
|
---|
| 2206 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
| 2207 | # Returns an integer count of the resulting zone list.
|
---|
| 2208 | sub getZoneCount {
|
---|
[477] | 2209 | my $self = shift;
|
---|
| 2210 | my $dbh = $self->{dbh};
|
---|
[237] | 2211 |
|
---|
| 2212 | my %args = @_;
|
---|
| 2213 |
|
---|
| 2214 | my @filterargs;
|
---|
[239] | 2215 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2216 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2217 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
[237] | 2218 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2219 |
|
---|
| 2220 | my $sql;
|
---|
| 2221 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
| 2222 | if ($args{revrec} eq 'n') {
|
---|
| 2223 | $sql = "SELECT count(*) FROM domains".
|
---|
| 2224 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2225 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
| 2226 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
| 2227 | } else {
|
---|
| 2228 | $sql = "SELECT count(*) FROM revzones".
|
---|
| 2229 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2230 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
|
---|
| 2231 | ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2232 | }
|
---|
| 2233 | my ($count) = $dbh->selectrow_array($sql, undef, @filterargs);
|
---|
| 2234 | return $count;
|
---|
| 2235 | } # end getZoneCount()
|
---|
| 2236 |
|
---|
| 2237 |
|
---|
| 2238 | ## DNSDB::getZoneList()
|
---|
| 2239 | # Get a list of zones in the specified group(s)
|
---|
| 2240 | # Takes the same arguments as getZoneCount() above
|
---|
| 2241 | # Returns a reference to an array of hashrefs suitable for feeding to HTML::Template
|
---|
| 2242 | sub getZoneList {
|
---|
[477] | 2243 | my $self = shift;
|
---|
| 2244 | my $dbh = $self->{dbh};
|
---|
[237] | 2245 |
|
---|
| 2246 | my %args = @_;
|
---|
| 2247 |
|
---|
| 2248 | my @zonelist;
|
---|
| 2249 |
|
---|
[475] | 2250 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
[239] | 2251 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[237] | 2252 |
|
---|
| 2253 | my @filterargs;
|
---|
[239] | 2254 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2255 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2256 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
[237] | 2257 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2258 |
|
---|
| 2259 | my $sql;
|
---|
| 2260 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
| 2261 | if ($args{revrec} eq 'n') {
|
---|
[475] | 2262 | $args{sortby} = 'domain' if !$args{sortby} || !grep /^$args{sortby}$/, ('domain','group','status');
|
---|
[237] | 2263 | $sql = "SELECT domain_id,domain,status,groups.group_name AS group FROM domains".
|
---|
| 2264 | " INNER JOIN groups ON domains.group_id=groups.group_id".
|
---|
| 2265 | " WHERE domains.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2266 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
| 2267 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
| 2268 | } else {
|
---|
[239] | 2269 | ##fixme: arguably startwith here is irrelevant. depends on the UI though.
|
---|
[475] | 2270 | $args{sortby} = 'revnet' if !$args{sortby} || !grep /^$args{sortby}$/, ('revnet','group','status');
|
---|
[237] | 2271 | $sql = "SELECT rdns_id,revnet,status,groups.group_name AS group FROM revzones".
|
---|
| 2272 | " INNER JOIN groups ON revzones.group_id=groups.group_id".
|
---|
| 2273 | " WHERE revzones.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2274 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
|
---|
| 2275 | ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2276 | }
|
---|
| 2277 | # A common tail.
|
---|
[239] | 2278 | $sql .= " ORDER BY ".($args{sortby} eq 'group' ? 'groups.group_name' : $args{sortby})." $args{sortorder} ".
|
---|
| 2279 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage}".
|
---|
[237] | 2280 | " OFFSET ".$args{offset}*$config{perpage});
|
---|
[402] | 2281 | my $sth = $dbh->prepare($sql);
|
---|
| 2282 | $sth->execute(@filterargs);
|
---|
| 2283 | my $rownum = 0;
|
---|
[237] | 2284 |
|
---|
[402] | 2285 | while (my @data = $sth->fetchrow_array) {
|
---|
| 2286 | my %row;
|
---|
| 2287 | $row{domain_id} = $data[0];
|
---|
| 2288 | $row{domain} = $data[1];
|
---|
| 2289 | $row{status} = $data[2];
|
---|
| 2290 | $row{group} = $data[3];
|
---|
| 2291 | push @zonelist, \%row;
|
---|
| 2292 | }
|
---|
| 2293 |
|
---|
| 2294 | return \@zonelist;
|
---|
[237] | 2295 | } # end getZoneList()
|
---|
| 2296 |
|
---|
| 2297 |
|
---|
[383] | 2298 | ## DNSDB::getZoneLocation()
|
---|
[387] | 2299 | # Retrieve the default location for a zone.
|
---|
[383] | 2300 | # Takes a database handle, forward/reverse flag, and zone ID
|
---|
| 2301 | sub getZoneLocation {
|
---|
[477] | 2302 | my $self = shift;
|
---|
| 2303 | my $dbh = $self->{dbh};
|
---|
[383] | 2304 | my $revrec = shift;
|
---|
| 2305 | my $zoneid = shift;
|
---|
| 2306 |
|
---|
| 2307 | my ($loc) = $dbh->selectrow_array("SELECT default_location FROM ".
|
---|
| 2308 | ($revrec eq 'n' ? 'domains WHERE domain_id = ?' : 'revzones WHERE rdns_id = ?'),
|
---|
| 2309 | undef, ($zoneid));
|
---|
| 2310 | return $loc;
|
---|
| 2311 | } # end getZoneLocation()
|
---|
| 2312 |
|
---|
| 2313 |
|
---|
[18] | 2314 | ## DNSDB::addGroup()
|
---|
| 2315 | # Add a group
|
---|
[66] | 2316 | # Takes a database handle, group name, parent group, hashref for permissions,
|
---|
[292] | 2317 | # and optional template-vs-cloneme flag for the default records
|
---|
[18] | 2318 | # Returns a status code and message
|
---|
| 2319 | sub addGroup {
|
---|
| 2320 | $errstr = '';
|
---|
[476] | 2321 | my $self = shift;
|
---|
| 2322 | my $dbh = $self->{dbh};
|
---|
[20] | 2323 | my $groupname = shift;
|
---|
| 2324 | my $pargroup = shift;
|
---|
[66] | 2325 | my $permissions = shift;
|
---|
[18] | 2326 |
|
---|
[66] | 2327 | # 0 indicates "custom", hardcoded.
|
---|
[18] | 2328 | # Any other value clones that group's default records, if it exists.
|
---|
[66] | 2329 | my $inherit = shift || 0;
|
---|
| 2330 | ##fixme: need a flag to indicate clone records or <?> ?
|
---|
[18] | 2331 |
|
---|
| 2332 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2333 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2334 | local $dbh->{AutoCommit} = 0;
|
---|
| 2335 | local $dbh->{RaiseError} = 1;
|
---|
| 2336 |
|
---|
[292] | 2337 | my ($group_id) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($groupname));
|
---|
[38] | 2338 |
|
---|
| 2339 | return ('FAIL', "Group already exists") if $group_id;
|
---|
| 2340 |
|
---|
[18] | 2341 | # Wrap all the SQL in a transaction
|
---|
| 2342 | eval {
|
---|
[292] | 2343 | $dbh->do("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)", undef, ($pargroup, $groupname) );
|
---|
[18] | 2344 |
|
---|
[292] | 2345 | my ($groupid) = $dbh->selectrow_array("SELECT currval('groups_group_id_seq')");
|
---|
[18] | 2346 |
|
---|
[292] | 2347 | # We work through the whole set of permissions instead of specifying them so
|
---|
| 2348 | # that when we add a new permission, we don't have to change the code anywhere
|
---|
| 2349 | # that doesn't explicitly deal with that specific permission.
|
---|
| 2350 | my @permvals;
|
---|
| 2351 | foreach (@permtypes) {
|
---|
| 2352 | if (!defined ($permissions->{$_})) {
|
---|
| 2353 | push @permvals, 0;
|
---|
| 2354 | } else {
|
---|
| 2355 | push @permvals, $permissions->{$_};
|
---|
[66] | 2356 | }
|
---|
[292] | 2357 | }
|
---|
| 2358 | $dbh->do("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")",
|
---|
| 2359 | undef, ($groupid, @permvals) );
|
---|
| 2360 | my ($permid) = $dbh->selectrow_array("SELECT currval('permissions_permission_id_seq')");
|
---|
| 2361 | $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
|
---|
[66] | 2362 |
|
---|
[292] | 2363 | # Default records
|
---|
[255] | 2364 | my $sthf = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
|
---|
[20] | 2365 | "VALUES ($groupid,?,?,?,?,?,?,?)");
|
---|
[255] | 2366 | my $sthr = $dbh->prepare("INSERT INTO default_rev_records (group_id,host,type,val,ttl) ".
|
---|
| 2367 | "VALUES ($groupid,?,?,?,?)");
|
---|
[66] | 2368 | if ($inherit) {
|
---|
[87] | 2369 | # Duplicate records from parent. Actually relying on inherited records feels
|
---|
| 2370 | # very fragile, and it would be problematic to roll over at a later time.
|
---|
[18] | 2371 | my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
[87] | 2372 | $sth2->execute($pargroup);
|
---|
[18] | 2373 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
[255] | 2374 | $sthf->execute(@clonedata);
|
---|
[18] | 2375 | }
|
---|
[255] | 2376 | # And now the reverse records
|
---|
[292] | 2377 | $sth2 = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
[255] | 2378 | $sth2->execute($pargroup);
|
---|
| 2379 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
| 2380 | $sthr->execute(@clonedata);
|
---|
| 2381 | }
|
---|
[18] | 2382 | } else {
|
---|
[66] | 2383 | ##fixme: Hardcoding is Bad, mmmmkaaaay?
|
---|
[18] | 2384 | # reasonable basic defaults for SOA, MX, NS, and minimal hosting
|
---|
| 2385 | # could load from a config file, but somewhere along the line we need hardcoded bits.
|
---|
[255] | 2386 | $sthf->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
|
---|
| 2387 | $sthf->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
|
---|
| 2388 | $sthf->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
|
---|
| 2389 | $sthf->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
|
---|
| 2390 | $sthf->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
|
---|
| 2391 | $sthf->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
|
---|
| 2392 | # reasonable basic defaults for generic reverse zone. Same as initial SQL tabledef.
|
---|
| 2393 | $sthr->execute('hostmaster.ADMINDOMAIN:ns1.ADMINDOMAIN', 6, '10800:3600:604800:10800', 86400);
|
---|
| 2394 | $sthr->execute('unused-%r.ADMINDOMAIN', 65283, 'ZONE', 3600);
|
---|
[18] | 2395 | }
|
---|
| 2396 |
|
---|
[487] | 2397 | $self->_log(group_id => $pargroup, entry => "Added group $groupname");
|
---|
[292] | 2398 |
|
---|
[18] | 2399 | # once we get here, we should have suceeded.
|
---|
| 2400 | $dbh->commit;
|
---|
| 2401 | }; # end eval
|
---|
| 2402 |
|
---|
| 2403 | if ($@) {
|
---|
| 2404 | my $msg = $@;
|
---|
| 2405 | eval { $dbh->rollback; };
|
---|
[292] | 2406 | if ($config{log_failures}) {
|
---|
[487] | 2407 | $self->_log(group_id => $pargroup, entry => "Failed to add group $groupname: $msg");
|
---|
[292] | 2408 | $dbh->commit;
|
---|
| 2409 | }
|
---|
[18] | 2410 | return ('FAIL',$msg);
|
---|
| 2411 | }
|
---|
| 2412 |
|
---|
[292] | 2413 | return ('OK','OK');
|
---|
[18] | 2414 | } # end addGroup()
|
---|
| 2415 |
|
---|
| 2416 |
|
---|
[22] | 2417 | ## DNSDB::delGroup()
|
---|
| 2418 | # Delete a group.
|
---|
| 2419 | # Takes a group ID
|
---|
| 2420 | # Returns a status code and message
|
---|
| 2421 | sub delGroup {
|
---|
[476] | 2422 | my $self = shift;
|
---|
| 2423 | my $dbh = $self->{dbh};
|
---|
[22] | 2424 | my $groupid = shift;
|
---|
| 2425 |
|
---|
| 2426 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2427 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2428 | local $dbh->{AutoCommit} = 0;
|
---|
| 2429 | local $dbh->{RaiseError} = 1;
|
---|
| 2430 |
|
---|
| 2431 | ##fixme: locate "knowable" error conditions and deal with them before the eval
|
---|
[23] | 2432 | # ... or inside, whatever.
|
---|
[22] | 2433 | # -> domains still exist in group
|
---|
| 2434 | # -> ...
|
---|
[23] | 2435 | my $failmsg = '';
|
---|
[293] | 2436 | my $resultmsg = '';
|
---|
[22] | 2437 |
|
---|
[293] | 2438 | # collect some pieces for logging and error messages
|
---|
[473] | 2439 | my $groupname = $self->groupName($groupid);
|
---|
| 2440 | my $parid = $self->parentID(id => $groupid, type => 'group');
|
---|
[293] | 2441 |
|
---|
[22] | 2442 | # Wrap all the SQL in a transaction
|
---|
| 2443 | eval {
|
---|
[293] | 2444 | # Check for Things in the group
|
---|
| 2445 | $failmsg = "Can't remove group $groupname";
|
---|
| 2446 | my ($grpcnt) = $dbh->selectrow_array("SELECT count(*) FROM groups WHERE parent_group_id=?", undef, ($groupid));
|
---|
| 2447 | die "$grpcnt groups still in group\n" if $grpcnt;
|
---|
| 2448 | my ($domcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($groupid));
|
---|
[23] | 2449 | die "$domcnt domains still in group\n" if $domcnt;
|
---|
[293] | 2450 | my ($usercnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($groupid));
|
---|
| 2451 | die "$usercnt users still in group\n" if $usercnt;
|
---|
[23] | 2452 |
|
---|
[293] | 2453 | $failmsg = "Failed to delete default records for $groupname";
|
---|
| 2454 | $dbh->do("DELETE from default_records WHERE group_id=?", undef, ($groupid));
|
---|
| 2455 | $failmsg = "Failed to delete default reverse records for $groupname";
|
---|
| 2456 | $dbh->do("DELETE from default_rev_records WHERE group_id=?", undef, ($groupid));
|
---|
| 2457 | $failmsg = "Failed to remove group $groupname";
|
---|
| 2458 | $dbh->do("DELETE from groups WHERE group_id=?", undef, ($groupid));
|
---|
[22] | 2459 |
|
---|
[487] | 2460 | $self->_log(group_id => $parid, entry => "Deleted group $groupname");
|
---|
[293] | 2461 | $resultmsg = "Deleted group $groupname";
|
---|
| 2462 |
|
---|
[22] | 2463 | # once we get here, we should have suceeded.
|
---|
| 2464 | $dbh->commit;
|
---|
| 2465 | }; # end eval
|
---|
| 2466 |
|
---|
| 2467 | if ($@) {
|
---|
| 2468 | my $msg = $@;
|
---|
| 2469 | eval { $dbh->rollback; };
|
---|
[293] | 2470 | if ($config{log_failures}) {
|
---|
[487] | 2471 | $self->_log(group_id => $parid, entry => "$failmsg: $msg");
|
---|
[293] | 2472 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2473 | }
|
---|
[23] | 2474 | return ('FAIL',"$failmsg: $msg");
|
---|
[22] | 2475 | }
|
---|
[293] | 2476 |
|
---|
| 2477 | return ('OK',$resultmsg);
|
---|
[22] | 2478 | } # end delGroup()
|
---|
| 2479 |
|
---|
| 2480 |
|
---|
[19] | 2481 | ## DNSDB::getChildren()
|
---|
| 2482 | # Get a list of all groups whose parent^n is group <n>
|
---|
[24] | 2483 | # Takes a database handle, group ID, reference to an array to put the group IDs in,
|
---|
| 2484 | # and an optional flag to return only immediate children or all children-of-children
|
---|
| 2485 | # default to returning all children
|
---|
[19] | 2486 | # Calls itself
|
---|
| 2487 | sub getChildren {
|
---|
| 2488 | $errstr = '';
|
---|
[476] | 2489 | my $self = shift;
|
---|
| 2490 | my $dbh = $self->{dbh};
|
---|
[20] | 2491 | my $rootgroup = shift;
|
---|
| 2492 | my $groupdest = shift;
|
---|
[24] | 2493 | my $immed = shift || 'all';
|
---|
[19] | 2494 |
|
---|
| 2495 | # special break for default group; otherwise we get stuck.
|
---|
[20] | 2496 | if ($rootgroup == 1) {
|
---|
[19] | 2497 | # by definition, group 1 is the Root Of All Groups
|
---|
[24] | 2498 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
|
---|
[331] | 2499 | ($immed ne 'all' ? " AND parent_group_id=1" : '')." ORDER BY group_name");
|
---|
[19] | 2500 | $sth->execute;
|
---|
| 2501 | while (my @this = $sth->fetchrow_array) {
|
---|
[20] | 2502 | push @$groupdest, @this;
|
---|
[19] | 2503 | }
|
---|
| 2504 | } else {
|
---|
[331] | 2505 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=? ORDER BY group_name");
|
---|
[20] | 2506 | $sth->execute($rootgroup);
|
---|
[19] | 2507 | return if $sth->rows == 0;
|
---|
[20] | 2508 | my @grouplist;
|
---|
| 2509 | while (my ($group) = $sth->fetchrow_array) {
|
---|
| 2510 | push @$groupdest, $group;
|
---|
[476] | 2511 | $self->getChildren($group, $groupdest) if $immed eq 'all';
|
---|
[19] | 2512 | }
|
---|
| 2513 | }
|
---|
| 2514 | } # end getChildren()
|
---|
| 2515 |
|
---|
| 2516 |
|
---|
[20] | 2517 | ## DNSDB::groupName()
|
---|
[17] | 2518 | # Return the group name based on a group ID
|
---|
| 2519 | # Takes a database handle and the group ID
|
---|
| 2520 | # Returns the group name or undef on failure
|
---|
[20] | 2521 | sub groupName {
|
---|
[13] | 2522 | $errstr = '';
|
---|
[473] | 2523 | my $self = shift;
|
---|
| 2524 | my $dbh = $self->{dbh};
|
---|
[20] | 2525 | my $groupid = shift;
|
---|
| 2526 | my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
|
---|
| 2527 | $sth->execute($groupid);
|
---|
| 2528 | my ($groupname) = $sth->fetchrow_array();
|
---|
| 2529 | $errstr = $DBI::errstr if !$groupname;
|
---|
| 2530 | return $groupname if $groupname;
|
---|
| 2531 | } # end groupName
|
---|
[13] | 2532 |
|
---|
| 2533 |
|
---|
[314] | 2534 | ## DNSDB::getGroupCount()
|
---|
| 2535 | # Get count of subgroups in group or groups
|
---|
| 2536 | # Takes a database handle and hash containing:
|
---|
| 2537 | # - the "current" group
|
---|
| 2538 | # - an array of "acceptable" groups
|
---|
| 2539 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
| 2540 | # Returns an integer count of the resulting group list.
|
---|
| 2541 | sub getGroupCount {
|
---|
[476] | 2542 | my $self = shift;
|
---|
| 2543 | my $dbh = $self->{dbh};
|
---|
[314] | 2544 |
|
---|
| 2545 | my %args = @_;
|
---|
| 2546 |
|
---|
| 2547 | my @filterargs;
|
---|
| 2548 |
|
---|
| 2549 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2550 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2551 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2552 |
|
---|
| 2553 | my $sql = "SELECT count(*) FROM groups ".
|
---|
| 2554 | "WHERE parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2555 | ($args{startwith} ? " AND group_name ~* ?" : '').
|
---|
| 2556 | ($args{filter} ? " AND group_name ~* ?" : '');
|
---|
| 2557 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 2558 | $errstr = $dbh->errstr if !$count;
|
---|
| 2559 | return $count;
|
---|
| 2560 | } # end getGroupCount
|
---|
| 2561 |
|
---|
| 2562 |
|
---|
| 2563 | ## DNSDB::getGroupList()
|
---|
| 2564 | # Get a list of sub^n-groups in the specified group(s)
|
---|
| 2565 | # Takes the same arguments as getGroupCount() above
|
---|
| 2566 | # Returns an arrayref containing hashrefs suitable for feeding straight to HTML::Template
|
---|
| 2567 | sub getGroupList {
|
---|
[476] | 2568 | my $self = shift;
|
---|
| 2569 | my $dbh = $self->{dbh};
|
---|
[314] | 2570 |
|
---|
| 2571 | my %args = @_;
|
---|
| 2572 |
|
---|
| 2573 | my @filterargs;
|
---|
| 2574 |
|
---|
| 2575 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2576 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2577 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2578 |
|
---|
| 2579 | # protection against bad or missing arguments
|
---|
| 2580 | $args{sortorder} = 'ASC' if !$args{sortorder};
|
---|
[397] | 2581 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[314] | 2582 |
|
---|
| 2583 | # munge sortby for columns in database
|
---|
| 2584 | $args{sortby} = 'g.group_name' if $args{sortby} eq 'group';
|
---|
| 2585 | $args{sortby} = 'g2.group_name' if $args{sortby} eq 'parent';
|
---|
| 2586 |
|
---|
[385] | 2587 | my $sql = q(SELECT g.group_id AS groupid, g.group_name AS groupname, g2.group_name AS pgroup
|
---|
[314] | 2588 | FROM groups g
|
---|
| 2589 | INNER JOIN groups g2 ON g2.group_id=g.parent_group_id
|
---|
| 2590 | ).
|
---|
[385] | 2591 | " WHERE g.parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
[314] | 2592 | ($args{startwith} ? " AND g.group_name ~* ?" : '').
|
---|
| 2593 | ($args{filter} ? " AND g.group_name ~* ?" : '').
|
---|
| 2594 | " GROUP BY g.group_id, g.group_name, g2.group_name ".
|
---|
| 2595 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
| 2596 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
| 2597 | my $glist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 2598 | $errstr = $dbh->errstr if !$glist;
|
---|
[385] | 2599 |
|
---|
| 2600 | # LEFT JOINs make the result set balloon beyond sanity just to include counts;
|
---|
| 2601 | # this means there's lots of crunching needed to trim the result set back down.
|
---|
| 2602 | # So instead we track the order of the groups, and push the counts into the
|
---|
| 2603 | # arrayref result separately.
|
---|
| 2604 | ##fixme: put this whole sub in a transaction? might be
|
---|
| 2605 | # needed for accurate results on very busy systems.
|
---|
[386] | 2606 | ##fixme: large group lists need prepared statements?
|
---|
| 2607 | #my $ucsth = $dbh->prepare("SELECT count(*) FROM users WHERE group_id=?");
|
---|
| 2608 | #my $dcsth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
|
---|
| 2609 | #my $rcsth = $dbh->prepare("SELECT count(*) FROM revzones WHERE group_id=?");
|
---|
[385] | 2610 | foreach (@{$glist}) {
|
---|
[386] | 2611 | my ($ucnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 2612 | $$_{nusers} = $ucnt;
|
---|
| 2613 | my ($dcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 2614 | $$_{ndomains} = $dcnt;
|
---|
| 2615 | my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 2616 | $$_{nrevzones} = $rcnt;
|
---|
[385] | 2617 | }
|
---|
| 2618 |
|
---|
[314] | 2619 | return $glist;
|
---|
| 2620 | } # end getGroupList
|
---|
| 2621 |
|
---|
| 2622 |
|
---|
[118] | 2623 | ## DNSDB::groupID()
|
---|
| 2624 | # Return the group ID based on the group name
|
---|
| 2625 | # Takes a database handle and the group name
|
---|
| 2626 | # Returns the group ID or undef on failure
|
---|
| 2627 | sub groupID {
|
---|
| 2628 | $errstr = '';
|
---|
[473] | 2629 | my $self = shift;
|
---|
| 2630 | my $dbh = $self->{dbh};
|
---|
[118] | 2631 | my $group = shift;
|
---|
[406] | 2632 | my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($group) );
|
---|
[118] | 2633 | $errstr = $DBI::errstr if !$grpid;
|
---|
| 2634 | return $grpid if $grpid;
|
---|
| 2635 | } # end groupID()
|
---|
| 2636 |
|
---|
| 2637 |
|
---|
[24] | 2638 | ## DNSDB::addUser()
|
---|
[87] | 2639 | # Add a user.
|
---|
| 2640 | # Takes a DB handle, username, group ID, password, state (active/inactive).
|
---|
| 2641 | # Optionally accepts:
|
---|
| 2642 | # user type (user/admin) - defaults to user
|
---|
| 2643 | # permissions string - defaults to inherit from group
|
---|
| 2644 | # three valid forms:
|
---|
| 2645 | # i - Inherit permissions
|
---|
| 2646 | # c:<user_id> - Clone permissions from <user_id>
|
---|
| 2647 | # C:<permission list> - Set these specific permissions
|
---|
| 2648 | # first name - defaults to username
|
---|
| 2649 | # last name - defaults to blank
|
---|
| 2650 | # phone - defaults to blank (could put other data within column def)
|
---|
[90] | 2651 | # Returns (OK,<uid>) on success, (FAIL,<message>) on failure
|
---|
[24] | 2652 | sub addUser {
|
---|
| 2653 | $errstr = '';
|
---|
[479] | 2654 | my $self = shift;
|
---|
| 2655 | my $dbh = $self->{dbh};
|
---|
[24] | 2656 | my $username = shift;
|
---|
| 2657 | my $group = shift;
|
---|
| 2658 | my $pass = shift;
|
---|
| 2659 | my $state = shift;
|
---|
[25] | 2660 |
|
---|
[90] | 2661 | return ('FAIL', "Missing one or more required entries") if !defined($state);
|
---|
| 2662 | return ('FAIL', "Username must not be blank") if !$username;
|
---|
[87] | 2663 |
|
---|
[408] | 2664 | # Munge in some alternate state values
|
---|
| 2665 | $state = 1 if $state =~ /^active$/;
|
---|
| 2666 | $state = 1 if $state =~ /^on$/;
|
---|
| 2667 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 2668 | $state = 0 if $state =~ /^off$/;
|
---|
| 2669 |
|
---|
[25] | 2670 | my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
|
---|
| 2671 |
|
---|
[67] | 2672 | my $permstring = shift || 'i'; # default is to inhert permissions from group
|
---|
| 2673 |
|
---|
[25] | 2674 | my $fname = shift || $username;
|
---|
[24] | 2675 | my $lname = shift || '';
|
---|
[25] | 2676 | my $phone = shift || ''; # not going format-check
|
---|
[24] | 2677 |
|
---|
[38] | 2678 | my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
|
---|
[24] | 2679 | my $user_id;
|
---|
| 2680 |
|
---|
[38] | 2681 | # quick check to start to see if we've already got one
|
---|
| 2682 | $sth->execute($username);
|
---|
| 2683 | ($user_id) = $sth->fetchrow_array;
|
---|
| 2684 |
|
---|
| 2685 | return ('FAIL', "User already exists") if $user_id;
|
---|
| 2686 |
|
---|
[24] | 2687 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2688 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2689 | local $dbh->{AutoCommit} = 0;
|
---|
| 2690 | local $dbh->{RaiseError} = 1;
|
---|
| 2691 |
|
---|
| 2692 | # Wrap all the SQL in a transaction
|
---|
| 2693 | eval {
|
---|
[87] | 2694 | # insert the user... note we set inherited perms by default since
|
---|
| 2695 | # it's simple and cleans up some other bits of state
|
---|
| 2696 | my $sth = $dbh->prepare("INSERT INTO users ".
|
---|
| 2697 | "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
|
---|
| 2698 | "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
|
---|
| 2699 | $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);
|
---|
[24] | 2700 |
|
---|
| 2701 | # get the ID...
|
---|
[94] | 2702 | ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");
|
---|
[24] | 2703 |
|
---|
[87] | 2704 | # Permissions! Gotta set'em all!
|
---|
[401] | 2705 | die "Invalid permission string $permstring\n"
|
---|
[87] | 2706 | if $permstring !~ /^(?:
|
---|
| 2707 | i # inherit
|
---|
| 2708 | |c:\d+ # clone
|
---|
| 2709 | # custom. no, the leading , is not a typo
|
---|
[391] | 2710 | |C:(?:,(?:group|user|domain|record|location|self)_(?:edit|create|delete|locchg|view))*
|
---|
[87] | 2711 | )$/x;
|
---|
| 2712 | # bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
|
---|
| 2713 | if ($permstring ne 'i') {
|
---|
| 2714 | # for cloned or custom permissions, we have to create a new permissions entry.
|
---|
| 2715 | my $clonesrc = $group;
|
---|
| 2716 | if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
|
---|
| 2717 | $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
|
---|
| 2718 | "SELECT $permlist,? FROM permissions WHERE permission_id=".
|
---|
| 2719 | "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
|
---|
| 2720 | undef, ($user_id,$clonesrc) );
|
---|
| 2721 | $dbh->do("UPDATE users SET permission_id=".
|
---|
| 2722 | "(SELECT permission_id FROM permissions WHERE user_id=?) ".
|
---|
| 2723 | "WHERE user_id=?", undef, ($user_id, $user_id) );
|
---|
| 2724 | }
|
---|
| 2725 | if ($permstring =~ /^C:/) {
|
---|
| 2726 | # finally for custom permissions, we set the passed-in permissions (and unset
|
---|
| 2727 | # any that might have been brought in by the clone operation above)
|
---|
| 2728 | my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
|
---|
| 2729 | undef, ($user_id) );
|
---|
| 2730 | foreach (@permtypes) {
|
---|
| 2731 | if ($permstring =~ /,$_/) {
|
---|
| 2732 | $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
|
---|
| 2733 | } else {
|
---|
| 2734 | $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
|
---|
| 2735 | }
|
---|
| 2736 | }
|
---|
| 2737 | }
|
---|
| 2738 |
|
---|
| 2739 | $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
|
---|
| 2740 |
|
---|
[25] | 2741 | ##fixme: add another table to hold name/email for log table?
|
---|
| 2742 |
|
---|
[487] | 2743 | $self->_log(group_id => $group, entry => "Added user $username ($fname $lname)");
|
---|
[24] | 2744 | # once we get here, we should have suceeded.
|
---|
| 2745 | $dbh->commit;
|
---|
| 2746 | }; # end eval
|
---|
| 2747 |
|
---|
| 2748 | if ($@) {
|
---|
| 2749 | my $msg = $@;
|
---|
| 2750 | eval { $dbh->rollback; };
|
---|
[294] | 2751 | if ($config{log_failures}) {
|
---|
[487] | 2752 | $self->_log(group_id => $group, entry => "Error adding user $username: $msg");
|
---|
[294] | 2753 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2754 | }
|
---|
| 2755 | return ('FAIL',"Error adding user $username: $msg");
|
---|
[24] | 2756 | }
|
---|
[294] | 2757 |
|
---|
| 2758 | return ('OK',"User $username ($fname $lname) added");
|
---|
[24] | 2759 | } # end addUser
|
---|
| 2760 |
|
---|
| 2761 |
|
---|
[325] | 2762 | ## DNSDB::getUserCount()
|
---|
| 2763 | # Get count of users in group
|
---|
| 2764 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
| 2765 | # - a reference list of secondary groups
|
---|
| 2766 | # - a filter string
|
---|
| 2767 | # - a "Starts with" string
|
---|
| 2768 | sub getUserCount {
|
---|
[479] | 2769 | my $self = shift;
|
---|
| 2770 | my $dbh = $self->{dbh};
|
---|
[325] | 2771 |
|
---|
| 2772 | my %args = @_;
|
---|
| 2773 |
|
---|
| 2774 | my @filterargs;
|
---|
| 2775 |
|
---|
| 2776 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2777 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2778 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2779 |
|
---|
| 2780 |
|
---|
| 2781 | my $sql = "SELECT count(*) FROM users ".
|
---|
| 2782 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2783 | ($args{startwith} ? " AND username ~* ?" : '').
|
---|
| 2784 | ($args{filter} ? " AND username ~* ?" : '');
|
---|
| 2785 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 2786 | $errstr = $dbh->errstr if !$count;
|
---|
| 2787 | return $count;
|
---|
| 2788 | } # end getUserCount()
|
---|
| 2789 |
|
---|
| 2790 |
|
---|
| 2791 | ## DNSDB::getUserList()
|
---|
| 2792 | # Get list of users
|
---|
| 2793 | # Takes the same arguments as getUserCount() above, plus optional:
|
---|
| 2794 | # - sort field
|
---|
| 2795 | # - sort order
|
---|
| 2796 | # - offset/return-all-everything flag (defaults to $perpage records)
|
---|
| 2797 | sub getUserList {
|
---|
[479] | 2798 | my $self = shift;
|
---|
| 2799 | my $dbh = $self->{dbh};
|
---|
[325] | 2800 |
|
---|
| 2801 | my %args = @_;
|
---|
| 2802 |
|
---|
| 2803 | my @filterargs;
|
---|
| 2804 |
|
---|
| 2805 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2806 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2807 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2808 |
|
---|
| 2809 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
| 2810 | my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
| 2811 | fname => 'fname');
|
---|
| 2812 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 2813 |
|
---|
| 2814 | # protection against bad or missing arguments
|
---|
| 2815 | $args{sortorder} = 'ASC' if !$args{sortorder};
|
---|
| 2816 | $args{sortby} = 'u.username' if !$args{sortby};
|
---|
[397] | 2817 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[325] | 2818 |
|
---|
| 2819 | my $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ".
|
---|
| 2820 | "FROM users u ".
|
---|
| 2821 | "INNER JOIN groups g ON u.group_id=g.group_id ".
|
---|
| 2822 | "WHERE u.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2823 | ($args{startwith} ? " AND u.username ~* ?" : '').
|
---|
| 2824 | ($args{filter} ? " AND u.username ~* ?" : '').
|
---|
[401] | 2825 | " AND NOT u.type = 'R' ".
|
---|
[325] | 2826 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
| 2827 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
| 2828 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 2829 | $errstr = $dbh->errstr if !$ulist;
|
---|
| 2830 | return $ulist;
|
---|
| 2831 | } # end getUserList()
|
---|
| 2832 |
|
---|
| 2833 |
|
---|
[326] | 2834 | ## DNSDB::getUserDropdown()
|
---|
| 2835 | # Get a list of usernames for use in a dropdown menu.
|
---|
| 2836 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
| 2837 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
| 2838 | sub getUserDropdown {
|
---|
[479] | 2839 | my $self = shift;
|
---|
| 2840 | my $dbh = $self->{dbh};
|
---|
[326] | 2841 | my $grp = shift;
|
---|
| 2842 | my $sel = shift || 0;
|
---|
| 2843 |
|
---|
| 2844 | my $sth = $dbh->prepare("SELECT username,user_id FROM users WHERE group_id=?");
|
---|
| 2845 | $sth->execute($grp);
|
---|
| 2846 |
|
---|
| 2847 | my @userlist;
|
---|
| 2848 | while (my ($username,$uid) = $sth->fetchrow_array) {
|
---|
| 2849 | my %row = (
|
---|
| 2850 | username => $username,
|
---|
| 2851 | uid => $uid,
|
---|
| 2852 | selected => ($sel == $uid ? 1 : 0)
|
---|
| 2853 | );
|
---|
| 2854 | push @userlist, \%row;
|
---|
| 2855 | }
|
---|
| 2856 | return \@userlist;
|
---|
| 2857 | } # end getUserDropdown()
|
---|
| 2858 |
|
---|
| 2859 |
|
---|
[83] | 2860 | ## DNSDB:: updateUser()
|
---|
[90] | 2861 | # Update general data about user
|
---|
[83] | 2862 | sub updateUser {
|
---|
[479] | 2863 | my $self = shift;
|
---|
| 2864 | my $dbh = $self->{dbh};
|
---|
[118] | 2865 |
|
---|
| 2866 | ##fixme: tweak calling convention so that we can update any given bit of data
|
---|
[83] | 2867 | my $uid = shift;
|
---|
| 2868 | my $username = shift;
|
---|
| 2869 | my $group = shift;
|
---|
| 2870 | my $pass = shift;
|
---|
| 2871 | my $state = shift;
|
---|
[87] | 2872 | my $type = shift || 'u';
|
---|
[83] | 2873 | my $fname = shift || $username;
|
---|
| 2874 | my $lname = shift || '';
|
---|
| 2875 | my $phone = shift || ''; # not going format-check
|
---|
| 2876 |
|
---|
[294] | 2877 | my $resultmsg = '';
|
---|
[83] | 2878 |
|
---|
[411] | 2879 | # Munge in some alternate state values
|
---|
| 2880 | $state = 1 if $state =~ /^active$/;
|
---|
| 2881 | $state = 1 if $state =~ /^on$/;
|
---|
| 2882 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 2883 | $state = 0 if $state =~ /^off$/;
|
---|
| 2884 |
|
---|
[83] | 2885 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2886 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2887 | local $dbh->{AutoCommit} = 0;
|
---|
| 2888 | local $dbh->{RaiseError} = 1;
|
---|
| 2889 |
|
---|
| 2890 | my $sth;
|
---|
| 2891 |
|
---|
| 2892 | # Password can be left blank; if so we assume there's one on file.
|
---|
| 2893 | # Actual blank passwords are bad, mm'kay?
|
---|
| 2894 | if (!$pass) {
|
---|
[294] | 2895 | ($pass) = $dbh->selectrow_array("SELECT password FROM users WHERE user_id=?", undef, ($uid));
|
---|
[83] | 2896 | } else {
|
---|
| 2897 | $pass = unix_md5_crypt($pass);
|
---|
| 2898 | }
|
---|
| 2899 |
|
---|
| 2900 | eval {
|
---|
[294] | 2901 | $dbh->do("UPDATE users SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?".
|
---|
| 2902 | " WHERE user_id=?", undef, ($username, $pass, $fname, $lname, $phone, $type, $state, $uid));
|
---|
| 2903 | $resultmsg = "Updated user info for $username ($fname $lname)";
|
---|
[487] | 2904 | $self->_log(group_id => $group, entry => $resultmsg);
|
---|
[83] | 2905 | $dbh->commit;
|
---|
| 2906 | };
|
---|
| 2907 | if ($@) {
|
---|
| 2908 | my $msg = $@;
|
---|
| 2909 | eval { $dbh->rollback; };
|
---|
[294] | 2910 | if ($config{log_failures}) {
|
---|
[487] | 2911 | $self->_log(group_id => $group, entry => "Error updating user $username: $msg");
|
---|
[294] | 2912 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2913 | }
|
---|
| 2914 | return ('FAIL',"Error updating user $username: $msg");
|
---|
[83] | 2915 | }
|
---|
[294] | 2916 |
|
---|
| 2917 | return ('OK',$resultmsg);
|
---|
[83] | 2918 | } # end updateUser()
|
---|
| 2919 |
|
---|
| 2920 |
|
---|
[24] | 2921 | ## DNSDB::delUser()
|
---|
[297] | 2922 | # Delete a user.
|
---|
| 2923 | # Takes a database handle and user ID
|
---|
| 2924 | # Returns a success/failure code and matching message
|
---|
[24] | 2925 | sub delUser {
|
---|
[479] | 2926 | my $self = shift;
|
---|
| 2927 | my $dbh = $self->{dbh};
|
---|
[25] | 2928 | my $userid = shift;
|
---|
| 2929 |
|
---|
[297] | 2930 | return ('FAIL',"Bad userid") if !defined($userid);
|
---|
[25] | 2931 |
|
---|
[479] | 2932 | my $userdata = $self->getUserData($userid);
|
---|
[25] | 2933 |
|
---|
[297] | 2934 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2935 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2936 | local $dbh->{AutoCommit} = 0;
|
---|
| 2937 | local $dbh->{RaiseError} = 1;
|
---|
[25] | 2938 |
|
---|
[297] | 2939 | eval {
|
---|
| 2940 | $dbh->do("DELETE FROM users WHERE user_id=?", undef, ($userid));
|
---|
[487] | 2941 | $self->_log(group_id => $userdata->{group_id},
|
---|
[297] | 2942 | entry => "Deleted user ID $userid/".$userdata->{username}.
|
---|
[487] | 2943 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")");
|
---|
[297] | 2944 | $dbh->commit;
|
---|
| 2945 | };
|
---|
| 2946 | if ($@) {
|
---|
| 2947 | my $msg = $@;
|
---|
| 2948 | eval { $dbh->rollback; };
|
---|
| 2949 | if ($config{log_failures}) {
|
---|
[487] | 2950 | $self->_log(group_id => $userdata->{group_id}, entry => "Error deleting user ID ".
|
---|
| 2951 | "$userid/".$userdata->{username}.": $msg");
|
---|
[297] | 2952 | $dbh->commit;
|
---|
| 2953 | }
|
---|
| 2954 | return ('FAIL',"Error deleting user $userid/".$userdata->{username}.": $msg");
|
---|
| 2955 | }
|
---|
| 2956 |
|
---|
| 2957 | return ('OK',"Deleted user ".$userdata->{username}." (".$userdata->{firstname}." ".$userdata->{lastname}.")");
|
---|
[24] | 2958 | } # end delUser
|
---|
| 2959 |
|
---|
| 2960 |
|
---|
[25] | 2961 | ## DNSDB::userFullName()
|
---|
| 2962 | # Return a pretty string!
|
---|
| 2963 | # Takes a user_id and optional printf-ish string to indicate which pieces where:
|
---|
| 2964 | # %u for the username
|
---|
| 2965 | # %f for the first name
|
---|
| 2966 | # %l for the last name
|
---|
| 2967 | # All other text in the passed string will be left as-is.
|
---|
| 2968 | ##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
|
---|
| 2969 | sub userFullName {
|
---|
| 2970 | $errstr = '';
|
---|
[473] | 2971 | my $self = shift;
|
---|
| 2972 | my $dbh = $self->{dbh};
|
---|
[25] | 2973 | my $userid = shift;
|
---|
| 2974 | my $fullformat = shift || '%f %l (%u)';
|
---|
| 2975 | my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
|
---|
| 2976 | $sth->execute($userid);
|
---|
| 2977 | my ($uname,$fname,$lname) = $sth->fetchrow_array();
|
---|
| 2978 | $errstr = $DBI::errstr if !$uname;
|
---|
| 2979 |
|
---|
| 2980 | $fullformat =~ s/\%u/$uname/g;
|
---|
| 2981 | $fullformat =~ s/\%f/$fname/g;
|
---|
| 2982 | $fullformat =~ s/\%l/$lname/g;
|
---|
| 2983 |
|
---|
| 2984 | return $fullformat;
|
---|
| 2985 | } # end userFullName
|
---|
| 2986 |
|
---|
| 2987 |
|
---|
[51] | 2988 | ## DNSDB::userStatus()
|
---|
| 2989 | # Sets and/or returns a user's status
|
---|
| 2990 | # Takes a database handle, user ID and optionally a status argument
|
---|
| 2991 | # Returns undef on errors.
|
---|
| 2992 | sub userStatus {
|
---|
[479] | 2993 | my $self = shift;
|
---|
| 2994 | my $dbh = $self->{dbh};
|
---|
[51] | 2995 | my $id = shift;
|
---|
[296] | 2996 | my $newstatus = shift || 'mu';
|
---|
[51] | 2997 |
|
---|
| 2998 | return undef if $id !~ /^\d+$/;
|
---|
| 2999 |
|
---|
[479] | 3000 | my $userdata = $self->getUserData($id);
|
---|
[51] | 3001 |
|
---|
[296] | 3002 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3003 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3004 | local $dbh->{AutoCommit} = 0;
|
---|
| 3005 | local $dbh->{RaiseError} = 1;
|
---|
| 3006 |
|
---|
| 3007 | if ($newstatus ne 'mu') {
|
---|
| 3008 | # ooo, fun! let's see what we were passed for status
|
---|
| 3009 | eval {
|
---|
| 3010 | $newstatus = 0 if $newstatus eq 'useroff';
|
---|
| 3011 | $newstatus = 1 if $newstatus eq 'useron';
|
---|
| 3012 | $dbh->do("UPDATE users SET status=? WHERE user_id=?", undef, ($newstatus, $id));
|
---|
| 3013 |
|
---|
[297] | 3014 | $resultstr = ($newstatus ? 'Enabled' : 'Disabled')." user ".$userdata->{username}.
|
---|
| 3015 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")";
|
---|
[296] | 3016 |
|
---|
| 3017 | my %loghash;
|
---|
[473] | 3018 | $loghash{group_id} = $self->parentID(id => $id, type => 'user');
|
---|
[296] | 3019 | $loghash{entry} = $resultstr;
|
---|
[487] | 3020 | $self->_log(%loghash);
|
---|
[296] | 3021 |
|
---|
| 3022 | $dbh->commit;
|
---|
| 3023 | };
|
---|
| 3024 | if ($@) {
|
---|
| 3025 | my $msg = $@;
|
---|
| 3026 | eval { $dbh->rollback; };
|
---|
| 3027 | $resultstr = '';
|
---|
| 3028 | $errstr = $msg;
|
---|
| 3029 | ##fixme: failure logging?
|
---|
| 3030 | return;
|
---|
[51] | 3031 | }
|
---|
| 3032 | }
|
---|
| 3033 |
|
---|
[296] | 3034 | my ($status) = $dbh->selectrow_array("SELECT status FROM users WHERE user_id=?", undef, ($id));
|
---|
[51] | 3035 | return $status;
|
---|
| 3036 | } # end userStatus()
|
---|
| 3037 |
|
---|
| 3038 |
|
---|
[83] | 3039 | ## DNSDB::getUserData()
|
---|
| 3040 | # Get misc user data for display
|
---|
| 3041 | sub getUserData {
|
---|
[479] | 3042 | my $self = shift;
|
---|
| 3043 | my $dbh = $self->{dbh};
|
---|
[83] | 3044 | my $uid = shift;
|
---|
| 3045 |
|
---|
| 3046 | my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
|
---|
| 3047 | "FROM users WHERE user_id=?");
|
---|
| 3048 | $sth->execute($uid);
|
---|
| 3049 | return $sth->fetchrow_hashref();
|
---|
| 3050 | } # end getUserData()
|
---|
| 3051 |
|
---|
| 3052 |
|
---|
[370] | 3053 | ## DNSDB::addLoc()
|
---|
[375] | 3054 | # Add a new location.
|
---|
| 3055 | # Takes a database handle, group ID, short and long description, and a comma-separated
|
---|
| 3056 | # list of IP addresses.
|
---|
| 3057 | # Returns ('OK',<location>) on success, ('FAIL',<failmsg>) on failure
|
---|
| 3058 | sub addLoc {
|
---|
[480] | 3059 | my $self = shift;
|
---|
| 3060 | my $dbh = $self->{dbh};
|
---|
[375] | 3061 | my $grp = shift;
|
---|
| 3062 | my $shdesc = shift;
|
---|
| 3063 | my $comments = shift;
|
---|
| 3064 | my $iplist = shift;
|
---|
[370] | 3065 |
|
---|
[375] | 3066 | # $shdesc gets set to the generated location ID if possible, but these can be de-undefined here.
|
---|
| 3067 | $comments = '' if !$comments;
|
---|
| 3068 | $iplist = '' if !$iplist;
|
---|
| 3069 |
|
---|
| 3070 | my $loc;
|
---|
| 3071 |
|
---|
| 3072 | # Generate a location ID. This is, by spec, a two-character widget. We'll use [a-z][a-z]
|
---|
| 3073 | # for now; 676 locations should satisfy all but the largest of the huge networks.
|
---|
| 3074 | # Not sure whether these are case-sensitive, or what other rules might apply - in any case
|
---|
| 3075 | # the absolute maximum is 16K (256*256) since it's parsed by tinydns as a two-character field.
|
---|
| 3076 |
|
---|
| 3077 | # add just after "my $origloc = $loc;":
|
---|
| 3078 | # # These expand the possible space from 26^2 to 52^2 [* note in testing only 2052 were achieved],
|
---|
| 3079 | # # and wrap it around.
|
---|
| 3080 | # # Yes, they skip a couple of possibles. No, I don't care.
|
---|
| 3081 | # $loc = 'aA' if $loc eq 'zz';
|
---|
| 3082 | # $loc = 'Aa' if $loc eq 'zZ';
|
---|
| 3083 | # $loc = 'ZA' if $loc eq 'Zz';
|
---|
| 3084 | # $loc = 'aa' if $loc eq 'ZZ';
|
---|
| 3085 |
|
---|
| 3086 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3087 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3088 | local $dbh->{AutoCommit} = 0;
|
---|
| 3089 | local $dbh->{RaiseError} = 1;
|
---|
| 3090 |
|
---|
| 3091 | ##fixme: There is probably a far better way to do this. Sequential increments
|
---|
| 3092 | # are marginally less stupid that pure random generation though, and the existence
|
---|
| 3093 | # check makes sure we don't stomp on an imported one.
|
---|
| 3094 |
|
---|
| 3095 | eval {
|
---|
| 3096 | # Get the "last" location. Note this is the only use for loc_id, because selecting on location Does Funky Things
|
---|
| 3097 | ($loc) = $dbh->selectrow_array("SELECT location FROM locations ORDER BY loc_id DESC LIMIT 1");
|
---|
[478] | 3098 | ($loc) = ($loc =~ /^(..)/) if $loc;
|
---|
[375] | 3099 | my $origloc = $loc;
|
---|
[446] | 3100 | $loc = 'aa' if !$loc;
|
---|
[375] | 3101 | # Make a change...
|
---|
| 3102 | $loc++;
|
---|
| 3103 | # ... and keep changing if it exists
|
---|
| 3104 | while ($dbh->selectrow_array("SELECT count(*) FROM locations WHERE location LIKE ?", undef, ($loc.'%'))) {
|
---|
| 3105 | $loc++;
|
---|
| 3106 | ($loc) = ($loc =~ /^(..)/);
|
---|
| 3107 | die "too many locations in use, can't add another one\n" if $loc eq $origloc;
|
---|
| 3108 | ##fixme: really need to handle this case faster somehow
|
---|
| 3109 | #if $loc eq $origloc die "<thwap> bad admin: all locations used, your network is too fragmented";
|
---|
| 3110 | }
|
---|
| 3111 | # And now we should have a unique location. tinydns fundamentally limits the
|
---|
| 3112 | # number of these but there's no doc on what characters are valid.
|
---|
| 3113 | $shdesc = $loc if !$shdesc;
|
---|
| 3114 | $dbh->do("INSERT INTO locations (location, group_id, iplist, description, comments) VALUES (?,?,?,?,?)",
|
---|
| 3115 | undef, ($loc, $grp, $iplist, $shdesc, $comments) );
|
---|
[487] | 3116 | $self->_log(entry => "Added location ($shdesc, '$iplist')");
|
---|
[377] | 3117 | $dbh->commit;
|
---|
[375] | 3118 | };
|
---|
| 3119 | if ($@) {
|
---|
| 3120 | my $msg = $@;
|
---|
| 3121 | eval { $dbh->rollback; };
|
---|
| 3122 | if ($config{log_failures}) {
|
---|
| 3123 | $shdesc = $loc if !$shdesc;
|
---|
[487] | 3124 | $self->_log(entry => "Failed adding location ($shdesc, '$iplist'): $msg");
|
---|
[375] | 3125 | $dbh->commit;
|
---|
| 3126 | }
|
---|
| 3127 | return ('FAIL',$msg);
|
---|
| 3128 | }
|
---|
| 3129 |
|
---|
| 3130 | return ('OK',$loc);
|
---|
[377] | 3131 | } # end addLoc()
|
---|
[375] | 3132 |
|
---|
| 3133 |
|
---|
[370] | 3134 | ## DNSDB::updateLoc()
|
---|
[428] | 3135 | # Update details of a location.
|
---|
| 3136 | # Takes a database handle, location ID, group ID, short description,
|
---|
| 3137 | # long comments/notes, and comma/space-separated IP list
|
---|
| 3138 | # Returns a result code and message
|
---|
[377] | 3139 | sub updateLoc {
|
---|
[480] | 3140 | my $self = shift;
|
---|
| 3141 | my $dbh = $self->{dbh};
|
---|
[377] | 3142 | my $loc = shift;
|
---|
| 3143 | my $grp = shift;
|
---|
| 3144 | my $shdesc = shift;
|
---|
| 3145 | my $comments = shift;
|
---|
| 3146 | my $iplist = shift;
|
---|
[370] | 3147 |
|
---|
[377] | 3148 | $shdesc = '' if !$shdesc;
|
---|
| 3149 | $comments = '' if !$comments;
|
---|
| 3150 | $iplist = '' if !$iplist;
|
---|
| 3151 |
|
---|
| 3152 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3153 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3154 | local $dbh->{AutoCommit} = 0;
|
---|
| 3155 | local $dbh->{RaiseError} = 1;
|
---|
| 3156 |
|
---|
[480] | 3157 | my $oldloc = $self->getLoc($loc);
|
---|
[377] | 3158 | my $okmsg = "Updated location (".$oldloc->{description}.", '".$oldloc->{iplist}."') to ($shdesc, '$iplist')";
|
---|
| 3159 |
|
---|
| 3160 | eval {
|
---|
| 3161 | $dbh->do("UPDATE locations SET group_id=?,iplist=?,description=?,comments=? WHERE location=?",
|
---|
| 3162 | undef, ($grp, $iplist, $shdesc, $comments, $loc) );
|
---|
[487] | 3163 | $self->_log(entry => $okmsg);
|
---|
[377] | 3164 | $dbh->commit;
|
---|
| 3165 | };
|
---|
| 3166 | if ($@) {
|
---|
| 3167 | my $msg = $@;
|
---|
| 3168 | eval { $dbh->rollback; };
|
---|
| 3169 | if ($config{log_failures}) {
|
---|
| 3170 | $shdesc = $loc if !$shdesc;
|
---|
[487] | 3171 | $self->_log(entry => "Failed updating location ($shdesc, '$iplist'): $msg");
|
---|
[377] | 3172 | $dbh->commit;
|
---|
| 3173 | }
|
---|
| 3174 | return ('FAIL',$msg);
|
---|
| 3175 | }
|
---|
| 3176 |
|
---|
| 3177 | return ('OK',$okmsg);
|
---|
| 3178 | } # end updateLoc()
|
---|
| 3179 |
|
---|
| 3180 |
|
---|
[370] | 3181 | ## DNSDB::delLoc()
|
---|
[428] | 3182 | sub delLoc {
|
---|
[480] | 3183 | my $self = shift;
|
---|
| 3184 | my $dbh = $self->{dbh};
|
---|
[428] | 3185 | my $loc = shift;
|
---|
[370] | 3186 |
|
---|
[428] | 3187 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3188 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3189 | local $dbh->{AutoCommit} = 0;
|
---|
| 3190 | local $dbh->{RaiseError} = 1;
|
---|
[370] | 3191 |
|
---|
[480] | 3192 | my $oldloc = $self->getLoc($loc);
|
---|
[428] | 3193 | my $olddesc = ($oldloc->{description} ? $oldloc->{description} : $loc);
|
---|
| 3194 | my $okmsg = "Deleted location ($olddesc, '".$oldloc->{iplist}."')";
|
---|
| 3195 |
|
---|
| 3196 | eval {
|
---|
| 3197 | # Check for records with this location first. Deleting a location without deleting records
|
---|
| 3198 | # tagged for that location will render them unpublished without other warning.
|
---|
| 3199 | my ($r) = $dbh->selectrow_array("SELECT record_id FROM records WHERE location=? LIMIT 1", undef, ($loc) );
|
---|
| 3200 | die "Records still exist in location $olddesc\n" if $r;
|
---|
| 3201 | $dbh->do("DELETE FROM locations WHERE location=?", undef, ($loc) );
|
---|
[487] | 3202 | $self->_log(entry => $okmsg);
|
---|
[428] | 3203 | $dbh->commit;
|
---|
| 3204 | };
|
---|
| 3205 | if ($@) {
|
---|
| 3206 | my $msg = $@;
|
---|
| 3207 | eval { $dbh->rollback; };
|
---|
| 3208 | if ($config{log_failures}) {
|
---|
[487] | 3209 | $self->_log(entry => "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
|
---|
[428] | 3210 | $dbh->commit;
|
---|
| 3211 | }
|
---|
| 3212 | return ('FAIL', "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
|
---|
| 3213 | }
|
---|
| 3214 |
|
---|
| 3215 | return ('OK',$okmsg);
|
---|
| 3216 | } # end delLoc()
|
---|
| 3217 |
|
---|
| 3218 |
|
---|
[375] | 3219 | ## DNSDB::getLoc()
|
---|
[428] | 3220 | # Get details about a location/view
|
---|
| 3221 | # Takes a database handle and location ID.
|
---|
| 3222 | # Returns a reference to a hash containing the group ID, IP list, description, and comments/notes
|
---|
[375] | 3223 | sub getLoc {
|
---|
[480] | 3224 | my $self = shift;
|
---|
| 3225 | my $dbh = $self->{dbh};
|
---|
[375] | 3226 | my $loc = shift;
|
---|
| 3227 |
|
---|
| 3228 | my $sth = $dbh->prepare("SELECT group_id,iplist,description,comments FROM locations WHERE location=?");
|
---|
| 3229 | $sth->execute($loc);
|
---|
| 3230 | return $sth->fetchrow_hashref();
|
---|
| 3231 | } # end getLoc()
|
---|
| 3232 |
|
---|
| 3233 |
|
---|
[370] | 3234 | ## DNSDB::getLocCount()
|
---|
| 3235 | # Get count of locations/views
|
---|
| 3236 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
| 3237 | # - a reference list of secondary groups
|
---|
| 3238 | # - a filter string
|
---|
| 3239 | # - a "Starts with" string
|
---|
| 3240 | sub getLocCount {
|
---|
[480] | 3241 | my $self = shift;
|
---|
| 3242 | my $dbh = $self->{dbh};
|
---|
[370] | 3243 |
|
---|
| 3244 | my %args = @_;
|
---|
| 3245 |
|
---|
| 3246 | my @filterargs;
|
---|
| 3247 |
|
---|
| 3248 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3249 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3250 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3251 |
|
---|
| 3252 |
|
---|
| 3253 | my $sql = "SELECT count(*) FROM locations ".
|
---|
| 3254 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3255 | ($args{startwith} ? " AND description ~* ?" : '').
|
---|
| 3256 | ($args{filter} ? " AND description ~* ?" : '');
|
---|
| 3257 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 3258 | $errstr = $dbh->errstr if !$count;
|
---|
| 3259 | return $count;
|
---|
| 3260 | } # end getLocCount()
|
---|
| 3261 |
|
---|
| 3262 |
|
---|
| 3263 | ## DNSDB::getLocList()
|
---|
| 3264 | sub getLocList {
|
---|
[480] | 3265 | my $self = shift;
|
---|
| 3266 | my $dbh = $self->{dbh};
|
---|
[370] | 3267 |
|
---|
| 3268 | my %args = @_;
|
---|
| 3269 |
|
---|
| 3270 | my @filterargs;
|
---|
| 3271 |
|
---|
| 3272 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3273 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3274 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3275 |
|
---|
| 3276 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
| 3277 | # my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
| 3278 | # fname => 'fname');
|
---|
| 3279 | # $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 3280 |
|
---|
| 3281 | # protection against bad or missing arguments
|
---|
| 3282 | $args{sortorder} = 'ASC' if !$args{sortorder};
|
---|
| 3283 | $args{sortby} = 'l.description' if !$args{sortby};
|
---|
[397] | 3284 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[370] | 3285 |
|
---|
| 3286 | my $sql = "SELECT l.location, l.description, l.iplist, g.group_name ".
|
---|
| 3287 | "FROM locations l ".
|
---|
| 3288 | "INNER JOIN groups g ON l.group_id=g.group_id ".
|
---|
| 3289 | "WHERE l.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3290 | ($args{startwith} ? " AND l.description ~* ?" : '').
|
---|
| 3291 | ($args{filter} ? " AND l.description ~* ?" : '').
|
---|
| 3292 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
| 3293 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
| 3294 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 3295 | $errstr = $dbh->errstr if !$ulist;
|
---|
| 3296 | return $ulist;
|
---|
| 3297 | } # end getLocList()
|
---|
| 3298 |
|
---|
| 3299 |
|
---|
| 3300 | ## DNSDB::getLocDropdown()
|
---|
[383] | 3301 | # Get a list of location names for use in a dropdown menu.
|
---|
| 3302 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
| 3303 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
| 3304 | sub getLocDropdown {
|
---|
[480] | 3305 | my $self = shift;
|
---|
| 3306 | my $dbh = $self->{dbh};
|
---|
[383] | 3307 | my $grp = shift;
|
---|
| 3308 | my $sel = shift || '';
|
---|
[370] | 3309 |
|
---|
[383] | 3310 | my $sth = $dbh->prepare(qq(
|
---|
| 3311 | SELECT description,location FROM locations
|
---|
| 3312 | WHERE group_id=?
|
---|
| 3313 | ORDER BY description
|
---|
| 3314 | ) );
|
---|
| 3315 | $sth->execute($grp);
|
---|
[370] | 3316 |
|
---|
[383] | 3317 | my @loclist;
|
---|
[446] | 3318 | push @loclist, { locname => "(Default/All)", loc => '', selected => ($sel ? 0 : ($sel eq '' ? 1 : 0)) };
|
---|
[383] | 3319 | while (my ($locname, $loc) = $sth->fetchrow_array) {
|
---|
| 3320 | my %row = (
|
---|
| 3321 | locname => $locname,
|
---|
| 3322 | loc => $loc,
|
---|
| 3323 | selected => ($sel eq $loc ? 1 : 0)
|
---|
| 3324 | );
|
---|
| 3325 | push @loclist, \%row;
|
---|
| 3326 | }
|
---|
| 3327 | return \@loclist;
|
---|
| 3328 | } # end getLocDropdown()
|
---|
| 3329 |
|
---|
| 3330 |
|
---|
[2] | 3331 | ## DNSDB::getSOA()
|
---|
| 3332 | # Return all suitable fields from an SOA record in separate elements of a hash
|
---|
[224] | 3333 | # Takes a database handle, default/live flag, domain/reverse flag, and parent ID
|
---|
[2] | 3334 | sub getSOA {
|
---|
| 3335 | $errstr = '';
|
---|
[481] | 3336 | my $self = shift;
|
---|
| 3337 | my $dbh = $self->{dbh};
|
---|
[2] | 3338 | my $def = shift;
|
---|
[224] | 3339 | my $rev = shift;
|
---|
[2] | 3340 | my $id = shift;
|
---|
| 3341 |
|
---|
[224] | 3342 | # (ab)use distance and weight columns to store SOA data? can't for default_rev_records...
|
---|
| 3343 | # - should really attach serial to the zone parent somewhere
|
---|
[101] | 3344 |
|
---|
[224] | 3345 | my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev).
|
---|
| 3346 | " WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}";
|
---|
[311] | 3347 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
| 3348 | return if !$ret;
|
---|
[246] | 3349 | ##fixme: stick a flag somewhere if the record doesn't exist. by the API, this is an impossible case, but...
|
---|
[2] | 3350 |
|
---|
[311] | 3351 | ($ret->{contact},$ret->{prins}) = split /:/, $ret->{host};
|
---|
| 3352 | delete $ret->{host};
|
---|
| 3353 | ($ret->{refresh},$ret->{retry},$ret->{expire},$ret->{minttl}) = split /:/, $ret->{val};
|
---|
| 3354 | delete $ret->{val};
|
---|
[2] | 3355 |
|
---|
[311] | 3356 | return $ret;
|
---|
[2] | 3357 | } # end getSOA()
|
---|
| 3358 |
|
---|
| 3359 |
|
---|
[246] | 3360 | ## DNSDB::updateSOA()
|
---|
| 3361 | # Update the specified SOA record
|
---|
| 3362 | # Takes a database handle, default/live flag, forward/reverse flag, and SOA data hash
|
---|
[277] | 3363 | # Returns a two-element list with a result code and message
|
---|
[246] | 3364 | sub updateSOA {
|
---|
[473] | 3365 | my $self = shift;
|
---|
| 3366 | my $dbh = $self->{dbh};
|
---|
[246] | 3367 | my $defrec = shift;
|
---|
[248] | 3368 | my $revrec = shift;
|
---|
[246] | 3369 |
|
---|
| 3370 | my %soa = @_;
|
---|
| 3371 |
|
---|
[473] | 3372 | my $oldsoa = $self->getSOA($defrec, $revrec, $soa{id});
|
---|
[277] | 3373 |
|
---|
[311] | 3374 | my $msg;
|
---|
| 3375 | my %logdata;
|
---|
| 3376 | if ($defrec eq 'n') {
|
---|
| 3377 | $logdata{domain_id} = $soa{id} if $revrec eq 'n';
|
---|
| 3378 | $logdata{rdns_id} = $soa{id} if $revrec eq 'y';
|
---|
[473] | 3379 | $logdata{group_id} = $self->parentID(id => $soa{id}, revrec => $revrec,
|
---|
| 3380 | type => ($revrec eq 'n' ? 'domain' : 'revzone') );
|
---|
[311] | 3381 | } else {
|
---|
| 3382 | $logdata{group_id} = $soa{id};
|
---|
| 3383 | }
|
---|
[473] | 3384 | my $parname = ($defrec eq 'y' ? $self->groupName($soa{id}) :
|
---|
| 3385 | ($revrec eq 'n' ? $self->domainName($soa{id}) : $self->revName($soa{id})) );
|
---|
[311] | 3386 |
|
---|
[277] | 3387 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3388 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3389 | local $dbh->{AutoCommit} = 0;
|
---|
| 3390 | local $dbh->{RaiseError} = 1;
|
---|
| 3391 |
|
---|
| 3392 | eval {
|
---|
| 3393 | my $sql = "UPDATE "._rectable($defrec, $revrec)." SET host=?, val=?, ttl=? WHERE record_id=? AND type=6";
|
---|
| 3394 | $dbh->do($sql, undef, ("$soa{contact}:$soa{prins}", "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}",
|
---|
[311] | 3395 | $soa{ttl}, $oldsoa->{record_id}) );
|
---|
| 3396 | $msg = "Updated ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse ' : 'default ') : '').
|
---|
| 3397 | "SOA for $parname: ".
|
---|
| 3398 | "(ns $oldsoa->{prins}, contact $oldsoa->{contact}, refresh $oldsoa->{refresh},".
|
---|
| 3399 | " retry $oldsoa->{retry}, expire $oldsoa->{expire}, minTTL $oldsoa->{minttl}, TTL $oldsoa->{ttl}) to ".
|
---|
[277] | 3400 | "(ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
|
---|
| 3401 | " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})";
|
---|
| 3402 |
|
---|
[311] | 3403 | $logdata{entry} = $msg;
|
---|
[487] | 3404 | $self->_log(%logdata);
|
---|
[277] | 3405 |
|
---|
| 3406 | $dbh->commit;
|
---|
| 3407 | };
|
---|
| 3408 | if ($@) {
|
---|
| 3409 | $msg = $@;
|
---|
| 3410 | eval { $dbh->rollback; };
|
---|
[311] | 3411 | $logdata{entry} = "Error updating ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse zone ' : 'default ') : '').
|
---|
| 3412 | "SOA record for $parname: $msg";
|
---|
| 3413 | if ($config{log_failures}) {
|
---|
[487] | 3414 | $self->_log(%logdata);
|
---|
[311] | 3415 | $dbh->commit;
|
---|
| 3416 | }
|
---|
| 3417 | return ('FAIL', $logdata{entry});
|
---|
[277] | 3418 | } else {
|
---|
| 3419 | return ('OK', $msg);
|
---|
| 3420 | }
|
---|
[246] | 3421 | } # end updateSOA()
|
---|
| 3422 |
|
---|
| 3423 |
|
---|
[2] | 3424 | ## DNSDB::getRecLine()
|
---|
| 3425 | # Return all data fields for a zone record in separate elements of a hash
|
---|
[243] | 3426 | # Takes a database handle, default/live flag, forward/reverse flag, and record ID
|
---|
[2] | 3427 | sub getRecLine {
|
---|
| 3428 | $errstr = '';
|
---|
[481] | 3429 | my $self = shift;
|
---|
| 3430 | my $dbh = $self->{dbh};
|
---|
[243] | 3431 | my $defrec = shift;
|
---|
| 3432 | my $revrec = shift;
|
---|
[2] | 3433 | my $id = shift;
|
---|
| 3434 |
|
---|
[429] | 3435 | my $sql = "SELECT record_id,host,type,val,ttl".
|
---|
| 3436 | ($defrec eq 'n' ? ',location' : '').
|
---|
| 3437 | ($revrec eq 'n' ? ',distance,weight,port' : '').
|
---|
[243] | 3438 | (($defrec eq 'y') ? ',group_id FROM ' : ',domain_id,rdns_id FROM ').
|
---|
| 3439 | _rectable($defrec,$revrec)." WHERE record_id=?";
|
---|
[123] | 3440 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
[2] | 3441 |
|
---|
[90] | 3442 | if ($dbh->err) {
|
---|
[2] | 3443 | $errstr = $DBI::errstr;
|
---|
| 3444 | return undef;
|
---|
| 3445 | }
|
---|
| 3446 |
|
---|
[123] | 3447 | if (!$ret) {
|
---|
| 3448 | $errstr = "No such record";
|
---|
| 3449 | return undef;
|
---|
| 3450 | }
|
---|
| 3451 |
|
---|
[243] | 3452 | # explicitly set a parent id
|
---|
| 3453 | if ($defrec eq 'y') {
|
---|
| 3454 | $ret->{parid} = $ret->{group_id};
|
---|
| 3455 | } else {
|
---|
| 3456 | $ret->{parid} = (($revrec eq 'n') ? $ret->{domain_id} : $ret->{rdns_id});
|
---|
| 3457 | # and a secondary if we have a custom type that lives in both a forward and reverse zone
|
---|
| 3458 | $ret->{secid} = (($revrec eq 'y') ? $ret->{domain_id} : $ret->{rdns_id}) if $ret->{type} > 65279;
|
---|
| 3459 | }
|
---|
[451] | 3460 | $ret->{address} = $ret->{val}; # because.
|
---|
[90] | 3461 |
|
---|
| 3462 | return $ret;
|
---|
[2] | 3463 | }
|
---|
| 3464 |
|
---|
| 3465 |
|
---|
| 3466 | ##fixme: should use above (getRecLine()) to get lines for below?
|
---|
| 3467 | ## DNSDB::getDomRecs()
|
---|
| 3468 | # Return records for a domain
|
---|
| 3469 | # Takes a database handle, default/live flag, group/domain ID, start,
|
---|
| 3470 | # number of records, sort field, and sort order
|
---|
| 3471 | # Returns a reference to an array of hashes
|
---|
| 3472 | sub getDomRecs {
|
---|
| 3473 | $errstr = '';
|
---|
[481] | 3474 | my $self = shift;
|
---|
| 3475 | my $dbh = $self->{dbh};
|
---|
[2] | 3476 |
|
---|
[397] | 3477 | my %args = @_;
|
---|
[4] | 3478 |
|
---|
[397] | 3479 | my @filterargs;
|
---|
[135] | 3480 |
|
---|
[397] | 3481 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3482 |
|
---|
| 3483 | # protection against bad or missing arguments
|
---|
| 3484 | $args{sortorder} = 'ASC' if !$args{sortorder};
|
---|
[399] | 3485 | $args{sortby} = 'host' if !$args{sortby} && $args{revrec} eq 'n'; # default sort by host on domain record list
|
---|
| 3486 | $args{sortby} = 'val' if !$args{sortby} && $args{revrec} eq 'y'; # default sort by IP on revzone record list
|
---|
[397] | 3487 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
| 3488 |
|
---|
[352] | 3489 | # sort reverse zones on IP, correctly
|
---|
[397] | 3490 | # do other fiddling with $args{sortby} while we're at it.
|
---|
[420] | 3491 | # whee! multisort means just passing comma-separated fields in sortby!
|
---|
| 3492 | my $newsort = '';
|
---|
| 3493 | foreach my $sf (split /,/, $args{sortby}) {
|
---|
| 3494 | $sf = "r.$sf";
|
---|
| 3495 | $sf =~ s/r\.val/CAST (r.val AS inet)/
|
---|
| 3496 | if $args{revrec} eq 'y' && $args{defrec} eq 'n';
|
---|
| 3497 | $sf =~ s/r\.type/t.alphaorder/;
|
---|
| 3498 | $newsort .= ",$sf";
|
---|
| 3499 | }
|
---|
| 3500 | $newsort =~ s/^,//;
|
---|
[352] | 3501 |
|
---|
[224] | 3502 | my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.ttl";
|
---|
[397] | 3503 | $sql .= ",l.description AS locname" if $args{defrec} eq 'n';
|
---|
| 3504 | $sql .= ",r.distance,r.weight,r.port" if $args{revrec} eq 'n';
|
---|
| 3505 | $sql .= " FROM "._rectable($args{defrec},$args{revrec})." r ";
|
---|
[104] | 3506 | $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
|
---|
[397] | 3507 | $sql .= "LEFT JOIN locations l ON r.location=l.location " if $args{defrec} eq 'n';
|
---|
| 3508 | $sql .= "WHERE "._recparent($args{defrec},$args{revrec})." = ?";
|
---|
[104] | 3509 | $sql .= " AND NOT r.type=$reverse_typemap{SOA}";
|
---|
[439] | 3510 | $sql .= " AND (r.host ~* ? OR r.val ~* ?)" if $args{filter};
|
---|
[420] | 3511 | $sql .= " ORDER BY $newsort $args{sortorder}";
|
---|
[324] | 3512 | # ensure consistent ordering by sorting on record_id too
|
---|
[397] | 3513 | $sql .= ", record_id $args{sortorder}";
|
---|
| 3514 | $sql .= ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
[4] | 3515 |
|
---|
[397] | 3516 | my @bindvars = ($args{id});
|
---|
[439] | 3517 | push @bindvars, ($args{filter},$args{filter}) if $args{filter};
|
---|
[224] | 3518 |
|
---|
[397] | 3519 | my $ret = $dbh->selectall_arrayref($sql, { Slice => {} }, (@bindvars) );
|
---|
[2] | 3520 | return $ret;
|
---|
| 3521 | } # end getDomRecs()
|
---|
| 3522 |
|
---|
| 3523 |
|
---|
[91] | 3524 | ## DNSDB::getRecCount()
|
---|
[224] | 3525 | # Return count of non-SOA records in zone (or default records in a group)
|
---|
| 3526 | # Takes a database handle, default/live flag, reverse/forward flag, group/domain ID,
|
---|
| 3527 | # and optional filtering modifier
|
---|
[91] | 3528 | # Returns the count
|
---|
| 3529 | sub getRecCount {
|
---|
[481] | 3530 | my $self = shift;
|
---|
| 3531 | my $dbh = $self->{dbh};
|
---|
[91] | 3532 | my $defrec = shift;
|
---|
[224] | 3533 | my $revrec = shift;
|
---|
[91] | 3534 | my $id = shift;
|
---|
[135] | 3535 | my $filter = shift || '';
|
---|
[91] | 3536 |
|
---|
[135] | 3537 | # keep the nasties down, since we can't ?-sub this bit. :/
|
---|
| 3538 | # note this is chars allowed in DNS hostnames
|
---|
| 3539 | $filter =~ s/[^a-zA-Z0-9_.:-]//g;
|
---|
| 3540 |
|
---|
[222] | 3541 | my @bindvars = ($id);
|
---|
| 3542 | push @bindvars, $filter if $filter;
|
---|
[224] | 3543 | my $sql = "SELECT count(*) FROM ".
|
---|
| 3544 | _rectable($defrec,$revrec).
|
---|
| 3545 | " WHERE "._recparent($defrec,$revrec)."=? ".
|
---|
| 3546 | "AND NOT type=$reverse_typemap{SOA}".
|
---|
| 3547 | ($filter ? " AND host ~* ?" : '');
|
---|
| 3548 | my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) );
|
---|
[91] | 3549 |
|
---|
| 3550 | return $count;
|
---|
| 3551 |
|
---|
| 3552 | } # end getRecCount()
|
---|
| 3553 |
|
---|
| 3554 |
|
---|
[3] | 3555 | ## DNSDB::addRec()
|
---|
[2] | 3556 | # Add a new record to a domain or a group's default records
|
---|
| 3557 | # Takes a database handle, default/live flag, group/domain ID,
|
---|
| 3558 | # host, type, value, and TTL
|
---|
| 3559 | # Some types require additional detail: "distance" for MX and SRV,
|
---|
| 3560 | # and weight/port for SRV
|
---|
| 3561 | # Returns a status code and detail message in case of error
|
---|
[234] | 3562 | ##fixme: pass a hash with the record data, not a series of separate values
|
---|
[2] | 3563 | sub addRec {
|
---|
| 3564 | $errstr = '';
|
---|
[481] | 3565 | my $self = shift;
|
---|
| 3566 | my $dbh = $self->{dbh};
|
---|
[2] | 3567 | my $defrec = shift;
|
---|
[226] | 3568 | my $revrec = shift;
|
---|
| 3569 | my $id = shift; # parent (group_id for defrecs, rdns_id for reverse records,
|
---|
| 3570 | # domain_id for domain records)
|
---|
[2] | 3571 |
|
---|
| 3572 | my $host = shift;
|
---|
[234] | 3573 | my $rectype = shift; # reference so we can coerce it if "+"-types can't find both zones
|
---|
[2] | 3574 | my $val = shift;
|
---|
| 3575 | my $ttl = shift;
|
---|
[389] | 3576 | my $location = shift;
|
---|
| 3577 | $location = '' if !$location;
|
---|
[2] | 3578 |
|
---|
[417] | 3579 | # Spaces are evil.
|
---|
| 3580 | $$host =~ s/^\s+//;
|
---|
| 3581 | $$host =~ s/\s+$//;
|
---|
[418] | 3582 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
[417] | 3583 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 3584 | $$val =~ s/^\s+//;
|
---|
| 3585 | $$val =~ s/\s+$//;
|
---|
| 3586 | }
|
---|
| 3587 |
|
---|
[226] | 3588 | # prep for validation
|
---|
[252] | 3589 | my $addr = NetAddr::IP->new($$val);
|
---|
| 3590 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
[226] | 3591 |
|
---|
| 3592 | my $domid = 0;
|
---|
| 3593 | my $revid = 0;
|
---|
| 3594 |
|
---|
| 3595 | my $retcode = 'OK'; # assume everything will go OK
|
---|
| 3596 | my $retmsg = '';
|
---|
| 3597 |
|
---|
| 3598 | # do simple validation first
|
---|
| 3599 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
|
---|
| 3600 |
|
---|
[234] | 3601 | # Quick check on hostname parts. Note the regex is more forgiving than the error message;
|
---|
| 3602 | # domain names technically are case-insensitive, and we use printf-like % codes for a couple
|
---|
| 3603 | # of types. Other things may also be added to validate default records of several flavours.
|
---|
| 3604 | return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z . _)")
|
---|
[350] | 3605 | if $defrec eq 'n' && ($revrec eq 'y' ? $$rectype != $reverse_typemap{TXT} : 1) &&
|
---|
| 3606 | $$host !~ /^[0-9a-z_%.-]+$/i;
|
---|
[226] | 3607 |
|
---|
[234] | 3608 | # Collect these even if we're only doing a simple A record so we can call *any* validation sub
|
---|
| 3609 | my $dist = shift;
|
---|
[281] | 3610 | my $weight = shift;
|
---|
[234] | 3611 | my $port = shift;
|
---|
[226] | 3612 |
|
---|
[234] | 3613 | my $fields;
|
---|
| 3614 | my @vallist;
|
---|
[226] | 3615 |
|
---|
[234] | 3616 | # Call the validation sub for the type requested.
|
---|
[481] | 3617 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec, id => $id,
|
---|
[249] | 3618 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
[234] | 3619 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
[481] | 3620 | fields => \$fields, vallist => \@vallist);
|
---|
[129] | 3621 |
|
---|
[234] | 3622 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
[209] | 3623 |
|
---|
[234] | 3624 | # Set up database fields and bind parameters
|
---|
[481] | 3625 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
| 3626 | push @vallist, ($$host,$$rectype,$$val,$ttl,$id);
|
---|
| 3627 |
|
---|
| 3628 | # locations are not for default records, silly coder!
|
---|
| 3629 | if ($defrec eq 'n') {
|
---|
| 3630 | $fields .= ",location";
|
---|
| 3631 | push @vallist, $location;
|
---|
| 3632 | }
|
---|
[234] | 3633 | my $vallen = '?'.(',?'x$#vallist);
|
---|
[2] | 3634 |
|
---|
[287] | 3635 | # Put together the success log entry. We have to use this horrible kludge
|
---|
| 3636 | # because domain_id and rdns_id may or may not be present, and if they are,
|
---|
| 3637 | # they're not at a guaranteed consistent index in the array. wheee!
|
---|
| 3638 | my %logdata;
|
---|
| 3639 | my @ftmp = split /,/, $fields;
|
---|
| 3640 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
| 3641 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
| 3642 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
| 3643 | }
|
---|
| 3644 | $logdata{group_id} = $id if $defrec eq 'y';
|
---|
[473] | 3645 | $logdata{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec)
|
---|
[287] | 3646 | if $defrec eq 'n';
|
---|
[328] | 3647 | $logdata{entry} = "Added ".($defrec eq 'y' ? 'default record' : 'record');
|
---|
| 3648 | # NS records for revzones get special treatment
|
---|
| 3649 | if ($revrec eq 'y' && $$rectype == 2) {
|
---|
| 3650 | $logdata{entry} .= " '$$val $typemap{$$rectype} $$host";
|
---|
| 3651 | } else {
|
---|
| 3652 | $logdata{entry} .= " '$$host $typemap{$$rectype} $$val";
|
---|
| 3653 | }
|
---|
| 3654 |
|
---|
[287] | 3655 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
| 3656 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]"
|
---|
| 3657 | if $typemap{$$rectype} eq 'SRV';
|
---|
[425] | 3658 | $logdata{entry} .= "', TTL $ttl";
|
---|
[480] | 3659 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location;
|
---|
[287] | 3660 |
|
---|
[90] | 3661 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3662 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3663 | local $dbh->{AutoCommit} = 0;
|
---|
| 3664 | local $dbh->{RaiseError} = 1;
|
---|
[2] | 3665 |
|
---|
[90] | 3666 | eval {
|
---|
[236] | 3667 | $dbh->do("INSERT INTO "._rectable($defrec, $revrec)." ($fields) VALUES ($vallen)",
|
---|
[90] | 3668 | undef, @vallist);
|
---|
[487] | 3669 | $self->_log(%logdata);
|
---|
[90] | 3670 | $dbh->commit;
|
---|
| 3671 | };
|
---|
| 3672 | if ($@) {
|
---|
| 3673 | my $msg = $@;
|
---|
| 3674 | eval { $dbh->rollback; };
|
---|
[289] | 3675 | if ($config{log_failures}) {
|
---|
| 3676 | $logdata{entry} = "Failed adding ".($defrec eq 'y' ? 'default ' : '').
|
---|
| 3677 | "record '$$host $typemap{$$rectype} $$val', TTL $ttl ($msg)";
|
---|
[487] | 3678 | $self->_log(%logdata);
|
---|
[289] | 3679 | $dbh->commit;
|
---|
| 3680 | }
|
---|
[90] | 3681 | return ('FAIL',$msg);
|
---|
| 3682 | }
|
---|
[2] | 3683 |
|
---|
[287] | 3684 | $resultstr = $logdata{entry};
|
---|
[226] | 3685 | return ($retcode, $retmsg);
|
---|
[90] | 3686 |
|
---|
[2] | 3687 | } # end addRec()
|
---|
| 3688 |
|
---|
| 3689 |
|
---|
[16] | 3690 | ## DNSDB::updateRec()
|
---|
| 3691 | # Update a record
|
---|
[273] | 3692 | # Takes a database handle, default and reverse flags, record ID, immediate parent ID, and new record data.
|
---|
| 3693 | # Returns a status code and message
|
---|
[16] | 3694 | sub updateRec {
|
---|
| 3695 | $errstr = '';
|
---|
[17] | 3696 |
|
---|
[481] | 3697 | my $self = shift;
|
---|
| 3698 | my $dbh = $self->{dbh};
|
---|
[16] | 3699 | my $defrec = shift;
|
---|
[272] | 3700 | my $revrec = shift;
|
---|
[16] | 3701 | my $id = shift;
|
---|
[272] | 3702 | my $parid = shift; # immediate parent entity that we're descending from to update the record
|
---|
[16] | 3703 |
|
---|
[273] | 3704 | # all records have these
|
---|
[16] | 3705 | my $host = shift;
|
---|
[272] | 3706 | my $hostbk = $$host; # Keep a backup copy of the original, so we can WARN if the update mangles the domain
|
---|
| 3707 | my $rectype = shift;
|
---|
[16] | 3708 | my $val = shift;
|
---|
| 3709 | my $ttl = shift;
|
---|
[389] | 3710 | my $location = shift; # may be empty/null/undef depending on caller
|
---|
| 3711 | $location = '' if !$location;
|
---|
[16] | 3712 |
|
---|
[417] | 3713 | # Spaces are evil.
|
---|
| 3714 | $$host =~ s/^\s+//;
|
---|
| 3715 | $$host =~ s/\s+$//;
|
---|
[418] | 3716 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
[417] | 3717 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 3718 | $$val =~ s/^\s+//;
|
---|
| 3719 | $$val =~ s/\s+$//;
|
---|
| 3720 | }
|
---|
| 3721 |
|
---|
[272] | 3722 | # prep for validation
|
---|
| 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.
|
---|
[16] | 3725 |
|
---|
[272] | 3726 | my $domid = 0;
|
---|
| 3727 | my $revid = 0;
|
---|
| 3728 |
|
---|
| 3729 | my $retcode = 'OK'; # assume everything will go OK
|
---|
| 3730 | my $retmsg = '';
|
---|
| 3731 |
|
---|
[273] | 3732 | # do simple validation first
|
---|
[272] | 3733 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
|
---|
| 3734 |
|
---|
| 3735 | # Quick check on hostname parts. Note the regex is more forgiving than the error message;
|
---|
| 3736 | # domain names technically are case-insensitive, and we use printf-like % codes for a couple
|
---|
| 3737 | # of types. Other things may also be added to validate default records of several flavours.
|
---|
[273] | 3738 | return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z - . _)")
|
---|
[350] | 3739 | if $defrec eq 'n' && ($revrec eq 'y' ? $$rectype != $reverse_typemap{TXT} : 1) &&
|
---|
| 3740 | $$host !~ /^[0-9a-z_%.-]+$/i;
|
---|
[272] | 3741 |
|
---|
[273] | 3742 | # only MX and SRV will use these
|
---|
[288] | 3743 | my $dist = shift || 0;
|
---|
| 3744 | my $weight = shift || 0;
|
---|
| 3745 | my $port = shift || 0;
|
---|
[16] | 3746 |
|
---|
[272] | 3747 | my $fields;
|
---|
| 3748 | my @vallist;
|
---|
[16] | 3749 |
|
---|
[273] | 3750 | # get old record data so we have the right parent ID
|
---|
| 3751 | # and for logging (eventually)
|
---|
[481] | 3752 | my $oldrec = $self->getRecLine($defrec, $revrec, $id);
|
---|
[223] | 3753 |
|
---|
[272] | 3754 | # Call the validation sub for the type requested.
|
---|
| 3755 | # Note the ID to pass here is the *parent*, not the record
|
---|
[481] | 3756 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec,
|
---|
[272] | 3757 | id => ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})),
|
---|
| 3758 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
| 3759 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
| 3760 | fields => \$fields, vallist => \@vallist,
|
---|
[481] | 3761 | update => $id);
|
---|
[272] | 3762 |
|
---|
| 3763 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
| 3764 |
|
---|
[273] | 3765 | # Set up database fields and bind parameters. Note only the optional fields
|
---|
| 3766 | # (distance, weight, port, secondary parent ID) are added in the validation call above
|
---|
[448] | 3767 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
| 3768 | push @vallist, ($$host,$$rectype,$$val,$ttl,
|
---|
[273] | 3769 | ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})) );
|
---|
[272] | 3770 |
|
---|
[448] | 3771 | # locations are not for default records, silly coder!
|
---|
| 3772 | if ($defrec eq 'n') {
|
---|
| 3773 | $fields .= ",location";
|
---|
| 3774 | push @vallist, $location;
|
---|
| 3775 | }
|
---|
| 3776 |
|
---|
[273] | 3777 | # hack hack PTHUI
|
---|
| 3778 | # need to forcibly make sure we disassociate a record with a parent it's no longer related to.
|
---|
| 3779 | # eg, PTR records may not have a domain parent, or A/AAAA records may not have a revzone parent.
|
---|
| 3780 | # mainly needed for crossover types that got coerced down to "standard" types
|
---|
| 3781 | if ($defrec eq 'n') {
|
---|
| 3782 | if ($$rectype == $reverse_typemap{PTR}) {
|
---|
| 3783 | $fields .= ",domain_id";
|
---|
| 3784 | push @vallist, 0;
|
---|
| 3785 | }
|
---|
| 3786 | if ($$rectype == $reverse_typemap{A} || $$rectype == $reverse_typemap{AAAA}) {
|
---|
| 3787 | $fields .= ",rdns_id";
|
---|
| 3788 | push @vallist, 0;
|
---|
| 3789 | }
|
---|
| 3790 | }
|
---|
[345] | 3791 | # fix fat-finger-originated record type changes
|
---|
| 3792 | if ($$rectype == 65285) {
|
---|
| 3793 | $fields .= ",rdns_id" if $revrec eq 'n';
|
---|
| 3794 | $fields .= ",domain_id" if $revrec eq 'y';
|
---|
| 3795 | push @vallist, 0;
|
---|
| 3796 | }
|
---|
[341] | 3797 | if ($defrec eq 'n') {
|
---|
| 3798 | $domid = $parid if $revrec eq 'n';
|
---|
| 3799 | $revid = $parid if $revrec eq 'y';
|
---|
| 3800 | }
|
---|
[272] | 3801 |
|
---|
[288] | 3802 | # Put together the success log entry. Horrible kludge from addRec() copied as-is since
|
---|
| 3803 | # we don't know whether the passed arguments or retrieved values for domain_id and rdns_id
|
---|
| 3804 | # will be maintained (due to "not-in-zone" validation changes)
|
---|
| 3805 | my %logdata;
|
---|
[341] | 3806 | $logdata{domain_id} = $domid;
|
---|
| 3807 | $logdata{rdns_id} = $revid;
|
---|
[288] | 3808 | my @ftmp = split /,/, $fields;
|
---|
| 3809 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
| 3810 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
| 3811 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
| 3812 | }
|
---|
| 3813 | $logdata{group_id} = $parid if $defrec eq 'y';
|
---|
[473] | 3814 | $logdata{group_id} = $self->parentID(id => $parid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec)
|
---|
[288] | 3815 | if $defrec eq 'n';
|
---|
[328] | 3816 | $logdata{entry} = "Updated ".($defrec eq 'y' ? 'default record' : 'record')." from\n";
|
---|
| 3817 | # NS records for revzones get special treatment
|
---|
| 3818 | if ($revrec eq 'y' && $$rectype == 2) {
|
---|
| 3819 | $logdata{entry} .= " '$oldrec->{val} $typemap{$oldrec->{type}} $oldrec->{host}";
|
---|
| 3820 | } else {
|
---|
| 3821 | $logdata{entry} .= " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
| 3822 | }
|
---|
[288] | 3823 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
| 3824 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
| 3825 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
[425] | 3826 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
[480] | 3827 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location};
|
---|
[425] | 3828 | $logdata{entry} .= "\nto\n";
|
---|
[328] | 3829 | # More NS special
|
---|
| 3830 | if ($revrec eq 'y' && $$rectype == 2) {
|
---|
| 3831 | $logdata{entry} .= "'$$val $typemap{$$rectype} $$host";
|
---|
| 3832 | } else {
|
---|
| 3833 | $logdata{entry} .= "'$$host $typemap{$$rectype} $$val";
|
---|
| 3834 | }
|
---|
[288] | 3835 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
| 3836 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$$rectype} eq 'SRV';
|
---|
[425] | 3837 | $logdata{entry} .= "', TTL $ttl";
|
---|
[480] | 3838 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location;
|
---|
[288] | 3839 |
|
---|
[90] | 3840 | local $dbh->{AutoCommit} = 0;
|
---|
| 3841 | local $dbh->{RaiseError} = 1;
|
---|
| 3842 |
|
---|
[341] | 3843 | # Fiddle the field list into something suitable for updates
|
---|
| 3844 | $fields =~ s/,/=?,/g;
|
---|
| 3845 | $fields .= "=?";
|
---|
| 3846 |
|
---|
[90] | 3847 | eval {
|
---|
[273] | 3848 | $dbh->do("UPDATE "._rectable($defrec,$revrec)." SET $fields WHERE record_id=?", undef, (@vallist, $id) );
|
---|
[487] | 3849 | $self->_log(%logdata);
|
---|
[130] | 3850 | $dbh->commit;
|
---|
[90] | 3851 | };
|
---|
| 3852 | if ($@) {
|
---|
| 3853 | my $msg = $@;
|
---|
[288] | 3854 | eval { $dbh->rollback; };
|
---|
[289] | 3855 | if ($config{log_failures}) {
|
---|
| 3856 | $logdata{entry} = "Failed updating ".($defrec eq 'y' ? 'default ' : '').
|
---|
| 3857 | "record '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
[487] | 3858 | $self->_log(%logdata);
|
---|
[289] | 3859 | $dbh->commit;
|
---|
| 3860 | }
|
---|
[90] | 3861 | return ('FAIL', $msg);
|
---|
| 3862 | }
|
---|
| 3863 |
|
---|
[288] | 3864 | $resultstr = $logdata{entry};
|
---|
[272] | 3865 | return ($retcode, $retmsg);
|
---|
[16] | 3866 | } # end updateRec()
|
---|
| 3867 |
|
---|
| 3868 |
|
---|
[459] | 3869 | ## DNSDB::downconvert()
|
---|
| 3870 | # A mostly internal (not exported) semiutilty sub to downconvert from pseudotype <x>
|
---|
| 3871 | # to a compatible component type. Only a handful of operations are valid, anything
|
---|
| 3872 | # else is a null-op.
|
---|
| 3873 | # Takes the record ID and the new type. Returns boolean.
|
---|
| 3874 | sub downconvert {
|
---|
[481] | 3875 | my $self = shift;
|
---|
| 3876 | my $dbh = $self->{dbh};
|
---|
[459] | 3877 | my $recid = shift;
|
---|
| 3878 | my $newtype = shift;
|
---|
| 3879 |
|
---|
| 3880 | # also, only work on live records; little to no value trying to do this on default records.
|
---|
[481] | 3881 | my $rec = $self->getRecLine('n', 'y', $recid);
|
---|
[459] | 3882 |
|
---|
| 3883 | # hm?
|
---|
| 3884 | #return 1 if !$rec;
|
---|
| 3885 |
|
---|
| 3886 | return 1 if $rec->{type} < 65000; # Only the reverse-record pseudotypes can be downconverted
|
---|
| 3887 | return 1 if $rec->{type} == 65282; # Nowhere to go
|
---|
| 3888 |
|
---|
| 3889 | my $delpar;
|
---|
| 3890 | my @sqlargs;
|
---|
| 3891 | if ($rec->{type} == 65280) {
|
---|
| 3892 | return 1 if $newtype != 1 && $newtype != 12;
|
---|
| 3893 | $delpar = ($newtype == 1 ? 'rdns_id' : 'domain_id');
|
---|
| 3894 | push @sqlargs, 0, $newtype, $recid;
|
---|
| 3895 | } elsif ($rec->{type} == 65281) {
|
---|
| 3896 | return 1 if $newtype != 28 && $newtype != 12;
|
---|
| 3897 | $delpar = ($newtype == 28 ? 'rdns_id' : 'domain_id');
|
---|
| 3898 | push @sqlargs, 0, $newtype, $recid;
|
---|
| 3899 | } elsif ($rec->{type} == 65283) {
|
---|
| 3900 | return 1 if $newtype != 65282;
|
---|
| 3901 | $delpar = 'rdns_id';
|
---|
| 3902 | } elsif ($rec->{type} == 65284) {
|
---|
| 3903 | return 1 if $newtype != 65282;
|
---|
| 3904 | $delpar = 'rdns_id';
|
---|
| 3905 | } else {
|
---|
| 3906 | # Your llama is on fire.
|
---|
| 3907 | }
|
---|
| 3908 |
|
---|
| 3909 | local $dbh->{AutoCommit} = 0;
|
---|
| 3910 | local $dbh->{RaiseError} = 1;
|
---|
| 3911 |
|
---|
| 3912 | eval {
|
---|
| 3913 | $dbh->do("UPDATE records SET $delpar = ?, type = ? WHERE record_id = ?", undef, @sqlargs);
|
---|
| 3914 | $dbh->commit;
|
---|
| 3915 | };
|
---|
| 3916 | if ($@) {
|
---|
| 3917 | $errstr = $@;
|
---|
| 3918 | eval { $dbh->rollback; };
|
---|
| 3919 | return 0;
|
---|
| 3920 | }
|
---|
| 3921 | return 1;
|
---|
| 3922 | } # end downconvert()
|
---|
| 3923 |
|
---|
| 3924 |
|
---|
[3] | 3925 | ## DNSDB::delRec()
|
---|
| 3926 | # Delete a record.
|
---|
| 3927 | sub delRec {
|
---|
| 3928 | $errstr = '';
|
---|
[481] | 3929 | my $self = shift;
|
---|
| 3930 | my $dbh = $self->{dbh};
|
---|
[3] | 3931 | my $defrec = shift;
|
---|
[243] | 3932 | my $revrec = shift;
|
---|
[3] | 3933 | my $id = shift;
|
---|
| 3934 |
|
---|
[481] | 3935 | my $oldrec = $self->getRecLine($defrec, $revrec, $id);
|
---|
[3] | 3936 |
|
---|
[290] | 3937 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3938 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3939 | local $dbh->{AutoCommit} = 0;
|
---|
| 3940 | local $dbh->{RaiseError} = 1;
|
---|
[3] | 3941 |
|
---|
[290] | 3942 | # Put together the log entry
|
---|
| 3943 | my %logdata;
|
---|
| 3944 | $logdata{domain_id} = $oldrec->{domain_id};
|
---|
| 3945 | $logdata{rdns_id} = $oldrec->{rdns_id};
|
---|
| 3946 | $logdata{group_id} = $oldrec->{group_id} if $defrec eq 'y';
|
---|
[473] | 3947 | $logdata{group_id} = $self->parentID(id => $oldrec->{domain_id}, type => ($revrec eq 'n' ? 'domain' : 'revzone'),
|
---|
| 3948 | revrec => $revrec)
|
---|
[290] | 3949 | if $defrec eq 'n';
|
---|
| 3950 | $logdata{entry} = "Deleted ".($defrec eq 'y' ? 'default record ' : 'record ').
|
---|
| 3951 | "'$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
| 3952 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
| 3953 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
| 3954 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
[425] | 3955 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
[480] | 3956 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location};
|
---|
[290] | 3957 |
|
---|
| 3958 | eval {
|
---|
| 3959 | my $sth = $dbh->do("DELETE FROM "._rectable($defrec,$revrec)." WHERE record_id=?", undef, ($id));
|
---|
[487] | 3960 | $self->_log(%logdata);
|
---|
[290] | 3961 | $dbh->commit;
|
---|
| 3962 | };
|
---|
| 3963 | if ($@) {
|
---|
| 3964 | my $msg = $@;
|
---|
| 3965 | eval { $dbh->rollback; };
|
---|
| 3966 | if ($config{log_failures}) {
|
---|
| 3967 | $logdata{entry} = "Error deleting ".($defrec eq 'y' ? 'default record' : 'record').
|
---|
| 3968 | " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
[487] | 3969 | $self->_log(%logdata);
|
---|
[290] | 3970 | $dbh->commit;
|
---|
| 3971 | }
|
---|
| 3972 | return ('FAIL', $msg);
|
---|
| 3973 | }
|
---|
| 3974 |
|
---|
| 3975 | return ('OK',$logdata{entry});
|
---|
[3] | 3976 | } # end delRec()
|
---|
| 3977 |
|
---|
| 3978 |
|
---|
[323] | 3979 | ## DNSDB::getLogCount()
|
---|
| 3980 | # Get a count of log entries
|
---|
| 3981 | # Takes a database handle and a hash containing at least:
|
---|
| 3982 | # - Entity ID and entity type as the primary log "slice"
|
---|
| 3983 | sub getLogCount {
|
---|
[483] | 3984 | my $self = shift;
|
---|
| 3985 | my $dbh = $self->{dbh};
|
---|
[323] | 3986 |
|
---|
| 3987 | my %args = @_;
|
---|
| 3988 |
|
---|
| 3989 | my @filterargs;
|
---|
| 3990 | ##fixme: which fields do we want to filter on?
|
---|
| 3991 | # push @filterargs,
|
---|
| 3992 |
|
---|
| 3993 | $errstr = 'Missing primary parent ID and/or type';
|
---|
| 3994 | # fail early if we don't have a "prime" ID to look for log entries for
|
---|
| 3995 | return if !$args{id};
|
---|
| 3996 |
|
---|
| 3997 | # or if the prime id type is missing or invalid
|
---|
| 3998 | return if !$args{logtype};
|
---|
| 3999 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
| 4000 | $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
|
---|
| 4001 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
|
---|
| 4002 |
|
---|
| 4003 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
| 4004 |
|
---|
| 4005 | my $sql = "SELECT count(*) FROM log ".
|
---|
| 4006 | "WHERE $id_col{$args{logtype}}=?".
|
---|
| 4007 | ($args{filter} ? " AND entry ~* ?" : '');
|
---|
| 4008 | my ($count) = $dbh->selectrow_array($sql, undef, ($args{id}, @filterargs) );
|
---|
| 4009 | $errstr = $dbh->errstr if !$count;
|
---|
| 4010 | return $count;
|
---|
| 4011 | } # end getLogCount()
|
---|
| 4012 |
|
---|
| 4013 |
|
---|
| 4014 | ## DNSDB::getLogEntries()
|
---|
| 4015 | # Get a list of log entries
|
---|
| 4016 | # Takes arguments as with getLogCount() above, plus optional:
|
---|
| 4017 | # - sort field
|
---|
| 4018 | # - sort order
|
---|
| 4019 | # - offset for pagination
|
---|
| 4020 | sub getLogEntries {
|
---|
[483] | 4021 | my $self = shift;
|
---|
| 4022 | my $dbh = $self->{dbh};
|
---|
[323] | 4023 |
|
---|
| 4024 | my %args = @_;
|
---|
| 4025 |
|
---|
| 4026 | my @filterargs;
|
---|
| 4027 |
|
---|
| 4028 | # fail early if we don't have a "prime" ID to look for log entries for
|
---|
| 4029 | return if !$args{id};
|
---|
| 4030 |
|
---|
| 4031 | # or if the prime id type is missing or invalid
|
---|
| 4032 | return if !$args{logtype};
|
---|
| 4033 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
| 4034 | $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
|
---|
| 4035 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
|
---|
| 4036 |
|
---|
| 4037 | # Sorting defaults
|
---|
| 4038 | $args{sortby} = 'stamp' if !$args{sortby};
|
---|
| 4039 | $args{sortorder} = 'DESC' if !$args{sortorder};
|
---|
[397] | 4040 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[323] | 4041 |
|
---|
[324] | 4042 | my %sortmap = (fname => 'name', username => 'email', entry => 'entry', stamp => 'stamp');
|
---|
[323] | 4043 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 4044 |
|
---|
| 4045 | my $sql = "SELECT user_id AS userid, email AS useremail, name AS userfname, entry AS logentry, ".
|
---|
| 4046 | "date_trunc('second',stamp) AS logtime ".
|
---|
| 4047 | "FROM log ".
|
---|
| 4048 | "WHERE $id_col{$args{logtype}}=?".
|
---|
| 4049 | ($args{filter} ? " AND entry ~* ?" : '').
|
---|
[324] | 4050 | " ORDER BY $args{sortby} $args{sortorder}, log_id $args{sortorder}".
|
---|
[323] | 4051 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
| 4052 | my $loglist = $dbh->selectall_arrayref($sql, { Slice => {} }, ($args{id}, @filterargs) );
|
---|
| 4053 | $errstr = $dbh->errstr if !$loglist;
|
---|
| 4054 | return $loglist;
|
---|
| 4055 | } # end getLogEntries()
|
---|
| 4056 |
|
---|
| 4057 |
|
---|
[452] | 4058 | ## IPDB::getRevPattern()
|
---|
| 4059 | # Get the narrowest template pattern applicable to a passed CIDR address (may be a netblock or an IP)
|
---|
| 4060 | sub getRevPattern {
|
---|
[483] | 4061 | my $self = shift;
|
---|
| 4062 | my $dbh = $self->{dbh};
|
---|
[452] | 4063 | my $cidr = shift;
|
---|
| 4064 | my $group = shift || 1; # just in case
|
---|
| 4065 |
|
---|
[462] | 4066 | # for speed! Casting and comparing even ~7K records takes ~2.5s, so narrow it down to one revzone first.
|
---|
| 4067 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >>= ? AND group_id = ?",
|
---|
| 4068 | undef, ($cidr, $group) );
|
---|
| 4069 |
|
---|
| 4070 | ##fixme? may need to narrow things down more by octet-chopping and doing text comparisons before casting.
|
---|
| 4071 | my ($revpatt) = $dbh->selectrow_array("SELECT host FROM records ".
|
---|
| 4072 | "WHERE (type in (12,65280,65281,65282,65283,65284)) AND rdns_id = ? AND CAST (val AS inet) >>= ? ".
|
---|
| 4073 | "ORDER BY CAST (val AS inet) DESC LIMIT 1", undef, ($revid, $cidr) );
|
---|
[452] | 4074 | return $revpatt;
|
---|
| 4075 | } # end getRevPattern()
|
---|
| 4076 |
|
---|
| 4077 |
|
---|
[225] | 4078 | ## DNSDB::getTypelist()
|
---|
| 4079 | # Get a list of record types for various UI dropdowns
|
---|
| 4080 | # Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A)
|
---|
| 4081 | # Returns an arrayref to list of hashrefs perfect for HTML::Template
|
---|
| 4082 | sub getTypelist {
|
---|
[483] | 4083 | my $self = shift;
|
---|
| 4084 | my $dbh = $self->{dbh};
|
---|
[225] | 4085 | my $recgroup = shift;
|
---|
| 4086 | my $type = shift || $reverse_typemap{A};
|
---|
| 4087 |
|
---|
| 4088 | # also accepting $webvar{revrec}!
|
---|
| 4089 | $recgroup = 'f' if $recgroup eq 'n';
|
---|
| 4090 | $recgroup = 'r' if $recgroup eq 'y';
|
---|
| 4091 |
|
---|
| 4092 | my $sql = "SELECT val,name FROM rectypes WHERE ";
|
---|
| 4093 | if ($recgroup eq 'r') {
|
---|
| 4094 | # reverse zone types
|
---|
| 4095 | $sql .= "stdflag=2 OR stdflag=3";
|
---|
| 4096 | } elsif ($recgroup eq 'l') {
|
---|
| 4097 | # DNS lookup types. Note we avoid our custom types >= 65280, since those are entirely internal.
|
---|
| 4098 | $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280";
|
---|
| 4099 | } else {
|
---|
| 4100 | # default; forward zone types. technically $type eq 'f' but not worth the error message.
|
---|
| 4101 | $sql .= "stdflag=1 OR stdflag=2";
|
---|
| 4102 | }
|
---|
| 4103 | $sql .= " ORDER BY listorder";
|
---|
| 4104 |
|
---|
| 4105 | my $sth = $dbh->prepare($sql);
|
---|
| 4106 | $sth->execute;
|
---|
| 4107 | my @typelist;
|
---|
| 4108 | while (my ($rval,$rname) = $sth->fetchrow_array()) {
|
---|
| 4109 | my %row = ( recval => $rval, recname => $rname );
|
---|
| 4110 | $row{tselect} = 1 if $rval == $type;
|
---|
| 4111 | push @typelist, \%row;
|
---|
| 4112 | }
|
---|
| 4113 |
|
---|
| 4114 | # Add SOA on lookups since it's not listed in other dropdowns.
|
---|
| 4115 | if ($recgroup eq 'l') {
|
---|
| 4116 | my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
|
---|
| 4117 | $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
|
---|
| 4118 | push @typelist, \%row;
|
---|
| 4119 | }
|
---|
| 4120 |
|
---|
| 4121 | return \@typelist;
|
---|
| 4122 | } # end getTypelist()
|
---|
| 4123 |
|
---|
| 4124 |
|
---|
[254] | 4125 | ## DNSDB::parentID()
|
---|
| 4126 | # Get ID of entity that is nearest parent to requested id
|
---|
| 4127 | # Takes a database handle and a hash of entity ID, entity type, optional parent type flag
|
---|
| 4128 | # (domain/reverse zone or group), and optional default/live and forward/reverse flags
|
---|
| 4129 | # Returns the ID or undef on failure
|
---|
| 4130 | sub parentID {
|
---|
[473] | 4131 | my $self = shift;
|
---|
| 4132 | my $dbh = $self->{dbh};
|
---|
[116] | 4133 |
|
---|
[254] | 4134 | my %args = @_;
|
---|
[116] | 4135 |
|
---|
[254] | 4136 | # clean up the parent-type. Set it to group if not set; coerce revzone to domain for simpler logic
|
---|
| 4137 | $args{partype} = 'group' if !$args{partype};
|
---|
| 4138 | $args{partype} = 'domain' if $args{partype} eq 'revzone';
|
---|
[116] | 4139 |
|
---|
[254] | 4140 | # clean up defrec and revrec. default to live record, forward zone
|
---|
| 4141 | $args{defrec} = 'n' if !$args{defrec};
|
---|
| 4142 | $args{revrec} = 'n' if !$args{revrec};
|
---|
[116] | 4143 |
|
---|
[254] | 4144 | if ($par_type{$args{partype}} eq 'domain') {
|
---|
| 4145 | # only live records can have a domain/zone parent
|
---|
| 4146 | return unless ($args{type} eq 'record' && $args{defrec} eq 'n');
|
---|
| 4147 | my $result = $dbh->selectrow_hashref("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
| 4148 | " FROM records WHERE record_id = ?",
|
---|
| 4149 | undef, ($args{id}) ) or return;
|
---|
| 4150 | return $result;
|
---|
| 4151 | } else {
|
---|
| 4152 | # snag some arguments that will either fall through or be overwritten to save some code duplication
|
---|
| 4153 | my $tmpid = $args{id};
|
---|
| 4154 | my $type = $args{type};
|
---|
| 4155 | if ($type eq 'record' && $args{defrec} eq 'n') {
|
---|
| 4156 | # Live records go through the records table first.
|
---|
| 4157 | ($tmpid) = $dbh->selectrow_array("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
| 4158 | " FROM records WHERE record_id = ?",
|
---|
| 4159 | undef, ($args{id}) ) or return;
|
---|
| 4160 | $type = ($args{revrec} eq 'n' ? 'domain' : 'revzone');
|
---|
| 4161 | }
|
---|
| 4162 | my ($result) = $dbh->selectrow_array("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
|
---|
| 4163 | undef, ($tmpid) );
|
---|
| 4164 | return $result;
|
---|
| 4165 | }
|
---|
| 4166 | # should be impossible to get here with even remotely sane arguments
|
---|
| 4167 | return;
|
---|
| 4168 | } # end parentID()
|
---|
[116] | 4169 |
|
---|
| 4170 |
|
---|
[117] | 4171 | ## DNSDB::isParent()
|
---|
| 4172 | # Returns true if $id1 is a parent of $id2, false otherwise
|
---|
| 4173 | sub isParent {
|
---|
[470] | 4174 | my $self = shift;
|
---|
| 4175 | my $dbh = $self->{dbh};
|
---|
[117] | 4176 | my $id1 = shift;
|
---|
| 4177 | my $type1 = shift;
|
---|
| 4178 | my $id2 = shift;
|
---|
| 4179 | my $type2 = shift;
|
---|
| 4180 | ##todo: immediate, secondary, full (default)
|
---|
| 4181 |
|
---|
[157] | 4182 | # Return false on invalid types
|
---|
[244] | 4183 | return 0 if !grep /^$type1$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
| 4184 | return 0 if !grep /^$type2$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
[157] | 4185 |
|
---|
[117] | 4186 | # Return false on impossible relations
|
---|
| 4187 | return 0 if $type1 eq 'record'; # nothing may be a child of a record
|
---|
| 4188 | return 0 if $type1 eq 'defrec'; # nothing may be a child of a record
|
---|
[244] | 4189 | return 0 if $type1 eq 'defrevrec'; # nothing may be a child of a record
|
---|
[117] | 4190 | return 0 if $type1 eq 'user'; # nothing may be child of a user
|
---|
| 4191 | return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record
|
---|
[244] | 4192 | return 0 if $type1 eq 'revzone' && $type2 ne 'record';# reverse zone may not be a parent of anything other than a record
|
---|
[117] | 4193 |
|
---|
[186] | 4194 | # ennnhhhh.... if we're passed an id of 0, it will never be found. usual
|
---|
| 4195 | # case would be the UI creating a new <thing>, and so we don't have an ID for
|
---|
| 4196 | # <thing> to look up yet. in that case the UI should check the parent as well.
|
---|
| 4197 | return 0 if $id1 == 0; # nothing can have a parent id of 0
|
---|
| 4198 | return 1 if $id2 == 0; # anything could have a child id of 0 (or "unknown")
|
---|
| 4199 |
|
---|
[117] | 4200 | # group 1 is the ultimate root parent
|
---|
| 4201 | return 1 if $type1 eq 'group' && $id1 == 1;
|
---|
| 4202 |
|
---|
[155] | 4203 | # groups are always (a) parent of themselves
|
---|
| 4204 | return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2;
|
---|
| 4205 |
|
---|
[117] | 4206 | my $id = $id2;
|
---|
| 4207 | my $type = $type2;
|
---|
| 4208 | my $foundparent = 0;
|
---|
[155] | 4209 |
|
---|
[244] | 4210 | # Records are the only entity with two possible parents. We need to split the parent checks on
|
---|
| 4211 | # domain/rdns.
|
---|
| 4212 | if ($type eq 'record') {
|
---|
| 4213 | my ($dom,$rdns) = $dbh->selectrow_array("SELECT domain_id,rdns_id FROM records WHERE record_id=?",
|
---|
| 4214 | undef, ($id));
|
---|
| 4215 | # check immediate parent against request
|
---|
| 4216 | return 1 if $type1 eq 'domain' && $id1 == $dom;
|
---|
| 4217 | return 1 if $type1 eq 'revzone' && $id1 == $rdns;
|
---|
| 4218 | # if request is group, check *both* parents. Only check if the parent is nonzero though.
|
---|
[470] | 4219 | return 1 if $dom && $self->isParent($id1, $type1, $dom, 'domain');
|
---|
| 4220 | return 1 if $rdns && $self->isParent($id1, $type1, $rdns, 'revzone');
|
---|
[244] | 4221 | # exit here since we've executed the loop below by proxy in the above recursive calls.
|
---|
| 4222 | return 0;
|
---|
| 4223 | }
|
---|
| 4224 |
|
---|
| 4225 | # almost the same loop as getParents() above
|
---|
[186] | 4226 | my $limiter = 0;
|
---|
[117] | 4227 | while (1) {
|
---|
[155] | 4228 | my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
|
---|
[117] | 4229 | my $result = $dbh->selectrow_hashref($sql,
|
---|
[157] | 4230 | undef, ($id) );
|
---|
[186] | 4231 | if (!$result) {
|
---|
| 4232 | $limiter++;
|
---|
[244] | 4233 | ##fixme: how often will this happen on a live site? fail at max limiter <n>?
|
---|
[186] | 4234 | warn "no results looking for $sql with id $id (depth $limiter)\n";
|
---|
| 4235 | last;
|
---|
| 4236 | }
|
---|
[157] | 4237 | if ($result && $result->{$par_col{$type}} == $id1) {
|
---|
[117] | 4238 | $foundparent = 1;
|
---|
| 4239 | last;
|
---|
[157] | 4240 | } else {
|
---|
| 4241 | ##fixme: do we care about trying to return a "no such record/domain/user/group" error?
|
---|
[244] | 4242 | # should be impossible to create an inconsistent DB just with API calls.
|
---|
[157] | 4243 | warn $dbh->errstr." $sql, $id" if $dbh->errstr;
|
---|
[117] | 4244 | }
|
---|
| 4245 | # group 1 is its own parent. need this here more to break strange loops than for detecting a parent
|
---|
| 4246 | last if $result->{$par_col{$type}} == 1;
|
---|
[152] | 4247 | $id = $result->{$par_col{$type}};
|
---|
[117] | 4248 | $type = $par_type{$type};
|
---|
| 4249 | }
|
---|
| 4250 |
|
---|
| 4251 | return $foundparent;
|
---|
| 4252 | } # end isParent()
|
---|
| 4253 |
|
---|
| 4254 |
|
---|
[275] | 4255 | ## DNSDB::zoneStatus()
|
---|
| 4256 | # Returns and optionally sets a zone's status
|
---|
| 4257 | # Takes a database handle, domain/revzone ID, forward/reverse flag, and optionally a status argument
|
---|
| 4258 | # Returns status, or undef on errors.
|
---|
| 4259 | sub zoneStatus {
|
---|
[477] | 4260 | my $self = shift;
|
---|
| 4261 | my $dbh = $self->{dbh};
|
---|
[3] | 4262 | my $id = shift;
|
---|
[275] | 4263 | my $revrec = shift;
|
---|
| 4264 | my $newstatus = shift || 'mu';
|
---|
[3] | 4265 |
|
---|
| 4266 | return undef if $id !~ /^\d+$/;
|
---|
| 4267 |
|
---|
[283] | 4268 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4269 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4270 | local $dbh->{AutoCommit} = 0;
|
---|
| 4271 | local $dbh->{RaiseError} = 1;
|
---|
| 4272 |
|
---|
[275] | 4273 | if ($newstatus ne 'mu') {
|
---|
[283] | 4274 | # ooo, fun! let's see what we were passed for status
|
---|
| 4275 | eval {
|
---|
| 4276 | $newstatus = 0 if $newstatus eq 'domoff';
|
---|
| 4277 | $newstatus = 1 if $newstatus eq 'domon';
|
---|
| 4278 | $dbh->do("UPDATE ".($revrec eq 'n' ? 'domains' : 'revzones')." SET status=? WHERE ".
|
---|
[275] | 4279 | ($revrec eq 'n' ? 'domain_id' : 'rdns_id')."=?", undef, ($newstatus,$id) );
|
---|
[283] | 4280 |
|
---|
| 4281 | ##fixme switch to more consise "Enabled <domain"/"Disabled <domain>" as with users?
|
---|
[473] | 4282 | $resultstr = "Changed ".($revrec eq 'n' ? $self->domainName($id) : $self->revName($id)).
|
---|
[283] | 4283 | " state to ".($newstatus ? 'active' : 'inactive');
|
---|
| 4284 |
|
---|
| 4285 | my %loghash;
|
---|
| 4286 | $loghash{domain_id} = $id if $revrec eq 'n';
|
---|
| 4287 | $loghash{rdns_id} = $id if $revrec eq 'y';
|
---|
[473] | 4288 | $loghash{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec);
|
---|
[283] | 4289 | $loghash{entry} = $resultstr;
|
---|
[487] | 4290 | $self->_log(%loghash);
|
---|
[283] | 4291 |
|
---|
| 4292 | $dbh->commit;
|
---|
| 4293 | };
|
---|
| 4294 | if ($@) {
|
---|
| 4295 | my $msg = $@;
|
---|
| 4296 | eval { $dbh->rollback; };
|
---|
| 4297 | $resultstr = '';
|
---|
| 4298 | $errstr = $msg;
|
---|
| 4299 | return;
|
---|
| 4300 | }
|
---|
[3] | 4301 | }
|
---|
| 4302 |
|
---|
[275] | 4303 | my ($status) = $dbh->selectrow_array("SELECT status FROM ".
|
---|
| 4304 | ($revrec eq 'n' ? "domains WHERE domain_id=?" : "revzones WHERE rdns_id=?"),
|
---|
| 4305 | undef, ($id) );
|
---|
[3] | 4306 | return $status;
|
---|
[275] | 4307 | } # end zoneStatus()
|
---|
[3] | 4308 |
|
---|
| 4309 |
|
---|
[452] | 4310 | ## DNSDB::getZonesByCIDR()
|
---|
| 4311 | # Get a list of zone names and IDs that records for a passed CIDR block are within.
|
---|
| 4312 | sub getZonesByCIDR {
|
---|
[477] | 4313 | my $self = shift;
|
---|
| 4314 | my $dbh = $self->{dbh};
|
---|
[452] | 4315 | my %args = @_;
|
---|
| 4316 |
|
---|
| 4317 | my $result = $dbh->selectall_arrayref("SELECT rdns_id,revnet FROM revzones WHERE revnet >>= ? OR revnet <<= ?",
|
---|
| 4318 | { Slice => {} }, ($args{cidr}, $args{cidr}) );
|
---|
| 4319 | return $result;
|
---|
| 4320 | } # end getZonesByCIDR()
|
---|
| 4321 |
|
---|
| 4322 |
|
---|
[33] | 4323 | ## DNSDB::importAXFR
|
---|
| 4324 | # Import a domain via AXFR
|
---|
[37] | 4325 | # Takes AXFR host, domain to transfer, group to put the domain in,
|
---|
[484] | 4326 | # and an optional hash containing:
|
---|
| 4327 | # status - active/inactive state flag (defaults to active)
|
---|
| 4328 | # rwsoa - overwrite-SOA flag (defaults to off)
|
---|
| 4329 | # rwns - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
|
---|
| 4330 | # merge - flag to automerge A or AAAA records with matching PTR records
|
---|
[37] | 4331 | # Returns a status code (OK, WARN, or FAIL) and message - message should be blank
|
---|
| 4332 | # if status is OK, but WARN includes conditions that are not fatal but should
|
---|
| 4333 | # really be reported.
|
---|
[33] | 4334 | sub importAXFR {
|
---|
[484] | 4335 | my $self = shift;
|
---|
| 4336 | my $dbh = $self->{dbh};
|
---|
[35] | 4337 | my $ifrom_in = shift;
|
---|
[301] | 4338 | my $zone = shift;
|
---|
[33] | 4339 | my $group = shift;
|
---|
[484] | 4340 |
|
---|
| 4341 | my %args = @_;
|
---|
| 4342 |
|
---|
[33] | 4343 | ##fixme: add mode to delete&replace, merge+overwrite, merge new?
|
---|
| 4344 |
|
---|
[484] | 4345 | $args{status} = (defined($args{status}) ? $args{status} : 0);
|
---|
| 4346 | $args{status} = 1 if $args{status} eq 'on';
|
---|
| 4347 |
|
---|
[37] | 4348 | my $nrecs = 0;
|
---|
| 4349 | my $soaflag = 0;
|
---|
| 4350 | my $nsflag = 0;
|
---|
| 4351 | my $warnmsg = '';
|
---|
| 4352 | my $ifrom;
|
---|
[33] | 4353 |
|
---|
[301] | 4354 | my $rev = 'n';
|
---|
[302] | 4355 | my $code = 'OK';
|
---|
| 4356 | my $msg = 'foobar?';
|
---|
[301] | 4357 |
|
---|
[35] | 4358 | # choke on possible bad setting in ifrom
|
---|
[37] | 4359 | # IPv4 and v6, and valid hostnames!
|
---|
[35] | 4360 | ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
| 4361 | return ('FAIL', "Bad AXFR source host $ifrom")
|
---|
| 4362 | unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
| 4363 |
|
---|
[301] | 4364 | my $errmsg;
|
---|
| 4365 |
|
---|
| 4366 | my $zone_id;
|
---|
| 4367 | my $domain_id = 0;
|
---|
| 4368 | my $rdns_id = 0;
|
---|
| 4369 | my $cidr;
|
---|
| 4370 |
|
---|
| 4371 | # magic happens! detect if we're importing a domain or a reverse zone
|
---|
| 4372 | # while we're at it, figure out what the CIDR netblock is (if we got a .arpa)
|
---|
| 4373 | # or what the formal .arpa zone is (if we got a CIDR netblock)
|
---|
| 4374 | # Handles sub-octet v4 zones in the format specified in the Cricket Book, 2nd Ed, p217-218
|
---|
| 4375 |
|
---|
| 4376 | if ($zone =~ m{(?:\.arpa\.?|/\d+)$}) {
|
---|
| 4377 | # we seem to have a reverse zone
|
---|
| 4378 | $rev = 'y';
|
---|
| 4379 |
|
---|
| 4380 | if ($zone =~ /\.arpa\.?$/) {
|
---|
| 4381 | # we have a formal reverse zone. call _zone2cidr and get the CIDR block.
|
---|
| 4382 | ($code,$msg) = _zone2cidr($zone);
|
---|
| 4383 | return ($code, $msg) if $code eq 'FAIL';
|
---|
| 4384 | $cidr = $msg;
|
---|
| 4385 | } elsif ($zone =~ m|^[\d.]+/\d+$|) {
|
---|
| 4386 | # v4 revzone, CIDR netblock
|
---|
| 4387 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 4388 | $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
| 4389 | } elsif ($zone =~ m|^[a-fA-F\d:]+/\d+$|) {
|
---|
| 4390 | # v6 revzone, CIDR netblock
|
---|
| 4391 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 4392 | return ('FAIL', "$zone is not a nibble-aligned block") if $cidr->masklen % 4 != 0;
|
---|
| 4393 | $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.');
|
---|
| 4394 | } else {
|
---|
| 4395 | # there is. no. else!
|
---|
| 4396 | return ('FAIL', "Unknown zone name format");
|
---|
| 4397 | }
|
---|
| 4398 |
|
---|
| 4399 | # quick check to start to see if we've already got one
|
---|
| 4400 |
|
---|
| 4401 | ($zone_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?",
|
---|
| 4402 | undef, ("$cidr"));
|
---|
| 4403 | $rdns_id = $zone_id;
|
---|
| 4404 | } else {
|
---|
| 4405 | # default to domain
|
---|
[349] | 4406 | ($zone_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
[301] | 4407 | undef, ($zone));
|
---|
| 4408 | $domain_id = $zone_id;
|
---|
| 4409 | }
|
---|
| 4410 |
|
---|
| 4411 | return ('FAIL', ($rev eq 'n' ? 'Domain' : 'Reverse zone')." already exists") if $zone_id;
|
---|
| 4412 |
|
---|
[303] | 4413 | # little local utility sub to swap $val and $host for revzone records.
|
---|
| 4414 | sub _revswap {
|
---|
| 4415 | my $rechost = shift;
|
---|
| 4416 | my $recdata = shift;
|
---|
| 4417 |
|
---|
| 4418 | if ($rechost =~ /\.in-addr\.arpa\.?$/) {
|
---|
| 4419 | $rechost =~ s/\.in-addr\.arpa\.?$//;
|
---|
| 4420 | $rechost = join '.', reverse split /\./, $rechost;
|
---|
| 4421 | } else {
|
---|
| 4422 | $rechost =~ s/\.ip6\.arpa\.?$//;
|
---|
| 4423 | my @nibs = reverse split /\./, $rechost;
|
---|
| 4424 | $rechost = '';
|
---|
| 4425 | my $nc;
|
---|
| 4426 | foreach (@nibs) {
|
---|
| 4427 | $rechost.= $_;
|
---|
| 4428 | $rechost .= ":" if ++$nc % 4 == 0 && $nc < 32;
|
---|
| 4429 | }
|
---|
[307] | 4430 | $rechost .= ":" if $nc < 32 && $rechost !~ /\*$/; # close netblock records?
|
---|
| 4431 | ##fixme: there's a case that ends up with a partial entry here:
|
---|
| 4432 | # ip:add:re:ss::
|
---|
| 4433 | # can't reproduce after letting it sit overnight after discovery. :(
|
---|
| 4434 | #print "$rechost\n";
|
---|
[303] | 4435 | # canonicalize with NetAddr::IP
|
---|
| 4436 | $rechost = NetAddr::IP->new($rechost)->addr unless $rechost =~ /\*$/;
|
---|
| 4437 | }
|
---|
| 4438 | return ($recdata,$rechost)
|
---|
| 4439 | }
|
---|
| 4440 |
|
---|
| 4441 |
|
---|
[33] | 4442 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4443 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4444 | local $dbh->{AutoCommit} = 0;
|
---|
| 4445 | local $dbh->{RaiseError} = 1;
|
---|
| 4446 |
|
---|
[301] | 4447 | my $sth;
|
---|
| 4448 | eval {
|
---|
[34] | 4449 |
|
---|
[301] | 4450 | if ($rev eq 'n') {
|
---|
[33] | 4451 | ##fixme: serial
|
---|
[484] | 4452 | $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef,
|
---|
| 4453 | ($zone, $group, $args{status}) );
|
---|
[301] | 4454 | # get domain id so we can do the records
|
---|
| 4455 | ($zone_id) = $dbh->selectrow_array("SELECT currval('domains_domain_id_seq')");
|
---|
| 4456 | $domain_id = $zone_id;
|
---|
[487] | 4457 | $self->_log(group_id => $group, domain_id => $domain_id,
|
---|
| 4458 | entry => "[Added ".($args{status} ? 'active' : 'inactive')." domain $zone via AXFR]");
|
---|
[301] | 4459 | } else {
|
---|
| 4460 | ##fixme: serial
|
---|
[484] | 4461 | $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef,
|
---|
| 4462 | ($cidr,$group,$args{status}) );
|
---|
[301] | 4463 | # get revzone id so we can do the records
|
---|
| 4464 | ($zone_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
| 4465 | $rdns_id = $zone_id;
|
---|
[487] | 4466 | $self->_log(group_id => $group, rdns_id => $rdns_id,
|
---|
| 4467 | entry => "[Added ".($args{status} ? 'active' : 'inactive')." reverse zone $cidr via AXFR]");
|
---|
[301] | 4468 | }
|
---|
[33] | 4469 |
|
---|
[35] | 4470 | ## bizarre DBI<->Net::DNS interaction bug:
|
---|
| 4471 | ## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
|
---|
[37] | 4472 | ## fixed, apparently I was doing *something* odd, but not certain what it was that
|
---|
| 4473 | ## caused a commit instead of barfing
|
---|
[35] | 4474 |
|
---|
[34] | 4475 | my $res = Net::DNS::Resolver->new;
|
---|
[35] | 4476 | $res->nameservers($ifrom);
|
---|
[301] | 4477 | $res->axfr_start($zone)
|
---|
[35] | 4478 | or die "Couldn't begin AXFR\n";
|
---|
[34] | 4479 |
|
---|
[301] | 4480 | $sth = $dbh->prepare("INSERT INTO records (domain_id,rdns_id,host,type,val,distance,weight,port,ttl)".
|
---|
| 4481 | " VALUES (?,?,?,?,?,?,?,?,?)");
|
---|
| 4482 |
|
---|
[307] | 4483 | # Stash info about sub-octet v4 revzones here so we don't have
|
---|
| 4484 | # to store the CNAMEs used to delegate a suboctet zone
|
---|
| 4485 | # $suboct{zone}{ns}[] -> array of nameservers
|
---|
| 4486 | # $suboct{zone}{cname}[] -> array of extant CNAMEs (Just In Case someone did something bizarre)
|
---|
| 4487 | ## commented pending actual use of this data. for now, we'll just
|
---|
| 4488 | ## auto-(re)create the CNAMEs in revzones on export
|
---|
| 4489 | # my %suboct;
|
---|
| 4490 |
|
---|
[35] | 4491 | while (my $rr = $res->axfr_next()) {
|
---|
[301] | 4492 |
|
---|
| 4493 | my $val;
|
---|
| 4494 | my $distance = 0;
|
---|
| 4495 | my $weight = 0;
|
---|
| 4496 | my $port = 0;
|
---|
[303] | 4497 | my $logfrag = '';
|
---|
[301] | 4498 |
|
---|
[33] | 4499 | my $type = $rr->type;
|
---|
[301] | 4500 | my $host = $rr->name;
|
---|
[484] | 4501 | my $ttl = ($args{newttl} ? $args{newttl} : $rr->ttl); # allow force-override TTLs
|
---|
[35] | 4502 |
|
---|
[37] | 4503 | $soaflag = 1 if $type eq 'SOA';
|
---|
| 4504 | $nsflag = 1 if $type eq 'NS';
|
---|
[35] | 4505 |
|
---|
[34] | 4506 | # "Primary" types:
|
---|
| 4507 | # A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
|
---|
| 4508 | # maybe KEY
|
---|
| 4509 |
|
---|
[302] | 4510 | # BIND supports:
|
---|
| 4511 | # [standard]
|
---|
| 4512 | # A AAAA CNAME MX NS PTR SOA TXT
|
---|
| 4513 | # [variously experimental, obsolete, or obscure]
|
---|
| 4514 | # 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
|
---|
| 4515 | # ... if one can ever find the right magic to format them correctly
|
---|
| 4516 |
|
---|
| 4517 | # Net::DNS supports:
|
---|
| 4518 | # RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
|
---|
| 4519 | # EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
|
---|
| 4520 | # DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
|
---|
| 4521 |
|
---|
[35] | 4522 | # nasty big ugly case-like thing here, since we have to do *some* different
|
---|
| 4523 | # processing depending on the record. le sigh.
|
---|
| 4524 |
|
---|
[105] | 4525 | ##fixme: what record types other than TXT can/will have >255-byte payloads?
|
---|
| 4526 |
|
---|
[34] | 4527 | if ($type eq 'A') {
|
---|
[301] | 4528 | $val = $rr->address;
|
---|
[34] | 4529 | } elsif ($type eq 'NS') {
|
---|
[37] | 4530 | # hmm. should we warn here if subdomain NS'es are left alone?
|
---|
[484] | 4531 | next if ($args{rwns} && ($rr->name eq $zone));
|
---|
[302] | 4532 | if ($rev eq 'y') {
|
---|
| 4533 | # revzones have records more or less reversed from forward zones.
|
---|
| 4534 | my ($tmpcode,$tmpmsg) = _zone2cidr($host);
|
---|
[401] | 4535 | die "Error converting NS record: $tmpmsg\n" if $tmpcode eq 'FAIL'; # hmm. may not make sense...
|
---|
[302] | 4536 | $val = "$tmpmsg";
|
---|
| 4537 | $host = $rr->nsdname;
|
---|
[303] | 4538 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
[307] | 4539 | # Tag and preserve. For now this is commented for a no-op, but we have Ideas for
|
---|
| 4540 | # another custom storage type ("DELEGATE") that will use these subzone-delegation records
|
---|
| 4541 | #if ($val ne "$cidr") {
|
---|
| 4542 | # push @{$suboct{$val}{ns}}, $host;
|
---|
| 4543 | #}
|
---|
[302] | 4544 | } else {
|
---|
| 4545 | $val = $rr->nsdname;
|
---|
| 4546 | }
|
---|
[35] | 4547 | $nsflag = 1;
|
---|
[34] | 4548 | } elsif ($type eq 'CNAME') {
|
---|
[302] | 4549 | if ($rev eq 'y') {
|
---|
[303] | 4550 | # hmm. do we even want to bother with storing these at this level? Sub-octet delegation
|
---|
| 4551 | # by CNAME is essentially a record-publication hack, and we want to just represent the
|
---|
| 4552 | # "true" logical intentions as far down the stack as we can from the UI.
|
---|
| 4553 | ($host,$val) = _revswap($host,$rr->cname);
|
---|
| 4554 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
[307] | 4555 | # Tag and preserve in case we want to commit them as-is later, but mostly we don't care.
|
---|
| 4556 | # Commented pending actually doing something with possibly new type DELEGATE
|
---|
| 4557 | #my $tmprev = $host;
|
---|
| 4558 | #$tmprev =~ s/^\d+\.//;
|
---|
| 4559 | #($code,$tmprev) = _zone2cidr($tmprev);
|
---|
| 4560 | #push @{$suboct{"$tmprev"}{cname}}, $val;
|
---|
| 4561 | # Silently skip CNAMEs in revzones.
|
---|
| 4562 | next;
|
---|
[302] | 4563 | } else {
|
---|
| 4564 | $val = $rr->cname;
|
---|
| 4565 | }
|
---|
[34] | 4566 | } elsif ($type eq 'SOA') {
|
---|
[484] | 4567 | next if $args{rwsoa};
|
---|
[307] | 4568 | $host = $rr->rname.":".$rr->mname;
|
---|
[301] | 4569 | $val = $rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum;
|
---|
[35] | 4570 | $soaflag = 1;
|
---|
[34] | 4571 | } elsif ($type eq 'PTR') {
|
---|
[303] | 4572 | ($host,$val) = _revswap($host,$rr->ptrdname);
|
---|
| 4573 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
[34] | 4574 | # hmm. PTR records should not be in forward zones.
|
---|
| 4575 | } elsif ($type eq 'MX') {
|
---|
[301] | 4576 | $val = $rr->exchange;
|
---|
| 4577 | $distance = $rr->preference;
|
---|
[34] | 4578 | } elsif ($type eq 'TXT') {
|
---|
| 4579 | ##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
|
---|
| 4580 | ## but don't really seem enthusiastic about it.
|
---|
[303] | 4581 | #print "should use rdatastr:\n\t".$rr->rdatastr."\n or char_str_list:\n\t".join(' ',$rr->char_str_list())."\n";
|
---|
| 4582 | # rdatastr returns a BIND-targetted logical string, including opening and closing quotes
|
---|
| 4583 | # char_str_list returns a list of the individual string fragments in the record
|
---|
[307] | 4584 | # txtdata returns the more useful all-in-one form (since we want to push such protocol
|
---|
| 4585 | # details as far down the stack as we can)
|
---|
[303] | 4586 | # NB: this may turn out to be more troublesome if we ever have need of >512-byte TXT records.
|
---|
| 4587 | if ($rev eq 'y') {
|
---|
| 4588 | ($host,$val) = _revswap($host,$rr->txtdata);
|
---|
| 4589 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
| 4590 | } else {
|
---|
| 4591 | $val = $rr->txtdata;
|
---|
| 4592 | }
|
---|
[34] | 4593 | } elsif ($type eq 'SPF') {
|
---|
| 4594 | ##fixme: and the same caveat here, since it is apparently a clone of ::TXT
|
---|
[301] | 4595 | $val = $rr->txtdata;
|
---|
[34] | 4596 | } elsif ($type eq 'AAAA') {
|
---|
[301] | 4597 | $val = $rr->address;
|
---|
[34] | 4598 | } elsif ($type eq 'SRV') {
|
---|
[301] | 4599 | $val = $rr->target;
|
---|
| 4600 | $distance = $rr->priority;
|
---|
| 4601 | $weight = $rr->weight;
|
---|
| 4602 | $port = $rr->port;
|
---|
[34] | 4603 | } elsif ($type eq 'KEY') {
|
---|
[35] | 4604 | # we don't actually know what to do with these...
|
---|
[301] | 4605 | $val = $rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname;
|
---|
[35] | 4606 | } else {
|
---|
[301] | 4607 | $val = $rr->rdatastr;
|
---|
[35] | 4608 | # Finding a different record type is not fatal.... just problematic.
|
---|
[37] | 4609 | # We may not be able to export it correctly.
|
---|
[35] | 4610 | $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
|
---|
[33] | 4611 | }
|
---|
| 4612 |
|
---|
[303] | 4613 | my $logentry = "[AXFR ".($rev eq 'n' ? $zone : $cidr)."] ";
|
---|
[34] | 4614 |
|
---|
[484] | 4615 | if ($args{merge}) {
|
---|
[307] | 4616 | if ($rev eq 'n') {
|
---|
| 4617 | # importing a domain; we have A and AAAA records that could be merged with matching PTR records
|
---|
| 4618 | my $etype;
|
---|
| 4619 | my ($erdns,$erid,$ettl) = $dbh->selectrow_array("SELECT rdns_id,record_id,ttl FROM records ".
|
---|
| 4620 | "WHERE host=? AND val=? AND type=12",
|
---|
| 4621 | undef, ($host, $val) );
|
---|
| 4622 | if ($erid) {
|
---|
| 4623 | if ($type eq 'A') { # PTR -> A+PTR
|
---|
| 4624 | $etype = 65280;
|
---|
| 4625 | $logentry .= "Merged A record with existing PTR record '$host A+PTR $val', TTL $ettl";
|
---|
| 4626 | }
|
---|
| 4627 | if ($type eq 'AAAA') { # PTR -> AAAA+PTR
|
---|
| 4628 | $etype = 65281;
|
---|
| 4629 | $logentry .= "Merged AAAA record with existing PTR record '$host AAAA+PTR $val', TTL $ettl";
|
---|
| 4630 | }
|
---|
| 4631 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
| 4632 | $dbh->do("UPDATE records SET domain_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
| 4633 | ($domain_id, $ettl, $etype, $erid));
|
---|
| 4634 | $nrecs++;
|
---|
[487] | 4635 | $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $erdns, entry => $logentry);
|
---|
[307] | 4636 | next; # while axfr_next
|
---|
| 4637 | }
|
---|
| 4638 | } # $rev eq 'n'
|
---|
| 4639 | else {
|
---|
| 4640 | # importing a revzone, we have PTR records that could be merged with matching A/AAAA records
|
---|
| 4641 | my ($domid,$erid,$ettl,$etype) = $dbh->selectrow_array("SELECT domain_id,record_id,ttl,type FROM records ".
|
---|
| 4642 | "WHERE host=? AND val=? AND (type=1 OR type=28)",
|
---|
| 4643 | undef, ($host, $val) );
|
---|
| 4644 | if ($erid) {
|
---|
| 4645 | if ($etype == 1) { # A -> A+PTR
|
---|
| 4646 | $etype = 65280;
|
---|
| 4647 | $logentry .= "Merged PTR record with existing matching A record '$host A+PTR $val', TTL $ettl";
|
---|
| 4648 | }
|
---|
| 4649 | if ($etype == 28) { # AAAA -> AAAA+PTR
|
---|
| 4650 | $etype = 65281;
|
---|
| 4651 | $logentry .= "Merged PTR record with existing matching AAAA record '$host AAAA+PTR $val', TTL $ettl";
|
---|
| 4652 | }
|
---|
| 4653 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
| 4654 | $dbh->do("UPDATE records SET rdns_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
| 4655 | ($rdns_id, $ettl, $etype, $erid));
|
---|
| 4656 | $nrecs++;
|
---|
[487] | 4657 | $self->_log(group_id => $group, domain_id => $domid, rdns_id => $rdns_id, entry => $logentry);
|
---|
[307] | 4658 | next; # while axfr_next
|
---|
| 4659 | }
|
---|
| 4660 | } # $rev eq 'y'
|
---|
[484] | 4661 | } # if $args{merge}
|
---|
[34] | 4662 |
|
---|
[302] | 4663 | # Insert the new record
|
---|
[301] | 4664 | $sth->execute($domain_id, $rdns_id, $host, $reverse_typemap{$type}, $val,
|
---|
| 4665 | $distance, $weight, $port, $ttl);
|
---|
| 4666 |
|
---|
[37] | 4667 | $nrecs++;
|
---|
[34] | 4668 |
|
---|
[301] | 4669 | if ($type eq 'SOA') {
|
---|
[484] | 4670 | # also !$args{rwsoa}, but if that's set, it should be impossible to get here.
|
---|
[301] | 4671 | my @tmp1 = split /:/, $host;
|
---|
| 4672 | my @tmp2 = split /:/, $val;
|
---|
| 4673 | $logentry .= "Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
| 4674 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl";
|
---|
[303] | 4675 | } elsif ($logfrag) {
|
---|
| 4676 | # special case for log entries we need to meddle with a little.
|
---|
| 4677 | $logentry .= $logfrag;
|
---|
[301] | 4678 | } else {
|
---|
| 4679 | $logentry .= "Added record '$host $type";
|
---|
| 4680 | $logentry .= " [distance $distance]" if $type eq 'MX';
|
---|
| 4681 | $logentry .= " [priority $distance] [weight $weight] [port $port]" if $type eq 'SRV';
|
---|
| 4682 | $logentry .= " $val', TTL $ttl";
|
---|
| 4683 | }
|
---|
[487] | 4684 | $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $rdns_id, entry => $logentry);
|
---|
[301] | 4685 |
|
---|
[37] | 4686 | } # while axfr_next
|
---|
| 4687 |
|
---|
[307] | 4688 | # Detect and handle delegated subzones
|
---|
| 4689 | # Placeholder for when we decide what to actually do with this, see previous comments in NS and CNAME handling.
|
---|
| 4690 | #foreach (keys %suboct) {
|
---|
| 4691 | # print "found ".($suboct{$_}{ns} ? @{$suboct{$_}{ns}} : '0')." NS records and ".
|
---|
| 4692 | # ($suboct{$_}{cname} ? @{$suboct{$_}{cname}} : '0')." CNAMEs for $_\n";
|
---|
| 4693 | #}
|
---|
| 4694 |
|
---|
[37] | 4695 | # Overwrite SOA record
|
---|
[484] | 4696 | if ($args{rwsoa}) {
|
---|
[37] | 4697 | $soaflag = 1;
|
---|
| 4698 | my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
|
---|
| 4699 | my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
| 4700 | $sthgetsoa->execute($group,$reverse_typemap{SOA});
|
---|
| 4701 | while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
|
---|
[301] | 4702 | $host =~ s/DOMAIN/$zone/g;
|
---|
| 4703 | $val =~ s/DOMAIN/$zone/g;
|
---|
| 4704 | $sthputsoa->execute($zone_id,$host,$reverse_typemap{SOA},$val,$ttl);
|
---|
[34] | 4705 | }
|
---|
[37] | 4706 | }
|
---|
[34] | 4707 |
|
---|
[37] | 4708 | # Overwrite NS records
|
---|
[484] | 4709 | if ($args{rwns}) {
|
---|
[37] | 4710 | $nsflag = 1;
|
---|
| 4711 | my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
|
---|
| 4712 | my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
| 4713 | $sthgetns->execute($group,$reverse_typemap{NS});
|
---|
| 4714 | while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
|
---|
[301] | 4715 | $host =~ s/DOMAIN/$zone/g;
|
---|
| 4716 | $val =~ s/DOMAIN/$zone/g;
|
---|
| 4717 | $sthputns->execute($zone_id,$host,$reverse_typemap{NS},$val,$ttl);
|
---|
[37] | 4718 | }
|
---|
| 4719 | }
|
---|
[34] | 4720 |
|
---|
[35] | 4721 | die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
|
---|
| 4722 | die "Bad zone: No SOA record!\n" if !$soaflag;
|
---|
| 4723 | die "Bad zone: No NS records!\n" if !$nsflag;
|
---|
| 4724 |
|
---|
[37] | 4725 | $dbh->commit;
|
---|
[35] | 4726 |
|
---|
[33] | 4727 | };
|
---|
| 4728 |
|
---|
| 4729 | if ($@) {
|
---|
| 4730 | my $msg = $@;
|
---|
| 4731 | eval { $dbh->rollback; };
|
---|
[34] | 4732 | return ('FAIL',$msg." $warnmsg");
|
---|
[33] | 4733 | } else {
|
---|
[35] | 4734 | return ('WARN', $warnmsg) if $warnmsg;
|
---|
[91] | 4735 | return ('OK',"Imported OK");
|
---|
[33] | 4736 | }
|
---|
| 4737 |
|
---|
[37] | 4738 | # it should be impossible to get here.
|
---|
[34] | 4739 | return ('WARN',"OOOK!");
|
---|
[33] | 4740 | } # end importAXFR()
|
---|
| 4741 |
|
---|
| 4742 |
|
---|
[302] | 4743 | ## DNSDB::importBIND()
|
---|
| 4744 | sub importBIND {
|
---|
| 4745 | } # end importBIND()
|
---|
| 4746 |
|
---|
| 4747 |
|
---|
| 4748 | ## DNSDB::import_tinydns()
|
---|
| 4749 | sub import_tinydns {
|
---|
| 4750 | } # end import_tinydns()
|
---|
| 4751 |
|
---|
| 4752 |
|
---|
[103] | 4753 | ## DNSDB::export()
|
---|
| 4754 | # Export the DNS database, or a part of it
|
---|
[485] | 4755 | # Takes a string indicating the export type, plus optional arguments depending on type
|
---|
[103] | 4756 | # Writes zone data to targets as appropriate for type
|
---|
| 4757 | sub export {
|
---|
[485] | 4758 | my $self = shift;
|
---|
[103] | 4759 | my $target = shift;
|
---|
| 4760 |
|
---|
| 4761 | if ($target eq 'tiny') {
|
---|
[485] | 4762 | $self->__export_tiny(@_);
|
---|
[103] | 4763 | }
|
---|
| 4764 | # elsif ($target eq 'foo') {
|
---|
[485] | 4765 | # __export_foo(@_);
|
---|
[103] | 4766 | #}
|
---|
| 4767 | # etc
|
---|
| 4768 |
|
---|
| 4769 | } # end export()
|
---|
| 4770 |
|
---|
| 4771 |
|
---|
| 4772 | ## DNSDB::__export_tiny
|
---|
| 4773 | # Internal sub to implement tinyDNS (compatible) export
|
---|
[485] | 4774 | # Takes filehandle to write export to, optional argument(s)
|
---|
[103] | 4775 | # to determine which data gets exported
|
---|
| 4776 | sub __export_tiny {
|
---|
[485] | 4777 | my $self = shift;
|
---|
| 4778 | my $dbh = $self->{dbh};
|
---|
[103] | 4779 | my $datafile = shift;
|
---|
| 4780 |
|
---|
| 4781 | ##fixme: slurp up further options to specify particular zone(s) to export
|
---|
| 4782 |
|
---|
| 4783 | ##fixme: fail if $datafile isn't an open, writable file
|
---|
| 4784 |
|
---|
| 4785 | # easy case - export all evarything
|
---|
| 4786 | # not-so-easy case - export item(s) specified
|
---|
| 4787 | # todo: figure out what kind of list we use to export items
|
---|
| 4788 |
|
---|
[329] | 4789 | # raw packet in unknown format: first byte indicates length
|
---|
| 4790 | # of remaining data, allows up to 255 raw bytes
|
---|
| 4791 |
|
---|
[372] | 4792 | # Locations/views - worth including in the caching setup?
|
---|
| 4793 | my $lochash = $dbh->selectall_hashref("SELECT location,iplist FROM locations", 'location');
|
---|
| 4794 | foreach my $location (keys %$lochash) {
|
---|
[375] | 4795 | foreach my $ipprefix (split /[,\s]+/, $lochash->{$location}{iplist}) {
|
---|
| 4796 | $ipprefix =~ s/\s+//g;
|
---|
[449] | 4797 | $ipprefix = new NetAddr::IP $ipprefix;
|
---|
| 4798 | ##fixme: how to handle IPv6?
|
---|
| 4799 | next if $ipprefix->{isv6};
|
---|
| 4800 | # have to account for /nn CIDR entries. tinydns only speaks octet-sliced prefix.
|
---|
| 4801 | if ($ipprefix->masklen <= 8) {
|
---|
| 4802 | foreach ($ipprefix->split(8)) {
|
---|
| 4803 | my $tmp = $_->addr;
|
---|
| 4804 | $tmp =~ s/\.\d+\.\d+\.\d+$//;
|
---|
| 4805 | print $datafile "%$location:$tmp\n";
|
---|
| 4806 | }
|
---|
| 4807 | } elsif ($ipprefix->masklen <= 16) {
|
---|
| 4808 | foreach ($ipprefix->split(16)) {
|
---|
| 4809 | my $tmp = $_->addr;
|
---|
| 4810 | $tmp =~ s/\.\d+\.\d+$//;
|
---|
| 4811 | print $datafile "%$location:$tmp\n";
|
---|
| 4812 | }
|
---|
| 4813 | } elsif ($ipprefix->masklen <= 24) {
|
---|
| 4814 | foreach ($ipprefix->split(24)) {
|
---|
| 4815 | my $tmp = $_->addr;
|
---|
| 4816 | $tmp =~ s/\.\d+$//;
|
---|
| 4817 | print $datafile "%$location:$tmp\n";
|
---|
| 4818 | }
|
---|
| 4819 | } else {
|
---|
| 4820 | foreach ($ipprefix->split(32)) {
|
---|
| 4821 | print $datafile "%$location:".$_->addr."\n";
|
---|
| 4822 | }
|
---|
| 4823 | }
|
---|
[372] | 4824 | }
|
---|
| 4825 | print $datafile "%$location\n" if !$lochash->{$location}{iplist};
|
---|
| 4826 | }
|
---|
| 4827 |
|
---|
[329] | 4828 | # tracking hash so we don't double-export A+PTR or AAAA+PTR records.
|
---|
| 4829 | my %recflags;
|
---|
| 4830 |
|
---|
[368] | 4831 | my $domsth = $dbh->prepare("SELECT domain_id,domain,status,changed FROM domains WHERE status=1");
|
---|
[372] | 4832 | my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
[368] | 4833 | "FROM records WHERE domain_id=? AND type < 65280"); # Just exclude all types relating to rDNS
|
---|
[372] | 4834 | my $zonesth = $dbh->prepare("UPDATE domains SET changed='n' WHERE domain_id=?");
|
---|
[103] | 4835 | $domsth->execute();
|
---|
[368] | 4836 | while (my ($domid,$dom,$domstat,$changed) = $domsth->fetchrow_array) {
|
---|
| 4837 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
| 4838 | # O_NOFOLLOW
|
---|
| 4839 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
| 4840 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
| 4841 | # still be followed.
|
---|
| 4842 | # but that doesn't help other platforms. :/
|
---|
| 4843 | sysopen(ZONECACHE, "$config{exportcache}/$dom", O_RDWR|O_CREAT);
|
---|
| 4844 | flock(ZONECACHE, LOCK_EX);
|
---|
| 4845 | if ($changed || -s "$config{exportcache}/$dom" == 0) {
|
---|
| 4846 | $recsth->execute($domid);
|
---|
[372] | 4847 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc) = $recsth->fetchrow_array) {
|
---|
[368] | 4848 | next if $recflags{$recid};
|
---|
[108] | 4849 |
|
---|
[372] | 4850 | $loc = '' if !$loc; # de-nullify - just in case
|
---|
| 4851 | ##fixme: handle case of record-with-location-that-doesn't-exist better.
|
---|
| 4852 | # note this currently fails safe (tested) - records with a location that
|
---|
| 4853 | # doesn't exist will not be sent to any client
|
---|
| 4854 | # $loc = '' if !$lochash->{$loc};
|
---|
| 4855 |
|
---|
[108] | 4856 | ##fixme: record validity timestamp. tinydns supports fiddling with timestamps.
|
---|
| 4857 | # note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
|
---|
| 4858 | # timestamps are TAI64
|
---|
| 4859 | # ~~ 2^62 + time()
|
---|
[368] | 4860 | my $stamp = '';
|
---|
[108] | 4861 |
|
---|
[368] | 4862 | # support tinydns' auto-TTL
|
---|
| 4863 | $ttl = '' if $ttl == '0';
|
---|
[367] | 4864 |
|
---|
[417] | 4865 | # Spaces are evil.
|
---|
[441] | 4866 | $host =~ s/^\s+//;
|
---|
| 4867 | $host =~ s/\s+$//;
|
---|
| 4868 | if ($typemap{$type} ne 'TXT') {
|
---|
[417] | 4869 | # Leading or trailng spaces could be legit in TXT records.
|
---|
[441] | 4870 | $val =~ s/^\s+//;
|
---|
| 4871 | $val =~ s/\s+$//;
|
---|
[417] | 4872 | }
|
---|
| 4873 |
|
---|
[368] | 4874 | _printrec_tiny(*ZONECACHE, 'n', \%recflags,
|
---|
| 4875 | $dom, $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp)
|
---|
| 4876 | if *ZONECACHE;
|
---|
[450] | 4877 |
|
---|
[368] | 4878 | # in case the zone shrunk, get rid of garbage at the end of the file.
|
---|
| 4879 | truncate(ZONECACHE, tell(ZONECACHE));
|
---|
| 4880 |
|
---|
| 4881 | $recflags{$recid} = 1;
|
---|
| 4882 | } # while ($recsth)
|
---|
| 4883 | }
|
---|
[450] | 4884 | # stream from cache, whether freshly created or existing
|
---|
| 4885 | print $datafile $_ while <ZONECACHE>;
|
---|
[368] | 4886 | close ZONECACHE;
|
---|
| 4887 | # mark domain as unmodified
|
---|
| 4888 | $zonesth->execute($domid);
|
---|
[329] | 4889 | } # while ($domsth)
|
---|
| 4890 |
|
---|
[368] | 4891 | my $revsth = $dbh->prepare("SELECT rdns_id,revnet,status,changed FROM revzones WHERE status=1 ".
|
---|
[337] | 4892 | "ORDER BY masklen(revnet) DESC");
|
---|
[372] | 4893 |
|
---|
[344] | 4894 | # For reasons unknown, we can't sanely UNION these statements. Feh.
|
---|
| 4895 | # Supposedly it should work though (note last 3 lines):
|
---|
| 4896 | ## PG manual
|
---|
| 4897 | #UNION Clause
|
---|
| 4898 | #
|
---|
| 4899 | #The UNION clause has this general form:
|
---|
| 4900 | #
|
---|
| 4901 | # select_statement UNION [ ALL ] select_statement
|
---|
| 4902 | #
|
---|
| 4903 | #select_statement is any SELECT statement without an ORDER BY, LIMIT, FOR UPDATE, or FOR SHARE clause. (ORDER BY
|
---|
| 4904 | #and LIMIT can be attached to a subexpression if it is enclosed in parentheses. Without parentheses, these
|
---|
| 4905 | #clauses will be taken to apply to the result of the UNION, not to its right-hand input expression.)
|
---|
[372] | 4906 | my $soasth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
[344] | 4907 | "FROM records WHERE rdns_id=? AND type=6");
|
---|
[372] | 4908 | $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
[337] | 4909 | "FROM records WHERE rdns_id=? AND not type=6 ".
|
---|
[344] | 4910 | "ORDER BY masklen(CAST(val AS inet)) DESC, CAST(val AS inet)");
|
---|
[372] | 4911 | $zonesth = $dbh->prepare("UPDATE revzones SET changed='n' WHERE rdns_id=?");
|
---|
[329] | 4912 | $revsth->execute();
|
---|
[368] | 4913 | while (my ($revid,$revzone,$revstat,$changed) = $revsth->fetchrow_array) {
|
---|
| 4914 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
| 4915 | # O_NOFOLLOW
|
---|
| 4916 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
| 4917 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
| 4918 | # still be followed.
|
---|
| 4919 | # but that doesn't help other platforms. :/
|
---|
| 4920 | my $tmpzone = NetAddr::IP->new($revzone);
|
---|
| 4921 | sysopen(ZONECACHE, "$config{exportcache}/".$tmpzone->network->addr, O_RDWR|O_CREAT);
|
---|
| 4922 | flock(ZONECACHE, LOCK_EX);
|
---|
| 4923 | if ($changed || -s "$config{exportcache}/".$tmpzone->network->addr == 0) {
|
---|
| 4924 | # need to fetch this separately since the rest of the records all (should) have real IPs in val
|
---|
| 4925 | $soasth->execute($revid);
|
---|
| 4926 | my (@zsoa) = $soasth->fetchrow_array();
|
---|
[445] | 4927 | _printrec_tiny(*ZONECACHE,'y',\%recflags,$revzone,
|
---|
| 4928 | $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],'');
|
---|
[344] | 4929 |
|
---|
[368] | 4930 | $recsth->execute($revid);
|
---|
[372] | 4931 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc) = $recsth->fetchrow_array) {
|
---|
[368] | 4932 | next if $recflags{$recid};
|
---|
[329] | 4933 |
|
---|
[372] | 4934 | $loc = '' if !$loc; # de-nullify - just in case
|
---|
| 4935 | ##fixme: handle case of record-with-location-that-doesn't-exist better.
|
---|
| 4936 | # note this currently fails safe (tested) - records with a location that
|
---|
| 4937 | # doesn't exist will not be sent to any client
|
---|
| 4938 | # $loc = '' if !$lochash->{$loc};
|
---|
| 4939 |
|
---|
[329] | 4940 | ##fixme: record validity timestamp. tinydns supports fiddling with timestamps.
|
---|
| 4941 | # note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
|
---|
| 4942 | # timestamps are TAI64
|
---|
| 4943 | # ~~ 2^62 + time()
|
---|
[368] | 4944 | my $stamp = '';
|
---|
[329] | 4945 |
|
---|
[368] | 4946 | # support tinydns' auto-TTL
|
---|
| 4947 | $ttl = '' if $ttl == '0';
|
---|
[367] | 4948 |
|
---|
[368] | 4949 | _printrec_tiny(*ZONECACHE, 'y', \%recflags, $revzone,
|
---|
| 4950 | $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp)
|
---|
| 4951 | if *ZONECACHE;
|
---|
[329] | 4952 |
|
---|
[450] | 4953 | # in case the zone shrunk, get rid of garbage at the end of the file.
|
---|
| 4954 | truncate(ZONECACHE, tell(ZONECACHE));
|
---|
| 4955 |
|
---|
[368] | 4956 | $recflags{$recid} = 1;
|
---|
| 4957 | } # while ($recsth)
|
---|
| 4958 | }
|
---|
[450] | 4959 | # stream from cache, whether freshly created or existing
|
---|
| 4960 | print $datafile $_ while <ZONECACHE>;
|
---|
[368] | 4961 | close ZONECACHE;
|
---|
[450] | 4962 | # mark zone as unmodified
|
---|
[368] | 4963 | $zonesth->execute($revid);
|
---|
[329] | 4964 | } # while ($domsth)
|
---|
| 4965 |
|
---|
| 4966 | } # end __export_tiny()
|
---|
| 4967 |
|
---|
| 4968 |
|
---|
| 4969 | # Utility sub for __export_tiny above
|
---|
| 4970 | sub _printrec_tiny {
|
---|
| 4971 | my ($datafile,$revrec,$recflags,$zone,$host,$type,$val,$dist,$weight,$port,$ttl,$loc,$stamp) = @_;
|
---|
| 4972 |
|
---|
| 4973 | ## Convert a bare number into an octal-coded pair of octets.
|
---|
| 4974 | # Take optional arg to indicate a decimal or hex input. Defaults to hex.
|
---|
| 4975 | sub octalize {
|
---|
| 4976 | my $tmp = shift;
|
---|
| 4977 | my $srctype = shift || 'h'; # default assumes hex string
|
---|
| 4978 | $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
|
---|
| 4979 | $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
|
---|
| 4980 | my @o = ($tmp =~ /^(..)(..)$/); # split into octets
|
---|
| 4981 | return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);;
|
---|
| 4982 | }
|
---|
| 4983 |
|
---|
[339] | 4984 | ## WARNING: This works to export even the whole Internet's worth of IP space...
|
---|
| 4985 | ## if you have the disk/RAM to handle the dataset, and you call this sub based on /16-sized chunks
|
---|
| 4986 | ## A /16 took ~3 seconds with a handful of separate records; adding a /8 pushed export time out to ~13m:40s
|
---|
| 4987 | ## 0/0 is estimated to take ~54 hours and ~256G of disk
|
---|
| 4988 | ## RAM usage depends on how many non-template entries you have in the set.
|
---|
| 4989 | ## This should probably be done on record addition rather than export; large blocks may need to be done in a
|
---|
| 4990 | ## forked process
|
---|
| 4991 | sub __publish_subnet {
|
---|
| 4992 | my $sub = shift;
|
---|
| 4993 | my $recflags = shift;
|
---|
| 4994 | my $hpat = shift;
|
---|
| 4995 | my $fh = shift;
|
---|
| 4996 | my $ttl = shift;
|
---|
| 4997 | my $stamp = shift;
|
---|
| 4998 | my $loc = shift;
|
---|
| 4999 | my $ptronly = shift || 0;
|
---|
| 5000 |
|
---|
| 5001 | my $iplist = $sub->splitref(32);
|
---|
| 5002 | foreach (@$iplist) {
|
---|
| 5003 | my $ip = $_->addr;
|
---|
| 5004 | # make as if we split the non-octet-aligned block into octet-aligned blocks as with SOA
|
---|
| 5005 | next if $ip =~ /\.(0|255)$/;
|
---|
| 5006 | next if $$recflags{$ip};
|
---|
| 5007 | $$recflags{$ip}++;
|
---|
[463] | 5008 | next if $hpat eq '%blank%'; # Allows blanking a subnet so no records are published.
|
---|
[339] | 5009 | my $rec = $hpat; # start fresh with the template for each IP
|
---|
| 5010 | _template4_expand(\$rec, $ip);
|
---|
| 5011 | print $fh ($ptronly ? "^"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$rec" : "=$rec:$ip").
|
---|
| 5012 | ":$ttl:$stamp:$loc\n";
|
---|
| 5013 | }
|
---|
| 5014 | }
|
---|
| 5015 |
|
---|
[103] | 5016 | ##fixme? append . to all host/val hostnames
|
---|
| 5017 | if ($typemap{$type} eq 'SOA') {
|
---|
| 5018 |
|
---|
| 5019 | # host contains pri-ns:responsible
|
---|
| 5020 | # val is abused to contain refresh:retry:expire:minttl
|
---|
| 5021 | ##fixme: "manual" serial vs tinydns-autoserial
|
---|
[202] | 5022 | # let's be explicit about abusing $host and $val
|
---|
| 5023 | my ($email, $primary) = (split /:/, $host)[0,1];
|
---|
| 5024 | my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
|
---|
[330] | 5025 | if ($revrec eq 'y') {
|
---|
[337] | 5026 | ##fixme: have to publish SOA records for each v4 /24 in sub-/16, and each /16 in sub-/8
|
---|
| 5027 | # what about v6?
|
---|
| 5028 | # -> only need SOA for local chunks offset from reverse delegation boundaries, so v6 is fine
|
---|
[330] | 5029 | $zone = NetAddr::IP->new($zone);
|
---|
[337] | 5030 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
| 5031 | if (!$zone->{isv6} && ($zone->masklen < 24) && ($zone->masklen % 8 != 0)) {
|
---|
| 5032 | foreach my $szone ($zone->split($zone->masklen + (8 - $zone->masklen % 8))) {
|
---|
| 5033 | $szone = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
| 5034 | print $datafile "Z$szone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
|
---|
| 5035 | }
|
---|
| 5036 | return; # skips "default" bits just below
|
---|
| 5037 | }
|
---|
[330] | 5038 | $zone = _ZONE($zone, 'ZONE', 'r', '.').($zone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 5039 | }
|
---|
[329] | 5040 | print $datafile "Z$zone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
|
---|
[103] | 5041 |
|
---|
| 5042 | } elsif ($typemap{$type} eq 'A') {
|
---|
| 5043 |
|
---|
[108] | 5044 | print $datafile "+$host:$val:$ttl:$stamp:$loc\n";
|
---|
[103] | 5045 |
|
---|
| 5046 | } elsif ($typemap{$type} eq 'NS') {
|
---|
| 5047 |
|
---|
[330] | 5048 | if ($revrec eq 'y') {
|
---|
| 5049 | $val = NetAddr::IP->new($val);
|
---|
[345] | 5050 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
| 5051 | if (!$val->{isv6} && ($val->masklen < 24) && ($val->masklen % 8 != 0)) {
|
---|
[346] | 5052 | foreach my $szone ($val->split($val->masklen + (8 - $val->masklen % 8))) {
|
---|
[345] | 5053 | my $szone2 = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
[346] | 5054 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
[345] | 5055 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n";
|
---|
[346] | 5056 | $$recflags{$szone2} = $val->masklen;
|
---|
[345] | 5057 | }
|
---|
[346] | 5058 | } elsif ($val->{isv6} && ($val->masklen < 64) && ($val->masklen % 4 !=0)) {
|
---|
| 5059 | foreach my $szone ($val->split($val->masklen + (4 - $val->masklen % 4))) {
|
---|
| 5060 | my $szone2 = _ZONE($szone, 'ZONE.ip6.arpa', 'r', '.');
|
---|
| 5061 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
| 5062 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n";
|
---|
| 5063 | $$recflags{$szone2} = $val->masklen;
|
---|
| 5064 | }
|
---|
| 5065 | } else {
|
---|
| 5066 | my $val2 = _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 5067 | print $datafile "\&$val2"."::$host:$ttl:$stamp:$loc\n";
|
---|
| 5068 | $$recflags{$val2} = $val->masklen;
|
---|
[345] | 5069 | }
|
---|
[330] | 5070 | } else {
|
---|
| 5071 | print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n";
|
---|
| 5072 | }
|
---|
[103] | 5073 |
|
---|
| 5074 | } elsif ($typemap{$type} eq 'AAAA') {
|
---|
| 5075 |
|
---|
| 5076 | print $datafile ":$host:28:";
|
---|
| 5077 | my $altgrp = 0;
|
---|
| 5078 | my @altconv;
|
---|
[108] | 5079 | # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
|
---|
[103] | 5080 | foreach (split /:/, $val) {
|
---|
| 5081 | if (/^$/) {
|
---|
| 5082 | # flag blank entry; this is a series of 0's of (currently) unknown length
|
---|
| 5083 | $altconv[$altgrp++] = 's';
|
---|
| 5084 | } else {
|
---|
| 5085 | # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
|
---|
| 5086 | $altconv[$altgrp++] = octalize($_)
|
---|
| 5087 | }
|
---|
| 5088 | }
|
---|
| 5089 | foreach my $octet (@altconv) {
|
---|
| 5090 | # if not 's', output
|
---|
| 5091 | print $datafile $octet unless $octet =~ /^s$/;
|
---|
| 5092 | # if 's', output (9-array length)x literal '\000\000'
|
---|
| 5093 | print $datafile '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
|
---|
| 5094 | }
|
---|
[108] | 5095 | print $datafile ":$ttl:$stamp:$loc\n";
|
---|
[103] | 5096 |
|
---|
| 5097 | } elsif ($typemap{$type} eq 'MX') {
|
---|
| 5098 |
|
---|
[108] | 5099 | print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n";
|
---|
[103] | 5100 |
|
---|
| 5101 | } elsif ($typemap{$type} eq 'TXT') {
|
---|
| 5102 |
|
---|
| 5103 | ##fixme: split v-e-r-y long TXT strings? will need to do so for BIND export, at least
|
---|
[350] | 5104 | if ($revrec eq 'n') {
|
---|
| 5105 | $val =~ s/:/\\072/g; # may need to replace other symbols
|
---|
| 5106 | print $datafile "'$host:$val:$ttl:$stamp:$loc\n";
|
---|
| 5107 | } else {
|
---|
| 5108 | $host =~ s/:/\\072/g; # may need to replace other symbols
|
---|
| 5109 | my $val2 = NetAddr::IP->new($val);
|
---|
| 5110 | print $datafile "'"._ZONE($val2, 'ZONE', 'r', '.').($val2->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
| 5111 | ":$host:$ttl:$stamp:$loc\n";
|
---|
| 5112 | }
|
---|
[103] | 5113 |
|
---|
| 5114 | # by-hand TXT
|
---|
| 5115 | #:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
|
---|
| 5116 | #@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
|
---|
| 5117 | #'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
|
---|
| 5118 |
|
---|
| 5119 | #txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
|
---|
| 5120 | #: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
|
---|
| 5121 |
|
---|
| 5122 | # very long TXT record as brought in by axfr-get
|
---|
| 5123 | # note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
|
---|
| 5124 | # also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
|
---|
| 5125 | #:longtxt.deepnet.cx:16:
|
---|
| 5126 | #\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
|
---|
| 5127 | #\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.
|
---|
| 5128 | #\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.
|
---|
| 5129 | #:3600
|
---|
| 5130 |
|
---|
| 5131 | } elsif ($typemap{$type} eq 'CNAME') {
|
---|
| 5132 |
|
---|
[372] | 5133 | if ($revrec eq 'n') {
|
---|
| 5134 | print $datafile "C$host:$val:$ttl:$stamp:$loc\n";
|
---|
| 5135 | } else {
|
---|
| 5136 | my $val2 = NetAddr::IP->new($val);
|
---|
| 5137 | print $datafile "C"._ZONE($val2, 'ZONE', 'r', '.').($val2->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
| 5138 | ":$host:$ttl:$stamp:$loc\n";
|
---|
| 5139 | }
|
---|
[103] | 5140 |
|
---|
| 5141 | } elsif ($typemap{$type} eq 'SRV') {
|
---|
| 5142 |
|
---|
| 5143 | # data is two-byte values for priority, weight, port, in that order,
|
---|
| 5144 | # followed by length/string data
|
---|
| 5145 |
|
---|
| 5146 | print $datafile ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
|
---|
| 5147 |
|
---|
| 5148 | $val .= '.' if $val !~ /\.$/;
|
---|
| 5149 | foreach (split /\./, $val) {
|
---|
| 5150 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
| 5151 | }
|
---|
[108] | 5152 | print $datafile "\\000:$ttl:$stamp:$loc\n";
|
---|
[103] | 5153 |
|
---|
| 5154 | } elsif ($typemap{$type} eq 'RP') {
|
---|
| 5155 |
|
---|
| 5156 | # RP consists of two mostly free-form strings.
|
---|
| 5157 | # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
|
---|
| 5158 | # The second is the "hostname" of a TXT record with more info.
|
---|
| 5159 | print $datafile ":$host:17:";
|
---|
| 5160 | my ($who,$what) = split /\s/, $val;
|
---|
| 5161 | foreach (split /\./, $who) {
|
---|
| 5162 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
| 5163 | }
|
---|
| 5164 | print $datafile '\000';
|
---|
| 5165 | foreach (split /\./, $what) {
|
---|
| 5166 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
| 5167 | }
|
---|
[108] | 5168 | print $datafile "\\000:$ttl:$stamp:$loc\n";
|
---|
[103] | 5169 |
|
---|
| 5170 | } elsif ($typemap{$type} eq 'PTR') {
|
---|
| 5171 |
|
---|
[332] | 5172 | $zone = NetAddr::IP->new($zone);
|
---|
[337] | 5173 | $$recflags{$val}++;
|
---|
[332] | 5174 | if (!$zone->{isv6} && $zone->masklen > 24) {
|
---|
| 5175 | ($val) = ($val =~ /\.(\d+)$/);
|
---|
| 5176 | print $datafile "^$val."._ZONE($zone, 'ZONE', 'r', '.').'.in-addr.arpa'.
|
---|
| 5177 | ":$host:ttl:$stamp:$loc\n";
|
---|
| 5178 | } else {
|
---|
| 5179 | $val = NetAddr::IP->new($val);
|
---|
| 5180 | print $datafile "^".
|
---|
| 5181 | _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
[334] | 5182 | ":$host:$ttl:$stamp:$loc\n";
|
---|
[332] | 5183 | }
|
---|
[103] | 5184 |
|
---|
[333] | 5185 | } elsif ($type == 65280) { # A+PTR
|
---|
[334] | 5186 |
|
---|
[337] | 5187 | $$recflags{$val}++;
|
---|
[334] | 5188 | print $datafile "=$host:$val:$ttl:$stamp:$loc\n";
|
---|
| 5189 |
|
---|
[333] | 5190 | } elsif ($type == 65281) { # AAAA+PTR
|
---|
| 5191 |
|
---|
[337] | 5192 | #$$recflags{$val}++;
|
---|
[333] | 5193 | # treat these as two separate records. since tinydns doesn't have
|
---|
| 5194 | # a native combined type, we have to create them separately anyway.
|
---|
| 5195 | if ($revrec eq 'n') {
|
---|
| 5196 | $type = 28;
|
---|
| 5197 | } else {
|
---|
| 5198 | $type = 12;
|
---|
| 5199 | }
|
---|
[334] | 5200 | _printrec_tiny($datafile,$revrec,$recflags,$zone,$host,$type,$val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
[335] | 5201 | ##fixme: add a config flag to indicate use of the patch from http://www.fefe.de/dns/
|
---|
| 5202 | # type 6 is for AAAA+PTR, type 3 is for AAAA
|
---|
[333] | 5203 |
|
---|
| 5204 | } elsif ($type == 65282) { # PTR template
|
---|
[335] | 5205 |
|
---|
| 5206 | # only useful for v4 with standard DNS software, since this expands all
|
---|
| 5207 | # IPs in $zone (or possibly $val?) with autogenerated records
|
---|
[337] | 5208 | $val = NetAddr::IP->new($val);
|
---|
| 5209 | return if $val->{isv6};
|
---|
[336] | 5210 |
|
---|
[339] | 5211 | if ($val->masklen <= 16) {
|
---|
| 5212 | foreach my $sub ($val->split(16)) {
|
---|
| 5213 | __publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, 1);
|
---|
| 5214 | }
|
---|
| 5215 | } else {
|
---|
| 5216 | __publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, 1);
|
---|
[337] | 5217 | }
|
---|
[335] | 5218 |
|
---|
[333] | 5219 | } elsif ($type == 65283) { # A+PTR template
|
---|
[335] | 5220 |
|
---|
[337] | 5221 | $val = NetAddr::IP->new($val);
|
---|
| 5222 | # Just In Case. An A+PTR should be impossible to add to a v6 revzone via API.
|
---|
| 5223 | return if $val->{isv6};
|
---|
[339] | 5224 |
|
---|
| 5225 | if ($val->masklen <= 16) {
|
---|
| 5226 | foreach my $sub ($val->split(16)) {
|
---|
| 5227 | __publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, 0);
|
---|
| 5228 | }
|
---|
| 5229 | } else {
|
---|
| 5230 | __publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, 0);
|
---|
[337] | 5231 | }
|
---|
[335] | 5232 |
|
---|
[333] | 5233 | } elsif ($type == 65284) { # AAAA+PTR template
|
---|
[335] | 5234 | # Stub for completeness. Could be exported to DNS software that supports
|
---|
| 5235 | # some degree of internal automagic in generic-record-creation
|
---|
| 5236 | # (eg http://search.cpan.org/dist/AllKnowingDNS/ )
|
---|
[333] | 5237 |
|
---|
[345] | 5238 | } elsif ($type == 65285) { # Delegation
|
---|
| 5239 | # This is intended for reverse zones, but may prove useful in forward zones.
|
---|
| 5240 |
|
---|
[346] | 5241 | # All delegations need to create one or more NS records. The NS record handler knows what to do.
|
---|
| 5242 | _printrec_tiny($datafile,$revrec,$recflags,$zone,$host,$reverse_typemap{'NS'},
|
---|
| 5243 | $val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
| 5244 | if ($revrec eq 'y') {
|
---|
| 5245 | # In the case of a sub-/24 v4 reverse delegation, we need to generate CNAMEs
|
---|
| 5246 | # to redirect all of the individual IP lookups as well.
|
---|
| 5247 | # Not sure how this would actually resolve if a /24 or larger was delegated
|
---|
| 5248 | # one way, and a sub-/24 in that >=/24 was delegated elsewhere...
|
---|
| 5249 | my $dblock = NetAddr::IP->new($val);
|
---|
| 5250 | if (!$dblock->{isv6} && $dblock->masklen > 24) {
|
---|
| 5251 | my @subs = $dblock->split;
|
---|
| 5252 | foreach (@subs) {
|
---|
| 5253 | next if $$recflags{"$_"};
|
---|
| 5254 | my ($oct) = ($_->addr =~ /(\d+)$/);
|
---|
| 5255 | print $datafile "C"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$oct.".
|
---|
| 5256 | _ZONE($dblock, 'ZONE.in-addr.arpa', 'r', '.').":$ttl:$stamp:$loc\n";
|
---|
| 5257 | $$recflags{"$_"}++;
|
---|
| 5258 | }
|
---|
| 5259 | }
|
---|
| 5260 | }
|
---|
[345] | 5261 |
|
---|
[364] | 5262 | ##
|
---|
| 5263 | ## Uncommon types. These will need better UI support Any Day Sometime Maybe(TM).
|
---|
| 5264 | ##
|
---|
| 5265 |
|
---|
| 5266 | } elsif ($type == 44) { # SSHFP
|
---|
| 5267 | my ($algo,$fpt,$fp) = split /\s+/, $val;
|
---|
| 5268 |
|
---|
| 5269 | my $rec = sprintf ":$host:44:\\%0.3o\\%0.3o", $algo, $fpt;
|
---|
| 5270 | while (my ($byte) = ($fp =~ /^(..)/) ) {
|
---|
| 5271 | $rec .= sprintf "\\%0.3o", hex($byte);
|
---|
| 5272 | $fp =~ s/^..//;
|
---|
| 5273 | }
|
---|
| 5274 | print $datafile "$rec:$ttl:$stamp:$loc\n";
|
---|
| 5275 |
|
---|
[345] | 5276 | } else {
|
---|
[108] | 5277 | # raw record. we don't know what's in here, so we ASS-U-ME the user has
|
---|
| 5278 | # put it in correctly, since either the user is messing directly with the
|
---|
| 5279 | # database, or the record was imported via AXFR
|
---|
| 5280 | # <split by char>
|
---|
| 5281 | # convert anything not a-zA-Z0-9.- to octal coding
|
---|
| 5282 |
|
---|
| 5283 | ##fixme: add flag to export "unknown" record types - note we'll probably end up
|
---|
| 5284 | # mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
|
---|
| 5285 | #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
|
---|
| 5286 |
|
---|
[103] | 5287 | } # record type if-else
|
---|
| 5288 |
|
---|
[329] | 5289 | } # end _printrec_tiny()
|
---|
[103] | 5290 |
|
---|
| 5291 |
|
---|
[197] | 5292 | ## DNSDB::mailNotify()
|
---|
[283] | 5293 | # Sends notification mail to recipients regarding a DNSDB operation
|
---|
[197] | 5294 | sub mailNotify {
|
---|
[483] | 5295 | my $self = shift;
|
---|
| 5296 | my $dbh = $self->{dbh};
|
---|
[197] | 5297 | my ($subj,$message) = @_;
|
---|
| 5298 |
|
---|
| 5299 | return if $config{mailhost} eq 'smtp.example.com'; # do nothing if still using default SMTP host.
|
---|
| 5300 |
|
---|
| 5301 | my $mailer = Net::SMTP->new($config{mailhost}, Hello => "dnsadmin.$config{domain}");
|
---|
| 5302 |
|
---|
| 5303 | my $mailsender = ($config{mailsender} ? $config{mailsender} : $config{mailnotify});
|
---|
| 5304 |
|
---|
| 5305 | $mailer->mail($mailsender);
|
---|
| 5306 | $mailer->to($config{mailnotify});
|
---|
[198] | 5307 | $mailer->data("From: \"$config{mailname}\" <$mailsender>\n",
|
---|
| 5308 | "To: <$config{mailnotify}>\n",
|
---|
[197] | 5309 | "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
|
---|
| 5310 | "Subject: $subj\n",
|
---|
| 5311 | "X-Mailer: DNSAdmin Notify v".sprintf("%.1d",$DNSDB::VERSION)."\n",
|
---|
| 5312 | "Organization: $config{orgname}\n",
|
---|
| 5313 | "\n$message\n");
|
---|
| 5314 | $mailer->quit;
|
---|
| 5315 | }
|
---|
| 5316 |
|
---|
[2] | 5317 | # shut Perl up
|
---|
| 5318 | 1;
|
---|