[2] | 1 | # dns/trunk/DNSDB.pm
|
---|
| 2 | # Abstraction functions for DNS administration
|
---|
[262] | 3 | ##
|
---|
| 4 | # $Id: DNSDB.pm 488 2013-03-19 21:30:51Z 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
|
---|
[67] | 40 | &initPermissions &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
|
---|
[390] | 62 | %permissions @permtypes $permlist %permchains
|
---|
[2] | 63 | );
|
---|
| 64 |
|
---|
[487] | 65 | @EXPORT = qw(%typemap %reverse_typemap %permissions @permtypes $permlist %permchains);
|
---|
[2] | 66 | %EXPORT_TAGS = ( ALL => [qw(
|
---|
[279] | 67 | &initGlobals &login &initActionLog
|
---|
[67] | 68 | &initPermissions &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
|
---|
[390] | 90 | %permissions @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 |
|
---|
[65] | 138 | our %permissions;
|
---|
[55] | 139 |
|
---|
[128] | 140 | # Prepopulate a basic config. Note some of these *will* cause errors if left unset.
|
---|
[195] | 141 | # note: add appropriate stanzas in loadConfig to parse these
|
---|
[128] | 142 | our %config = (
|
---|
| 143 | # Database connection info
|
---|
| 144 | dbname => 'dnsdb',
|
---|
| 145 | dbuser => 'dnsdb',
|
---|
| 146 | dbpass => 'secret',
|
---|
| 147 | dbhost => '',
|
---|
| 148 |
|
---|
| 149 | # Email notice settings
|
---|
| 150 | mailhost => 'smtp.example.com',
|
---|
[195] | 151 | mailnotify => 'dnsdb@example.com', # to
|
---|
| 152 | mailsender => 'dnsdb@example.com', # from
|
---|
[128] | 153 | mailname => 'DNS Administration',
|
---|
[195] | 154 | orgname => 'Example Corp',
|
---|
| 155 | domain => 'example.com',
|
---|
[128] | 156 |
|
---|
| 157 | # Template directory
|
---|
| 158 | templatedir => 'templates/',
|
---|
| 159 | # fmeh. this is a real web path, not a logical internal one. hm..
|
---|
[163] | 160 | # cssdir => 'templates/',
|
---|
[216] | 161 | sessiondir => 'session/',
|
---|
[368] | 162 | exportcache => 'cache/',
|
---|
[163] | 163 |
|
---|
| 164 | # Session params
|
---|
[195] | 165 | timeout => '3600', # 1 hour default
|
---|
| 166 |
|
---|
| 167 | # Other miscellanea
|
---|
| 168 | log_failures => 1, # log all evarthing by default
|
---|
[201] | 169 | perpage => 15,
|
---|
[128] | 170 | );
|
---|
| 171 |
|
---|
[228] | 172 | ## (Semi)private variables
|
---|
[278] | 173 |
|
---|
[228] | 174 | # Hash of functions for validating record types. Filled in initGlobals() since
|
---|
| 175 | # it relies on visibility flags from the rectypes table in the DB
|
---|
| 176 | my %validators;
|
---|
[128] | 177 |
|
---|
[295] | 178 | # Entity-relationship reference hashes.
|
---|
| 179 | my %par_tbl = (
|
---|
| 180 | group => 'groups',
|
---|
| 181 | user => 'users',
|
---|
| 182 | defrec => 'default_records',
|
---|
| 183 | defrevrec => 'default_rev_records',
|
---|
| 184 | domain => 'domains',
|
---|
| 185 | revzone => 'revzones',
|
---|
| 186 | record => 'records'
|
---|
| 187 | );
|
---|
| 188 | my %id_col = (
|
---|
| 189 | group => 'group_id',
|
---|
| 190 | user => 'user_id',
|
---|
| 191 | defrec => 'record_id',
|
---|
| 192 | defrevrec => 'record_id',
|
---|
| 193 | domain => 'domain_id',
|
---|
| 194 | revzone => 'rdns_id',
|
---|
| 195 | record => 'record_id'
|
---|
| 196 | );
|
---|
| 197 | my %par_col = (
|
---|
| 198 | group => 'parent_group_id',
|
---|
| 199 | user => 'group_id',
|
---|
| 200 | defrec => 'group_id',
|
---|
| 201 | defrevrec => 'group_id',
|
---|
| 202 | domain => 'group_id',
|
---|
| 203 | revzone => 'group_id',
|
---|
| 204 | record => 'domain_id'
|
---|
| 205 | );
|
---|
| 206 | my %par_type = (
|
---|
| 207 | group => 'group',
|
---|
| 208 | user => 'group',
|
---|
| 209 | defrec => 'group',
|
---|
| 210 | defrevrec => 'group',
|
---|
| 211 | domain => 'group',
|
---|
| 212 | revzone => 'group',
|
---|
| 213 | record => 'domain'
|
---|
| 214 | );
|
---|
[278] | 215 |
|
---|
[2] | 216 | ##
|
---|
[465] | 217 | ## Constructor and destructor
|
---|
| 218 | ##
|
---|
| 219 |
|
---|
| 220 | sub new {
|
---|
| 221 | my $this = shift;
|
---|
| 222 | my $class = ref($this) || $this;
|
---|
| 223 | my %args = @_;
|
---|
| 224 | ##fixme? to ponder: do we do some magic if the caller sets eg dbname to prevent parsing of the config file?
|
---|
| 225 | if (!loadConfig(basename => $args{configfile})) {
|
---|
| 226 | warn "Using default configuration; unable to load custom settings: $errstr\n";
|
---|
| 227 | }
|
---|
| 228 | my $self = \%config;
|
---|
| 229 | $self->{configfile} = $args{configfile};
|
---|
| 230 | bless $self, $class;
|
---|
| 231 | $self->{dbh} = connectDB($self->{dbname}, $self->{dbuser}, $self->{dbpass}, $self->{dbhost}) or return;
|
---|
| 232 | $self->initGlobals();
|
---|
| 233 |
|
---|
| 234 | return $self;
|
---|
| 235 | }
|
---|
| 236 |
|
---|
| 237 | sub DESTROY {
|
---|
| 238 | my $self = shift;
|
---|
| 239 | $self->{dbh}->disconnect;
|
---|
| 240 | }
|
---|
| 241 |
|
---|
| 242 | ##
|
---|
[225] | 243 | ## utility functions
|
---|
[281] | 244 | ##
|
---|
| 245 |
|
---|
| 246 | ## DNSDB::_rectable()
|
---|
[224] | 247 | # Takes default+rdns flags, returns appropriate table name
|
---|
| 248 | sub _rectable {
|
---|
| 249 | my $def = shift;
|
---|
| 250 | my $rev = shift;
|
---|
| 251 |
|
---|
| 252 | return 'records' if $def ne 'y';
|
---|
| 253 | return 'default_records' if $rev ne 'y';
|
---|
| 254 | return 'default_rev_records';
|
---|
| 255 | } # end _rectable()
|
---|
| 256 |
|
---|
[281] | 257 | ## DNSDB::_recparent()
|
---|
[224] | 258 | # Takes default+rdns flags, returns appropriate parent-id column name
|
---|
| 259 | sub _recparent {
|
---|
| 260 | my $def = shift;
|
---|
| 261 | my $rev = shift;
|
---|
| 262 |
|
---|
| 263 | return 'group_id' if $def eq 'y';
|
---|
| 264 | return 'rdns_id' if $rev eq 'y';
|
---|
| 265 | return 'domain_id';
|
---|
| 266 | } # end _recparent()
|
---|
| 267 |
|
---|
[281] | 268 | ## DNSDB::_ipparent()
|
---|
[226] | 269 | # Check an IP to be added in a reverse zone to see if it's really in the requested parent.
|
---|
[466] | 270 | # Takes default and reverse flags, IP (fragment) to check, parent zone ID,
|
---|
[226] | 271 | # and a reference to a NetAddr::IP object (also used to pass back a fully-reconstructed IP for
|
---|
| 272 | # database insertion)
|
---|
| 273 | sub _ipparent {
|
---|
[466] | 274 | my $self = shift;
|
---|
| 275 | my $dbh = $self->{dbh};
|
---|
[226] | 276 | my $defrec = shift;
|
---|
| 277 | my $revrec = shift;
|
---|
| 278 | my $val = shift;
|
---|
| 279 | my $id = shift;
|
---|
| 280 | my $addr = shift;
|
---|
[224] | 281 |
|
---|
[232] | 282 | return if $revrec ne 'y'; # this sub not useful in forward zones
|
---|
| 283 |
|
---|
| 284 | $$addr = NetAddr::IP->new($$val); #necessary?
|
---|
| 285 |
|
---|
[226] | 286 | # subsub to split, reverse, and overlay an IP fragment on a netblock
|
---|
| 287 | sub __rev_overlay {
|
---|
| 288 | my $splitme = shift; # ':' or '.', m'lud?
|
---|
| 289 | my $parnet = shift;
|
---|
| 290 | my $val = shift;
|
---|
| 291 | my $addr = shift;
|
---|
| 292 |
|
---|
| 293 | my $joinme = $splitme;
|
---|
| 294 | $splitme = '\.' if $splitme eq '.';
|
---|
[232] | 295 | my @working = reverse(split($splitme, $parnet->addr));
|
---|
| 296 | my @parts = reverse(split($splitme, $$val));
|
---|
[226] | 297 | for (my $i = 0; $i <= $#parts; $i++) {
|
---|
| 298 | $working[$i] = $parts[$i];
|
---|
| 299 | }
|
---|
[232] | 300 | my $checkme = NetAddr::IP->new(join($joinme, reverse(@working))) or return 0;
|
---|
| 301 | return 0 unless $checkme->within($parnet);
|
---|
[226] | 302 | $$addr = $checkme; # force "correct" IP to be recorded.
|
---|
| 303 | return 1;
|
---|
| 304 | }
|
---|
| 305 |
|
---|
| 306 | my ($parstr) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id = ?", undef, ($id));
|
---|
| 307 | my $parnet = NetAddr::IP->new($parstr);
|
---|
| 308 |
|
---|
| 309 | # Fail early on v6-in-v4 or v4-in-v6. We're not accepting these ATM.
|
---|
[232] | 310 | return 0 if $parnet->addr =~ /\./ && $$val =~ /:/;
|
---|
| 311 | return 0 if $parnet->addr =~ /:/ && $$val =~ /\./;
|
---|
[226] | 312 |
|
---|
[340] | 313 | if ($$addr && ($$val =~ /^[\da-fA-F][\da-fA-F:]+[\da-fA-F]$/ || $$val =~ m|/\d+$|)) {
|
---|
| 314 | # the only case where NetAddr::IP's acceptance of legitimate IPs is "correct" is for a proper IPv6 address,
|
---|
| 315 | # or a netblock (only expected on templates)
|
---|
[232] | 316 | # the rest we have to restructure before fiddling. *sigh*
|
---|
| 317 | return 1 if $$addr->within($parnet);
|
---|
| 318 | } else {
|
---|
[340] | 319 | # We don't have a complete IP in $$val (yet)... unless we have a netblock
|
---|
[232] | 320 | if ($parnet->addr =~ /:/) {
|
---|
| 321 | $$val =~ s/^:+//; # gotta strip'em all...
|
---|
[226] | 322 | return __rev_overlay(':', $parnet, $val, $addr);
|
---|
| 323 | }
|
---|
[232] | 324 | if ($parnet->addr =~ /\./) {
|
---|
| 325 | $$val =~ s/^\.+//;
|
---|
| 326 | return __rev_overlay('.', $parnet, $val, $addr);
|
---|
| 327 | }
|
---|
[226] | 328 | # should be impossible to get here...
|
---|
| 329 | }
|
---|
| 330 | # ... and here.
|
---|
| 331 | # can't do nuttin' in forward zones
|
---|
| 332 | } # end _ipparent()
|
---|
| 333 |
|
---|
[281] | 334 | ## DNSDB::_hostparent()
|
---|
[232] | 335 | # A little different than _ipparent above; this tries to *find* the parent zone of a hostname
|
---|
[466] | 336 | # Takes a hostname.
|
---|
[281] | 337 | # Returns the domain ID of the parent domain if one was found.
|
---|
[232] | 338 | sub _hostparent {
|
---|
[466] | 339 | my $self = shift;
|
---|
| 340 | my $dbh = $self->{dbh};
|
---|
[232] | 341 | my $hname = shift;
|
---|
[347] | 342 |
|
---|
| 343 | $hname =~ s/^\*\.//; # this should be impossible to find in the domains table.
|
---|
[232] | 344 | my @hostbits = split /\./, $hname;
|
---|
[349] | 345 | my $sth = $dbh->prepare("SELECT count(*),domain_id FROM domains WHERE lower(domain) = lower(?) GROUP BY domain_id");
|
---|
[232] | 346 | foreach (@hostbits) {
|
---|
| 347 | $sth->execute($hname);
|
---|
| 348 | my ($found, $parid) = $sth->fetchrow_array;
|
---|
| 349 | if ($found) {
|
---|
| 350 | return $parid;
|
---|
| 351 | }
|
---|
| 352 | $hname =~ s/^$_\.//;
|
---|
| 353 | }
|
---|
| 354 | } # end _hostparent()
|
---|
[228] | 355 |
|
---|
[281] | 356 | ## DNSDB::_log()
|
---|
| 357 | # Log an action
|
---|
[466] | 358 | # Takes a log entry hash containing at least:
|
---|
[282] | 359 | # group_id, log entry
|
---|
[281] | 360 | # and optionally one or more of:
|
---|
| 361 | # domain_id, rdns_id
|
---|
[282] | 362 | # The %userdata hash provides the user ID, username, and fullname
|
---|
[281] | 363 | sub _log {
|
---|
[466] | 364 | my $self = shift;
|
---|
| 365 | my $dbh = $self->{dbh};
|
---|
[281] | 366 |
|
---|
| 367 | my %args = @_;
|
---|
| 368 |
|
---|
| 369 | $args{rdns_id} = 0 if !$args{rdns_id};
|
---|
| 370 | $args{domain_id} = 0 if !$args{domain_id};
|
---|
| 371 |
|
---|
| 372 | ##fixme: farm out the actual logging to different subs for file, syslog, internal, etc based on config
|
---|
| 373 | # if ($config{log_channel} eq 'sql') {
|
---|
| 374 | $dbh->do("INSERT INTO log (domain_id,rdns_id,group_id,entry,user_id,email,name) VALUES (?,?,?,?,?,?,?)",
|
---|
| 375 | undef,
|
---|
| 376 | ($args{domain_id}, $args{rdns_id}, $args{group_id}, $args{entry},
|
---|
[488] | 377 | $self->{loguserid}, $self->{logusername}, $self->{logfullname}) );
|
---|
[281] | 378 | # } elsif ($config{log_channel} eq 'file') {
|
---|
| 379 | # } elsif ($config{log_channel} eq 'syslog') {
|
---|
| 380 | # }
|
---|
| 381 | } # end _log
|
---|
| 382 |
|
---|
| 383 |
|
---|
[224] | 384 | ##
|
---|
[228] | 385 | ## Record validation subs.
|
---|
| 386 | ##
|
---|
| 387 |
|
---|
[281] | 388 | ## All of these subs take substantially the same arguments:
|
---|
| 389 | # a hash containing at least the following keys:
|
---|
| 390 | # - defrec (default/live flag)
|
---|
| 391 | # - revrec (forward/reverse flag)
|
---|
| 392 | # - id (parent entity ID)
|
---|
| 393 | # - host (hostname)
|
---|
| 394 | # - rectype
|
---|
| 395 | # - val (IP, hostname [CNAME/MX/SRV] or text)
|
---|
| 396 | # - addr (NetAddr::IP object from val. May be undef.)
|
---|
| 397 | # MX and SRV record validation also expect distance, and SRV records expect weight and port as well.
|
---|
| 398 | # host, rectype, and addr should be references as these may be modified in validation
|
---|
| 399 |
|
---|
[228] | 400 | # A record
|
---|
| 401 | sub _validate_1 {
|
---|
[467] | 402 | my $self = shift;
|
---|
| 403 | my $dbh = $self->{dbh};
|
---|
[229] | 404 |
|
---|
[230] | 405 | my %args = @_;
|
---|
[229] | 406 |
|
---|
[230] | 407 | return ('FAIL', 'Reverse zones cannot contain A records') if $args{revrec} eq 'y';
|
---|
[229] | 408 |
|
---|
| 409 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 410 | # or the intended parent domain for live records.
|
---|
[467] | 411 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[230] | 412 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
[229] | 413 |
|
---|
| 414 | # Check IP is well-formed, and that it's a v4 address
|
---|
[234] | 415 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
|
---|
[232] | 416 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
[234] | 417 | unless ${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/;
|
---|
| 418 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
[230] | 419 | unless $args{addr} && !$args{addr}->{isv6};
|
---|
[229] | 420 | # coerce IP/value to normalized form for storage
|
---|
[230] | 421 | ${$args{val}} = $args{addr}->addr;
|
---|
[229] | 422 |
|
---|
[228] | 423 | return ('OK','OK');
|
---|
| 424 | } # done A record
|
---|
| 425 |
|
---|
| 426 | # NS record
|
---|
| 427 | sub _validate_2 {
|
---|
[467] | 428 | my $self = shift;
|
---|
| 429 | my $dbh = $self->{dbh};
|
---|
[230] | 430 |
|
---|
| 431 | my %args = @_;
|
---|
| 432 |
|
---|
[328] | 433 | # Check that the target of the record is within the parent.
|
---|
| 434 | # Yes, host<->val are mixed up here; can't see a way to avoid it. :(
|
---|
| 435 | if ($args{defrec} eq 'n') {
|
---|
| 436 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
| 437 | if ($args{revrec} eq 'y') {
|
---|
| 438 | my $tmpip = NetAddr::IP->new(${$args{val}});
|
---|
[467] | 439 | my $pname = $self->revName($args{id});
|
---|
[328] | 440 | return ('FAIL',"${$args{val}} not within $pname")
|
---|
[467] | 441 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$tmpip);
|
---|
[328] | 442 | # Sub the returned thing for ZONE? This could get stupid if you have typos...
|
---|
| 443 | ${$args{val}} =~ s/ZONE/$tmpip->address/;
|
---|
| 444 | } else {
|
---|
[467] | 445 | my $pname = $self->domainName($args{id});
|
---|
[328] | 446 | ${$args{host}} = $pname if ${$args{host}} !~ /\.$pname$/;
|
---|
| 447 | }
|
---|
[230] | 448 | } else {
|
---|
[328] | 449 | # Default reverse NS records should always refer to the implied parent
|
---|
| 450 | ${$args{host}} = 'DOMAIN' if $args{revrec} eq 'n';
|
---|
| 451 | ${$args{val}} = 'ZONE' if $args{revrec} eq 'y';
|
---|
[230] | 452 | }
|
---|
| 453 |
|
---|
| 454 | # Let this lie for now. Needs more magic.
|
---|
| 455 | # # Check IP is well-formed, and that it's a v4 address
|
---|
| 456 | # return ('FAIL',"A record must be a valid IPv4 address")
|
---|
| 457 | # unless $addr && !$addr->{isv6};
|
---|
| 458 | # # coerce IP/value to normalized form for storage
|
---|
| 459 | # $$val = $addr->addr;
|
---|
| 460 |
|
---|
[228] | 461 | return ('OK','OK');
|
---|
| 462 | } # done NS record
|
---|
| 463 |
|
---|
| 464 | # CNAME record
|
---|
| 465 | sub _validate_5 {
|
---|
[467] | 466 | my $self = shift;
|
---|
| 467 | my $dbh = $self->{dbh};
|
---|
[230] | 468 |
|
---|
| 469 | my %args = @_;
|
---|
| 470 |
|
---|
| 471 | # Not really true, but these are only useful for delegating smaller-than-/24 IP blocks.
|
---|
| 472 | # This is fundamentally a messy operation and should really just be taken care of by the
|
---|
| 473 | # export process, not manual maintenance of the necessary records.
|
---|
| 474 | return ('FAIL', 'Reverse zones cannot contain CNAME records') if $args{revrec} eq 'y';
|
---|
| 475 |
|
---|
| 476 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 477 | # or the intended parent domain for live records.
|
---|
[467] | 478 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[230] | 479 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 480 |
|
---|
[228] | 481 | return ('OK','OK');
|
---|
| 482 | } # done CNAME record
|
---|
| 483 |
|
---|
| 484 | # SOA record
|
---|
| 485 | sub _validate_6 {
|
---|
[230] | 486 | # Smart monkeys won't stick their fingers in here; we have
|
---|
| 487 | # separate dedicated routines to deal with SOA records.
|
---|
[228] | 488 | return ('OK','OK');
|
---|
| 489 | } # done SOA record
|
---|
| 490 |
|
---|
| 491 | # PTR record
|
---|
| 492 | sub _validate_12 {
|
---|
[467] | 493 | my $self = shift;
|
---|
| 494 | my $dbh = $self->{dbh};
|
---|
[232] | 495 |
|
---|
| 496 | my %args = @_;
|
---|
| 497 |
|
---|
| 498 | if ($args{revrec} eq 'y') {
|
---|
| 499 | if ($args{defrec} eq 'n') {
|
---|
[467] | 500 | return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
| 501 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
[232] | 502 | ${$args{val}} = $args{addr}->addr;
|
---|
| 503 | } else {
|
---|
[234] | 504 | if (${$args{val}} =~ /\./) {
|
---|
| 505 | # looks like a v4 or fragment
|
---|
| 506 | if (${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/) {
|
---|
| 507 | # woo! a complete IP! validate it and normalize, or fail.
|
---|
| 508 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
| 509 | or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
|
---|
| 510 | ${$args{val}} = $args{addr}->addr;
|
---|
| 511 | } else {
|
---|
[249] | 512 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
[234] | 513 | }
|
---|
| 514 | } elsif (${$args{val}} =~ /[a-f:]/) {
|
---|
| 515 | # looks like a v6 or fragment
|
---|
[251] | 516 | ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
|
---|
[234] | 517 | if ($args{addr}) {
|
---|
| 518 | if ($args{addr}->addr =~ /^0/) {
|
---|
[251] | 519 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
[234] | 520 | } else {
|
---|
| 521 | ${$args{val}} = $args{addr}->addr;
|
---|
| 522 | }
|
---|
| 523 | }
|
---|
| 524 | } else {
|
---|
| 525 | # bare number (probably). These could be v4 or v6, so we'll
|
---|
| 526 | # expand on these on creation of a reverse zone.
|
---|
[251] | 527 | ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
|
---|
[234] | 528 | }
|
---|
[249] | 529 | ${$args{host}} =~ s/\.*$/\.$config{domain}/ if ${$args{host}} !~ /(?:$config{domain}|ADMINDOMAIN)$/;
|
---|
[232] | 530 | }
|
---|
| 531 |
|
---|
| 532 | # Multiple PTR records do NOT generally do what most people believe they do,
|
---|
| 533 | # and tend to fail in the most awkward way possible. Check and warn.
|
---|
| 534 | # We use $val instead of $addr->addr since we may be in a defrec, and may have eg "ZONE::42" or "ZONE.12"
|
---|
[249] | 535 |
|
---|
| 536 | my @checkvals = (${$args{val}});
|
---|
| 537 | if (${$args{val}} =~ /,/) {
|
---|
| 538 | # push . and :: variants into checkvals if val has ,
|
---|
| 539 | my $tmp;
|
---|
| 540 | ($tmp = ${$args{val}}) =~ s/,/./;
|
---|
| 541 | push @checkvals, $tmp;
|
---|
| 542 | ($tmp = ${$args{val}}) =~ s/,/::/;
|
---|
| 543 | push @checkvals, $tmp;
|
---|
| 544 | }
|
---|
| 545 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ?");
|
---|
| 546 | foreach my $checkme (@checkvals) {
|
---|
[272] | 547 | if ($args{update}) {
|
---|
| 548 | # Record update. There should usually be an existing PTR (the record being updated)
|
---|
| 549 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 550 | " WHERE val = ?", undef, ($checkme)) };
|
---|
| 551 | return ('WARN', "PTR record for $checkme already exists; adding another will probably not do what you want")
|
---|
[273] | 552 | if @ptrs && (!grep /^$args{update}$/, @ptrs);
|
---|
[272] | 553 | } else {
|
---|
| 554 | # New record. Always warn if a PTR exists
|
---|
| 555 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 556 | " WHERE val = ?", undef, ($checkme));
|
---|
| 557 | return ('WARN', "PTR record for $checkme already exists; adding another will probably not do what you want")
|
---|
| 558 | if $ptrcount;
|
---|
| 559 | }
|
---|
[249] | 560 | }
|
---|
[272] | 561 |
|
---|
[232] | 562 | } else {
|
---|
| 563 | # Not absolutely true but only useful if you hack things up for sub-/24 v4 reverse delegations
|
---|
| 564 | # Simpler to just create the reverse zone and grant access for the customer to edit it, and create direct
|
---|
| 565 | # PTR records on export
|
---|
| 566 | return ('FAIL',"Forward zones cannot contain PTR records");
|
---|
| 567 | }
|
---|
| 568 |
|
---|
[228] | 569 | return ('OK','OK');
|
---|
| 570 | } # done PTR record
|
---|
| 571 |
|
---|
| 572 | # MX record
|
---|
| 573 | sub _validate_15 {
|
---|
[467] | 574 | my $self = shift;
|
---|
| 575 | my $dbh = $self->{dbh};
|
---|
[230] | 576 |
|
---|
| 577 | my %args = @_;
|
---|
| 578 |
|
---|
| 579 | # Not absolutely true but WTF use is an MX record for a reverse zone?
|
---|
| 580 | return ('FAIL', 'Reverse zones cannot contain MX records') if $args{revrec} eq 'y';
|
---|
| 581 |
|
---|
| 582 | return ('FAIL', "Distance is required for MX records") unless defined(${$args{dist}});
|
---|
| 583 | ${$args{dist}} =~ s/\s*//g;
|
---|
| 584 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
|
---|
| 585 |
|
---|
| 586 | ${$args{fields}} = "distance,";
|
---|
| 587 | push @{$args{vallist}}, ${$args{dist}};
|
---|
| 588 |
|
---|
| 589 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 590 | # or the intended parent domain for live records.
|
---|
[467] | 591 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[230] | 592 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 593 |
|
---|
[273] | 594 | # hmm.. this might work. except possibly for something pointing to "deadbeef.ca". <g>
|
---|
| 595 | # if ($type == $reverse_typemap{NS} || $type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
|
---|
| 596 | # if ($val =~ /^\s*[\da-f:.]+\s*$/) {
|
---|
| 597 | # return ('FAIL',"$val is not a valid IP address") if !$addr;
|
---|
| 598 | # }
|
---|
| 599 | # }
|
---|
| 600 |
|
---|
[228] | 601 | return ('OK','OK');
|
---|
| 602 | } # done MX record
|
---|
| 603 |
|
---|
| 604 | # TXT record
|
---|
| 605 | sub _validate_16 {
|
---|
[231] | 606 | # Could arguably put a WARN return here on very long (>512) records
|
---|
[228] | 607 | return ('OK','OK');
|
---|
| 608 | } # done TXT record
|
---|
| 609 |
|
---|
| 610 | # RP record
|
---|
| 611 | sub _validate_17 {
|
---|
[231] | 612 | # Probably have to validate these some day
|
---|
[228] | 613 | return ('OK','OK');
|
---|
| 614 | } # done RP record
|
---|
| 615 |
|
---|
| 616 | # AAAA record
|
---|
| 617 | sub _validate_28 {
|
---|
[467] | 618 | my $self = shift;
|
---|
| 619 | my $dbh = $self->{dbh};
|
---|
[229] | 620 |
|
---|
[230] | 621 | my %args = @_;
|
---|
[229] | 622 |
|
---|
[230] | 623 | return ('FAIL', 'Reverse zones cannot contain AAAA records') if $args{revrec} eq 'y';
|
---|
[229] | 624 |
|
---|
| 625 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 626 | # or the intended parent domain for live records.
|
---|
[467] | 627 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[230] | 628 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
[229] | 629 |
|
---|
| 630 | # Check IP is well-formed, and that it's a v6 address
|
---|
[232] | 631 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
|
---|
[230] | 632 | unless $args{addr} && $args{addr}->{isv6};
|
---|
[229] | 633 | # coerce IP/value to normalized form for storage
|
---|
[230] | 634 | ${$args{val}} = $args{addr}->addr;
|
---|
[229] | 635 |
|
---|
[228] | 636 | return ('OK','OK');
|
---|
| 637 | } # done AAAA record
|
---|
| 638 |
|
---|
| 639 | # SRV record
|
---|
| 640 | sub _validate_33 {
|
---|
[467] | 641 | my $self = shift;
|
---|
| 642 | my $dbh = $self->{dbh};
|
---|
[231] | 643 |
|
---|
| 644 | my %args = @_;
|
---|
| 645 |
|
---|
| 646 | # Not absolutely true but WTF use is an SRV record for a reverse zone?
|
---|
| 647 | return ('FAIL', 'Reverse zones cannot contain SRV records') if $args{revrec} eq 'y';
|
---|
| 648 |
|
---|
| 649 | return ('FAIL', "Distance is required for SRV records") unless defined(${$args{dist}});
|
---|
| 650 | ${$args{dist}} =~ s/\s*//g;
|
---|
| 651 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
|
---|
| 652 |
|
---|
| 653 | return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]")
|
---|
| 654 | unless ${$args{host}} =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/;
|
---|
| 655 | return ('FAIL',"Port and weight are required for SRV records")
|
---|
| 656 | unless defined(${$args{weight}}) && defined(${$args{port}});
|
---|
| 657 | ${$args{weight}} =~ s/\s*//g;
|
---|
| 658 | ${$args{port}} =~ s/\s*//g;
|
---|
| 659 |
|
---|
| 660 | return ('FAIL',"Port and weight are required, and must be numeric")
|
---|
| 661 | unless ${$args{weight}} =~ /^\d+$/ && ${$args{port}} =~ /^\d+$/;
|
---|
| 662 |
|
---|
| 663 | ${$args{fields}} = "distance,weight,port,";
|
---|
| 664 | push @{$args{vallist}}, (${$args{dist}}, ${$args{weight}}, ${$args{port}});
|
---|
| 665 |
|
---|
| 666 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 667 | # or the intended parent domain for live records.
|
---|
[467] | 668 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[231] | 669 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 670 |
|
---|
[228] | 671 | return ('OK','OK');
|
---|
| 672 | } # done SRV record
|
---|
| 673 |
|
---|
| 674 | # Now the custom types
|
---|
| 675 |
|
---|
[232] | 676 | # A+PTR record. With a very little bit of magic we can also use this sub to validate AAAA+PTR. Whee!
|
---|
[228] | 677 | sub _validate_65280 {
|
---|
[467] | 678 | my $self = shift;
|
---|
| 679 | my $dbh = $self->{dbh};
|
---|
[232] | 680 |
|
---|
| 681 | my %args = @_;
|
---|
| 682 |
|
---|
| 683 | my $code = 'OK';
|
---|
| 684 | my $msg = 'OK';
|
---|
| 685 |
|
---|
| 686 | if ($args{defrec} eq 'n') {
|
---|
| 687 | # live record; revrec determines whether we validate the PTR or A component first.
|
---|
[233] | 688 |
|
---|
[232] | 689 | if ($args{revrec} eq 'y') {
|
---|
[467] | 690 | ($code,$msg) = $self->_validate_12(%args);
|
---|
[232] | 691 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 692 |
|
---|
[467] | 693 | # check A+PTR is really v4
|
---|
| 694 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
| 695 | if ${$args{rectype}} == 65280 && $args{addr}->{isv6};
|
---|
| 696 | # check AAAA+PTR is really v6
|
---|
| 697 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
|
---|
| 698 | if ${$args{rectype}} == 65281 && !$args{addr}->{isv6};
|
---|
| 699 |
|
---|
[232] | 700 | # Check if the reqested domain exists. If not, coerce the type down to PTR and warn.
|
---|
[467] | 701 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) {
|
---|
[272] | 702 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
| 703 | " as PTR instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
[232] | 704 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
| 705 | $msg = $addmsg if $code eq 'OK';
|
---|
| 706 | ${$args{rectype}} = $reverse_typemap{PTR};
|
---|
| 707 | return ('WARN', $msg);
|
---|
| 708 | }
|
---|
| 709 |
|
---|
[242] | 710 | # Add domain ID to field list and values
|
---|
| 711 | ${$args{fields}} .= "domain_id,";
|
---|
| 712 | push @{$args{vallist}}, ${$args{domid}};
|
---|
| 713 |
|
---|
[232] | 714 | } else {
|
---|
[467] | 715 | ($code,$msg) = $self->_validate_1(%args) if ${$args{rectype}} == 65280;
|
---|
| 716 | ($code,$msg) = $self->_validate_28(%args) if ${$args{rectype}} == 65281;
|
---|
[232] | 717 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 718 |
|
---|
| 719 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
| 720 | # work here since we don't *know* which parent to put it in.
|
---|
[233] | 721 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
[232] | 722 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
| 723 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
| 724 | if (!$revid) {
|
---|
[272] | 725 | $msg = "Record ".($args{update} ? 'updated' : 'added')." as ".(${$args{rectype}} == 65280 ? 'A' : 'AAAA').
|
---|
[232] | 726 | " instead of $typemap{${$args{rectype}}}; reverse zone not found for ${$args{val}}";
|
---|
| 727 | ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
| 728 | return ('WARN', $msg);
|
---|
| 729 | }
|
---|
| 730 |
|
---|
| 731 | # Check for duplicate PTRs. Note we don't have to play games with $code and $msg, because
|
---|
| 732 | # by definition there can't be duplicate PTRs if the reverse zone isn't managed here.
|
---|
[272] | 733 | if ($args{update}) {
|
---|
| 734 | # Record update. There should usually be an existing PTR (the record being updated)
|
---|
| 735 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 736 | " WHERE val = ?", undef, (${$args{val}})) };
|
---|
[273] | 737 | if (@ptrs && (!grep /^$args{update}$/, @ptrs)) {
|
---|
[272] | 738 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
|
---|
| 739 | $code = 'WARN';
|
---|
| 740 | }
|
---|
| 741 | } else {
|
---|
| 742 | # New record. Always warn if a PTR exists
|
---|
| 743 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 744 | " WHERE val = ?", undef, (${$args{val}}));
|
---|
| 745 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want"
|
---|
| 746 | if $ptrcount;
|
---|
| 747 | $code = 'WARN' if $ptrcount;
|
---|
[232] | 748 | }
|
---|
| 749 |
|
---|
[272] | 750 | # my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 751 | # " WHERE val = ?", undef, ${$args{val}});
|
---|
| 752 | # if ($ptrcount) {
|
---|
| 753 | # my $curid = $dbh->selectrow_array("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 754 | # " WHERE val = ?
|
---|
| 755 | # $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
|
---|
| 756 | # $code = 'WARN';
|
---|
| 757 | # }
|
---|
| 758 |
|
---|
[232] | 759 | ${$args{fields}} .= "rdns_id,";
|
---|
| 760 | push @{$args{vallist}}, $revid;
|
---|
| 761 | }
|
---|
| 762 |
|
---|
[233] | 763 | } else { # defrec eq 'y'
|
---|
| 764 | if ($args{revrec} eq 'y') {
|
---|
[467] | 765 | ($code,$msg) = $self->_validate_12(%args);
|
---|
[233] | 766 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 767 | if (${$args{rectype}} == 65280) {
|
---|
| 768 | return ('FAIL',"A+PTR record must be a valid IPv4 address or fragment")
|
---|
| 769 | if ${$args{val}} =~ /:/;
|
---|
[234] | 770 | ${$args{val}} =~ s/^ZONE,/ZONE./; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
[233] | 771 | } elsif (${$args{rectype}} == 65281) {
|
---|
| 772 | return ('FAIL',"AAAA+PTR record must be a valid IPv6 address or fragment")
|
---|
| 773 | if ${$args{val}} =~ /\./;
|
---|
[234] | 774 | ${$args{val}} =~ s/^ZONE,/ZONE::/; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
[233] | 775 | }
|
---|
| 776 | } else {
|
---|
| 777 | # This is easy. I also can't see a real use-case for A/AAAA+PTR in *all* forward
|
---|
| 778 | # domains, since you wouldn't be able to substitute both domain and reverse zone
|
---|
| 779 | # sanely, and you'd end up with guaranteed over-replicated PTR records that would
|
---|
| 780 | # confuse the hell out of pretty much anything that uses them.
|
---|
[234] | 781 | ##fixme: make this a config flag?
|
---|
[233] | 782 | return ('FAIL', "$typemap{${$args{rectype}}} records not allowed in default domains");
|
---|
| 783 | }
|
---|
[232] | 784 | }
|
---|
| 785 |
|
---|
| 786 | return ($code, $msg);
|
---|
[228] | 787 | } # done A+PTR record
|
---|
| 788 |
|
---|
| 789 | # AAAA+PTR record
|
---|
[232] | 790 | # A+PTR above has been magicked to handle AAAA+PTR as well.
|
---|
[228] | 791 | sub _validate_65281 {
|
---|
[232] | 792 | return _validate_65280(@_);
|
---|
[228] | 793 | } # done AAAA+PTR record
|
---|
| 794 |
|
---|
| 795 | # PTR template record
|
---|
| 796 | sub _validate_65282 {
|
---|
[467] | 797 | my $self = shift;
|
---|
| 798 | my $dbh = $self->{dbh};
|
---|
[340] | 799 |
|
---|
| 800 | my %args = @_;
|
---|
| 801 |
|
---|
| 802 | # we're *this* >.< close to being able to just call _validate_12... unfortunately we can't, quite.
|
---|
| 803 | if ($args{revrec} eq 'y') {
|
---|
| 804 | if ($args{defrec} eq 'n') {
|
---|
[467] | 805 | return ('FAIL', "Template block ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
| 806 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
[340] | 807 | ##fixme: warn if $args{val} is not /31 or larger block?
|
---|
| 808 | ${$args{val}} = "$args{addr}";
|
---|
| 809 | } else {
|
---|
| 810 | if (${$args{val}} =~ /\./) {
|
---|
| 811 | # looks like a v4 or fragment
|
---|
| 812 | if (${$args{val}} =~ m|^\d+\.\d+\.\d+\.\d+(?:/\d+)?$|) {
|
---|
| 813 | # woo! a complete IP! validate it and normalize, or fail.
|
---|
| 814 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
| 815 | or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
|
---|
| 816 | ${$args{val}} = "$args{addr}";
|
---|
| 817 | } else {
|
---|
| 818 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
| 819 | }
|
---|
| 820 | } elsif (${$args{val}} =~ /[a-f:]/) {
|
---|
| 821 | # looks like a v6 or fragment
|
---|
| 822 | ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
|
---|
| 823 | if ($args{addr}) {
|
---|
| 824 | if ($args{addr}->addr =~ /^0/) {
|
---|
| 825 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
| 826 | } else {
|
---|
| 827 | ${$args{val}} = "$args{addr}";
|
---|
| 828 | }
|
---|
| 829 | }
|
---|
| 830 | } else {
|
---|
| 831 | # bare number (probably). These could be v4 or v6, so we'll
|
---|
| 832 | # expand on these on creation of a reverse zone.
|
---|
| 833 | ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
|
---|
| 834 | }
|
---|
| 835 | }
|
---|
| 836 | ##fixme: validate %-patterns?
|
---|
| 837 |
|
---|
| 838 | # Unlike single PTR records, there is absolutely no way to sanely support multiple
|
---|
| 839 | # PTR templates for the same block, since they expect to expand to all the individual
|
---|
| 840 | # IPs on export. Nested templates should be supported though.
|
---|
| 841 |
|
---|
| 842 | my @checkvals = (${$args{val}});
|
---|
| 843 | if (${$args{val}} =~ /,/) {
|
---|
| 844 | # push . and :: variants into checkvals if val has ,
|
---|
| 845 | my $tmp;
|
---|
| 846 | ($tmp = ${$args{val}}) =~ s/,/./;
|
---|
| 847 | push @checkvals, $tmp;
|
---|
| 848 | ($tmp = ${$args{val}}) =~ s/,/::/;
|
---|
| 849 | push @checkvals, $tmp;
|
---|
| 850 | }
|
---|
| 851 | ##fixme: this feels wrong still - need to restrict template pseudorecords to One Of Each
|
---|
| 852 | # Per Netblock such that they don't conflict on export
|
---|
| 853 | my $typeck;
|
---|
| 854 | # type 65282 -> ptr template -> look for any of 65282, 65283, 65284
|
---|
| 855 | $typeck = 'type=65283 OR type=65284' if ${$args{rectype}} == 65282;
|
---|
| 856 | # type 65283 -> a+ptr template -> v4 -> look for 65282 or 65283
|
---|
| 857 | $typeck = 'type=65283' if ${$args{rectype}} == 65282;
|
---|
| 858 | # type 65284 -> aaaa+ptr template -> v6 -> look for 65282 or 65284
|
---|
| 859 | $typeck = 'type=65284' if ${$args{rectype}} == 65282;
|
---|
| 860 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ? ".
|
---|
| 861 | "AND (type=65282 OR $typeck)");
|
---|
| 862 | foreach my $checkme (@checkvals) {
|
---|
| 863 | $pcsth->execute($checkme);
|
---|
| 864 | my ($rc) = $pcsth->fetchrow_array;
|
---|
[442] | 865 | return ('FAIL', "Only one template pseudorecord may exist for a given IP block") if $rc > 1;
|
---|
[340] | 866 | }
|
---|
| 867 |
|
---|
| 868 | } else {
|
---|
| 869 | return ('FAIL', "Forward zones cannot contain PTR records");
|
---|
| 870 | }
|
---|
| 871 |
|
---|
[228] | 872 | return ('OK','OK');
|
---|
| 873 | } # done PTR template record
|
---|
| 874 |
|
---|
| 875 | # A+PTR template record
|
---|
| 876 | sub _validate_65283 {
|
---|
[467] | 877 | my $self = shift;
|
---|
| 878 | my $dbh = $self->{dbh};
|
---|
[340] | 879 |
|
---|
| 880 | my %args = @_;
|
---|
| 881 |
|
---|
| 882 | my ($code,$msg) = ('OK','OK');
|
---|
| 883 |
|
---|
| 884 | ##fixme: need to fiddle things since A+PTR templates are acceptable in live
|
---|
| 885 | # forward zones but not default records
|
---|
| 886 | if ($args{defrec} eq 'n') {
|
---|
| 887 | if ($args{revrec} eq 'n') {
|
---|
[467] | 888 | ($code,$msg) = $self->_validate_1(%args) if ${$args{rectype}} == 65280;
|
---|
| 889 | ($code,$msg) = $self->_validate_28(%args) if ${$args{rectype}} == 65281;
|
---|
[340] | 890 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 891 |
|
---|
| 892 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
| 893 | # work here since we don't *know* which parent to put it in.
|
---|
| 894 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
| 895 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
| 896 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
| 897 | # Fail if no match; we can't coerce a PTR-template type down to not include the PTR bit currently.
|
---|
| 898 | if (!$revid) {
|
---|
| 899 | $msg = "Can't ".($args{update} ? 'update' : 'add')." ${$args{host}}/${$args{val}} as ".
|
---|
| 900 | "$typemap{${$args{rectype}}}: reverse zone not found for ${$args{val}}";
|
---|
| 901 | ##fixme: add A template, AAAA template types?
|
---|
| 902 | # ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
| 903 | return ('FAIL', $msg);
|
---|
| 904 | }
|
---|
| 905 |
|
---|
| 906 | # Add reverse zone ID to field list and values
|
---|
| 907 | ${$args{fields}} .= "rdns_id,";
|
---|
| 908 | push @{$args{vallist}}, $revid;
|
---|
| 909 |
|
---|
| 910 | } else {
|
---|
[467] | 911 | return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
| 912 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
[340] | 913 | ${$args{val}} = "$args{addr}";
|
---|
| 914 |
|
---|
[467] | 915 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) {
|
---|
[340] | 916 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
| 917 | " as PTR template instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
| 918 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
| 919 | $msg = $addmsg if $code eq 'OK';
|
---|
| 920 | ${$args{rectype}} = 65282;
|
---|
| 921 | return ('WARN', $msg);
|
---|
| 922 | }
|
---|
| 923 |
|
---|
| 924 | # Add domain ID to field list and values
|
---|
| 925 | ${$args{fields}} .= "domain_id,";
|
---|
| 926 | push @{$args{vallist}}, ${$args{domid}};
|
---|
| 927 | }
|
---|
| 928 |
|
---|
| 929 | } else {
|
---|
[467] | 930 | my ($code,$msg) = $self->_validate_65282(%args);
|
---|
[340] | 931 | return ($code, $msg) if $code eq 'FAIL';
|
---|
| 932 | # get domain, check against ${$args{name}}
|
---|
| 933 | }
|
---|
| 934 |
|
---|
[228] | 935 | return ('OK','OK');
|
---|
| 936 | } # done AAAA+PTR template record
|
---|
| 937 |
|
---|
| 938 | # AAAA+PTR template record
|
---|
| 939 | sub _validate_65284 {
|
---|
| 940 | return ('OK','OK');
|
---|
| 941 | } # done AAAA+PTR template record
|
---|
| 942 |
|
---|
[342] | 943 | # Delegation record
|
---|
[345] | 944 | # This is essentially a specialized clone of the NS record, primarily useful
|
---|
| 945 | # for delegating IPv4 sub-/24 reverse blocks
|
---|
[342] | 946 | sub _validate_65285 {
|
---|
[467] | 947 | my $self = shift;
|
---|
| 948 | my $dbh = $self->{dbh};
|
---|
[345] | 949 |
|
---|
| 950 | my %args = @_;
|
---|
| 951 |
|
---|
| 952 | # Almost, but not quite, identical to NS record validation.
|
---|
| 953 |
|
---|
| 954 | # Check that the target of the record is within the parent.
|
---|
| 955 | # Yes, host<->val are mixed up here; can't see a way to avoid it. :(
|
---|
| 956 | if ($args{defrec} eq 'n') {
|
---|
| 957 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
| 958 | if ($args{revrec} eq 'y') {
|
---|
| 959 | my $tmpip = NetAddr::IP->new(${$args{val}});
|
---|
[467] | 960 | my $pname = $self->revName($args{id});
|
---|
[345] | 961 | return ('FAIL',"${$args{val}} not within $pname")
|
---|
[467] | 962 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$tmpip);
|
---|
[345] | 963 | # Normalize
|
---|
| 964 | ${$args{val}} = "$tmpip";
|
---|
| 965 | } else {
|
---|
[467] | 966 | my $pname = $self->domainName($args{id});
|
---|
[345] | 967 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 968 | }
|
---|
| 969 | } else {
|
---|
| 970 | return ('FAIL',"Delegation records are not permitted in default record sets");
|
---|
| 971 | }
|
---|
[342] | 972 | return ('OK','OK');
|
---|
| 973 | }
|
---|
[228] | 974 |
|
---|
[342] | 975 |
|
---|
[265] | 976 | ##
|
---|
| 977 | ## Record data substitution subs
|
---|
| 978 | ##
|
---|
[228] | 979 |
|
---|
[298] | 980 | # Replace ZONE in hostname, or create (most of) the actual proper zone name
|
---|
[265] | 981 | sub _ZONE {
|
---|
| 982 | my $zone = shift;
|
---|
| 983 | my $string = shift;
|
---|
| 984 | my $fr = shift || 'f'; # flag for forward/reverse order? nb: ignored for IP
|
---|
[298] | 985 | my $sep = shift || '-'; # Separator character - unlikely we'll ever need more than . or -
|
---|
[265] | 986 |
|
---|
[298] | 987 | my $prefix;
|
---|
[265] | 988 |
|
---|
| 989 | $string =~ s/,/./ if !$zone->{isv6};
|
---|
| 990 | $string =~ s/,/::/ if $zone->{isv6};
|
---|
| 991 |
|
---|
[298] | 992 | # Subbing ZONE in the host. We need to properly ID the netblock range
|
---|
| 993 | # The subbed text should have "network IP with trailing zeros stripped" for
|
---|
| 994 | # blocks lined up on octet (for v4) or hex-quad (for v6) boundaries
|
---|
| 995 | # For blocks that do NOT line up on these boundaries, we take the most
|
---|
| 996 | # significant octet or 16-bit chunk of the "broadcast" IP and append it
|
---|
| 997 | # after a double-dash
|
---|
| 998 | # ie:
|
---|
| 999 | # 8.0.0.0/6 -> 8.0.0.0 -> 11.255.255.255; sub should be 8--11
|
---|
| 1000 | # 10.0.0.0/12 -> 10.0.0.0 -> 10.0.0.0 -> 10.15.255.255; sub should be 10-0--15
|
---|
| 1001 | # 192.168.4.0/22 -> 192.168.4.0 -> 192.168.7.255; sub should be 192-168-4--7
|
---|
| 1002 | # 192.168.0.8/29 -> 192.168.0.8 -> 192.168.0.15; sub should be 192-168-0-8--15
|
---|
| 1003 | # Similar for v6
|
---|
[265] | 1004 |
|
---|
[298] | 1005 | if (!$zone->{isv6}) { # IPv4
|
---|
| 1006 |
|
---|
| 1007 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
| 1008 | # a funky subnet that had host bits set.
|
---|
| 1009 | my $bc = $zone->broadcast->addr;
|
---|
| 1010 |
|
---|
| 1011 | if ($zone->masklen > 24) {
|
---|
| 1012 | $bc =~ s/^\d+\.\d+\.\d+\.//;
|
---|
| 1013 | } elsif ($zone->masklen > 16) {
|
---|
| 1014 | $prefix =~ s/\.0$//;
|
---|
| 1015 | $bc =~ s/^\d+\.\d+\.//;
|
---|
| 1016 | } elsif ($zone->masklen > 8) {
|
---|
| 1017 | $bc =~ s/^\d+\.//;
|
---|
| 1018 | $prefix =~ s/\.0\.0$//;
|
---|
| 1019 | } else {
|
---|
| 1020 | $prefix =~ s/\.0\.0\.0$//;
|
---|
| 1021 | }
|
---|
| 1022 | if ($zone->masklen % 8) {
|
---|
| 1023 | $bc =~ s/(\.255)+$//;
|
---|
| 1024 | $prefix .= "--$bc"; #"--".zone->masklen; # use range or mask length?
|
---|
| 1025 | }
|
---|
| 1026 | if ($fr eq 'f') {
|
---|
| 1027 | $prefix =~ s/\.+/$sep/g;
|
---|
| 1028 | } else {
|
---|
| 1029 | $prefix = join($sep, reverse(split(/\./, $prefix)));
|
---|
| 1030 | }
|
---|
| 1031 |
|
---|
| 1032 | } else { # IPv6
|
---|
| 1033 |
|
---|
| 1034 | if ($fr eq 'f') {
|
---|
| 1035 |
|
---|
| 1036 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
| 1037 | # a funky subnet that had host bits set.
|
---|
[265] | 1038 | my $bc = $zone->broadcast->addr;
|
---|
| 1039 | if (($zone->masklen % 16) != 0) {
|
---|
[298] | 1040 | # Strip trailing :0 off $prefix, and :ffff off the broadcast IP
|
---|
| 1041 | for (my $i=0; $i<(7-int($zone->masklen / 16)); $i++) {
|
---|
| 1042 | $prefix =~ s/:0$//;
|
---|
| 1043 | $bc =~ s/:ffff$//;
|
---|
| 1044 | }
|
---|
| 1045 | # Strip the leading 16-bit chunks off the front of the broadcast IP
|
---|
| 1046 | $bc =~ s/^([a-f0-9]+:)+//;
|
---|
| 1047 | # Append the remaining 16-bit chunk to the prefix after "--"
|
---|
| 1048 | $prefix .= "--$bc";
|
---|
[265] | 1049 | } else {
|
---|
[298] | 1050 | # Strip off :0 from the end until we reach the netblock length.
|
---|
| 1051 | for (my $i=0; $i<(8-$zone->masklen / 16); $i++) {
|
---|
[265] | 1052 | $prefix =~ s/:0$//;
|
---|
[298] | 1053 | }
|
---|
[265] | 1054 | }
|
---|
[298] | 1055 | # Actually deal with the separator
|
---|
| 1056 | $prefix =~ s/:/$sep/g;
|
---|
| 1057 |
|
---|
| 1058 | } else { # $fr eq 'f'
|
---|
| 1059 |
|
---|
| 1060 | $prefix = $zone->network->full; # Just In Case someone managed to slip in
|
---|
| 1061 | # a funky subnet that had host bits set.
|
---|
| 1062 | my $bc = $zone->broadcast->full;
|
---|
| 1063 | $prefix =~ s/://g; # clean these out since they're not spaced right for this case
|
---|
| 1064 | $bc =~ s/://g;
|
---|
| 1065 | # Strip trailing 0 off $prefix, and f off the broadcast IP, to match the mask length
|
---|
| 1066 | for (my $i=0; $i<(31-int($zone->masklen / 4)); $i++) {
|
---|
| 1067 | $prefix =~ s/0$//;
|
---|
| 1068 | $bc =~ s/f$//;
|
---|
| 1069 | }
|
---|
| 1070 | # Split and reverse the order of the nibbles in the network/broadcast IPs
|
---|
[332] | 1071 | # trim another 0 for nibble-aligned blocks first, but only if we really have a block, not an IP
|
---|
| 1072 | $prefix =~ s/0$// if $zone->masklen % 4 == 0 && $zone->masklen != 128;
|
---|
[298] | 1073 | my @nbits = reverse split //, $prefix;
|
---|
| 1074 | my @bbits = reverse split //, $bc;
|
---|
| 1075 | # Handle the sub-nibble case. Eww. I feel dirty supporting this...
|
---|
| 1076 | $nbits[0] = "$nbits[0]-$bbits[0]" if ($zone->masklen % 4) != 0;
|
---|
| 1077 | # Glue it back together
|
---|
| 1078 | $prefix = join($sep, @nbits);
|
---|
| 1079 |
|
---|
| 1080 | } # $fr ne 'f'
|
---|
| 1081 |
|
---|
| 1082 | } # $zone->{isv6}
|
---|
| 1083 |
|
---|
| 1084 | # Do the substitution, finally
|
---|
| 1085 | $string =~ s/ZONE/$prefix/;
|
---|
| 1086 | $string =~ s/--/-/ if $sep ne '-'; # - as separator needs extra help for sub-octet v4 netblocks
|
---|
| 1087 | return $string;
|
---|
| 1088 | } # done _ZONE()
|
---|
| 1089 |
|
---|
| 1090 | # Not quite a substitution sub, but placed here as it's basically the inverse of above;
|
---|
| 1091 | # given the .arpa zone name, return the CIDR netblock the zone is for.
|
---|
[304] | 1092 | # Supports v4 non-octet/non-classful netblocks as per the method outlined in the Grasshopper Book (2nd Ed p217-218)
|
---|
[298] | 1093 | # Does NOT support non-quad v6 netblocks via the same scheme; it shouldn't ever be necessary.
|
---|
| 1094 | # Takes a nominal .arpa zone name, returns a success code and NetAddr::IP, or a fail code and message
|
---|
| 1095 | sub _zone2cidr {
|
---|
| 1096 | my $zone = shift;
|
---|
| 1097 |
|
---|
| 1098 | my $cidr;
|
---|
[301] | 1099 | my $tmpcidr;
|
---|
| 1100 | my $warnmsg = '';
|
---|
[298] | 1101 |
|
---|
| 1102 | if ($zone =~ /\.in-addr\.arpa\.?$/) {
|
---|
| 1103 | # v4 revzone, formal zone name type
|
---|
| 1104 | my $tmpzone = $zone;
|
---|
| 1105 | $tmpzone =~ s/\.in-addr\.arpa\.?//;
|
---|
[301] | 1106 | return ('FAIL', "Non-numerics in apparent IPv4 reverse zone name") if $tmpzone !~ /^(?:\d+-)?[\d\.]+$/;
|
---|
[298] | 1107 |
|
---|
| 1108 | # Snag the octet pieces
|
---|
| 1109 | my @octs = split /\./, $tmpzone;
|
---|
| 1110 |
|
---|
| 1111 | # Map result of a range manipulation to a mask length change. Cheaper than finding the 2-root of $octets[0]+1.
|
---|
[304] | 1112 | # Note we will not support /31 blocks, mostly due to issues telling "24-31" -> .24/29 apart from
|
---|
| 1113 | # "24-31" -> .24/31", with a litte bit of "/31 is icky".
|
---|
| 1114 | my %maskmap = ( 3 => 2, 7 => 3, 15 => 4, 31 => 5, 63 => 6, 127 => 7,
|
---|
| 1115 | 30 => 2, 29 => 3, 28 => 4, 27 => 5, 26 => 6, 25 => 7
|
---|
| 1116 | );
|
---|
[298] | 1117 |
|
---|
| 1118 | # Handle "range" blocks, eg, 80-83.168.192.in-addr.arpa (192.168.80.0/22)
|
---|
| 1119 | # Need to take the size of the range to offset the basic octet-based mask length,
|
---|
| 1120 | # and make sure the first number in the range gets used as the network address for the block
|
---|
[304] | 1121 | # Alternate form: The second number is actually the real netmask, not the end of the range.
|
---|
[298] | 1122 | my $masklen = 0;
|
---|
[307] | 1123 | if ($octs[0] =~ /^((\d+)-(\d+))$/) { # take the range...
|
---|
| 1124 | if (24 < $3 && $3 < 31) {
|
---|
[304] | 1125 | # we have a real netmask
|
---|
[307] | 1126 | $masklen = -$maskmap{$3};
|
---|
[304] | 1127 | } else {
|
---|
| 1128 | # we have a range. NB: only real CIDR ranges are supported
|
---|
[307] | 1129 | $masklen -= $maskmap{-(eval $1)}; # find the mask base...
|
---|
[304] | 1130 | }
|
---|
[307] | 1131 | $octs[0] = $2; # set the base octet of the range...
|
---|
[265] | 1132 | }
|
---|
[298] | 1133 | @octs = reverse @octs; # We can reverse the octet pieces now that we've extracted and munged any ranges
|
---|
[265] | 1134 |
|
---|
[304] | 1135 | # arguably we should only allow sub-octet range/mask in-addr.arpa
|
---|
| 1136 | # specifications in the least significant octet, but the code is
|
---|
| 1137 | # simpler if we deal with sub-octet delegations at any level.
|
---|
| 1138 |
|
---|
[298] | 1139 | # Now we find the "true" mask with the aid of the "base" calculated above
|
---|
| 1140 | if ($#octs == 0) {
|
---|
| 1141 | $masklen += 8;
|
---|
| 1142 | $tmpcidr = "$octs[0].0.0.0/$masklen"; # really hope we don't see one of these very often.
|
---|
| 1143 | } elsif ($#octs == 1) {
|
---|
| 1144 | $masklen += 16;
|
---|
| 1145 | $tmpcidr = "$octs[0].$octs[1].0.0/$masklen";
|
---|
| 1146 | } elsif ($#octs == 2) {
|
---|
| 1147 | $masklen += 24;
|
---|
| 1148 | $tmpcidr = "$octs[0].$octs[1].$octs[2].0/$masklen";
|
---|
[265] | 1149 | } else {
|
---|
[298] | 1150 | $masklen += 32;
|
---|
| 1151 | $tmpcidr = "$octs[0].$octs[1].$octs[2].$octs[3]/$masklen";
|
---|
[265] | 1152 | }
|
---|
| 1153 |
|
---|
[298] | 1154 | } elsif ($zone =~ /\.ip6\.arpa$/) {
|
---|
| 1155 | # v6 revzone, formal zone name type
|
---|
| 1156 | my $tmpzone = $zone;
|
---|
| 1157 | $tmpzone =~ s/\.ip6\.arpa\.?//;
|
---|
[301] | 1158 | ##fixme: if-n-when we decide we can support sub-nibble v6 zone names, we'll need to change this segment
|
---|
| 1159 | return ('FAIL', "Non-hexadecimals in apparent IPv6 reverse zone name") if $tmpzone !~ /^[a-fA-F\d\.]+$/;
|
---|
[298] | 1160 | my @quads = reverse(split(/\./, $tmpzone));
|
---|
| 1161 | $warnmsg .= "Apparent sub-/64 IPv6 reverse zone\n" if $#quads > 15;
|
---|
| 1162 | my $nc;
|
---|
| 1163 | foreach (@quads) {
|
---|
[301] | 1164 | $tmpcidr .= $_;
|
---|
| 1165 | $tmpcidr .= ":" if ++$nc % 4 == 0;
|
---|
[298] | 1166 | }
|
---|
| 1167 | my $nq = 1 if $nc % 4 != 0;
|
---|
| 1168 | my $mask = $nc * 4; # need to do this here because we probably increment it below
|
---|
| 1169 | while ($nc++ % 4 != 0) {
|
---|
[301] | 1170 | $tmpcidr .= "0";
|
---|
[298] | 1171 | }
|
---|
[301] | 1172 | $tmpcidr .= ($nq ? '::' : ':')."/$mask";
|
---|
[298] | 1173 | }
|
---|
[301] | 1174 |
|
---|
| 1175 | # Just to be sure, use NetAddr::IP to validate. Saves a lot of nasty regex watching for valid octet values.
|
---|
| 1176 | return ('FAIL', "Invalid zone $zone (apparent netblock $tmpcidr)")
|
---|
| 1177 | unless $cidr = NetAddr::IP->new($tmpcidr);
|
---|
| 1178 |
|
---|
| 1179 | if ($warnmsg) {
|
---|
| 1180 | $errstr = $warnmsg;
|
---|
| 1181 | return ('WARN', $cidr);
|
---|
| 1182 | }
|
---|
| 1183 | return ('OK', $cidr);
|
---|
[298] | 1184 | } # done _zone2cidr()
|
---|
[265] | 1185 |
|
---|
[337] | 1186 | # Record template %-parameter expansion, IPv4. Note that IPv6 doesn't
|
---|
| 1187 | # really have a sane way to handle this type of expansion at the moment
|
---|
| 1188 | # due to the size of the address space.
|
---|
| 1189 | # Takes a reference to a template string to be expanded, and an IP to use in the replacement.
|
---|
| 1190 | sub _template4_expand {
|
---|
| 1191 | my $tmpl = shift;
|
---|
| 1192 | my $ip = shift;
|
---|
[298] | 1193 |
|
---|
[337] | 1194 | my @ipparts = split /\./, $ip;
|
---|
| 1195 | my @iphex;
|
---|
| 1196 | my @ippad;
|
---|
| 1197 | for (@ipparts) {
|
---|
| 1198 | push @iphex, sprintf("%x", $_);
|
---|
[443] | 1199 | push @ippad, sprintf("%0.3u", $_);
|
---|
[337] | 1200 | }
|
---|
| 1201 |
|
---|
| 1202 | # IP substitutions in template records:
|
---|
| 1203 | #major patterns:
|
---|
| 1204 | #dashed IP, forward and reverse
|
---|
| 1205 | #dotted IP, forward and reverse (even if forward is... dumb)
|
---|
| 1206 | # -> %r for reverse, %i for forward, leading - or . to indicate separator, defaults to -
|
---|
| 1207 | # %r or %-r => %4d-%3d-%2d-%1d
|
---|
| 1208 | # %.r => %4d.%3d.%2d.%1d
|
---|
| 1209 | # %i or %-i => %1d-%2d-%3d-%4d
|
---|
| 1210 | # %.i => %1d.%2d.%3d.%4d
|
---|
| 1211 | $$tmpl =~ s/\%r/\%4d-\%3d-\%2d-\%1d/g;
|
---|
| 1212 | $$tmpl =~ s/\%([-.])r/\%4d$1\%3d$1\%2d$1\%1d/g;
|
---|
| 1213 | $$tmpl =~ s/\%i/\%1d-\%2d-\%3d-\%4d/g;
|
---|
| 1214 | $$tmpl =~ s/\%([-.])i/\%1d$1\%2d$1\%3d$1\%4d/g;
|
---|
| 1215 |
|
---|
| 1216 | #hex-coded IP
|
---|
| 1217 | # %h
|
---|
| 1218 | $$tmpl =~ s/\%h/$iphex[0]$iphex[1]$iphex[2]$iphex[3]/g;
|
---|
| 1219 |
|
---|
| 1220 | #IP as decimal-coded 32-bit value
|
---|
| 1221 | # %d
|
---|
| 1222 | my $iptmp = $ipparts[0]*256*256*256 + $ipparts[1]*256*256 + $ipparts[2]*256 + $ipparts[3];
|
---|
| 1223 | $$tmpl =~ s/\%d/$iptmp/g;
|
---|
| 1224 |
|
---|
| 1225 | #minor patterns (per-octet)
|
---|
| 1226 | # %[1234][dh0]
|
---|
| 1227 | #octet
|
---|
| 1228 | #hex-coded octet
|
---|
| 1229 | #0-padded octet
|
---|
| 1230 | $$tmpl =~ s/\%([1234])d/$ipparts[$1-1]/g;
|
---|
| 1231 | $$tmpl =~ s/\%([1234])h/$iphex[$1-1]/g;
|
---|
[443] | 1232 | $$tmpl =~ s/\%([1234])0/$ippad[$1-1]/g;
|
---|
[337] | 1233 | } # _template4_expand()
|
---|
| 1234 |
|
---|
| 1235 |
|
---|
[228] | 1236 | ##
|
---|
[2] | 1237 | ## Initialization and cleanup subs
|
---|
| 1238 | ##
|
---|
| 1239 |
|
---|
[128] | 1240 | ## DNSDB::loadConfig()
|
---|
| 1241 | # Load the minimum required initial state (DB connect info) from a config file
|
---|
| 1242 | # Load misc other bits while we're at it.
|
---|
[400] | 1243 | # Takes an optional hash that may contain:
|
---|
| 1244 | # - basename and config path to look for
|
---|
[128] | 1245 | # Populates the %config and %def hashes
|
---|
| 1246 | sub loadConfig {
|
---|
[400] | 1247 | my %args = @_;
|
---|
[465] | 1248 | $args{configfile} = '' if !$args{configfile};
|
---|
[128] | 1249 |
|
---|
[465] | 1250 | ##fixme this is *intended* to load a system-default config template, and allow
|
---|
| 1251 | # overriding on a per-tool or per-web-UI-instance basis with a secondary config
|
---|
| 1252 | # file. The "default" config file can't be deleted in the current form.
|
---|
| 1253 |
|
---|
[128] | 1254 | my $deferr = ''; # place to put error from default config file in case we can't find either one
|
---|
| 1255 |
|
---|
[219] | 1256 | my $configroot = "/etc/dnsdb"; ##CFG_LEAF##
|
---|
[465] | 1257 | $configroot = '' if $args{configfile} =~ m|^/|; # allow passed siteconfig to specify an arbitrary absolute path
|
---|
| 1258 | $args{configfile} .= ".conf" if $args{configfile} !~ /\.conf$/;
|
---|
[128] | 1259 | my $defconfig = "$configroot/dnsdb.conf";
|
---|
[465] | 1260 | my $siteconfig = "$configroot/$args{configfile}";
|
---|
[128] | 1261 |
|
---|
| 1262 | # System defaults
|
---|
[465] | 1263 | __cfgload("$defconfig") or $deferr = $errstr;
|
---|
[128] | 1264 |
|
---|
[131] | 1265 | # Per-site-ish settings.
|
---|
[465] | 1266 | if ($args{configfile} ne '.conf') {
|
---|
| 1267 | unless (__cfgload("$siteconfig")) {
|
---|
[131] | 1268 | $errstr = ($deferr ? "Error opening default config file $defconfig: $deferr\n" : '').
|
---|
[128] | 1269 | "Error opening site config file $siteconfig";
|
---|
[131] | 1270 | return;
|
---|
| 1271 | }
|
---|
[128] | 1272 | }
|
---|
| 1273 |
|
---|
[195] | 1274 | # Munge log_failures.
|
---|
| 1275 | if ($config{log_failures} ne '1' && $config{log_failures} ne '0') {
|
---|
| 1276 | # true/false, on/off, yes/no all valid.
|
---|
| 1277 | if ($config{log_failures} =~ /^(?:true|false|on|off|yes|no)$/) {
|
---|
| 1278 | if ($config{log_failures} =~ /(?:true|on|yes)/) {
|
---|
| 1279 | $config{log_failures} = 1;
|
---|
| 1280 | } else {
|
---|
| 1281 | $config{log_failures} = 0;
|
---|
| 1282 | }
|
---|
| 1283 | } else {
|
---|
| 1284 | $errstr = "Bad log_failures setting $config{log_failures}";
|
---|
| 1285 | $config{log_failures} = 1;
|
---|
| 1286 | # Bad setting shouldn't be fatal.
|
---|
| 1287 | # return 2;
|
---|
| 1288 | }
|
---|
| 1289 | }
|
---|
| 1290 |
|
---|
[128] | 1291 | # All good, clear the error and go home.
|
---|
| 1292 | $errstr = '';
|
---|
| 1293 | return 1;
|
---|
| 1294 | } # end loadConfig()
|
---|
| 1295 |
|
---|
| 1296 |
|
---|
| 1297 | ## DNSDB::__cfgload()
|
---|
| 1298 | # Private sub to parse a config file and load it into %config
|
---|
[465] | 1299 | # Takes a filename
|
---|
[128] | 1300 | sub __cfgload {
|
---|
| 1301 | $errstr = '';
|
---|
| 1302 | my $cfgfile = shift;
|
---|
[131] | 1303 |
|
---|
[128] | 1304 | if (open CFG, "<$cfgfile") {
|
---|
| 1305 | while (<CFG>) {
|
---|
| 1306 | chomp;
|
---|
| 1307 | s/^\s*//;
|
---|
| 1308 | next if /^#/;
|
---|
| 1309 | next if /^$/;
|
---|
| 1310 | # hmm. more complex bits in this file might require [heading] headers, maybe?
|
---|
| 1311 | # $mode = $1 if /^\[(a-z)+]/;
|
---|
| 1312 | # DB connect info
|
---|
| 1313 | $config{dbname} = $1 if /^dbname\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1314 | $config{dbuser} = $1 if /^dbuser\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1315 | $config{dbpass} = $1 if /^dbpass\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1316 | $config{dbhost} = $1 if /^dbhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1317 | # SOA defaults
|
---|
| 1318 | $def{contact} = $1 if /^contact\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1319 | $def{prins} = $1 if /^prins\s*=\s*([a-z0-9_.-]+)/i;
|
---|
[201] | 1320 | $def{soattl} = $1 if /^soattl\s*=\s*(\d+)/i;
|
---|
| 1321 | $def{refresh} = $1 if /^refresh\s*=\s*(\d+)/i;
|
---|
| 1322 | $def{retry} = $1 if /^retry\s*=\s*(\d+)/i;
|
---|
| 1323 | $def{expire} = $1 if /^expire\s*=\s*(\d+)/i;
|
---|
| 1324 | $def{minttl} = $1 if /^minttl\s*=\s*(\d+)/i;
|
---|
| 1325 | $def{ttl} = $1 if /^ttl\s*=\s*(\d+)/i;
|
---|
[128] | 1326 | # Mail settings
|
---|
| 1327 | $config{mailhost} = $1 if /^mailhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
[198] | 1328 | $config{mailnotify} = $1 if /^mailnotify\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
| 1329 | $config{mailsender} = $1 if /^mailsender\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
[128] | 1330 | $config{mailname} = $1 if /^mailname\s*=\s*([a-z0-9\s_.-]+)/i;
|
---|
[195] | 1331 | $config{orgname} = $1 if /^orgname\s*=\s*([a-z0-9\s_.,'-]+)/i;
|
---|
| 1332 | $config{domain} = $1 if /^domain\s*=\s*([a-z0-9_.-]+)/i;
|
---|
[163] | 1333 | # session - note this is fed directly to CGI::Session
|
---|
[216] | 1334 | $config{timeout} = $1 if /^[tT][iI][mM][eE][oO][uU][tT]\s*=\s*(\d+[smhdwMy]?)/;
|
---|
| 1335 | $config{sessiondir} = $1 if m{^sessiondir\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
[201] | 1336 | # misc
|
---|
[195] | 1337 | $config{log_failures} = $1 if /^log_failures\s*=\s*([a-z01]+)/i;
|
---|
[201] | 1338 | $config{perpage} = $1 if /^perpage\s*=\s*(\d+)/i;
|
---|
[368] | 1339 | $config{exportcache} = $1 if m{^exportcache\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
[400] | 1340 | # RPC options
|
---|
[465] | 1341 | $config{rpcmode} = $1 if /^rpc_mode\s*=\s*(socket|HTTP|XMLRPC)\s*$/i;
|
---|
| 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::initPermissions()
|
---|
| 1562 | # Set up permissions global
|
---|
| 1563 | # Takes database handle and UID
|
---|
| 1564 | sub initPermissions {
|
---|
[469] | 1565 | my $self = shift;
|
---|
| 1566 | my $dbh = $self->{dbh};
|
---|
[65] | 1567 | my $uid = shift;
|
---|
| 1568 |
|
---|
[469] | 1569 | # %permissions = $(getPermissions('user',$uid));
|
---|
| 1570 | $self->getPermissions('user', $uid, \%permissions);
|
---|
[65] | 1571 |
|
---|
| 1572 | } # end initPermissions()
|
---|
| 1573 |
|
---|
| 1574 |
|
---|
| 1575 | ## DNSDB::getPermissions()
|
---|
| 1576 | # Get permissions from DB
|
---|
| 1577 | # Requires DB handle, group or user flag, ID, and hashref.
|
---|
| 1578 | sub getPermissions {
|
---|
[469] | 1579 | my $self = shift;
|
---|
| 1580 | my $dbh = $self->{dbh};
|
---|
| 1581 |
|
---|
[65] | 1582 | my $type = shift;
|
---|
| 1583 | my $id = shift;
|
---|
| 1584 | my $hash = shift;
|
---|
| 1585 |
|
---|
| 1586 | my $sql = qq(
|
---|
| 1587 | SELECT
|
---|
| 1588 | p.admin,p.self_edit,
|
---|
| 1589 | p.group_create,p.group_edit,p.group_delete,
|
---|
| 1590 | p.user_create,p.user_edit,p.user_delete,
|
---|
| 1591 | p.domain_create,p.domain_edit,p.domain_delete,
|
---|
[387] | 1592 | p.record_create,p.record_edit,p.record_delete,p.record_locchg,
|
---|
[382] | 1593 | p.location_create,p.location_edit,p.location_delete,p.location_view
|
---|
[65] | 1594 | FROM permissions p
|
---|
| 1595 | );
|
---|
| 1596 | if ($type eq 'group') {
|
---|
| 1597 | $sql .= qq(
|
---|
| 1598 | JOIN groups g ON g.permission_id=p.permission_id
|
---|
| 1599 | WHERE g.group_id=?
|
---|
| 1600 | );
|
---|
| 1601 | } else {
|
---|
| 1602 | $sql .= qq(
|
---|
| 1603 | JOIN users u ON u.permission_id=p.permission_id
|
---|
| 1604 | WHERE u.user_id=?
|
---|
| 1605 | );
|
---|
| 1606 | }
|
---|
| 1607 |
|
---|
| 1608 | my $sth = $dbh->prepare($sql);
|
---|
| 1609 |
|
---|
| 1610 | $sth->execute($id) or die "argh: ".$sth->errstr;
|
---|
| 1611 |
|
---|
| 1612 | # my $permref = $sth->fetchrow_hashref;
|
---|
| 1613 | # return $permref;
|
---|
| 1614 | # $hash = $permref;
|
---|
| 1615 | # Eww. Need to learn how to forcibly drop a hashref onto an existing hash.
|
---|
| 1616 | ($hash->{admin},$hash->{self_edit},
|
---|
| 1617 | $hash->{group_create},$hash->{group_edit},$hash->{group_delete},
|
---|
| 1618 | $hash->{user_create},$hash->{user_edit},$hash->{user_delete},
|
---|
| 1619 | $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete},
|
---|
[387] | 1620 | $hash->{record_create},$hash->{record_edit},$hash->{record_delete},$hash->{record_locchg},
|
---|
[382] | 1621 | $hash->{location_create},$hash->{location_edit},$hash->{location_delete},$hash->{location_view}
|
---|
| 1622 | ) = $sth->fetchrow_array;
|
---|
[65] | 1623 |
|
---|
| 1624 | } # end getPermissions()
|
---|
| 1625 |
|
---|
| 1626 |
|
---|
| 1627 | ## DNSDB::changePermissions()
|
---|
| 1628 | # Update an ACL entry
|
---|
| 1629 | # Takes a db handle, type, owner-id, and hashref for the changed permissions.
|
---|
| 1630 | sub changePermissions {
|
---|
[474] | 1631 | my $self = shift;
|
---|
| 1632 | my $dbh = $self->{dbh};
|
---|
[65] | 1633 | my $type = shift;
|
---|
| 1634 | my $id = shift;
|
---|
| 1635 | my $newperms = shift;
|
---|
[87] | 1636 | my $inherit = shift || 0;
|
---|
[65] | 1637 |
|
---|
[294] | 1638 | my $resultmsg = '';
|
---|
[66] | 1639 |
|
---|
[87] | 1640 | # see if we're switching from inherited to custom. for bonus points,
|
---|
| 1641 | # snag the permid and parent permid anyway, since we'll need the permid
|
---|
| 1642 | # to set/alter custom perms, and both if we're switching from custom to
|
---|
| 1643 | # inherited.
|
---|
[294] | 1644 | my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id,".
|
---|
| 1645 | ($type eq 'user' ? 'u.group_id,u.username' : 'u.parent_group_id,u.group_name').
|
---|
[65] | 1646 | " FROM ".($type eq 'user' ? 'users' : 'groups')." u ".
|
---|
[66] | 1647 | " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ".
|
---|
[65] | 1648 | " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?");
|
---|
| 1649 | $sth->execute($id);
|
---|
| 1650 |
|
---|
[294] | 1651 | my ($wasinherited,$permid,$parpermid,$parid,$name) = $sth->fetchrow_array;
|
---|
[66] | 1652 |
|
---|
[78] | 1653 | # hack phtoui
|
---|
| 1654 | # group id 1 is "special" in that it's it's own parent (err... possibly.)
|
---|
| 1655 | # may make its parent id 0 which doesn't exist, and as a bonus is Perl-false.
|
---|
| 1656 | $wasinherited = 0 if ($type eq 'group' && $id == 1);
|
---|
| 1657 |
|
---|
[66] | 1658 | local $dbh->{AutoCommit} = 0;
|
---|
| 1659 | local $dbh->{RaiseError} = 1;
|
---|
| 1660 |
|
---|
| 1661 | # Wrap all the SQL in a transaction
|
---|
| 1662 | eval {
|
---|
[87] | 1663 | if ($inherit) {
|
---|
| 1664 |
|
---|
| 1665 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ".
|
---|
| 1666 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) );
|
---|
| 1667 | $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) );
|
---|
| 1668 |
|
---|
| 1669 | } else {
|
---|
| 1670 |
|
---|
| 1671 | if ($wasinherited) { # munge new permission entry in if we're switching from inherited perms
|
---|
[66] | 1672 | ##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users
|
---|
[87] | 1673 | # ... if'n'when we have groups with fully inherited permissions.
|
---|
| 1674 | # SQL is coo
|
---|
| 1675 | $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ".
|
---|
| 1676 | "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) );
|
---|
| 1677 | ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ".
|
---|
| 1678 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) );
|
---|
| 1679 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ".
|
---|
| 1680 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) );
|
---|
[66] | 1681 | }
|
---|
[78] | 1682 |
|
---|
[87] | 1683 | # and now set the permissions we were passed
|
---|
| 1684 | foreach (@permtypes) {
|
---|
| 1685 | if (defined ($newperms->{$_})) {
|
---|
| 1686 | $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) );
|
---|
| 1687 | }
|
---|
| 1688 | }
|
---|
| 1689 |
|
---|
| 1690 | } # (inherited->)? custom
|
---|
| 1691 |
|
---|
[294] | 1692 | if ($type eq 'user') {
|
---|
| 1693 | $resultmsg = "Updated permissions for user $name";
|
---|
| 1694 | } else {
|
---|
| 1695 | $resultmsg = "Updated default permissions for group $name";
|
---|
| 1696 | }
|
---|
[487] | 1697 | $self->_log(group_id => ($type eq 'user' ? $parid : $id), entry => $resultmsg);
|
---|
[66] | 1698 | $dbh->commit;
|
---|
| 1699 | }; # end eval
|
---|
| 1700 | if ($@) {
|
---|
| 1701 | my $msg = $@;
|
---|
| 1702 | eval { $dbh->rollback; };
|
---|
[294] | 1703 | return ('FAIL',"Error changing permissions: $msg");
|
---|
[66] | 1704 | }
|
---|
| 1705 |
|
---|
[294] | 1706 | return ('OK',$resultmsg);
|
---|
[65] | 1707 | } # end changePermissions()
|
---|
| 1708 |
|
---|
| 1709 |
|
---|
[67] | 1710 | ## DNSDB::comparePermissions()
|
---|
| 1711 | # Compare two permission hashes
|
---|
| 1712 | # Returns '>', '<', '=', '!'
|
---|
| 1713 | sub comparePermissions {
|
---|
| 1714 | my $p1 = shift;
|
---|
| 1715 | my $p2 = shift;
|
---|
| 1716 |
|
---|
| 1717 | my $retval = '='; # assume equality until proven otherwise
|
---|
| 1718 |
|
---|
| 1719 | no warnings "uninitialized";
|
---|
| 1720 |
|
---|
| 1721 | foreach (@permtypes) {
|
---|
| 1722 | next if $p1->{$_} == $p2->{$_}; # equal is good
|
---|
| 1723 | if ($p1->{$_} && !$p2->{$_}) {
|
---|
| 1724 | if ($retval eq '<') { # if we've already found an unequal pair where
|
---|
| 1725 | $retval = '!'; # $p2 has more access, and we now find a pair
|
---|
| 1726 | last; # where $p1 has more access, the overall access
|
---|
| 1727 | } # is neither greater or lesser, it's unequal.
|
---|
| 1728 | $retval = '>';
|
---|
| 1729 | }
|
---|
| 1730 | if (!$p1->{$_} && $p2->{$_}) {
|
---|
| 1731 | if ($retval eq '>') { # if we've already found an unequal pair where
|
---|
| 1732 | $retval = '!'; # $p1 has more access, and we now find a pair
|
---|
| 1733 | last; # where $p2 has more access, the overall access
|
---|
| 1734 | } # is neither greater or lesser, it's unequal.
|
---|
| 1735 | $retval = '<';
|
---|
| 1736 | }
|
---|
| 1737 | }
|
---|
| 1738 | return $retval;
|
---|
| 1739 | } # end comparePermissions()
|
---|
| 1740 |
|
---|
| 1741 |
|
---|
[112] | 1742 | ## DNSDB::changeGroup()
|
---|
| 1743 | # Change group ID of an entity
|
---|
| 1744 | # Takes a database handle, entity type, entity ID, and new group ID
|
---|
| 1745 | sub changeGroup {
|
---|
[476] | 1746 | my $self = shift;
|
---|
| 1747 | my $dbh = $self->{dbh};
|
---|
[112] | 1748 | my $type = shift;
|
---|
| 1749 | my $id = shift;
|
---|
| 1750 | my $newgrp = shift;
|
---|
| 1751 |
|
---|
| 1752 | ##fixme: fail on not enough args
|
---|
| 1753 | #return ('FAIL', "Missing
|
---|
| 1754 |
|
---|
[295] | 1755 | return ('FAIL', "Can't change the group of a $type")
|
---|
| 1756 | unless grep /^$type$/, ('domain','revzone','user','group'); # could be extended for defrecs?
|
---|
| 1757 |
|
---|
| 1758 | # Collect some names for logging and messages
|
---|
| 1759 | my $entname;
|
---|
[112] | 1760 | if ($type eq 'domain') {
|
---|
[473] | 1761 | $entname = $self->domainName($id);
|
---|
[295] | 1762 | } elsif ($type eq 'revzone') {
|
---|
[473] | 1763 | $entname = $self->revName($id);
|
---|
[112] | 1764 | } elsif ($type eq 'user') {
|
---|
[473] | 1765 | $entname = $self->userFullName($id, '%u');
|
---|
[112] | 1766 | } elsif ($type eq 'group') {
|
---|
[473] | 1767 | $entname = $self->groupName($id);
|
---|
[112] | 1768 | }
|
---|
[295] | 1769 |
|
---|
| 1770 | my ($oldgid) = $dbh->selectrow_array("SELECT group_id FROM $par_tbl{$type} WHERE $id_col{$type}=?",
|
---|
| 1771 | undef, ($id));
|
---|
[473] | 1772 | my $oldgname = $self->groupName($oldgid);
|
---|
| 1773 | my $newgname = $self->groupName($newgrp);
|
---|
[295] | 1774 |
|
---|
| 1775 | return ('FAIL', "Can't move things into a group that doesn't exist") if !$newgname;
|
---|
| 1776 |
|
---|
| 1777 | return ('WARN', "Nothing to do, new group is the same as the old group") if $oldgid == $newgrp;
|
---|
| 1778 |
|
---|
| 1779 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 1780 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 1781 | local $dbh->{AutoCommit} = 0;
|
---|
| 1782 | local $dbh->{RaiseError} = 1;
|
---|
| 1783 |
|
---|
| 1784 | eval {
|
---|
| 1785 | $dbh->do("UPDATE $par_tbl{$type} SET group_id=? WHERE $id_col{$type}=?", undef, ($newgrp, $id));
|
---|
| 1786 | # Log the change in both the old and new groups
|
---|
[487] | 1787 | $self->_log(group_id => $oldgid, entry => "Moved $type $entname from $oldgname to $newgname");
|
---|
| 1788 | $self->_log(group_id => $newgrp, entry => "Moved $type $entname from $oldgname to $newgname");
|
---|
[295] | 1789 | $dbh->commit;
|
---|
| 1790 | };
|
---|
| 1791 | if ($@) {
|
---|
| 1792 | my $msg = $@;
|
---|
| 1793 | eval { $dbh->rollback; };
|
---|
| 1794 | if ($config{log_failures}) {
|
---|
[487] | 1795 | $self->_log(group_id => $oldgid, entry => "Error moving $type $entname to $newgname: $msg");
|
---|
[295] | 1796 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 1797 | }
|
---|
| 1798 | return ('FAIL',"Error moving $type $entname to $newgname: $msg");
|
---|
| 1799 | }
|
---|
| 1800 |
|
---|
| 1801 | return ('OK',"Moved $type $entname from $oldgname to $newgname");
|
---|
[112] | 1802 | } # end changeGroup()
|
---|
| 1803 |
|
---|
| 1804 |
|
---|
[2] | 1805 | ##
|
---|
| 1806 | ## Processing subs
|
---|
| 1807 | ##
|
---|
| 1808 |
|
---|
| 1809 | ## DNSDB::addDomain()
|
---|
| 1810 | # Add a domain
|
---|
[190] | 1811 | # Takes a database handle, domain name, numeric group, boolean(ish) state (active/inactive),
|
---|
| 1812 | # and user info hash (for logging).
|
---|
[2] | 1813 | # Returns a status code and message
|
---|
| 1814 | sub addDomain {
|
---|
| 1815 | $errstr = '';
|
---|
[477] | 1816 | my $self = shift;
|
---|
| 1817 | my $dbh = $self->{dbh};
|
---|
[2] | 1818 | return ('FAIL',"Need database handle") if !$dbh;
|
---|
| 1819 | my $domain = shift;
|
---|
[91] | 1820 | return ('FAIL',"Domain must not be blank") if !$domain;
|
---|
[2] | 1821 | my $group = shift;
|
---|
| 1822 | return ('FAIL',"Need group") if !defined($group);
|
---|
| 1823 | my $state = shift;
|
---|
| 1824 | return ('FAIL',"Need domain status") if !defined($state);
|
---|
| 1825 |
|
---|
[116] | 1826 | $state = 1 if $state =~ /^active$/;
|
---|
| 1827 | $state = 1 if $state =~ /^on$/;
|
---|
| 1828 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 1829 | $state = 0 if $state =~ /^off$/;
|
---|
| 1830 |
|
---|
| 1831 | return ('FAIL',"Invalid domain status") if $state !~ /^\d+$/;
|
---|
| 1832 |
|
---|
[190] | 1833 | return ('FAIL', "Invalid characters in domain") if $domain !~ /^[a-zA-Z0-9_.-]+$/;
|
---|
| 1834 |
|
---|
[349] | 1835 | my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)");
|
---|
[3] | 1836 | my $dom_id;
|
---|
| 1837 |
|
---|
[38] | 1838 | # quick check to start to see if we've already got one
|
---|
| 1839 | $sth->execute($domain);
|
---|
| 1840 | ($dom_id) = $sth->fetchrow_array;
|
---|
| 1841 |
|
---|
| 1842 | return ('FAIL', "Domain already exists") if $dom_id;
|
---|
| 1843 |
|
---|
[2] | 1844 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 1845 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 1846 | local $dbh->{AutoCommit} = 0;
|
---|
| 1847 | local $dbh->{RaiseError} = 1;
|
---|
| 1848 |
|
---|
| 1849 | # Wrap all the SQL in a transaction
|
---|
| 1850 | eval {
|
---|
| 1851 | # insert the domain...
|
---|
[190] | 1852 | $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef, ($domain, $group, $state));
|
---|
[2] | 1853 |
|
---|
| 1854 | # get the ID...
|
---|
[349] | 1855 | ($dom_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
| 1856 | undef, ($domain));
|
---|
[2] | 1857 |
|
---|
[487] | 1858 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
| 1859 | entry => "Added ".($state ? 'active' : 'inactive')." domain $domain");
|
---|
[190] | 1860 |
|
---|
[2] | 1861 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
[190] | 1862 | my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
| 1863 | my $sth_in = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,distance,weight,port,ttl)".
|
---|
| 1864 | " VALUES ($dom_id,?,?,?,?,?,?,?)");
|
---|
| 1865 | $sth->execute($group);
|
---|
[3] | 1866 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $sth->fetchrow_array()) {
|
---|
[2] | 1867 | $host =~ s/DOMAIN/$domain/g;
|
---|
[37] | 1868 | $val =~ s/DOMAIN/$domain/g;
|
---|
[3] | 1869 | $sth_in->execute($host,$type,$val,$dist,$weight,$port,$ttl);
|
---|
[190] | 1870 | if ($typemap{$type} eq 'SOA') {
|
---|
| 1871 | my @tmp1 = split /:/, $host;
|
---|
| 1872 | my @tmp2 = split /:/, $val;
|
---|
[487] | 1873 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
[284] | 1874 | entry => "[new $domain] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
[487] | 1875 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl");
|
---|
[190] | 1876 | } else {
|
---|
| 1877 | my $logentry = "[new $domain] Added record '$host $typemap{$type}";
|
---|
| 1878 | $logentry .= " [distance $dist]" if $typemap{$type} eq 'MX';
|
---|
| 1879 | $logentry .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$type} eq 'SRV';
|
---|
[487] | 1880 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
| 1881 | entry => $logentry." $val', TTL $ttl");
|
---|
[190] | 1882 | }
|
---|
[2] | 1883 | }
|
---|
| 1884 |
|
---|
| 1885 | # once we get here, we should have suceeded.
|
---|
| 1886 | $dbh->commit;
|
---|
| 1887 | }; # end eval
|
---|
| 1888 |
|
---|
| 1889 | if ($@) {
|
---|
| 1890 | my $msg = $@;
|
---|
| 1891 | eval { $dbh->rollback; };
|
---|
[487] | 1892 | $self->_log(group_id => $group, entry => "Failed adding domain $domain ($msg)")
|
---|
[284] | 1893 | if $config{log_failures};
|
---|
| 1894 | $dbh->commit; # since we enabled transactions earlier
|
---|
[193] | 1895 | return ('FAIL',$msg);
|
---|
[2] | 1896 | } else {
|
---|
[3] | 1897 | return ('OK',$dom_id);
|
---|
[2] | 1898 | }
|
---|
| 1899 | } # end addDomain
|
---|
| 1900 |
|
---|
| 1901 |
|
---|
[274] | 1902 | ## DNSDB::delZone()
|
---|
| 1903 | # Delete a forward or reverse zone.
|
---|
| 1904 | # Takes a database handle, zone ID, and forward/reverse flag.
|
---|
[3] | 1905 | # for now, just delete the records, then the domain.
|
---|
| 1906 | # later we may want to archive it in some way instead (status code 2, for example?)
|
---|
[274] | 1907 | sub delZone {
|
---|
[477] | 1908 | my $self = shift;
|
---|
| 1909 | my $dbh = $self->{dbh};
|
---|
[274] | 1910 | my $zoneid = shift;
|
---|
| 1911 | my $revrec = shift;
|
---|
[3] | 1912 |
|
---|
| 1913 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 1914 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 1915 | local $dbh->{AutoCommit} = 0;
|
---|
| 1916 | local $dbh->{RaiseError} = 1;
|
---|
| 1917 |
|
---|
[285] | 1918 | my $msg = '';
|
---|
[23] | 1919 | my $failmsg = '';
|
---|
[473] | 1920 | my $zone = ($revrec eq 'n' ? $self->domainName($zoneid) : $self->revName($zoneid));
|
---|
[23] | 1921 |
|
---|
[343] | 1922 | return ('FAIL', ($revrec eq 'n' ? 'Domain' : 'Reverse zone')." ID $zoneid doesn't exist") if !$zone;
|
---|
| 1923 |
|
---|
[285] | 1924 | # Set this up here since we may use if if $config{log_failures} is enabled
|
---|
| 1925 | my %loghash;
|
---|
| 1926 | $loghash{domain_id} = $zoneid if $revrec eq 'n';
|
---|
| 1927 | $loghash{rdns_id} = $zoneid if $revrec eq 'y';
|
---|
[473] | 1928 | $loghash{group_id} = $self->parentID(
|
---|
| 1929 | id => $zoneid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec);
|
---|
[285] | 1930 |
|
---|
[3] | 1931 | # Wrap all the SQL in a transaction
|
---|
| 1932 | eval {
|
---|
[274] | 1933 | # Disentangle custom record types before removing the
|
---|
| 1934 | # ones that are only in the zone to be deleted
|
---|
| 1935 | if ($revrec eq 'n') {
|
---|
| 1936 | my $sth = $dbh->prepare("UPDATE records SET type=?,domain_id=0 WHERE domain_id=? AND type=?");
|
---|
| 1937 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
| 1938 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65280);
|
---|
| 1939 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65281);
|
---|
| 1940 | $sth->execute(65282, $zoneid, 65283);
|
---|
| 1941 | $sth->execute(65282, $zoneid, 65284);
|
---|
| 1942 | $failmsg = "Failure removing domain records";
|
---|
| 1943 | $dbh->do("DELETE FROM records WHERE domain_id=?", undef, ($zoneid));
|
---|
| 1944 | $failmsg = "Failure removing domain";
|
---|
| 1945 | $dbh->do("DELETE FROM domains WHERE domain_id=?", undef, ($zoneid));
|
---|
| 1946 | } else {
|
---|
| 1947 | my $sth = $dbh->prepare("UPDATE records SET type=?,rdns_id=0 WHERE rdns_id=? AND type=?");
|
---|
| 1948 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
| 1949 | $sth->execute($reverse_typemap{A}, $zoneid, 65280);
|
---|
| 1950 | $sth->execute($reverse_typemap{AAAA}, $zoneid, 65281);
|
---|
| 1951 | # We don't have an "A template" or "AAAA template" type, although it might be useful for symmetry.
|
---|
[345] | 1952 | # $sth->execute(65286?, $zoneid, 65283);
|
---|
| 1953 | # $sth->execute(65286?, $zoneid, 65284);
|
---|
[274] | 1954 | $failmsg = "Failure removing reverse records";
|
---|
| 1955 | $dbh->do("DELETE FROM records WHERE rdns_id=?", undef, ($zoneid));
|
---|
| 1956 | $failmsg = "Failure removing reverse zone";
|
---|
| 1957 | $dbh->do("DELETE FROM revzones WHERE rdns_id=?", undef, ($zoneid));
|
---|
| 1958 | }
|
---|
[3] | 1959 |
|
---|
[285] | 1960 | $msg = "Deleted ".($revrec eq 'n' ? 'domain' : 'reverse zone')." $zone";
|
---|
| 1961 | $loghash{entry} = $msg;
|
---|
[487] | 1962 | $self->_log(%loghash);
|
---|
[285] | 1963 |
|
---|
[3] | 1964 | # once we get here, we should have suceeded.
|
---|
[23] | 1965 | $dbh->commit;
|
---|
[3] | 1966 | }; # end eval
|
---|
| 1967 |
|
---|
| 1968 | if ($@) {
|
---|
[285] | 1969 | $msg = $@;
|
---|
[3] | 1970 | eval { $dbh->rollback; };
|
---|
[295] | 1971 | $loghash{entry} = "Error deleting $zone: $msg ($failmsg)";
|
---|
| 1972 | if ($config{log_failures}) {
|
---|
[487] | 1973 | $self->_log(%loghash);
|
---|
[295] | 1974 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 1975 | }
|
---|
| 1976 | return ('FAIL', $loghash{entry});
|
---|
[3] | 1977 | } else {
|
---|
[295] | 1978 | return ('OK', $msg);
|
---|
[3] | 1979 | }
|
---|
| 1980 |
|
---|
[274] | 1981 | } # end delZone()
|
---|
[3] | 1982 |
|
---|
| 1983 |
|
---|
[2] | 1984 | ## DNSDB::domainName()
|
---|
| 1985 | # Return the domain name based on a domain ID
|
---|
| 1986 | # Takes a database handle and the domain ID
|
---|
| 1987 | # Returns the domain name or undef on failure
|
---|
| 1988 | sub domainName {
|
---|
| 1989 | $errstr = '';
|
---|
[473] | 1990 | my $self = shift;
|
---|
| 1991 | my $dbh = $self->{dbh};
|
---|
[2] | 1992 | my $domid = shift;
|
---|
[91] | 1993 | my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
|
---|
[2] | 1994 | $errstr = $DBI::errstr if !$domname;
|
---|
| 1995 | return $domname if $domname;
|
---|
[91] | 1996 | } # end domainName()
|
---|
[2] | 1997 |
|
---|
| 1998 |
|
---|
[224] | 1999 | ## DNSDB::revName()
|
---|
| 2000 | # Return the reverse zone name based on an rDNS ID
|
---|
| 2001 | # Takes a database handle and the rDNS ID
|
---|
| 2002 | # Returns the reverse zone name or undef on failure
|
---|
| 2003 | sub revName {
|
---|
| 2004 | $errstr = '';
|
---|
[473] | 2005 | my $self = shift;
|
---|
| 2006 | my $dbh = $self->{dbh};
|
---|
[224] | 2007 | my $revid = shift;
|
---|
| 2008 | my ($revname) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id=?", undef, ($revid) );
|
---|
| 2009 | $errstr = $DBI::errstr if !$revname;
|
---|
| 2010 | return $revname if $revname;
|
---|
| 2011 | } # end revName()
|
---|
| 2012 |
|
---|
| 2013 |
|
---|
[91] | 2014 | ## DNSDB::domainID()
|
---|
| 2015 | # Takes a database handle and domain name
|
---|
| 2016 | # Returns the domain ID number
|
---|
| 2017 | sub domainID {
|
---|
| 2018 | $errstr = '';
|
---|
[473] | 2019 | my $self = shift;
|
---|
| 2020 | my $dbh = $self->{dbh};
|
---|
[91] | 2021 | my $domain = shift;
|
---|
[349] | 2022 | my ($domid) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
| 2023 | undef, ($domain) );
|
---|
[91] | 2024 | $errstr = $DBI::errstr if !$domid;
|
---|
| 2025 | return $domid if $domid;
|
---|
| 2026 | } # end domainID()
|
---|
| 2027 |
|
---|
| 2028 |
|
---|
[276] | 2029 | ## DNSDB::revID()
|
---|
| 2030 | # Takes a database handle and reverse zone name
|
---|
| 2031 | # Returns the rDNS ID number
|
---|
| 2032 | sub revID {
|
---|
| 2033 | $errstr = '';
|
---|
[473] | 2034 | my $self = shift;
|
---|
| 2035 | my $dbh = $self->{dbh};
|
---|
[276] | 2036 | my $revzone = shift;
|
---|
| 2037 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ($revzone) );
|
---|
| 2038 | $errstr = $DBI::errstr if !$revid;
|
---|
| 2039 | return $revid if $revid;
|
---|
| 2040 | } # end revID()
|
---|
| 2041 |
|
---|
| 2042 |
|
---|
[260] | 2043 | ## DNSDB::addRDNS
|
---|
| 2044 | # Adds a reverse DNS zone
|
---|
[286] | 2045 | # Takes a database handle, CIDR block, reverse DNS pattern, numeric group,
|
---|
| 2046 | # and boolean(ish) state (active/inactive)
|
---|
[260] | 2047 | # Returns a status code and message
|
---|
| 2048 | sub addRDNS {
|
---|
[477] | 2049 | my $self = shift;
|
---|
| 2050 | my $dbh = $self->{dbh};
|
---|
[260] | 2051 | my $zone = NetAddr::IP->new(shift);
|
---|
[446] | 2052 |
|
---|
[260] | 2053 | return ('FAIL',"Zone name must be a valid CIDR netblock") unless ($zone && $zone->addr !~ /^0/);
|
---|
[270] | 2054 | my $revpatt = shift; # construct a custom (A/AAAA+)? PTR template record
|
---|
[260] | 2055 | my $group = shift;
|
---|
| 2056 | my $state = shift;
|
---|
[446] | 2057 | my $defloc = shift || '';
|
---|
[260] | 2058 |
|
---|
| 2059 | $state = 1 if $state =~ /^active$/;
|
---|
| 2060 | $state = 1 if $state =~ /^on$/;
|
---|
| 2061 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 2062 | $state = 0 if $state =~ /^off$/;
|
---|
| 2063 |
|
---|
| 2064 | return ('FAIL',"Invalid zone status") if $state !~ /^\d+$/;
|
---|
| 2065 |
|
---|
| 2066 | # quick check to start to see if we've already got one
|
---|
[299] | 2067 | my ($rdns_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ("$zone"));
|
---|
[260] | 2068 |
|
---|
| 2069 | return ('FAIL', "Zone already exists") if $rdns_id;
|
---|
| 2070 |
|
---|
| 2071 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2072 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2073 | local $dbh->{AutoCommit} = 0;
|
---|
| 2074 | local $dbh->{RaiseError} = 1;
|
---|
| 2075 |
|
---|
[264] | 2076 | my $warnstr = '';
|
---|
[270] | 2077 | my $defttl = 3600; # 1 hour should be reasonable. And unless things have gone horribly
|
---|
| 2078 | # wrong, we should have a value to override this anyway.
|
---|
[264] | 2079 |
|
---|
[260] | 2080 | # Wrap all the SQL in a transaction
|
---|
| 2081 | eval {
|
---|
[446] | 2082 | # insert the zone...
|
---|
| 2083 | $dbh->do("INSERT INTO revzones (revnet,group_id,status,default_location) VALUES (?,?,?,?)", undef,
|
---|
| 2084 | ($zone, $group, $state, $defloc) );
|
---|
[260] | 2085 |
|
---|
| 2086 | # get the ID...
|
---|
| 2087 | ($rdns_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
| 2088 |
|
---|
[487] | 2089 | $self->_log(rdns_id => $rdns_id, group_id => $group,
|
---|
| 2090 | entry => "Added ".($state ? 'active' : 'inactive')." reverse zone $zone");
|
---|
[260] | 2091 |
|
---|
| 2092 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
| 2093 | my $sth = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
[446] | 2094 | my $sth_in = $dbh->prepare("INSERT INTO records (rdns_id,domain_id,host,type,val,ttl,location)".
|
---|
| 2095 | " VALUES ($rdns_id,?,?,?,?,?,?)");
|
---|
[260] | 2096 | $sth->execute($group);
|
---|
| 2097 | while (my ($host,$type,$val,$ttl) = $sth->fetchrow_array()) {
|
---|
[264] | 2098 | # Silently skip v4/v6 mismatches. This is not an error, this is expected.
|
---|
| 2099 | if ($zone->{isv6}) {
|
---|
| 2100 | next if ($type == 65280 || $type == 65283);
|
---|
| 2101 | } else {
|
---|
| 2102 | next if ($type == 65281 || $type == 65284);
|
---|
| 2103 | }
|
---|
[269] | 2104 |
|
---|
[260] | 2105 | $host =~ s/ADMINDOMAIN/$config{domain}/g;
|
---|
[264] | 2106 |
|
---|
[265] | 2107 | # Check to make sure the IP stubs will fit in the zone. Under most usage failures here should be rare.
|
---|
| 2108 | # On failure, tack a note on to a warning string and continue without adding this record.
|
---|
| 2109 | # While we're at it, we substitute $zone for ZONE in the value.
|
---|
| 2110 | if ($val eq 'ZONE') {
|
---|
[444] | 2111 | # If we've got a pattern, we skip the default record version on (A+)PTR-template types
|
---|
| 2112 | next if $revpatt && ($type == 65282 || $type == 65283);
|
---|
[269] | 2113 | ##fixme? do we care if we have multiple whole-zone templates?
|
---|
[265] | 2114 | $val = $zone->network;
|
---|
| 2115 | } elsif ($val =~ /ZONE/) {
|
---|
| 2116 | my $tmpval = $val;
|
---|
| 2117 | $tmpval =~ s/ZONE//;
|
---|
[269] | 2118 | # Bend the rules and allow single-trailing-number PTR or PTR template records to be inserted
|
---|
| 2119 | # as either v4 or v6. May make this an off-by-default config flag
|
---|
| 2120 | # Note that the origin records that may trigger this **SHOULD** already have ZONE,\d
|
---|
| 2121 | if ($type == 12 || $type == 65282) {
|
---|
| 2122 | $tmpval =~ s/[,.]/::/ if ($tmpval =~ /^[,.]\d+$/ && $zone->{isv6});
|
---|
| 2123 | $tmpval =~ s/[,:]+/./ if ($tmpval =~ /^(?:,|::)\d+$/ && !$zone->{isv6});
|
---|
| 2124 | }
|
---|
[265] | 2125 | my $addr;
|
---|
[471] | 2126 | if ($self->_ipparent('n', 'y', \$tmpval, $rdns_id, \$addr)) {
|
---|
[265] | 2127 | $val = $addr->addr;
|
---|
| 2128 | } else {
|
---|
[269] | 2129 | $warnstr .= "\nDefault record '$val $typemap{$type} $host' doesn't fit in $zone, skipping";
|
---|
[264] | 2130 | next;
|
---|
| 2131 | }
|
---|
| 2132 | }
|
---|
| 2133 |
|
---|
[328] | 2134 | # Substitute $zone for ZONE in the hostname, but only for non-NS records.
|
---|
| 2135 | # NS records get this substitution on the value instead.
|
---|
| 2136 | $host = _ZONE($zone, $host) if $type != 2;
|
---|
[265] | 2137 |
|
---|
[269] | 2138 | # Fill in the forward domain ID if we can find it, otherwise:
|
---|
| 2139 | # Coerce type down to PTR or PTR template if we can't
|
---|
| 2140 | my $domid = 0;
|
---|
| 2141 | if ($type >= 65280) {
|
---|
[471] | 2142 | if (!($domid = $self->_hostparent($host))) {
|
---|
[269] | 2143 | $warnstr .= "\nRecord added as PTR instead of $typemap{$type}; domain not found for $host";
|
---|
| 2144 | $type = $reverse_typemap{PTR};
|
---|
| 2145 | $domid = 0; # just to be explicit.
|
---|
| 2146 | }
|
---|
| 2147 | }
|
---|
| 2148 |
|
---|
[446] | 2149 | $sth_in->execute($domid,$host,$type,$val,$ttl,$defloc);
|
---|
[269] | 2150 |
|
---|
[260] | 2151 | if ($typemap{$type} eq 'SOA') {
|
---|
| 2152 | my @tmp1 = split /:/, $host;
|
---|
| 2153 | my @tmp2 = split /:/, $val;
|
---|
[487] | 2154 | $self->_log(rdns_id => $rdns_id, group_id => $group,
|
---|
[286] | 2155 | entry => "[new $zone] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
[487] | 2156 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl");
|
---|
[270] | 2157 | $defttl = $tmp2[3];
|
---|
[260] | 2158 | } else {
|
---|
[446] | 2159 | my $logentry = "[new $zone] Added record '$host $typemap{$type} $val', TTL $ttl";
|
---|
[480] | 2160 | $logentry .= ", default location ".$self->getLoc($defloc)->{description} if $defloc;
|
---|
[487] | 2161 | $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group, entry => $logentry);
|
---|
[260] | 2162 | }
|
---|
| 2163 | }
|
---|
| 2164 |
|
---|
[270] | 2165 | # Generate record based on provided pattern.
|
---|
| 2166 | if ($revpatt) {
|
---|
| 2167 | my $host;
|
---|
| 2168 | my $type = ($zone->{isv6} ? 65284 : 65283);
|
---|
| 2169 | my $val = $zone->network;
|
---|
[269] | 2170 |
|
---|
[270] | 2171 | # Substitute $zone for ZONE in the hostname.
|
---|
| 2172 | $host = _ZONE($zone, $revpatt);
|
---|
| 2173 |
|
---|
| 2174 | my $domid = 0;
|
---|
[471] | 2175 | if (!($domid = $self->_hostparent($host))) {
|
---|
[270] | 2176 | $warnstr .= "\nDefault pattern added as PTR template instead of $typemap{$type}; domain not found for $host";
|
---|
| 2177 | $type = 65282;
|
---|
| 2178 | $domid = 0; # just to be explicit.
|
---|
| 2179 | }
|
---|
| 2180 |
|
---|
[446] | 2181 | $sth_in->execute($domid,$host,$type,$val,$defttl,$defloc);
|
---|
[286] | 2182 | my $logentry = "[new $zone] Added record '$host $typemap{$type}";
|
---|
[487] | 2183 | $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group,
|
---|
| 2184 | entry => $logentry." $val', TTL $defttl from pattern");
|
---|
[270] | 2185 | }
|
---|
| 2186 |
|
---|
[264] | 2187 | # If there are warnings (presumably about default records skipped for cause) log them
|
---|
[487] | 2188 | $self->_log(rdns_id => $rdns_id, group_id => $group, entry => "Warning(s) adding $zone:$warnstr")
|
---|
[264] | 2189 | if $warnstr;
|
---|
[269] | 2190 |
|
---|
[260] | 2191 | # once we get here, we should have suceeded.
|
---|
| 2192 | $dbh->commit;
|
---|
| 2193 | }; # end eval
|
---|
| 2194 |
|
---|
| 2195 | if ($@) {
|
---|
| 2196 | my $msg = $@;
|
---|
| 2197 | eval { $dbh->rollback; };
|
---|
[487] | 2198 | $self->_log(group_id => $group, entry => "Failed adding reverse zone $zone ($msg)")
|
---|
[286] | 2199 | if $config{log_failures};
|
---|
| 2200 | $dbh->commit; # since we enabled transactions earlier
|
---|
[260] | 2201 | return ('FAIL',$msg);
|
---|
| 2202 | } else {
|
---|
[286] | 2203 | my $retcode = 'OK';
|
---|
| 2204 | if ($warnstr) {
|
---|
| 2205 | $resultstr = $warnstr;
|
---|
| 2206 | $retcode = 'WARN';
|
---|
| 2207 | }
|
---|
| 2208 | return ($retcode, $rdns_id);
|
---|
[260] | 2209 | }
|
---|
| 2210 |
|
---|
| 2211 | } # end addRDNS()
|
---|
| 2212 |
|
---|
| 2213 |
|
---|
[237] | 2214 | ## DNSDB::getZoneCount
|
---|
| 2215 | # Get count of zones in group or groups
|
---|
| 2216 | # Takes a database handle and hash containing:
|
---|
| 2217 | # - the "current" group
|
---|
| 2218 | # - an array of "acceptable" groups
|
---|
| 2219 | # - a flag for forward/reverse zones
|
---|
| 2220 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
| 2221 | # Returns an integer count of the resulting zone list.
|
---|
| 2222 | sub getZoneCount {
|
---|
[477] | 2223 | my $self = shift;
|
---|
| 2224 | my $dbh = $self->{dbh};
|
---|
[237] | 2225 |
|
---|
| 2226 | my %args = @_;
|
---|
| 2227 |
|
---|
| 2228 | my @filterargs;
|
---|
[239] | 2229 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2230 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2231 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
[237] | 2232 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2233 |
|
---|
| 2234 | my $sql;
|
---|
| 2235 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
| 2236 | if ($args{revrec} eq 'n') {
|
---|
| 2237 | $sql = "SELECT count(*) FROM domains".
|
---|
| 2238 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2239 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
| 2240 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
| 2241 | } else {
|
---|
| 2242 | $sql = "SELECT count(*) FROM revzones".
|
---|
| 2243 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2244 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
|
---|
| 2245 | ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2246 | }
|
---|
| 2247 | my ($count) = $dbh->selectrow_array($sql, undef, @filterargs);
|
---|
| 2248 | return $count;
|
---|
| 2249 | } # end getZoneCount()
|
---|
| 2250 |
|
---|
| 2251 |
|
---|
| 2252 | ## DNSDB::getZoneList()
|
---|
| 2253 | # Get a list of zones in the specified group(s)
|
---|
| 2254 | # Takes the same arguments as getZoneCount() above
|
---|
| 2255 | # Returns a reference to an array of hashrefs suitable for feeding to HTML::Template
|
---|
| 2256 | sub getZoneList {
|
---|
[477] | 2257 | my $self = shift;
|
---|
| 2258 | my $dbh = $self->{dbh};
|
---|
[237] | 2259 |
|
---|
| 2260 | my %args = @_;
|
---|
| 2261 |
|
---|
| 2262 | my @zonelist;
|
---|
| 2263 |
|
---|
[475] | 2264 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
[239] | 2265 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[237] | 2266 |
|
---|
| 2267 | my @filterargs;
|
---|
[239] | 2268 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2269 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2270 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
[237] | 2271 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2272 |
|
---|
| 2273 | my $sql;
|
---|
| 2274 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
| 2275 | if ($args{revrec} eq 'n') {
|
---|
[475] | 2276 | $args{sortby} = 'domain' if !$args{sortby} || !grep /^$args{sortby}$/, ('domain','group','status');
|
---|
[237] | 2277 | $sql = "SELECT domain_id,domain,status,groups.group_name AS group FROM domains".
|
---|
| 2278 | " INNER JOIN groups ON domains.group_id=groups.group_id".
|
---|
| 2279 | " WHERE domains.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2280 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
| 2281 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
| 2282 | } else {
|
---|
[239] | 2283 | ##fixme: arguably startwith here is irrelevant. depends on the UI though.
|
---|
[475] | 2284 | $args{sortby} = 'revnet' if !$args{sortby} || !grep /^$args{sortby}$/, ('revnet','group','status');
|
---|
[237] | 2285 | $sql = "SELECT rdns_id,revnet,status,groups.group_name AS group FROM revzones".
|
---|
| 2286 | " INNER JOIN groups ON revzones.group_id=groups.group_id".
|
---|
| 2287 | " WHERE revzones.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2288 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
|
---|
| 2289 | ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2290 | }
|
---|
| 2291 | # A common tail.
|
---|
[239] | 2292 | $sql .= " ORDER BY ".($args{sortby} eq 'group' ? 'groups.group_name' : $args{sortby})." $args{sortorder} ".
|
---|
| 2293 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage}".
|
---|
[237] | 2294 | " OFFSET ".$args{offset}*$config{perpage});
|
---|
[402] | 2295 | my $sth = $dbh->prepare($sql);
|
---|
| 2296 | $sth->execute(@filterargs);
|
---|
| 2297 | my $rownum = 0;
|
---|
[237] | 2298 |
|
---|
[402] | 2299 | while (my @data = $sth->fetchrow_array) {
|
---|
| 2300 | my %row;
|
---|
| 2301 | $row{domain_id} = $data[0];
|
---|
| 2302 | $row{domain} = $data[1];
|
---|
| 2303 | $row{status} = $data[2];
|
---|
| 2304 | $row{group} = $data[3];
|
---|
| 2305 | push @zonelist, \%row;
|
---|
| 2306 | }
|
---|
| 2307 |
|
---|
| 2308 | return \@zonelist;
|
---|
[237] | 2309 | } # end getZoneList()
|
---|
| 2310 |
|
---|
| 2311 |
|
---|
[383] | 2312 | ## DNSDB::getZoneLocation()
|
---|
[387] | 2313 | # Retrieve the default location for a zone.
|
---|
[383] | 2314 | # Takes a database handle, forward/reverse flag, and zone ID
|
---|
| 2315 | sub getZoneLocation {
|
---|
[477] | 2316 | my $self = shift;
|
---|
| 2317 | my $dbh = $self->{dbh};
|
---|
[383] | 2318 | my $revrec = shift;
|
---|
| 2319 | my $zoneid = shift;
|
---|
| 2320 |
|
---|
| 2321 | my ($loc) = $dbh->selectrow_array("SELECT default_location FROM ".
|
---|
| 2322 | ($revrec eq 'n' ? 'domains WHERE domain_id = ?' : 'revzones WHERE rdns_id = ?'),
|
---|
| 2323 | undef, ($zoneid));
|
---|
| 2324 | return $loc;
|
---|
| 2325 | } # end getZoneLocation()
|
---|
| 2326 |
|
---|
| 2327 |
|
---|
[18] | 2328 | ## DNSDB::addGroup()
|
---|
| 2329 | # Add a group
|
---|
[66] | 2330 | # Takes a database handle, group name, parent group, hashref for permissions,
|
---|
[292] | 2331 | # and optional template-vs-cloneme flag for the default records
|
---|
[18] | 2332 | # Returns a status code and message
|
---|
| 2333 | sub addGroup {
|
---|
| 2334 | $errstr = '';
|
---|
[476] | 2335 | my $self = shift;
|
---|
| 2336 | my $dbh = $self->{dbh};
|
---|
[20] | 2337 | my $groupname = shift;
|
---|
| 2338 | my $pargroup = shift;
|
---|
[66] | 2339 | my $permissions = shift;
|
---|
[18] | 2340 |
|
---|
[66] | 2341 | # 0 indicates "custom", hardcoded.
|
---|
[18] | 2342 | # Any other value clones that group's default records, if it exists.
|
---|
[66] | 2343 | my $inherit = shift || 0;
|
---|
| 2344 | ##fixme: need a flag to indicate clone records or <?> ?
|
---|
[18] | 2345 |
|
---|
| 2346 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2347 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2348 | local $dbh->{AutoCommit} = 0;
|
---|
| 2349 | local $dbh->{RaiseError} = 1;
|
---|
| 2350 |
|
---|
[292] | 2351 | my ($group_id) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($groupname));
|
---|
[38] | 2352 |
|
---|
| 2353 | return ('FAIL', "Group already exists") if $group_id;
|
---|
| 2354 |
|
---|
[18] | 2355 | # Wrap all the SQL in a transaction
|
---|
| 2356 | eval {
|
---|
[292] | 2357 | $dbh->do("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)", undef, ($pargroup, $groupname) );
|
---|
[18] | 2358 |
|
---|
[292] | 2359 | my ($groupid) = $dbh->selectrow_array("SELECT currval('groups_group_id_seq')");
|
---|
[18] | 2360 |
|
---|
[292] | 2361 | # We work through the whole set of permissions instead of specifying them so
|
---|
| 2362 | # that when we add a new permission, we don't have to change the code anywhere
|
---|
| 2363 | # that doesn't explicitly deal with that specific permission.
|
---|
| 2364 | my @permvals;
|
---|
| 2365 | foreach (@permtypes) {
|
---|
| 2366 | if (!defined ($permissions->{$_})) {
|
---|
| 2367 | push @permvals, 0;
|
---|
| 2368 | } else {
|
---|
| 2369 | push @permvals, $permissions->{$_};
|
---|
[66] | 2370 | }
|
---|
[292] | 2371 | }
|
---|
| 2372 | $dbh->do("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")",
|
---|
| 2373 | undef, ($groupid, @permvals) );
|
---|
| 2374 | my ($permid) = $dbh->selectrow_array("SELECT currval('permissions_permission_id_seq')");
|
---|
| 2375 | $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
|
---|
[66] | 2376 |
|
---|
[292] | 2377 | # Default records
|
---|
[255] | 2378 | my $sthf = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
|
---|
[20] | 2379 | "VALUES ($groupid,?,?,?,?,?,?,?)");
|
---|
[255] | 2380 | my $sthr = $dbh->prepare("INSERT INTO default_rev_records (group_id,host,type,val,ttl) ".
|
---|
| 2381 | "VALUES ($groupid,?,?,?,?)");
|
---|
[66] | 2382 | if ($inherit) {
|
---|
[87] | 2383 | # Duplicate records from parent. Actually relying on inherited records feels
|
---|
| 2384 | # very fragile, and it would be problematic to roll over at a later time.
|
---|
[18] | 2385 | my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
[87] | 2386 | $sth2->execute($pargroup);
|
---|
[18] | 2387 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
[255] | 2388 | $sthf->execute(@clonedata);
|
---|
[18] | 2389 | }
|
---|
[255] | 2390 | # And now the reverse records
|
---|
[292] | 2391 | $sth2 = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
[255] | 2392 | $sth2->execute($pargroup);
|
---|
| 2393 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
| 2394 | $sthr->execute(@clonedata);
|
---|
| 2395 | }
|
---|
[18] | 2396 | } else {
|
---|
[66] | 2397 | ##fixme: Hardcoding is Bad, mmmmkaaaay?
|
---|
[18] | 2398 | # reasonable basic defaults for SOA, MX, NS, and minimal hosting
|
---|
| 2399 | # could load from a config file, but somewhere along the line we need hardcoded bits.
|
---|
[255] | 2400 | $sthf->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
|
---|
| 2401 | $sthf->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
|
---|
| 2402 | $sthf->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
|
---|
| 2403 | $sthf->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
|
---|
| 2404 | $sthf->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
|
---|
| 2405 | $sthf->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
|
---|
| 2406 | # reasonable basic defaults for generic reverse zone. Same as initial SQL tabledef.
|
---|
| 2407 | $sthr->execute('hostmaster.ADMINDOMAIN:ns1.ADMINDOMAIN', 6, '10800:3600:604800:10800', 86400);
|
---|
| 2408 | $sthr->execute('unused-%r.ADMINDOMAIN', 65283, 'ZONE', 3600);
|
---|
[18] | 2409 | }
|
---|
| 2410 |
|
---|
[487] | 2411 | $self->_log(group_id => $pargroup, entry => "Added group $groupname");
|
---|
[292] | 2412 |
|
---|
[18] | 2413 | # once we get here, we should have suceeded.
|
---|
| 2414 | $dbh->commit;
|
---|
| 2415 | }; # end eval
|
---|
| 2416 |
|
---|
| 2417 | if ($@) {
|
---|
| 2418 | my $msg = $@;
|
---|
| 2419 | eval { $dbh->rollback; };
|
---|
[292] | 2420 | if ($config{log_failures}) {
|
---|
[487] | 2421 | $self->_log(group_id => $pargroup, entry => "Failed to add group $groupname: $msg");
|
---|
[292] | 2422 | $dbh->commit;
|
---|
| 2423 | }
|
---|
[18] | 2424 | return ('FAIL',$msg);
|
---|
| 2425 | }
|
---|
| 2426 |
|
---|
[292] | 2427 | return ('OK','OK');
|
---|
[18] | 2428 | } # end addGroup()
|
---|
| 2429 |
|
---|
| 2430 |
|
---|
[22] | 2431 | ## DNSDB::delGroup()
|
---|
| 2432 | # Delete a group.
|
---|
| 2433 | # Takes a group ID
|
---|
| 2434 | # Returns a status code and message
|
---|
| 2435 | sub delGroup {
|
---|
[476] | 2436 | my $self = shift;
|
---|
| 2437 | my $dbh = $self->{dbh};
|
---|
[22] | 2438 | my $groupid = shift;
|
---|
| 2439 |
|
---|
| 2440 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2441 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2442 | local $dbh->{AutoCommit} = 0;
|
---|
| 2443 | local $dbh->{RaiseError} = 1;
|
---|
| 2444 |
|
---|
| 2445 | ##fixme: locate "knowable" error conditions and deal with them before the eval
|
---|
[23] | 2446 | # ... or inside, whatever.
|
---|
[22] | 2447 | # -> domains still exist in group
|
---|
| 2448 | # -> ...
|
---|
[23] | 2449 | my $failmsg = '';
|
---|
[293] | 2450 | my $resultmsg = '';
|
---|
[22] | 2451 |
|
---|
[293] | 2452 | # collect some pieces for logging and error messages
|
---|
[473] | 2453 | my $groupname = $self->groupName($groupid);
|
---|
| 2454 | my $parid = $self->parentID(id => $groupid, type => 'group');
|
---|
[293] | 2455 |
|
---|
[22] | 2456 | # Wrap all the SQL in a transaction
|
---|
| 2457 | eval {
|
---|
[293] | 2458 | # Check for Things in the group
|
---|
| 2459 | $failmsg = "Can't remove group $groupname";
|
---|
| 2460 | my ($grpcnt) = $dbh->selectrow_array("SELECT count(*) FROM groups WHERE parent_group_id=?", undef, ($groupid));
|
---|
| 2461 | die "$grpcnt groups still in group\n" if $grpcnt;
|
---|
| 2462 | my ($domcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($groupid));
|
---|
[23] | 2463 | die "$domcnt domains still in group\n" if $domcnt;
|
---|
[293] | 2464 | my ($usercnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($groupid));
|
---|
| 2465 | die "$usercnt users still in group\n" if $usercnt;
|
---|
[23] | 2466 |
|
---|
[293] | 2467 | $failmsg = "Failed to delete default records for $groupname";
|
---|
| 2468 | $dbh->do("DELETE from default_records WHERE group_id=?", undef, ($groupid));
|
---|
| 2469 | $failmsg = "Failed to delete default reverse records for $groupname";
|
---|
| 2470 | $dbh->do("DELETE from default_rev_records WHERE group_id=?", undef, ($groupid));
|
---|
| 2471 | $failmsg = "Failed to remove group $groupname";
|
---|
| 2472 | $dbh->do("DELETE from groups WHERE group_id=?", undef, ($groupid));
|
---|
[22] | 2473 |
|
---|
[487] | 2474 | $self->_log(group_id => $parid, entry => "Deleted group $groupname");
|
---|
[293] | 2475 | $resultmsg = "Deleted group $groupname";
|
---|
| 2476 |
|
---|
[22] | 2477 | # once we get here, we should have suceeded.
|
---|
| 2478 | $dbh->commit;
|
---|
| 2479 | }; # end eval
|
---|
| 2480 |
|
---|
| 2481 | if ($@) {
|
---|
| 2482 | my $msg = $@;
|
---|
| 2483 | eval { $dbh->rollback; };
|
---|
[293] | 2484 | if ($config{log_failures}) {
|
---|
[487] | 2485 | $self->_log(group_id => $parid, entry => "$failmsg: $msg");
|
---|
[293] | 2486 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2487 | }
|
---|
[23] | 2488 | return ('FAIL',"$failmsg: $msg");
|
---|
[22] | 2489 | }
|
---|
[293] | 2490 |
|
---|
| 2491 | return ('OK',$resultmsg);
|
---|
[22] | 2492 | } # end delGroup()
|
---|
| 2493 |
|
---|
| 2494 |
|
---|
[19] | 2495 | ## DNSDB::getChildren()
|
---|
| 2496 | # Get a list of all groups whose parent^n is group <n>
|
---|
[24] | 2497 | # Takes a database handle, group ID, reference to an array to put the group IDs in,
|
---|
| 2498 | # and an optional flag to return only immediate children or all children-of-children
|
---|
| 2499 | # default to returning all children
|
---|
[19] | 2500 | # Calls itself
|
---|
| 2501 | sub getChildren {
|
---|
| 2502 | $errstr = '';
|
---|
[476] | 2503 | my $self = shift;
|
---|
| 2504 | my $dbh = $self->{dbh};
|
---|
[20] | 2505 | my $rootgroup = shift;
|
---|
| 2506 | my $groupdest = shift;
|
---|
[24] | 2507 | my $immed = shift || 'all';
|
---|
[19] | 2508 |
|
---|
| 2509 | # special break for default group; otherwise we get stuck.
|
---|
[20] | 2510 | if ($rootgroup == 1) {
|
---|
[19] | 2511 | # by definition, group 1 is the Root Of All Groups
|
---|
[24] | 2512 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
|
---|
[331] | 2513 | ($immed ne 'all' ? " AND parent_group_id=1" : '')." ORDER BY group_name");
|
---|
[19] | 2514 | $sth->execute;
|
---|
| 2515 | while (my @this = $sth->fetchrow_array) {
|
---|
[20] | 2516 | push @$groupdest, @this;
|
---|
[19] | 2517 | }
|
---|
| 2518 | } else {
|
---|
[331] | 2519 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=? ORDER BY group_name");
|
---|
[20] | 2520 | $sth->execute($rootgroup);
|
---|
[19] | 2521 | return if $sth->rows == 0;
|
---|
[20] | 2522 | my @grouplist;
|
---|
| 2523 | while (my ($group) = $sth->fetchrow_array) {
|
---|
| 2524 | push @$groupdest, $group;
|
---|
[476] | 2525 | $self->getChildren($group, $groupdest) if $immed eq 'all';
|
---|
[19] | 2526 | }
|
---|
| 2527 | }
|
---|
| 2528 | } # end getChildren()
|
---|
| 2529 |
|
---|
| 2530 |
|
---|
[20] | 2531 | ## DNSDB::groupName()
|
---|
[17] | 2532 | # Return the group name based on a group ID
|
---|
| 2533 | # Takes a database handle and the group ID
|
---|
| 2534 | # Returns the group name or undef on failure
|
---|
[20] | 2535 | sub groupName {
|
---|
[13] | 2536 | $errstr = '';
|
---|
[473] | 2537 | my $self = shift;
|
---|
| 2538 | my $dbh = $self->{dbh};
|
---|
[20] | 2539 | my $groupid = shift;
|
---|
| 2540 | my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
|
---|
| 2541 | $sth->execute($groupid);
|
---|
| 2542 | my ($groupname) = $sth->fetchrow_array();
|
---|
| 2543 | $errstr = $DBI::errstr if !$groupname;
|
---|
| 2544 | return $groupname if $groupname;
|
---|
| 2545 | } # end groupName
|
---|
[13] | 2546 |
|
---|
| 2547 |
|
---|
[314] | 2548 | ## DNSDB::getGroupCount()
|
---|
| 2549 | # Get count of subgroups in group or groups
|
---|
| 2550 | # Takes a database handle and hash containing:
|
---|
| 2551 | # - the "current" group
|
---|
| 2552 | # - an array of "acceptable" groups
|
---|
| 2553 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
| 2554 | # Returns an integer count of the resulting group list.
|
---|
| 2555 | sub getGroupCount {
|
---|
[476] | 2556 | my $self = shift;
|
---|
| 2557 | my $dbh = $self->{dbh};
|
---|
[314] | 2558 |
|
---|
| 2559 | my %args = @_;
|
---|
| 2560 |
|
---|
| 2561 | my @filterargs;
|
---|
| 2562 |
|
---|
| 2563 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2564 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2565 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2566 |
|
---|
| 2567 | my $sql = "SELECT count(*) FROM groups ".
|
---|
| 2568 | "WHERE parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2569 | ($args{startwith} ? " AND group_name ~* ?" : '').
|
---|
| 2570 | ($args{filter} ? " AND group_name ~* ?" : '');
|
---|
| 2571 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 2572 | $errstr = $dbh->errstr if !$count;
|
---|
| 2573 | return $count;
|
---|
| 2574 | } # end getGroupCount
|
---|
| 2575 |
|
---|
| 2576 |
|
---|
| 2577 | ## DNSDB::getGroupList()
|
---|
| 2578 | # Get a list of sub^n-groups in the specified group(s)
|
---|
| 2579 | # Takes the same arguments as getGroupCount() above
|
---|
| 2580 | # Returns an arrayref containing hashrefs suitable for feeding straight to HTML::Template
|
---|
| 2581 | sub getGroupList {
|
---|
[476] | 2582 | my $self = shift;
|
---|
| 2583 | my $dbh = $self->{dbh};
|
---|
[314] | 2584 |
|
---|
| 2585 | my %args = @_;
|
---|
| 2586 |
|
---|
| 2587 | my @filterargs;
|
---|
| 2588 |
|
---|
| 2589 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2590 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2591 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2592 |
|
---|
| 2593 | # protection against bad or missing arguments
|
---|
| 2594 | $args{sortorder} = 'ASC' if !$args{sortorder};
|
---|
[397] | 2595 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[314] | 2596 |
|
---|
| 2597 | # munge sortby for columns in database
|
---|
| 2598 | $args{sortby} = 'g.group_name' if $args{sortby} eq 'group';
|
---|
| 2599 | $args{sortby} = 'g2.group_name' if $args{sortby} eq 'parent';
|
---|
| 2600 |
|
---|
[385] | 2601 | my $sql = q(SELECT g.group_id AS groupid, g.group_name AS groupname, g2.group_name AS pgroup
|
---|
[314] | 2602 | FROM groups g
|
---|
| 2603 | INNER JOIN groups g2 ON g2.group_id=g.parent_group_id
|
---|
| 2604 | ).
|
---|
[385] | 2605 | " WHERE g.parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
[314] | 2606 | ($args{startwith} ? " AND g.group_name ~* ?" : '').
|
---|
| 2607 | ($args{filter} ? " AND g.group_name ~* ?" : '').
|
---|
| 2608 | " GROUP BY g.group_id, g.group_name, g2.group_name ".
|
---|
| 2609 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
| 2610 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
| 2611 | my $glist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 2612 | $errstr = $dbh->errstr if !$glist;
|
---|
[385] | 2613 |
|
---|
| 2614 | # LEFT JOINs make the result set balloon beyond sanity just to include counts;
|
---|
| 2615 | # this means there's lots of crunching needed to trim the result set back down.
|
---|
| 2616 | # So instead we track the order of the groups, and push the counts into the
|
---|
| 2617 | # arrayref result separately.
|
---|
| 2618 | ##fixme: put this whole sub in a transaction? might be
|
---|
| 2619 | # needed for accurate results on very busy systems.
|
---|
[386] | 2620 | ##fixme: large group lists need prepared statements?
|
---|
| 2621 | #my $ucsth = $dbh->prepare("SELECT count(*) FROM users WHERE group_id=?");
|
---|
| 2622 | #my $dcsth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
|
---|
| 2623 | #my $rcsth = $dbh->prepare("SELECT count(*) FROM revzones WHERE group_id=?");
|
---|
[385] | 2624 | foreach (@{$glist}) {
|
---|
[386] | 2625 | my ($ucnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 2626 | $$_{nusers} = $ucnt;
|
---|
| 2627 | my ($dcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 2628 | $$_{ndomains} = $dcnt;
|
---|
| 2629 | my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 2630 | $$_{nrevzones} = $rcnt;
|
---|
[385] | 2631 | }
|
---|
| 2632 |
|
---|
[314] | 2633 | return $glist;
|
---|
| 2634 | } # end getGroupList
|
---|
| 2635 |
|
---|
| 2636 |
|
---|
[118] | 2637 | ## DNSDB::groupID()
|
---|
| 2638 | # Return the group ID based on the group name
|
---|
| 2639 | # Takes a database handle and the group name
|
---|
| 2640 | # Returns the group ID or undef on failure
|
---|
| 2641 | sub groupID {
|
---|
| 2642 | $errstr = '';
|
---|
[473] | 2643 | my $self = shift;
|
---|
| 2644 | my $dbh = $self->{dbh};
|
---|
[118] | 2645 | my $group = shift;
|
---|
[406] | 2646 | my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($group) );
|
---|
[118] | 2647 | $errstr = $DBI::errstr if !$grpid;
|
---|
| 2648 | return $grpid if $grpid;
|
---|
| 2649 | } # end groupID()
|
---|
| 2650 |
|
---|
| 2651 |
|
---|
[24] | 2652 | ## DNSDB::addUser()
|
---|
[87] | 2653 | # Add a user.
|
---|
| 2654 | # Takes a DB handle, username, group ID, password, state (active/inactive).
|
---|
| 2655 | # Optionally accepts:
|
---|
| 2656 | # user type (user/admin) - defaults to user
|
---|
| 2657 | # permissions string - defaults to inherit from group
|
---|
| 2658 | # three valid forms:
|
---|
| 2659 | # i - Inherit permissions
|
---|
| 2660 | # c:<user_id> - Clone permissions from <user_id>
|
---|
| 2661 | # C:<permission list> - Set these specific permissions
|
---|
| 2662 | # first name - defaults to username
|
---|
| 2663 | # last name - defaults to blank
|
---|
| 2664 | # phone - defaults to blank (could put other data within column def)
|
---|
[90] | 2665 | # Returns (OK,<uid>) on success, (FAIL,<message>) on failure
|
---|
[24] | 2666 | sub addUser {
|
---|
| 2667 | $errstr = '';
|
---|
[479] | 2668 | my $self = shift;
|
---|
| 2669 | my $dbh = $self->{dbh};
|
---|
[24] | 2670 | my $username = shift;
|
---|
| 2671 | my $group = shift;
|
---|
| 2672 | my $pass = shift;
|
---|
| 2673 | my $state = shift;
|
---|
[25] | 2674 |
|
---|
[90] | 2675 | return ('FAIL', "Missing one or more required entries") if !defined($state);
|
---|
| 2676 | return ('FAIL', "Username must not be blank") if !$username;
|
---|
[87] | 2677 |
|
---|
[408] | 2678 | # Munge in some alternate state values
|
---|
| 2679 | $state = 1 if $state =~ /^active$/;
|
---|
| 2680 | $state = 1 if $state =~ /^on$/;
|
---|
| 2681 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 2682 | $state = 0 if $state =~ /^off$/;
|
---|
| 2683 |
|
---|
[25] | 2684 | my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
|
---|
| 2685 |
|
---|
[67] | 2686 | my $permstring = shift || 'i'; # default is to inhert permissions from group
|
---|
| 2687 |
|
---|
[25] | 2688 | my $fname = shift || $username;
|
---|
[24] | 2689 | my $lname = shift || '';
|
---|
[25] | 2690 | my $phone = shift || ''; # not going format-check
|
---|
[24] | 2691 |
|
---|
[38] | 2692 | my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
|
---|
[24] | 2693 | my $user_id;
|
---|
| 2694 |
|
---|
[38] | 2695 | # quick check to start to see if we've already got one
|
---|
| 2696 | $sth->execute($username);
|
---|
| 2697 | ($user_id) = $sth->fetchrow_array;
|
---|
| 2698 |
|
---|
| 2699 | return ('FAIL', "User already exists") if $user_id;
|
---|
| 2700 |
|
---|
[24] | 2701 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2702 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2703 | local $dbh->{AutoCommit} = 0;
|
---|
| 2704 | local $dbh->{RaiseError} = 1;
|
---|
| 2705 |
|
---|
| 2706 | # Wrap all the SQL in a transaction
|
---|
| 2707 | eval {
|
---|
[87] | 2708 | # insert the user... note we set inherited perms by default since
|
---|
| 2709 | # it's simple and cleans up some other bits of state
|
---|
| 2710 | my $sth = $dbh->prepare("INSERT INTO users ".
|
---|
| 2711 | "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
|
---|
| 2712 | "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
|
---|
| 2713 | $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);
|
---|
[24] | 2714 |
|
---|
| 2715 | # get the ID...
|
---|
[94] | 2716 | ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");
|
---|
[24] | 2717 |
|
---|
[87] | 2718 | # Permissions! Gotta set'em all!
|
---|
[401] | 2719 | die "Invalid permission string $permstring\n"
|
---|
[87] | 2720 | if $permstring !~ /^(?:
|
---|
| 2721 | i # inherit
|
---|
| 2722 | |c:\d+ # clone
|
---|
| 2723 | # custom. no, the leading , is not a typo
|
---|
[391] | 2724 | |C:(?:,(?:group|user|domain|record|location|self)_(?:edit|create|delete|locchg|view))*
|
---|
[87] | 2725 | )$/x;
|
---|
| 2726 | # bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
|
---|
| 2727 | if ($permstring ne 'i') {
|
---|
| 2728 | # for cloned or custom permissions, we have to create a new permissions entry.
|
---|
| 2729 | my $clonesrc = $group;
|
---|
| 2730 | if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
|
---|
| 2731 | $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
|
---|
| 2732 | "SELECT $permlist,? FROM permissions WHERE permission_id=".
|
---|
| 2733 | "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
|
---|
| 2734 | undef, ($user_id,$clonesrc) );
|
---|
| 2735 | $dbh->do("UPDATE users SET permission_id=".
|
---|
| 2736 | "(SELECT permission_id FROM permissions WHERE user_id=?) ".
|
---|
| 2737 | "WHERE user_id=?", undef, ($user_id, $user_id) );
|
---|
| 2738 | }
|
---|
| 2739 | if ($permstring =~ /^C:/) {
|
---|
| 2740 | # finally for custom permissions, we set the passed-in permissions (and unset
|
---|
| 2741 | # any that might have been brought in by the clone operation above)
|
---|
| 2742 | my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
|
---|
| 2743 | undef, ($user_id) );
|
---|
| 2744 | foreach (@permtypes) {
|
---|
| 2745 | if ($permstring =~ /,$_/) {
|
---|
| 2746 | $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
|
---|
| 2747 | } else {
|
---|
| 2748 | $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
|
---|
| 2749 | }
|
---|
| 2750 | }
|
---|
| 2751 | }
|
---|
| 2752 |
|
---|
| 2753 | $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
|
---|
| 2754 |
|
---|
[25] | 2755 | ##fixme: add another table to hold name/email for log table?
|
---|
| 2756 |
|
---|
[487] | 2757 | $self->_log(group_id => $group, entry => "Added user $username ($fname $lname)");
|
---|
[24] | 2758 | # once we get here, we should have suceeded.
|
---|
| 2759 | $dbh->commit;
|
---|
| 2760 | }; # end eval
|
---|
| 2761 |
|
---|
| 2762 | if ($@) {
|
---|
| 2763 | my $msg = $@;
|
---|
| 2764 | eval { $dbh->rollback; };
|
---|
[294] | 2765 | if ($config{log_failures}) {
|
---|
[487] | 2766 | $self->_log(group_id => $group, entry => "Error adding user $username: $msg");
|
---|
[294] | 2767 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2768 | }
|
---|
| 2769 | return ('FAIL',"Error adding user $username: $msg");
|
---|
[24] | 2770 | }
|
---|
[294] | 2771 |
|
---|
| 2772 | return ('OK',"User $username ($fname $lname) added");
|
---|
[24] | 2773 | } # end addUser
|
---|
| 2774 |
|
---|
| 2775 |
|
---|
[325] | 2776 | ## DNSDB::getUserCount()
|
---|
| 2777 | # Get count of users in group
|
---|
| 2778 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
| 2779 | # - a reference list of secondary groups
|
---|
| 2780 | # - a filter string
|
---|
| 2781 | # - a "Starts with" string
|
---|
| 2782 | sub getUserCount {
|
---|
[479] | 2783 | my $self = shift;
|
---|
| 2784 | my $dbh = $self->{dbh};
|
---|
[325] | 2785 |
|
---|
| 2786 | my %args = @_;
|
---|
| 2787 |
|
---|
| 2788 | my @filterargs;
|
---|
| 2789 |
|
---|
| 2790 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2791 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2792 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2793 |
|
---|
| 2794 |
|
---|
| 2795 | my $sql = "SELECT count(*) FROM users ".
|
---|
| 2796 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2797 | ($args{startwith} ? " AND username ~* ?" : '').
|
---|
| 2798 | ($args{filter} ? " AND username ~* ?" : '');
|
---|
| 2799 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 2800 | $errstr = $dbh->errstr if !$count;
|
---|
| 2801 | return $count;
|
---|
| 2802 | } # end getUserCount()
|
---|
| 2803 |
|
---|
| 2804 |
|
---|
| 2805 | ## DNSDB::getUserList()
|
---|
| 2806 | # Get list of users
|
---|
| 2807 | # Takes the same arguments as getUserCount() above, plus optional:
|
---|
| 2808 | # - sort field
|
---|
| 2809 | # - sort order
|
---|
| 2810 | # - offset/return-all-everything flag (defaults to $perpage records)
|
---|
| 2811 | sub getUserList {
|
---|
[479] | 2812 | my $self = shift;
|
---|
| 2813 | my $dbh = $self->{dbh};
|
---|
[325] | 2814 |
|
---|
| 2815 | my %args = @_;
|
---|
| 2816 |
|
---|
| 2817 | my @filterargs;
|
---|
| 2818 |
|
---|
| 2819 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2820 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2821 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2822 |
|
---|
| 2823 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
| 2824 | my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
| 2825 | fname => 'fname');
|
---|
| 2826 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 2827 |
|
---|
| 2828 | # protection against bad or missing arguments
|
---|
| 2829 | $args{sortorder} = 'ASC' if !$args{sortorder};
|
---|
| 2830 | $args{sortby} = 'u.username' if !$args{sortby};
|
---|
[397] | 2831 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[325] | 2832 |
|
---|
| 2833 | my $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ".
|
---|
| 2834 | "FROM users u ".
|
---|
| 2835 | "INNER JOIN groups g ON u.group_id=g.group_id ".
|
---|
| 2836 | "WHERE u.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2837 | ($args{startwith} ? " AND u.username ~* ?" : '').
|
---|
| 2838 | ($args{filter} ? " AND u.username ~* ?" : '').
|
---|
[401] | 2839 | " AND NOT u.type = 'R' ".
|
---|
[325] | 2840 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
| 2841 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
| 2842 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 2843 | $errstr = $dbh->errstr if !$ulist;
|
---|
| 2844 | return $ulist;
|
---|
| 2845 | } # end getUserList()
|
---|
| 2846 |
|
---|
| 2847 |
|
---|
[326] | 2848 | ## DNSDB::getUserDropdown()
|
---|
| 2849 | # Get a list of usernames for use in a dropdown menu.
|
---|
| 2850 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
| 2851 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
| 2852 | sub getUserDropdown {
|
---|
[479] | 2853 | my $self = shift;
|
---|
| 2854 | my $dbh = $self->{dbh};
|
---|
[326] | 2855 | my $grp = shift;
|
---|
| 2856 | my $sel = shift || 0;
|
---|
| 2857 |
|
---|
| 2858 | my $sth = $dbh->prepare("SELECT username,user_id FROM users WHERE group_id=?");
|
---|
| 2859 | $sth->execute($grp);
|
---|
| 2860 |
|
---|
| 2861 | my @userlist;
|
---|
| 2862 | while (my ($username,$uid) = $sth->fetchrow_array) {
|
---|
| 2863 | my %row = (
|
---|
| 2864 | username => $username,
|
---|
| 2865 | uid => $uid,
|
---|
| 2866 | selected => ($sel == $uid ? 1 : 0)
|
---|
| 2867 | );
|
---|
| 2868 | push @userlist, \%row;
|
---|
| 2869 | }
|
---|
| 2870 | return \@userlist;
|
---|
| 2871 | } # end getUserDropdown()
|
---|
| 2872 |
|
---|
| 2873 |
|
---|
[83] | 2874 | ## DNSDB:: updateUser()
|
---|
[90] | 2875 | # Update general data about user
|
---|
[83] | 2876 | sub updateUser {
|
---|
[479] | 2877 | my $self = shift;
|
---|
| 2878 | my $dbh = $self->{dbh};
|
---|
[118] | 2879 |
|
---|
| 2880 | ##fixme: tweak calling convention so that we can update any given bit of data
|
---|
[83] | 2881 | my $uid = shift;
|
---|
| 2882 | my $username = shift;
|
---|
| 2883 | my $group = shift;
|
---|
| 2884 | my $pass = shift;
|
---|
| 2885 | my $state = shift;
|
---|
[87] | 2886 | my $type = shift || 'u';
|
---|
[83] | 2887 | my $fname = shift || $username;
|
---|
| 2888 | my $lname = shift || '';
|
---|
| 2889 | my $phone = shift || ''; # not going format-check
|
---|
| 2890 |
|
---|
[294] | 2891 | my $resultmsg = '';
|
---|
[83] | 2892 |
|
---|
[411] | 2893 | # Munge in some alternate state values
|
---|
| 2894 | $state = 1 if $state =~ /^active$/;
|
---|
| 2895 | $state = 1 if $state =~ /^on$/;
|
---|
| 2896 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 2897 | $state = 0 if $state =~ /^off$/;
|
---|
| 2898 |
|
---|
[83] | 2899 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2900 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2901 | local $dbh->{AutoCommit} = 0;
|
---|
| 2902 | local $dbh->{RaiseError} = 1;
|
---|
| 2903 |
|
---|
| 2904 | my $sth;
|
---|
| 2905 |
|
---|
| 2906 | # Password can be left blank; if so we assume there's one on file.
|
---|
| 2907 | # Actual blank passwords are bad, mm'kay?
|
---|
| 2908 | if (!$pass) {
|
---|
[294] | 2909 | ($pass) = $dbh->selectrow_array("SELECT password FROM users WHERE user_id=?", undef, ($uid));
|
---|
[83] | 2910 | } else {
|
---|
| 2911 | $pass = unix_md5_crypt($pass);
|
---|
| 2912 | }
|
---|
| 2913 |
|
---|
| 2914 | eval {
|
---|
[294] | 2915 | $dbh->do("UPDATE users SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?".
|
---|
| 2916 | " WHERE user_id=?", undef, ($username, $pass, $fname, $lname, $phone, $type, $state, $uid));
|
---|
| 2917 | $resultmsg = "Updated user info for $username ($fname $lname)";
|
---|
[487] | 2918 | $self->_log(group_id => $group, entry => $resultmsg);
|
---|
[83] | 2919 | $dbh->commit;
|
---|
| 2920 | };
|
---|
| 2921 | if ($@) {
|
---|
| 2922 | my $msg = $@;
|
---|
| 2923 | eval { $dbh->rollback; };
|
---|
[294] | 2924 | if ($config{log_failures}) {
|
---|
[487] | 2925 | $self->_log(group_id => $group, entry => "Error updating user $username: $msg");
|
---|
[294] | 2926 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2927 | }
|
---|
| 2928 | return ('FAIL',"Error updating user $username: $msg");
|
---|
[83] | 2929 | }
|
---|
[294] | 2930 |
|
---|
| 2931 | return ('OK',$resultmsg);
|
---|
[83] | 2932 | } # end updateUser()
|
---|
| 2933 |
|
---|
| 2934 |
|
---|
[24] | 2935 | ## DNSDB::delUser()
|
---|
[297] | 2936 | # Delete a user.
|
---|
| 2937 | # Takes a database handle and user ID
|
---|
| 2938 | # Returns a success/failure code and matching message
|
---|
[24] | 2939 | sub delUser {
|
---|
[479] | 2940 | my $self = shift;
|
---|
| 2941 | my $dbh = $self->{dbh};
|
---|
[25] | 2942 | my $userid = shift;
|
---|
| 2943 |
|
---|
[297] | 2944 | return ('FAIL',"Bad userid") if !defined($userid);
|
---|
[25] | 2945 |
|
---|
[479] | 2946 | my $userdata = $self->getUserData($userid);
|
---|
[25] | 2947 |
|
---|
[297] | 2948 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2949 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2950 | local $dbh->{AutoCommit} = 0;
|
---|
| 2951 | local $dbh->{RaiseError} = 1;
|
---|
[25] | 2952 |
|
---|
[297] | 2953 | eval {
|
---|
| 2954 | $dbh->do("DELETE FROM users WHERE user_id=?", undef, ($userid));
|
---|
[487] | 2955 | $self->_log(group_id => $userdata->{group_id},
|
---|
[297] | 2956 | entry => "Deleted user ID $userid/".$userdata->{username}.
|
---|
[487] | 2957 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")");
|
---|
[297] | 2958 | $dbh->commit;
|
---|
| 2959 | };
|
---|
| 2960 | if ($@) {
|
---|
| 2961 | my $msg = $@;
|
---|
| 2962 | eval { $dbh->rollback; };
|
---|
| 2963 | if ($config{log_failures}) {
|
---|
[487] | 2964 | $self->_log(group_id => $userdata->{group_id}, entry => "Error deleting user ID ".
|
---|
| 2965 | "$userid/".$userdata->{username}.": $msg");
|
---|
[297] | 2966 | $dbh->commit;
|
---|
| 2967 | }
|
---|
| 2968 | return ('FAIL',"Error deleting user $userid/".$userdata->{username}.": $msg");
|
---|
| 2969 | }
|
---|
| 2970 |
|
---|
| 2971 | return ('OK',"Deleted user ".$userdata->{username}." (".$userdata->{firstname}." ".$userdata->{lastname}.")");
|
---|
[24] | 2972 | } # end delUser
|
---|
| 2973 |
|
---|
| 2974 |
|
---|
[25] | 2975 | ## DNSDB::userFullName()
|
---|
| 2976 | # Return a pretty string!
|
---|
| 2977 | # Takes a user_id and optional printf-ish string to indicate which pieces where:
|
---|
| 2978 | # %u for the username
|
---|
| 2979 | # %f for the first name
|
---|
| 2980 | # %l for the last name
|
---|
| 2981 | # All other text in the passed string will be left as-is.
|
---|
| 2982 | ##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
|
---|
| 2983 | sub userFullName {
|
---|
| 2984 | $errstr = '';
|
---|
[473] | 2985 | my $self = shift;
|
---|
| 2986 | my $dbh = $self->{dbh};
|
---|
[25] | 2987 | my $userid = shift;
|
---|
| 2988 | my $fullformat = shift || '%f %l (%u)';
|
---|
| 2989 | my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
|
---|
| 2990 | $sth->execute($userid);
|
---|
| 2991 | my ($uname,$fname,$lname) = $sth->fetchrow_array();
|
---|
| 2992 | $errstr = $DBI::errstr if !$uname;
|
---|
| 2993 |
|
---|
| 2994 | $fullformat =~ s/\%u/$uname/g;
|
---|
| 2995 | $fullformat =~ s/\%f/$fname/g;
|
---|
| 2996 | $fullformat =~ s/\%l/$lname/g;
|
---|
| 2997 |
|
---|
| 2998 | return $fullformat;
|
---|
| 2999 | } # end userFullName
|
---|
| 3000 |
|
---|
| 3001 |
|
---|
[51] | 3002 | ## DNSDB::userStatus()
|
---|
| 3003 | # Sets and/or returns a user's status
|
---|
| 3004 | # Takes a database handle, user ID and optionally a status argument
|
---|
| 3005 | # Returns undef on errors.
|
---|
| 3006 | sub userStatus {
|
---|
[479] | 3007 | my $self = shift;
|
---|
| 3008 | my $dbh = $self->{dbh};
|
---|
[51] | 3009 | my $id = shift;
|
---|
[296] | 3010 | my $newstatus = shift || 'mu';
|
---|
[51] | 3011 |
|
---|
| 3012 | return undef if $id !~ /^\d+$/;
|
---|
| 3013 |
|
---|
[479] | 3014 | my $userdata = $self->getUserData($id);
|
---|
[51] | 3015 |
|
---|
[296] | 3016 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3017 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3018 | local $dbh->{AutoCommit} = 0;
|
---|
| 3019 | local $dbh->{RaiseError} = 1;
|
---|
| 3020 |
|
---|
| 3021 | if ($newstatus ne 'mu') {
|
---|
| 3022 | # ooo, fun! let's see what we were passed for status
|
---|
| 3023 | eval {
|
---|
| 3024 | $newstatus = 0 if $newstatus eq 'useroff';
|
---|
| 3025 | $newstatus = 1 if $newstatus eq 'useron';
|
---|
| 3026 | $dbh->do("UPDATE users SET status=? WHERE user_id=?", undef, ($newstatus, $id));
|
---|
| 3027 |
|
---|
[297] | 3028 | $resultstr = ($newstatus ? 'Enabled' : 'Disabled')." user ".$userdata->{username}.
|
---|
| 3029 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")";
|
---|
[296] | 3030 |
|
---|
| 3031 | my %loghash;
|
---|
[473] | 3032 | $loghash{group_id} = $self->parentID(id => $id, type => 'user');
|
---|
[296] | 3033 | $loghash{entry} = $resultstr;
|
---|
[487] | 3034 | $self->_log(%loghash);
|
---|
[296] | 3035 |
|
---|
| 3036 | $dbh->commit;
|
---|
| 3037 | };
|
---|
| 3038 | if ($@) {
|
---|
| 3039 | my $msg = $@;
|
---|
| 3040 | eval { $dbh->rollback; };
|
---|
| 3041 | $resultstr = '';
|
---|
| 3042 | $errstr = $msg;
|
---|
| 3043 | ##fixme: failure logging?
|
---|
| 3044 | return;
|
---|
[51] | 3045 | }
|
---|
| 3046 | }
|
---|
| 3047 |
|
---|
[296] | 3048 | my ($status) = $dbh->selectrow_array("SELECT status FROM users WHERE user_id=?", undef, ($id));
|
---|
[51] | 3049 | return $status;
|
---|
| 3050 | } # end userStatus()
|
---|
| 3051 |
|
---|
| 3052 |
|
---|
[83] | 3053 | ## DNSDB::getUserData()
|
---|
| 3054 | # Get misc user data for display
|
---|
| 3055 | sub getUserData {
|
---|
[479] | 3056 | my $self = shift;
|
---|
| 3057 | my $dbh = $self->{dbh};
|
---|
[83] | 3058 | my $uid = shift;
|
---|
| 3059 |
|
---|
| 3060 | my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
|
---|
| 3061 | "FROM users WHERE user_id=?");
|
---|
| 3062 | $sth->execute($uid);
|
---|
| 3063 | return $sth->fetchrow_hashref();
|
---|
| 3064 | } # end getUserData()
|
---|
| 3065 |
|
---|
| 3066 |
|
---|
[370] | 3067 | ## DNSDB::addLoc()
|
---|
[375] | 3068 | # Add a new location.
|
---|
| 3069 | # Takes a database handle, group ID, short and long description, and a comma-separated
|
---|
| 3070 | # list of IP addresses.
|
---|
| 3071 | # Returns ('OK',<location>) on success, ('FAIL',<failmsg>) on failure
|
---|
| 3072 | sub addLoc {
|
---|
[480] | 3073 | my $self = shift;
|
---|
| 3074 | my $dbh = $self->{dbh};
|
---|
[375] | 3075 | my $grp = shift;
|
---|
| 3076 | my $shdesc = shift;
|
---|
| 3077 | my $comments = shift;
|
---|
| 3078 | my $iplist = shift;
|
---|
[370] | 3079 |
|
---|
[375] | 3080 | # $shdesc gets set to the generated location ID if possible, but these can be de-undefined here.
|
---|
| 3081 | $comments = '' if !$comments;
|
---|
| 3082 | $iplist = '' if !$iplist;
|
---|
| 3083 |
|
---|
| 3084 | my $loc;
|
---|
| 3085 |
|
---|
| 3086 | # Generate a location ID. This is, by spec, a two-character widget. We'll use [a-z][a-z]
|
---|
| 3087 | # for now; 676 locations should satisfy all but the largest of the huge networks.
|
---|
| 3088 | # Not sure whether these are case-sensitive, or what other rules might apply - in any case
|
---|
| 3089 | # the absolute maximum is 16K (256*256) since it's parsed by tinydns as a two-character field.
|
---|
| 3090 |
|
---|
| 3091 | # add just after "my $origloc = $loc;":
|
---|
| 3092 | # # These expand the possible space from 26^2 to 52^2 [* note in testing only 2052 were achieved],
|
---|
| 3093 | # # and wrap it around.
|
---|
| 3094 | # # Yes, they skip a couple of possibles. No, I don't care.
|
---|
| 3095 | # $loc = 'aA' if $loc eq 'zz';
|
---|
| 3096 | # $loc = 'Aa' if $loc eq 'zZ';
|
---|
| 3097 | # $loc = 'ZA' if $loc eq 'Zz';
|
---|
| 3098 | # $loc = 'aa' if $loc eq 'ZZ';
|
---|
| 3099 |
|
---|
| 3100 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3101 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3102 | local $dbh->{AutoCommit} = 0;
|
---|
| 3103 | local $dbh->{RaiseError} = 1;
|
---|
| 3104 |
|
---|
| 3105 | ##fixme: There is probably a far better way to do this. Sequential increments
|
---|
| 3106 | # are marginally less stupid that pure random generation though, and the existence
|
---|
| 3107 | # check makes sure we don't stomp on an imported one.
|
---|
| 3108 |
|
---|
| 3109 | eval {
|
---|
| 3110 | # Get the "last" location. Note this is the only use for loc_id, because selecting on location Does Funky Things
|
---|
| 3111 | ($loc) = $dbh->selectrow_array("SELECT location FROM locations ORDER BY loc_id DESC LIMIT 1");
|
---|
[478] | 3112 | ($loc) = ($loc =~ /^(..)/) if $loc;
|
---|
[375] | 3113 | my $origloc = $loc;
|
---|
[446] | 3114 | $loc = 'aa' if !$loc;
|
---|
[375] | 3115 | # Make a change...
|
---|
| 3116 | $loc++;
|
---|
| 3117 | # ... and keep changing if it exists
|
---|
| 3118 | while ($dbh->selectrow_array("SELECT count(*) FROM locations WHERE location LIKE ?", undef, ($loc.'%'))) {
|
---|
| 3119 | $loc++;
|
---|
| 3120 | ($loc) = ($loc =~ /^(..)/);
|
---|
| 3121 | die "too many locations in use, can't add another one\n" if $loc eq $origloc;
|
---|
| 3122 | ##fixme: really need to handle this case faster somehow
|
---|
| 3123 | #if $loc eq $origloc die "<thwap> bad admin: all locations used, your network is too fragmented";
|
---|
| 3124 | }
|
---|
| 3125 | # And now we should have a unique location. tinydns fundamentally limits the
|
---|
| 3126 | # number of these but there's no doc on what characters are valid.
|
---|
| 3127 | $shdesc = $loc if !$shdesc;
|
---|
| 3128 | $dbh->do("INSERT INTO locations (location, group_id, iplist, description, comments) VALUES (?,?,?,?,?)",
|
---|
| 3129 | undef, ($loc, $grp, $iplist, $shdesc, $comments) );
|
---|
[487] | 3130 | $self->_log(entry => "Added location ($shdesc, '$iplist')");
|
---|
[377] | 3131 | $dbh->commit;
|
---|
[375] | 3132 | };
|
---|
| 3133 | if ($@) {
|
---|
| 3134 | my $msg = $@;
|
---|
| 3135 | eval { $dbh->rollback; };
|
---|
| 3136 | if ($config{log_failures}) {
|
---|
| 3137 | $shdesc = $loc if !$shdesc;
|
---|
[487] | 3138 | $self->_log(entry => "Failed adding location ($shdesc, '$iplist'): $msg");
|
---|
[375] | 3139 | $dbh->commit;
|
---|
| 3140 | }
|
---|
| 3141 | return ('FAIL',$msg);
|
---|
| 3142 | }
|
---|
| 3143 |
|
---|
| 3144 | return ('OK',$loc);
|
---|
[377] | 3145 | } # end addLoc()
|
---|
[375] | 3146 |
|
---|
| 3147 |
|
---|
[370] | 3148 | ## DNSDB::updateLoc()
|
---|
[428] | 3149 | # Update details of a location.
|
---|
| 3150 | # Takes a database handle, location ID, group ID, short description,
|
---|
| 3151 | # long comments/notes, and comma/space-separated IP list
|
---|
| 3152 | # Returns a result code and message
|
---|
[377] | 3153 | sub updateLoc {
|
---|
[480] | 3154 | my $self = shift;
|
---|
| 3155 | my $dbh = $self->{dbh};
|
---|
[377] | 3156 | my $loc = shift;
|
---|
| 3157 | my $grp = shift;
|
---|
| 3158 | my $shdesc = shift;
|
---|
| 3159 | my $comments = shift;
|
---|
| 3160 | my $iplist = shift;
|
---|
[370] | 3161 |
|
---|
[377] | 3162 | $shdesc = '' if !$shdesc;
|
---|
| 3163 | $comments = '' if !$comments;
|
---|
| 3164 | $iplist = '' if !$iplist;
|
---|
| 3165 |
|
---|
| 3166 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3167 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3168 | local $dbh->{AutoCommit} = 0;
|
---|
| 3169 | local $dbh->{RaiseError} = 1;
|
---|
| 3170 |
|
---|
[480] | 3171 | my $oldloc = $self->getLoc($loc);
|
---|
[377] | 3172 | my $okmsg = "Updated location (".$oldloc->{description}.", '".$oldloc->{iplist}."') to ($shdesc, '$iplist')";
|
---|
| 3173 |
|
---|
| 3174 | eval {
|
---|
| 3175 | $dbh->do("UPDATE locations SET group_id=?,iplist=?,description=?,comments=? WHERE location=?",
|
---|
| 3176 | undef, ($grp, $iplist, $shdesc, $comments, $loc) );
|
---|
[487] | 3177 | $self->_log(entry => $okmsg);
|
---|
[377] | 3178 | $dbh->commit;
|
---|
| 3179 | };
|
---|
| 3180 | if ($@) {
|
---|
| 3181 | my $msg = $@;
|
---|
| 3182 | eval { $dbh->rollback; };
|
---|
| 3183 | if ($config{log_failures}) {
|
---|
| 3184 | $shdesc = $loc if !$shdesc;
|
---|
[487] | 3185 | $self->_log(entry => "Failed updating location ($shdesc, '$iplist'): $msg");
|
---|
[377] | 3186 | $dbh->commit;
|
---|
| 3187 | }
|
---|
| 3188 | return ('FAIL',$msg);
|
---|
| 3189 | }
|
---|
| 3190 |
|
---|
| 3191 | return ('OK',$okmsg);
|
---|
| 3192 | } # end updateLoc()
|
---|
| 3193 |
|
---|
| 3194 |
|
---|
[370] | 3195 | ## DNSDB::delLoc()
|
---|
[428] | 3196 | sub delLoc {
|
---|
[480] | 3197 | my $self = shift;
|
---|
| 3198 | my $dbh = $self->{dbh};
|
---|
[428] | 3199 | my $loc = shift;
|
---|
[370] | 3200 |
|
---|
[428] | 3201 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3202 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3203 | local $dbh->{AutoCommit} = 0;
|
---|
| 3204 | local $dbh->{RaiseError} = 1;
|
---|
[370] | 3205 |
|
---|
[480] | 3206 | my $oldloc = $self->getLoc($loc);
|
---|
[428] | 3207 | my $olddesc = ($oldloc->{description} ? $oldloc->{description} : $loc);
|
---|
| 3208 | my $okmsg = "Deleted location ($olddesc, '".$oldloc->{iplist}."')";
|
---|
| 3209 |
|
---|
| 3210 | eval {
|
---|
| 3211 | # Check for records with this location first. Deleting a location without deleting records
|
---|
| 3212 | # tagged for that location will render them unpublished without other warning.
|
---|
| 3213 | my ($r) = $dbh->selectrow_array("SELECT record_id FROM records WHERE location=? LIMIT 1", undef, ($loc) );
|
---|
| 3214 | die "Records still exist in location $olddesc\n" if $r;
|
---|
| 3215 | $dbh->do("DELETE FROM locations WHERE location=?", undef, ($loc) );
|
---|
[487] | 3216 | $self->_log(entry => $okmsg);
|
---|
[428] | 3217 | $dbh->commit;
|
---|
| 3218 | };
|
---|
| 3219 | if ($@) {
|
---|
| 3220 | my $msg = $@;
|
---|
| 3221 | eval { $dbh->rollback; };
|
---|
| 3222 | if ($config{log_failures}) {
|
---|
[487] | 3223 | $self->_log(entry => "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
|
---|
[428] | 3224 | $dbh->commit;
|
---|
| 3225 | }
|
---|
| 3226 | return ('FAIL', "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
|
---|
| 3227 | }
|
---|
| 3228 |
|
---|
| 3229 | return ('OK',$okmsg);
|
---|
| 3230 | } # end delLoc()
|
---|
| 3231 |
|
---|
| 3232 |
|
---|
[375] | 3233 | ## DNSDB::getLoc()
|
---|
[428] | 3234 | # Get details about a location/view
|
---|
| 3235 | # Takes a database handle and location ID.
|
---|
| 3236 | # Returns a reference to a hash containing the group ID, IP list, description, and comments/notes
|
---|
[375] | 3237 | sub getLoc {
|
---|
[480] | 3238 | my $self = shift;
|
---|
| 3239 | my $dbh = $self->{dbh};
|
---|
[375] | 3240 | my $loc = shift;
|
---|
| 3241 |
|
---|
| 3242 | my $sth = $dbh->prepare("SELECT group_id,iplist,description,comments FROM locations WHERE location=?");
|
---|
| 3243 | $sth->execute($loc);
|
---|
| 3244 | return $sth->fetchrow_hashref();
|
---|
| 3245 | } # end getLoc()
|
---|
| 3246 |
|
---|
| 3247 |
|
---|
[370] | 3248 | ## DNSDB::getLocCount()
|
---|
| 3249 | # Get count of locations/views
|
---|
| 3250 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
| 3251 | # - a reference list of secondary groups
|
---|
| 3252 | # - a filter string
|
---|
| 3253 | # - a "Starts with" string
|
---|
| 3254 | sub getLocCount {
|
---|
[480] | 3255 | my $self = shift;
|
---|
| 3256 | my $dbh = $self->{dbh};
|
---|
[370] | 3257 |
|
---|
| 3258 | my %args = @_;
|
---|
| 3259 |
|
---|
| 3260 | my @filterargs;
|
---|
| 3261 |
|
---|
| 3262 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3263 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3264 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3265 |
|
---|
| 3266 |
|
---|
| 3267 | my $sql = "SELECT count(*) FROM locations ".
|
---|
| 3268 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3269 | ($args{startwith} ? " AND description ~* ?" : '').
|
---|
| 3270 | ($args{filter} ? " AND description ~* ?" : '');
|
---|
| 3271 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 3272 | $errstr = $dbh->errstr if !$count;
|
---|
| 3273 | return $count;
|
---|
| 3274 | } # end getLocCount()
|
---|
| 3275 |
|
---|
| 3276 |
|
---|
| 3277 | ## DNSDB::getLocList()
|
---|
| 3278 | sub getLocList {
|
---|
[480] | 3279 | my $self = shift;
|
---|
| 3280 | my $dbh = $self->{dbh};
|
---|
[370] | 3281 |
|
---|
| 3282 | my %args = @_;
|
---|
| 3283 |
|
---|
| 3284 | my @filterargs;
|
---|
| 3285 |
|
---|
| 3286 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3287 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3288 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3289 |
|
---|
| 3290 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
| 3291 | # my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
| 3292 | # fname => 'fname');
|
---|
| 3293 | # $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 3294 |
|
---|
| 3295 | # protection against bad or missing arguments
|
---|
| 3296 | $args{sortorder} = 'ASC' if !$args{sortorder};
|
---|
| 3297 | $args{sortby} = 'l.description' if !$args{sortby};
|
---|
[397] | 3298 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[370] | 3299 |
|
---|
| 3300 | my $sql = "SELECT l.location, l.description, l.iplist, g.group_name ".
|
---|
| 3301 | "FROM locations l ".
|
---|
| 3302 | "INNER JOIN groups g ON l.group_id=g.group_id ".
|
---|
| 3303 | "WHERE l.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3304 | ($args{startwith} ? " AND l.description ~* ?" : '').
|
---|
| 3305 | ($args{filter} ? " AND l.description ~* ?" : '').
|
---|
| 3306 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
| 3307 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
| 3308 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 3309 | $errstr = $dbh->errstr if !$ulist;
|
---|
| 3310 | return $ulist;
|
---|
| 3311 | } # end getLocList()
|
---|
| 3312 |
|
---|
| 3313 |
|
---|
| 3314 | ## DNSDB::getLocDropdown()
|
---|
[383] | 3315 | # Get a list of location names for use in a dropdown menu.
|
---|
| 3316 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
| 3317 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
| 3318 | sub getLocDropdown {
|
---|
[480] | 3319 | my $self = shift;
|
---|
| 3320 | my $dbh = $self->{dbh};
|
---|
[383] | 3321 | my $grp = shift;
|
---|
| 3322 | my $sel = shift || '';
|
---|
[370] | 3323 |
|
---|
[383] | 3324 | my $sth = $dbh->prepare(qq(
|
---|
| 3325 | SELECT description,location FROM locations
|
---|
| 3326 | WHERE group_id=?
|
---|
| 3327 | ORDER BY description
|
---|
| 3328 | ) );
|
---|
| 3329 | $sth->execute($grp);
|
---|
[370] | 3330 |
|
---|
[383] | 3331 | my @loclist;
|
---|
[446] | 3332 | push @loclist, { locname => "(Default/All)", loc => '', selected => ($sel ? 0 : ($sel eq '' ? 1 : 0)) };
|
---|
[383] | 3333 | while (my ($locname, $loc) = $sth->fetchrow_array) {
|
---|
| 3334 | my %row = (
|
---|
| 3335 | locname => $locname,
|
---|
| 3336 | loc => $loc,
|
---|
| 3337 | selected => ($sel eq $loc ? 1 : 0)
|
---|
| 3338 | );
|
---|
| 3339 | push @loclist, \%row;
|
---|
| 3340 | }
|
---|
| 3341 | return \@loclist;
|
---|
| 3342 | } # end getLocDropdown()
|
---|
| 3343 |
|
---|
| 3344 |
|
---|
[2] | 3345 | ## DNSDB::getSOA()
|
---|
| 3346 | # Return all suitable fields from an SOA record in separate elements of a hash
|
---|
[224] | 3347 | # Takes a database handle, default/live flag, domain/reverse flag, and parent ID
|
---|
[2] | 3348 | sub getSOA {
|
---|
| 3349 | $errstr = '';
|
---|
[481] | 3350 | my $self = shift;
|
---|
| 3351 | my $dbh = $self->{dbh};
|
---|
[2] | 3352 | my $def = shift;
|
---|
[224] | 3353 | my $rev = shift;
|
---|
[2] | 3354 | my $id = shift;
|
---|
| 3355 |
|
---|
[224] | 3356 | # (ab)use distance and weight columns to store SOA data? can't for default_rev_records...
|
---|
| 3357 | # - should really attach serial to the zone parent somewhere
|
---|
[101] | 3358 |
|
---|
[224] | 3359 | my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev).
|
---|
| 3360 | " WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}";
|
---|
[311] | 3361 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
| 3362 | return if !$ret;
|
---|
[246] | 3363 | ##fixme: stick a flag somewhere if the record doesn't exist. by the API, this is an impossible case, but...
|
---|
[2] | 3364 |
|
---|
[311] | 3365 | ($ret->{contact},$ret->{prins}) = split /:/, $ret->{host};
|
---|
| 3366 | delete $ret->{host};
|
---|
| 3367 | ($ret->{refresh},$ret->{retry},$ret->{expire},$ret->{minttl}) = split /:/, $ret->{val};
|
---|
| 3368 | delete $ret->{val};
|
---|
[2] | 3369 |
|
---|
[311] | 3370 | return $ret;
|
---|
[2] | 3371 | } # end getSOA()
|
---|
| 3372 |
|
---|
| 3373 |
|
---|
[246] | 3374 | ## DNSDB::updateSOA()
|
---|
| 3375 | # Update the specified SOA record
|
---|
| 3376 | # Takes a database handle, default/live flag, forward/reverse flag, and SOA data hash
|
---|
[277] | 3377 | # Returns a two-element list with a result code and message
|
---|
[246] | 3378 | sub updateSOA {
|
---|
[473] | 3379 | my $self = shift;
|
---|
| 3380 | my $dbh = $self->{dbh};
|
---|
[246] | 3381 | my $defrec = shift;
|
---|
[248] | 3382 | my $revrec = shift;
|
---|
[246] | 3383 |
|
---|
| 3384 | my %soa = @_;
|
---|
| 3385 |
|
---|
[473] | 3386 | my $oldsoa = $self->getSOA($defrec, $revrec, $soa{id});
|
---|
[277] | 3387 |
|
---|
[311] | 3388 | my $msg;
|
---|
| 3389 | my %logdata;
|
---|
| 3390 | if ($defrec eq 'n') {
|
---|
| 3391 | $logdata{domain_id} = $soa{id} if $revrec eq 'n';
|
---|
| 3392 | $logdata{rdns_id} = $soa{id} if $revrec eq 'y';
|
---|
[473] | 3393 | $logdata{group_id} = $self->parentID(id => $soa{id}, revrec => $revrec,
|
---|
| 3394 | type => ($revrec eq 'n' ? 'domain' : 'revzone') );
|
---|
[311] | 3395 | } else {
|
---|
| 3396 | $logdata{group_id} = $soa{id};
|
---|
| 3397 | }
|
---|
[473] | 3398 | my $parname = ($defrec eq 'y' ? $self->groupName($soa{id}) :
|
---|
| 3399 | ($revrec eq 'n' ? $self->domainName($soa{id}) : $self->revName($soa{id})) );
|
---|
[311] | 3400 |
|
---|
[277] | 3401 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3402 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3403 | local $dbh->{AutoCommit} = 0;
|
---|
| 3404 | local $dbh->{RaiseError} = 1;
|
---|
| 3405 |
|
---|
| 3406 | eval {
|
---|
| 3407 | my $sql = "UPDATE "._rectable($defrec, $revrec)." SET host=?, val=?, ttl=? WHERE record_id=? AND type=6";
|
---|
| 3408 | $dbh->do($sql, undef, ("$soa{contact}:$soa{prins}", "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}",
|
---|
[311] | 3409 | $soa{ttl}, $oldsoa->{record_id}) );
|
---|
| 3410 | $msg = "Updated ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse ' : 'default ') : '').
|
---|
| 3411 | "SOA for $parname: ".
|
---|
| 3412 | "(ns $oldsoa->{prins}, contact $oldsoa->{contact}, refresh $oldsoa->{refresh},".
|
---|
| 3413 | " retry $oldsoa->{retry}, expire $oldsoa->{expire}, minTTL $oldsoa->{minttl}, TTL $oldsoa->{ttl}) to ".
|
---|
[277] | 3414 | "(ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
|
---|
| 3415 | " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})";
|
---|
| 3416 |
|
---|
[311] | 3417 | $logdata{entry} = $msg;
|
---|
[487] | 3418 | $self->_log(%logdata);
|
---|
[277] | 3419 |
|
---|
| 3420 | $dbh->commit;
|
---|
| 3421 | };
|
---|
| 3422 | if ($@) {
|
---|
| 3423 | $msg = $@;
|
---|
| 3424 | eval { $dbh->rollback; };
|
---|
[311] | 3425 | $logdata{entry} = "Error updating ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse zone ' : 'default ') : '').
|
---|
| 3426 | "SOA record for $parname: $msg";
|
---|
| 3427 | if ($config{log_failures}) {
|
---|
[487] | 3428 | $self->_log(%logdata);
|
---|
[311] | 3429 | $dbh->commit;
|
---|
| 3430 | }
|
---|
| 3431 | return ('FAIL', $logdata{entry});
|
---|
[277] | 3432 | } else {
|
---|
| 3433 | return ('OK', $msg);
|
---|
| 3434 | }
|
---|
[246] | 3435 | } # end updateSOA()
|
---|
| 3436 |
|
---|
| 3437 |
|
---|
[2] | 3438 | ## DNSDB::getRecLine()
|
---|
| 3439 | # Return all data fields for a zone record in separate elements of a hash
|
---|
[243] | 3440 | # Takes a database handle, default/live flag, forward/reverse flag, and record ID
|
---|
[2] | 3441 | sub getRecLine {
|
---|
| 3442 | $errstr = '';
|
---|
[481] | 3443 | my $self = shift;
|
---|
| 3444 | my $dbh = $self->{dbh};
|
---|
[243] | 3445 | my $defrec = shift;
|
---|
| 3446 | my $revrec = shift;
|
---|
[2] | 3447 | my $id = shift;
|
---|
| 3448 |
|
---|
[429] | 3449 | my $sql = "SELECT record_id,host,type,val,ttl".
|
---|
| 3450 | ($defrec eq 'n' ? ',location' : '').
|
---|
| 3451 | ($revrec eq 'n' ? ',distance,weight,port' : '').
|
---|
[243] | 3452 | (($defrec eq 'y') ? ',group_id FROM ' : ',domain_id,rdns_id FROM ').
|
---|
| 3453 | _rectable($defrec,$revrec)." WHERE record_id=?";
|
---|
[123] | 3454 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
[2] | 3455 |
|
---|
[90] | 3456 | if ($dbh->err) {
|
---|
[2] | 3457 | $errstr = $DBI::errstr;
|
---|
| 3458 | return undef;
|
---|
| 3459 | }
|
---|
| 3460 |
|
---|
[123] | 3461 | if (!$ret) {
|
---|
| 3462 | $errstr = "No such record";
|
---|
| 3463 | return undef;
|
---|
| 3464 | }
|
---|
| 3465 |
|
---|
[243] | 3466 | # explicitly set a parent id
|
---|
| 3467 | if ($defrec eq 'y') {
|
---|
| 3468 | $ret->{parid} = $ret->{group_id};
|
---|
| 3469 | } else {
|
---|
| 3470 | $ret->{parid} = (($revrec eq 'n') ? $ret->{domain_id} : $ret->{rdns_id});
|
---|
| 3471 | # and a secondary if we have a custom type that lives in both a forward and reverse zone
|
---|
| 3472 | $ret->{secid} = (($revrec eq 'y') ? $ret->{domain_id} : $ret->{rdns_id}) if $ret->{type} > 65279;
|
---|
| 3473 | }
|
---|
[451] | 3474 | $ret->{address} = $ret->{val}; # because.
|
---|
[90] | 3475 |
|
---|
| 3476 | return $ret;
|
---|
[2] | 3477 | }
|
---|
| 3478 |
|
---|
| 3479 |
|
---|
| 3480 | ##fixme: should use above (getRecLine()) to get lines for below?
|
---|
| 3481 | ## DNSDB::getDomRecs()
|
---|
| 3482 | # Return records for a domain
|
---|
| 3483 | # Takes a database handle, default/live flag, group/domain ID, start,
|
---|
| 3484 | # number of records, sort field, and sort order
|
---|
| 3485 | # Returns a reference to an array of hashes
|
---|
| 3486 | sub getDomRecs {
|
---|
| 3487 | $errstr = '';
|
---|
[481] | 3488 | my $self = shift;
|
---|
| 3489 | my $dbh = $self->{dbh};
|
---|
[2] | 3490 |
|
---|
[397] | 3491 | my %args = @_;
|
---|
[4] | 3492 |
|
---|
[397] | 3493 | my @filterargs;
|
---|
[135] | 3494 |
|
---|
[397] | 3495 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3496 |
|
---|
| 3497 | # protection against bad or missing arguments
|
---|
| 3498 | $args{sortorder} = 'ASC' if !$args{sortorder};
|
---|
[399] | 3499 | $args{sortby} = 'host' if !$args{sortby} && $args{revrec} eq 'n'; # default sort by host on domain record list
|
---|
| 3500 | $args{sortby} = 'val' if !$args{sortby} && $args{revrec} eq 'y'; # default sort by IP on revzone record list
|
---|
[397] | 3501 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
| 3502 |
|
---|
[352] | 3503 | # sort reverse zones on IP, correctly
|
---|
[397] | 3504 | # do other fiddling with $args{sortby} while we're at it.
|
---|
[420] | 3505 | # whee! multisort means just passing comma-separated fields in sortby!
|
---|
| 3506 | my $newsort = '';
|
---|
| 3507 | foreach my $sf (split /,/, $args{sortby}) {
|
---|
| 3508 | $sf = "r.$sf";
|
---|
| 3509 | $sf =~ s/r\.val/CAST (r.val AS inet)/
|
---|
| 3510 | if $args{revrec} eq 'y' && $args{defrec} eq 'n';
|
---|
| 3511 | $sf =~ s/r\.type/t.alphaorder/;
|
---|
| 3512 | $newsort .= ",$sf";
|
---|
| 3513 | }
|
---|
| 3514 | $newsort =~ s/^,//;
|
---|
[352] | 3515 |
|
---|
[224] | 3516 | my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.ttl";
|
---|
[397] | 3517 | $sql .= ",l.description AS locname" if $args{defrec} eq 'n';
|
---|
| 3518 | $sql .= ",r.distance,r.weight,r.port" if $args{revrec} eq 'n';
|
---|
| 3519 | $sql .= " FROM "._rectable($args{defrec},$args{revrec})." r ";
|
---|
[104] | 3520 | $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
|
---|
[397] | 3521 | $sql .= "LEFT JOIN locations l ON r.location=l.location " if $args{defrec} eq 'n';
|
---|
| 3522 | $sql .= "WHERE "._recparent($args{defrec},$args{revrec})." = ?";
|
---|
[104] | 3523 | $sql .= " AND NOT r.type=$reverse_typemap{SOA}";
|
---|
[439] | 3524 | $sql .= " AND (r.host ~* ? OR r.val ~* ?)" if $args{filter};
|
---|
[420] | 3525 | $sql .= " ORDER BY $newsort $args{sortorder}";
|
---|
[324] | 3526 | # ensure consistent ordering by sorting on record_id too
|
---|
[397] | 3527 | $sql .= ", record_id $args{sortorder}";
|
---|
| 3528 | $sql .= ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
[4] | 3529 |
|
---|
[397] | 3530 | my @bindvars = ($args{id});
|
---|
[439] | 3531 | push @bindvars, ($args{filter},$args{filter}) if $args{filter};
|
---|
[224] | 3532 |
|
---|
[397] | 3533 | my $ret = $dbh->selectall_arrayref($sql, { Slice => {} }, (@bindvars) );
|
---|
[2] | 3534 | return $ret;
|
---|
| 3535 | } # end getDomRecs()
|
---|
| 3536 |
|
---|
| 3537 |
|
---|
[91] | 3538 | ## DNSDB::getRecCount()
|
---|
[224] | 3539 | # Return count of non-SOA records in zone (or default records in a group)
|
---|
| 3540 | # Takes a database handle, default/live flag, reverse/forward flag, group/domain ID,
|
---|
| 3541 | # and optional filtering modifier
|
---|
[91] | 3542 | # Returns the count
|
---|
| 3543 | sub getRecCount {
|
---|
[481] | 3544 | my $self = shift;
|
---|
| 3545 | my $dbh = $self->{dbh};
|
---|
[91] | 3546 | my $defrec = shift;
|
---|
[224] | 3547 | my $revrec = shift;
|
---|
[91] | 3548 | my $id = shift;
|
---|
[135] | 3549 | my $filter = shift || '';
|
---|
[91] | 3550 |
|
---|
[135] | 3551 | # keep the nasties down, since we can't ?-sub this bit. :/
|
---|
| 3552 | # note this is chars allowed in DNS hostnames
|
---|
| 3553 | $filter =~ s/[^a-zA-Z0-9_.:-]//g;
|
---|
| 3554 |
|
---|
[222] | 3555 | my @bindvars = ($id);
|
---|
| 3556 | push @bindvars, $filter if $filter;
|
---|
[224] | 3557 | my $sql = "SELECT count(*) FROM ".
|
---|
| 3558 | _rectable($defrec,$revrec).
|
---|
| 3559 | " WHERE "._recparent($defrec,$revrec)."=? ".
|
---|
| 3560 | "AND NOT type=$reverse_typemap{SOA}".
|
---|
| 3561 | ($filter ? " AND host ~* ?" : '');
|
---|
| 3562 | my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) );
|
---|
[91] | 3563 |
|
---|
| 3564 | return $count;
|
---|
| 3565 |
|
---|
| 3566 | } # end getRecCount()
|
---|
| 3567 |
|
---|
| 3568 |
|
---|
[3] | 3569 | ## DNSDB::addRec()
|
---|
[2] | 3570 | # Add a new record to a domain or a group's default records
|
---|
| 3571 | # Takes a database handle, default/live flag, group/domain ID,
|
---|
| 3572 | # host, type, value, and TTL
|
---|
| 3573 | # Some types require additional detail: "distance" for MX and SRV,
|
---|
| 3574 | # and weight/port for SRV
|
---|
| 3575 | # Returns a status code and detail message in case of error
|
---|
[234] | 3576 | ##fixme: pass a hash with the record data, not a series of separate values
|
---|
[2] | 3577 | sub addRec {
|
---|
| 3578 | $errstr = '';
|
---|
[481] | 3579 | my $self = shift;
|
---|
| 3580 | my $dbh = $self->{dbh};
|
---|
[2] | 3581 | my $defrec = shift;
|
---|
[226] | 3582 | my $revrec = shift;
|
---|
| 3583 | my $id = shift; # parent (group_id for defrecs, rdns_id for reverse records,
|
---|
| 3584 | # domain_id for domain records)
|
---|
[2] | 3585 |
|
---|
| 3586 | my $host = shift;
|
---|
[234] | 3587 | my $rectype = shift; # reference so we can coerce it if "+"-types can't find both zones
|
---|
[2] | 3588 | my $val = shift;
|
---|
| 3589 | my $ttl = shift;
|
---|
[389] | 3590 | my $location = shift;
|
---|
| 3591 | $location = '' if !$location;
|
---|
[2] | 3592 |
|
---|
[417] | 3593 | # Spaces are evil.
|
---|
| 3594 | $$host =~ s/^\s+//;
|
---|
| 3595 | $$host =~ s/\s+$//;
|
---|
[418] | 3596 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
[417] | 3597 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 3598 | $$val =~ s/^\s+//;
|
---|
| 3599 | $$val =~ s/\s+$//;
|
---|
| 3600 | }
|
---|
| 3601 |
|
---|
[226] | 3602 | # prep for validation
|
---|
[252] | 3603 | my $addr = NetAddr::IP->new($$val);
|
---|
| 3604 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
[226] | 3605 |
|
---|
| 3606 | my $domid = 0;
|
---|
| 3607 | my $revid = 0;
|
---|
| 3608 |
|
---|
| 3609 | my $retcode = 'OK'; # assume everything will go OK
|
---|
| 3610 | my $retmsg = '';
|
---|
| 3611 |
|
---|
| 3612 | # do simple validation first
|
---|
| 3613 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
|
---|
| 3614 |
|
---|
[234] | 3615 | # Quick check on hostname parts. Note the regex is more forgiving than the error message;
|
---|
| 3616 | # domain names technically are case-insensitive, and we use printf-like % codes for a couple
|
---|
| 3617 | # of types. Other things may also be added to validate default records of several flavours.
|
---|
| 3618 | return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z . _)")
|
---|
[350] | 3619 | if $defrec eq 'n' && ($revrec eq 'y' ? $$rectype != $reverse_typemap{TXT} : 1) &&
|
---|
| 3620 | $$host !~ /^[0-9a-z_%.-]+$/i;
|
---|
[226] | 3621 |
|
---|
[234] | 3622 | # Collect these even if we're only doing a simple A record so we can call *any* validation sub
|
---|
| 3623 | my $dist = shift;
|
---|
[281] | 3624 | my $weight = shift;
|
---|
[234] | 3625 | my $port = shift;
|
---|
[226] | 3626 |
|
---|
[234] | 3627 | my $fields;
|
---|
| 3628 | my @vallist;
|
---|
[226] | 3629 |
|
---|
[234] | 3630 | # Call the validation sub for the type requested.
|
---|
[481] | 3631 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec, id => $id,
|
---|
[249] | 3632 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
[234] | 3633 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
[481] | 3634 | fields => \$fields, vallist => \@vallist);
|
---|
[129] | 3635 |
|
---|
[234] | 3636 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
[209] | 3637 |
|
---|
[234] | 3638 | # Set up database fields and bind parameters
|
---|
[481] | 3639 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
| 3640 | push @vallist, ($$host,$$rectype,$$val,$ttl,$id);
|
---|
| 3641 |
|
---|
| 3642 | # locations are not for default records, silly coder!
|
---|
| 3643 | if ($defrec eq 'n') {
|
---|
| 3644 | $fields .= ",location";
|
---|
| 3645 | push @vallist, $location;
|
---|
| 3646 | }
|
---|
[234] | 3647 | my $vallen = '?'.(',?'x$#vallist);
|
---|
[2] | 3648 |
|
---|
[287] | 3649 | # Put together the success log entry. We have to use this horrible kludge
|
---|
| 3650 | # because domain_id and rdns_id may or may not be present, and if they are,
|
---|
| 3651 | # they're not at a guaranteed consistent index in the array. wheee!
|
---|
| 3652 | my %logdata;
|
---|
| 3653 | my @ftmp = split /,/, $fields;
|
---|
| 3654 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
| 3655 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
| 3656 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
| 3657 | }
|
---|
| 3658 | $logdata{group_id} = $id if $defrec eq 'y';
|
---|
[473] | 3659 | $logdata{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec)
|
---|
[287] | 3660 | if $defrec eq 'n';
|
---|
[328] | 3661 | $logdata{entry} = "Added ".($defrec eq 'y' ? 'default record' : 'record');
|
---|
| 3662 | # NS records for revzones get special treatment
|
---|
| 3663 | if ($revrec eq 'y' && $$rectype == 2) {
|
---|
| 3664 | $logdata{entry} .= " '$$val $typemap{$$rectype} $$host";
|
---|
| 3665 | } else {
|
---|
| 3666 | $logdata{entry} .= " '$$host $typemap{$$rectype} $$val";
|
---|
| 3667 | }
|
---|
| 3668 |
|
---|
[287] | 3669 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
| 3670 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]"
|
---|
| 3671 | if $typemap{$$rectype} eq 'SRV';
|
---|
[425] | 3672 | $logdata{entry} .= "', TTL $ttl";
|
---|
[480] | 3673 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location;
|
---|
[287] | 3674 |
|
---|
[90] | 3675 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3676 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3677 | local $dbh->{AutoCommit} = 0;
|
---|
| 3678 | local $dbh->{RaiseError} = 1;
|
---|
[2] | 3679 |
|
---|
[90] | 3680 | eval {
|
---|
[236] | 3681 | $dbh->do("INSERT INTO "._rectable($defrec, $revrec)." ($fields) VALUES ($vallen)",
|
---|
[90] | 3682 | undef, @vallist);
|
---|
[487] | 3683 | $self->_log(%logdata);
|
---|
[90] | 3684 | $dbh->commit;
|
---|
| 3685 | };
|
---|
| 3686 | if ($@) {
|
---|
| 3687 | my $msg = $@;
|
---|
| 3688 | eval { $dbh->rollback; };
|
---|
[289] | 3689 | if ($config{log_failures}) {
|
---|
| 3690 | $logdata{entry} = "Failed adding ".($defrec eq 'y' ? 'default ' : '').
|
---|
| 3691 | "record '$$host $typemap{$$rectype} $$val', TTL $ttl ($msg)";
|
---|
[487] | 3692 | $self->_log(%logdata);
|
---|
[289] | 3693 | $dbh->commit;
|
---|
| 3694 | }
|
---|
[90] | 3695 | return ('FAIL',$msg);
|
---|
| 3696 | }
|
---|
[2] | 3697 |
|
---|
[287] | 3698 | $resultstr = $logdata{entry};
|
---|
[226] | 3699 | return ($retcode, $retmsg);
|
---|
[90] | 3700 |
|
---|
[2] | 3701 | } # end addRec()
|
---|
| 3702 |
|
---|
| 3703 |
|
---|
[16] | 3704 | ## DNSDB::updateRec()
|
---|
| 3705 | # Update a record
|
---|
[273] | 3706 | # Takes a database handle, default and reverse flags, record ID, immediate parent ID, and new record data.
|
---|
| 3707 | # Returns a status code and message
|
---|
[16] | 3708 | sub updateRec {
|
---|
| 3709 | $errstr = '';
|
---|
[17] | 3710 |
|
---|
[481] | 3711 | my $self = shift;
|
---|
| 3712 | my $dbh = $self->{dbh};
|
---|
[16] | 3713 | my $defrec = shift;
|
---|
[272] | 3714 | my $revrec = shift;
|
---|
[16] | 3715 | my $id = shift;
|
---|
[272] | 3716 | my $parid = shift; # immediate parent entity that we're descending from to update the record
|
---|
[16] | 3717 |
|
---|
[273] | 3718 | # all records have these
|
---|
[16] | 3719 | my $host = shift;
|
---|
[272] | 3720 | my $hostbk = $$host; # Keep a backup copy of the original, so we can WARN if the update mangles the domain
|
---|
| 3721 | my $rectype = shift;
|
---|
[16] | 3722 | my $val = shift;
|
---|
| 3723 | my $ttl = shift;
|
---|
[389] | 3724 | my $location = shift; # may be empty/null/undef depending on caller
|
---|
| 3725 | $location = '' if !$location;
|
---|
[16] | 3726 |
|
---|
[417] | 3727 | # Spaces are evil.
|
---|
| 3728 | $$host =~ s/^\s+//;
|
---|
| 3729 | $$host =~ s/\s+$//;
|
---|
[418] | 3730 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
[417] | 3731 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 3732 | $$val =~ s/^\s+//;
|
---|
| 3733 | $$val =~ s/\s+$//;
|
---|
| 3734 | }
|
---|
| 3735 |
|
---|
[272] | 3736 | # prep for validation
|
---|
| 3737 | my $addr = NetAddr::IP->new($$val);
|
---|
| 3738 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
[16] | 3739 |
|
---|
[272] | 3740 | my $domid = 0;
|
---|
| 3741 | my $revid = 0;
|
---|
| 3742 |
|
---|
| 3743 | my $retcode = 'OK'; # assume everything will go OK
|
---|
| 3744 | my $retmsg = '';
|
---|
| 3745 |
|
---|
[273] | 3746 | # do simple validation first
|
---|
[272] | 3747 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
|
---|
| 3748 |
|
---|
| 3749 | # Quick check on hostname parts. Note the regex is more forgiving than the error message;
|
---|
| 3750 | # domain names technically are case-insensitive, and we use printf-like % codes for a couple
|
---|
| 3751 | # of types. Other things may also be added to validate default records of several flavours.
|
---|
[273] | 3752 | return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z - . _)")
|
---|
[350] | 3753 | if $defrec eq 'n' && ($revrec eq 'y' ? $$rectype != $reverse_typemap{TXT} : 1) &&
|
---|
| 3754 | $$host !~ /^[0-9a-z_%.-]+$/i;
|
---|
[272] | 3755 |
|
---|
[273] | 3756 | # only MX and SRV will use these
|
---|
[288] | 3757 | my $dist = shift || 0;
|
---|
| 3758 | my $weight = shift || 0;
|
---|
| 3759 | my $port = shift || 0;
|
---|
[16] | 3760 |
|
---|
[272] | 3761 | my $fields;
|
---|
| 3762 | my @vallist;
|
---|
[16] | 3763 |
|
---|
[273] | 3764 | # get old record data so we have the right parent ID
|
---|
| 3765 | # and for logging (eventually)
|
---|
[481] | 3766 | my $oldrec = $self->getRecLine($defrec, $revrec, $id);
|
---|
[223] | 3767 |
|
---|
[272] | 3768 | # Call the validation sub for the type requested.
|
---|
| 3769 | # Note the ID to pass here is the *parent*, not the record
|
---|
[481] | 3770 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec,
|
---|
[272] | 3771 | id => ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})),
|
---|
| 3772 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
| 3773 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
| 3774 | fields => \$fields, vallist => \@vallist,
|
---|
[481] | 3775 | update => $id);
|
---|
[272] | 3776 |
|
---|
| 3777 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
| 3778 |
|
---|
[273] | 3779 | # Set up database fields and bind parameters. Note only the optional fields
|
---|
| 3780 | # (distance, weight, port, secondary parent ID) are added in the validation call above
|
---|
[448] | 3781 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
| 3782 | push @vallist, ($$host,$$rectype,$$val,$ttl,
|
---|
[273] | 3783 | ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})) );
|
---|
[272] | 3784 |
|
---|
[448] | 3785 | # locations are not for default records, silly coder!
|
---|
| 3786 | if ($defrec eq 'n') {
|
---|
| 3787 | $fields .= ",location";
|
---|
| 3788 | push @vallist, $location;
|
---|
| 3789 | }
|
---|
| 3790 |
|
---|
[273] | 3791 | # hack hack PTHUI
|
---|
| 3792 | # need to forcibly make sure we disassociate a record with a parent it's no longer related to.
|
---|
| 3793 | # eg, PTR records may not have a domain parent, or A/AAAA records may not have a revzone parent.
|
---|
| 3794 | # mainly needed for crossover types that got coerced down to "standard" types
|
---|
| 3795 | if ($defrec eq 'n') {
|
---|
| 3796 | if ($$rectype == $reverse_typemap{PTR}) {
|
---|
| 3797 | $fields .= ",domain_id";
|
---|
| 3798 | push @vallist, 0;
|
---|
| 3799 | }
|
---|
| 3800 | if ($$rectype == $reverse_typemap{A} || $$rectype == $reverse_typemap{AAAA}) {
|
---|
| 3801 | $fields .= ",rdns_id";
|
---|
| 3802 | push @vallist, 0;
|
---|
| 3803 | }
|
---|
| 3804 | }
|
---|
[345] | 3805 | # fix fat-finger-originated record type changes
|
---|
| 3806 | if ($$rectype == 65285) {
|
---|
| 3807 | $fields .= ",rdns_id" if $revrec eq 'n';
|
---|
| 3808 | $fields .= ",domain_id" if $revrec eq 'y';
|
---|
| 3809 | push @vallist, 0;
|
---|
| 3810 | }
|
---|
[341] | 3811 | if ($defrec eq 'n') {
|
---|
| 3812 | $domid = $parid if $revrec eq 'n';
|
---|
| 3813 | $revid = $parid if $revrec eq 'y';
|
---|
| 3814 | }
|
---|
[272] | 3815 |
|
---|
[288] | 3816 | # Put together the success log entry. Horrible kludge from addRec() copied as-is since
|
---|
| 3817 | # we don't know whether the passed arguments or retrieved values for domain_id and rdns_id
|
---|
| 3818 | # will be maintained (due to "not-in-zone" validation changes)
|
---|
| 3819 | my %logdata;
|
---|
[341] | 3820 | $logdata{domain_id} = $domid;
|
---|
| 3821 | $logdata{rdns_id} = $revid;
|
---|
[288] | 3822 | my @ftmp = split /,/, $fields;
|
---|
| 3823 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
| 3824 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
| 3825 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
| 3826 | }
|
---|
| 3827 | $logdata{group_id} = $parid if $defrec eq 'y';
|
---|
[473] | 3828 | $logdata{group_id} = $self->parentID(id => $parid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec)
|
---|
[288] | 3829 | if $defrec eq 'n';
|
---|
[328] | 3830 | $logdata{entry} = "Updated ".($defrec eq 'y' ? 'default record' : 'record')." from\n";
|
---|
| 3831 | # NS records for revzones get special treatment
|
---|
| 3832 | if ($revrec eq 'y' && $$rectype == 2) {
|
---|
| 3833 | $logdata{entry} .= " '$oldrec->{val} $typemap{$oldrec->{type}} $oldrec->{host}";
|
---|
| 3834 | } else {
|
---|
| 3835 | $logdata{entry} .= " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
| 3836 | }
|
---|
[288] | 3837 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
| 3838 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
| 3839 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
[425] | 3840 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
[480] | 3841 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location};
|
---|
[425] | 3842 | $logdata{entry} .= "\nto\n";
|
---|
[328] | 3843 | # More NS special
|
---|
| 3844 | if ($revrec eq 'y' && $$rectype == 2) {
|
---|
| 3845 | $logdata{entry} .= "'$$val $typemap{$$rectype} $$host";
|
---|
| 3846 | } else {
|
---|
| 3847 | $logdata{entry} .= "'$$host $typemap{$$rectype} $$val";
|
---|
| 3848 | }
|
---|
[288] | 3849 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
| 3850 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$$rectype} eq 'SRV';
|
---|
[425] | 3851 | $logdata{entry} .= "', TTL $ttl";
|
---|
[480] | 3852 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location;
|
---|
[288] | 3853 |
|
---|
[90] | 3854 | local $dbh->{AutoCommit} = 0;
|
---|
| 3855 | local $dbh->{RaiseError} = 1;
|
---|
| 3856 |
|
---|
[341] | 3857 | # Fiddle the field list into something suitable for updates
|
---|
| 3858 | $fields =~ s/,/=?,/g;
|
---|
| 3859 | $fields .= "=?";
|
---|
| 3860 |
|
---|
[90] | 3861 | eval {
|
---|
[273] | 3862 | $dbh->do("UPDATE "._rectable($defrec,$revrec)." SET $fields WHERE record_id=?", undef, (@vallist, $id) );
|
---|
[487] | 3863 | $self->_log(%logdata);
|
---|
[130] | 3864 | $dbh->commit;
|
---|
[90] | 3865 | };
|
---|
| 3866 | if ($@) {
|
---|
| 3867 | my $msg = $@;
|
---|
[288] | 3868 | eval { $dbh->rollback; };
|
---|
[289] | 3869 | if ($config{log_failures}) {
|
---|
| 3870 | $logdata{entry} = "Failed updating ".($defrec eq 'y' ? 'default ' : '').
|
---|
| 3871 | "record '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
[487] | 3872 | $self->_log(%logdata);
|
---|
[289] | 3873 | $dbh->commit;
|
---|
| 3874 | }
|
---|
[90] | 3875 | return ('FAIL', $msg);
|
---|
| 3876 | }
|
---|
| 3877 |
|
---|
[288] | 3878 | $resultstr = $logdata{entry};
|
---|
[272] | 3879 | return ($retcode, $retmsg);
|
---|
[16] | 3880 | } # end updateRec()
|
---|
| 3881 |
|
---|
| 3882 |
|
---|
[459] | 3883 | ## DNSDB::downconvert()
|
---|
| 3884 | # A mostly internal (not exported) semiutilty sub to downconvert from pseudotype <x>
|
---|
| 3885 | # to a compatible component type. Only a handful of operations are valid, anything
|
---|
| 3886 | # else is a null-op.
|
---|
| 3887 | # Takes the record ID and the new type. Returns boolean.
|
---|
| 3888 | sub downconvert {
|
---|
[481] | 3889 | my $self = shift;
|
---|
| 3890 | my $dbh = $self->{dbh};
|
---|
[459] | 3891 | my $recid = shift;
|
---|
| 3892 | my $newtype = shift;
|
---|
| 3893 |
|
---|
| 3894 | # also, only work on live records; little to no value trying to do this on default records.
|
---|
[481] | 3895 | my $rec = $self->getRecLine('n', 'y', $recid);
|
---|
[459] | 3896 |
|
---|
| 3897 | # hm?
|
---|
| 3898 | #return 1 if !$rec;
|
---|
| 3899 |
|
---|
| 3900 | return 1 if $rec->{type} < 65000; # Only the reverse-record pseudotypes can be downconverted
|
---|
| 3901 | return 1 if $rec->{type} == 65282; # Nowhere to go
|
---|
| 3902 |
|
---|
| 3903 | my $delpar;
|
---|
| 3904 | my @sqlargs;
|
---|
| 3905 | if ($rec->{type} == 65280) {
|
---|
| 3906 | return 1 if $newtype != 1 && $newtype != 12;
|
---|
| 3907 | $delpar = ($newtype == 1 ? 'rdns_id' : 'domain_id');
|
---|
| 3908 | push @sqlargs, 0, $newtype, $recid;
|
---|
| 3909 | } elsif ($rec->{type} == 65281) {
|
---|
| 3910 | return 1 if $newtype != 28 && $newtype != 12;
|
---|
| 3911 | $delpar = ($newtype == 28 ? 'rdns_id' : 'domain_id');
|
---|
| 3912 | push @sqlargs, 0, $newtype, $recid;
|
---|
| 3913 | } elsif ($rec->{type} == 65283) {
|
---|
| 3914 | return 1 if $newtype != 65282;
|
---|
| 3915 | $delpar = 'rdns_id';
|
---|
| 3916 | } elsif ($rec->{type} == 65284) {
|
---|
| 3917 | return 1 if $newtype != 65282;
|
---|
| 3918 | $delpar = 'rdns_id';
|
---|
| 3919 | } else {
|
---|
| 3920 | # Your llama is on fire.
|
---|
| 3921 | }
|
---|
| 3922 |
|
---|
| 3923 | local $dbh->{AutoCommit} = 0;
|
---|
| 3924 | local $dbh->{RaiseError} = 1;
|
---|
| 3925 |
|
---|
| 3926 | eval {
|
---|
| 3927 | $dbh->do("UPDATE records SET $delpar = ?, type = ? WHERE record_id = ?", undef, @sqlargs);
|
---|
| 3928 | $dbh->commit;
|
---|
| 3929 | };
|
---|
| 3930 | if ($@) {
|
---|
| 3931 | $errstr = $@;
|
---|
| 3932 | eval { $dbh->rollback; };
|
---|
| 3933 | return 0;
|
---|
| 3934 | }
|
---|
| 3935 | return 1;
|
---|
| 3936 | } # end downconvert()
|
---|
| 3937 |
|
---|
| 3938 |
|
---|
[3] | 3939 | ## DNSDB::delRec()
|
---|
| 3940 | # Delete a record.
|
---|
| 3941 | sub delRec {
|
---|
| 3942 | $errstr = '';
|
---|
[481] | 3943 | my $self = shift;
|
---|
| 3944 | my $dbh = $self->{dbh};
|
---|
[3] | 3945 | my $defrec = shift;
|
---|
[243] | 3946 | my $revrec = shift;
|
---|
[3] | 3947 | my $id = shift;
|
---|
| 3948 |
|
---|
[481] | 3949 | my $oldrec = $self->getRecLine($defrec, $revrec, $id);
|
---|
[3] | 3950 |
|
---|
[290] | 3951 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3952 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3953 | local $dbh->{AutoCommit} = 0;
|
---|
| 3954 | local $dbh->{RaiseError} = 1;
|
---|
[3] | 3955 |
|
---|
[290] | 3956 | # Put together the log entry
|
---|
| 3957 | my %logdata;
|
---|
| 3958 | $logdata{domain_id} = $oldrec->{domain_id};
|
---|
| 3959 | $logdata{rdns_id} = $oldrec->{rdns_id};
|
---|
| 3960 | $logdata{group_id} = $oldrec->{group_id} if $defrec eq 'y';
|
---|
[473] | 3961 | $logdata{group_id} = $self->parentID(id => $oldrec->{domain_id}, type => ($revrec eq 'n' ? 'domain' : 'revzone'),
|
---|
| 3962 | revrec => $revrec)
|
---|
[290] | 3963 | if $defrec eq 'n';
|
---|
| 3964 | $logdata{entry} = "Deleted ".($defrec eq 'y' ? 'default record ' : 'record ').
|
---|
| 3965 | "'$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
| 3966 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
| 3967 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
| 3968 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
[425] | 3969 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
[480] | 3970 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location};
|
---|
[290] | 3971 |
|
---|
| 3972 | eval {
|
---|
| 3973 | my $sth = $dbh->do("DELETE FROM "._rectable($defrec,$revrec)." WHERE record_id=?", undef, ($id));
|
---|
[487] | 3974 | $self->_log(%logdata);
|
---|
[290] | 3975 | $dbh->commit;
|
---|
| 3976 | };
|
---|
| 3977 | if ($@) {
|
---|
| 3978 | my $msg = $@;
|
---|
| 3979 | eval { $dbh->rollback; };
|
---|
| 3980 | if ($config{log_failures}) {
|
---|
| 3981 | $logdata{entry} = "Error deleting ".($defrec eq 'y' ? 'default record' : 'record').
|
---|
| 3982 | " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
[487] | 3983 | $self->_log(%logdata);
|
---|
[290] | 3984 | $dbh->commit;
|
---|
| 3985 | }
|
---|
| 3986 | return ('FAIL', $msg);
|
---|
| 3987 | }
|
---|
| 3988 |
|
---|
| 3989 | return ('OK',$logdata{entry});
|
---|
[3] | 3990 | } # end delRec()
|
---|
| 3991 |
|
---|
| 3992 |
|
---|
[323] | 3993 | ## DNSDB::getLogCount()
|
---|
| 3994 | # Get a count of log entries
|
---|
| 3995 | # Takes a database handle and a hash containing at least:
|
---|
| 3996 | # - Entity ID and entity type as the primary log "slice"
|
---|
| 3997 | sub getLogCount {
|
---|
[483] | 3998 | my $self = shift;
|
---|
| 3999 | my $dbh = $self->{dbh};
|
---|
[323] | 4000 |
|
---|
| 4001 | my %args = @_;
|
---|
| 4002 |
|
---|
| 4003 | my @filterargs;
|
---|
| 4004 | ##fixme: which fields do we want to filter on?
|
---|
| 4005 | # push @filterargs,
|
---|
| 4006 |
|
---|
| 4007 | $errstr = 'Missing primary parent ID and/or type';
|
---|
| 4008 | # fail early if we don't have a "prime" ID to look for log entries for
|
---|
| 4009 | return if !$args{id};
|
---|
| 4010 |
|
---|
| 4011 | # or if the prime id type is missing or invalid
|
---|
| 4012 | return if !$args{logtype};
|
---|
| 4013 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
| 4014 | $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
|
---|
| 4015 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
|
---|
| 4016 |
|
---|
| 4017 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
| 4018 |
|
---|
| 4019 | my $sql = "SELECT count(*) FROM log ".
|
---|
| 4020 | "WHERE $id_col{$args{logtype}}=?".
|
---|
| 4021 | ($args{filter} ? " AND entry ~* ?" : '');
|
---|
| 4022 | my ($count) = $dbh->selectrow_array($sql, undef, ($args{id}, @filterargs) );
|
---|
| 4023 | $errstr = $dbh->errstr if !$count;
|
---|
| 4024 | return $count;
|
---|
| 4025 | } # end getLogCount()
|
---|
| 4026 |
|
---|
| 4027 |
|
---|
| 4028 | ## DNSDB::getLogEntries()
|
---|
| 4029 | # Get a list of log entries
|
---|
| 4030 | # Takes arguments as with getLogCount() above, plus optional:
|
---|
| 4031 | # - sort field
|
---|
| 4032 | # - sort order
|
---|
| 4033 | # - offset for pagination
|
---|
| 4034 | sub getLogEntries {
|
---|
[483] | 4035 | my $self = shift;
|
---|
| 4036 | my $dbh = $self->{dbh};
|
---|
[323] | 4037 |
|
---|
| 4038 | my %args = @_;
|
---|
| 4039 |
|
---|
| 4040 | my @filterargs;
|
---|
| 4041 |
|
---|
| 4042 | # fail early if we don't have a "prime" ID to look for log entries for
|
---|
| 4043 | return if !$args{id};
|
---|
| 4044 |
|
---|
| 4045 | # or if the prime id type is missing or invalid
|
---|
| 4046 | return if !$args{logtype};
|
---|
| 4047 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
| 4048 | $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
|
---|
| 4049 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
|
---|
| 4050 |
|
---|
| 4051 | # Sorting defaults
|
---|
| 4052 | $args{sortby} = 'stamp' if !$args{sortby};
|
---|
| 4053 | $args{sortorder} = 'DESC' if !$args{sortorder};
|
---|
[397] | 4054 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[323] | 4055 |
|
---|
[324] | 4056 | my %sortmap = (fname => 'name', username => 'email', entry => 'entry', stamp => 'stamp');
|
---|
[323] | 4057 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 4058 |
|
---|
| 4059 | my $sql = "SELECT user_id AS userid, email AS useremail, name AS userfname, entry AS logentry, ".
|
---|
| 4060 | "date_trunc('second',stamp) AS logtime ".
|
---|
| 4061 | "FROM log ".
|
---|
| 4062 | "WHERE $id_col{$args{logtype}}=?".
|
---|
| 4063 | ($args{filter} ? " AND entry ~* ?" : '').
|
---|
[324] | 4064 | " ORDER BY $args{sortby} $args{sortorder}, log_id $args{sortorder}".
|
---|
[323] | 4065 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
| 4066 | my $loglist = $dbh->selectall_arrayref($sql, { Slice => {} }, ($args{id}, @filterargs) );
|
---|
| 4067 | $errstr = $dbh->errstr if !$loglist;
|
---|
| 4068 | return $loglist;
|
---|
| 4069 | } # end getLogEntries()
|
---|
| 4070 |
|
---|
| 4071 |
|
---|
[452] | 4072 | ## IPDB::getRevPattern()
|
---|
| 4073 | # Get the narrowest template pattern applicable to a passed CIDR address (may be a netblock or an IP)
|
---|
| 4074 | sub getRevPattern {
|
---|
[483] | 4075 | my $self = shift;
|
---|
| 4076 | my $dbh = $self->{dbh};
|
---|
[452] | 4077 | my $cidr = shift;
|
---|
| 4078 | my $group = shift || 1; # just in case
|
---|
| 4079 |
|
---|
[462] | 4080 | # for speed! Casting and comparing even ~7K records takes ~2.5s, so narrow it down to one revzone first.
|
---|
| 4081 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >>= ? AND group_id = ?",
|
---|
| 4082 | undef, ($cidr, $group) );
|
---|
| 4083 |
|
---|
| 4084 | ##fixme? may need to narrow things down more by octet-chopping and doing text comparisons before casting.
|
---|
| 4085 | my ($revpatt) = $dbh->selectrow_array("SELECT host FROM records ".
|
---|
| 4086 | "WHERE (type in (12,65280,65281,65282,65283,65284)) AND rdns_id = ? AND CAST (val AS inet) >>= ? ".
|
---|
| 4087 | "ORDER BY CAST (val AS inet) DESC LIMIT 1", undef, ($revid, $cidr) );
|
---|
[452] | 4088 | return $revpatt;
|
---|
| 4089 | } # end getRevPattern()
|
---|
| 4090 |
|
---|
| 4091 |
|
---|
[225] | 4092 | ## DNSDB::getTypelist()
|
---|
| 4093 | # Get a list of record types for various UI dropdowns
|
---|
| 4094 | # Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A)
|
---|
| 4095 | # Returns an arrayref to list of hashrefs perfect for HTML::Template
|
---|
| 4096 | sub getTypelist {
|
---|
[483] | 4097 | my $self = shift;
|
---|
| 4098 | my $dbh = $self->{dbh};
|
---|
[225] | 4099 | my $recgroup = shift;
|
---|
| 4100 | my $type = shift || $reverse_typemap{A};
|
---|
| 4101 |
|
---|
| 4102 | # also accepting $webvar{revrec}!
|
---|
| 4103 | $recgroup = 'f' if $recgroup eq 'n';
|
---|
| 4104 | $recgroup = 'r' if $recgroup eq 'y';
|
---|
| 4105 |
|
---|
| 4106 | my $sql = "SELECT val,name FROM rectypes WHERE ";
|
---|
| 4107 | if ($recgroup eq 'r') {
|
---|
| 4108 | # reverse zone types
|
---|
| 4109 | $sql .= "stdflag=2 OR stdflag=3";
|
---|
| 4110 | } elsif ($recgroup eq 'l') {
|
---|
| 4111 | # DNS lookup types. Note we avoid our custom types >= 65280, since those are entirely internal.
|
---|
| 4112 | $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280";
|
---|
| 4113 | } else {
|
---|
| 4114 | # default; forward zone types. technically $type eq 'f' but not worth the error message.
|
---|
| 4115 | $sql .= "stdflag=1 OR stdflag=2";
|
---|
| 4116 | }
|
---|
| 4117 | $sql .= " ORDER BY listorder";
|
---|
| 4118 |
|
---|
| 4119 | my $sth = $dbh->prepare($sql);
|
---|
| 4120 | $sth->execute;
|
---|
| 4121 | my @typelist;
|
---|
| 4122 | while (my ($rval,$rname) = $sth->fetchrow_array()) {
|
---|
| 4123 | my %row = ( recval => $rval, recname => $rname );
|
---|
| 4124 | $row{tselect} = 1 if $rval == $type;
|
---|
| 4125 | push @typelist, \%row;
|
---|
| 4126 | }
|
---|
| 4127 |
|
---|
| 4128 | # Add SOA on lookups since it's not listed in other dropdowns.
|
---|
| 4129 | if ($recgroup eq 'l') {
|
---|
| 4130 | my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
|
---|
| 4131 | $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
|
---|
| 4132 | push @typelist, \%row;
|
---|
| 4133 | }
|
---|
| 4134 |
|
---|
| 4135 | return \@typelist;
|
---|
| 4136 | } # end getTypelist()
|
---|
| 4137 |
|
---|
| 4138 |
|
---|
[254] | 4139 | ## DNSDB::parentID()
|
---|
| 4140 | # Get ID of entity that is nearest parent to requested id
|
---|
| 4141 | # Takes a database handle and a hash of entity ID, entity type, optional parent type flag
|
---|
| 4142 | # (domain/reverse zone or group), and optional default/live and forward/reverse flags
|
---|
| 4143 | # Returns the ID or undef on failure
|
---|
| 4144 | sub parentID {
|
---|
[473] | 4145 | my $self = shift;
|
---|
| 4146 | my $dbh = $self->{dbh};
|
---|
[116] | 4147 |
|
---|
[254] | 4148 | my %args = @_;
|
---|
[116] | 4149 |
|
---|
[254] | 4150 | # clean up the parent-type. Set it to group if not set; coerce revzone to domain for simpler logic
|
---|
| 4151 | $args{partype} = 'group' if !$args{partype};
|
---|
| 4152 | $args{partype} = 'domain' if $args{partype} eq 'revzone';
|
---|
[116] | 4153 |
|
---|
[254] | 4154 | # clean up defrec and revrec. default to live record, forward zone
|
---|
| 4155 | $args{defrec} = 'n' if !$args{defrec};
|
---|
| 4156 | $args{revrec} = 'n' if !$args{revrec};
|
---|
[116] | 4157 |
|
---|
[254] | 4158 | if ($par_type{$args{partype}} eq 'domain') {
|
---|
| 4159 | # only live records can have a domain/zone parent
|
---|
| 4160 | return unless ($args{type} eq 'record' && $args{defrec} eq 'n');
|
---|
| 4161 | my $result = $dbh->selectrow_hashref("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
| 4162 | " FROM records WHERE record_id = ?",
|
---|
| 4163 | undef, ($args{id}) ) or return;
|
---|
| 4164 | return $result;
|
---|
| 4165 | } else {
|
---|
| 4166 | # snag some arguments that will either fall through or be overwritten to save some code duplication
|
---|
| 4167 | my $tmpid = $args{id};
|
---|
| 4168 | my $type = $args{type};
|
---|
| 4169 | if ($type eq 'record' && $args{defrec} eq 'n') {
|
---|
| 4170 | # Live records go through the records table first.
|
---|
| 4171 | ($tmpid) = $dbh->selectrow_array("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
| 4172 | " FROM records WHERE record_id = ?",
|
---|
| 4173 | undef, ($args{id}) ) or return;
|
---|
| 4174 | $type = ($args{revrec} eq 'n' ? 'domain' : 'revzone');
|
---|
| 4175 | }
|
---|
| 4176 | my ($result) = $dbh->selectrow_array("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
|
---|
| 4177 | undef, ($tmpid) );
|
---|
| 4178 | return $result;
|
---|
| 4179 | }
|
---|
| 4180 | # should be impossible to get here with even remotely sane arguments
|
---|
| 4181 | return;
|
---|
| 4182 | } # end parentID()
|
---|
[116] | 4183 |
|
---|
| 4184 |
|
---|
[117] | 4185 | ## DNSDB::isParent()
|
---|
| 4186 | # Returns true if $id1 is a parent of $id2, false otherwise
|
---|
| 4187 | sub isParent {
|
---|
[470] | 4188 | my $self = shift;
|
---|
| 4189 | my $dbh = $self->{dbh};
|
---|
[117] | 4190 | my $id1 = shift;
|
---|
| 4191 | my $type1 = shift;
|
---|
| 4192 | my $id2 = shift;
|
---|
| 4193 | my $type2 = shift;
|
---|
| 4194 | ##todo: immediate, secondary, full (default)
|
---|
| 4195 |
|
---|
[157] | 4196 | # Return false on invalid types
|
---|
[244] | 4197 | return 0 if !grep /^$type1$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
| 4198 | return 0 if !grep /^$type2$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
[157] | 4199 |
|
---|
[117] | 4200 | # Return false on impossible relations
|
---|
| 4201 | return 0 if $type1 eq 'record'; # nothing may be a child of a record
|
---|
| 4202 | return 0 if $type1 eq 'defrec'; # nothing may be a child of a record
|
---|
[244] | 4203 | return 0 if $type1 eq 'defrevrec'; # nothing may be a child of a record
|
---|
[117] | 4204 | return 0 if $type1 eq 'user'; # nothing may be child of a user
|
---|
| 4205 | return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record
|
---|
[244] | 4206 | return 0 if $type1 eq 'revzone' && $type2 ne 'record';# reverse zone may not be a parent of anything other than a record
|
---|
[117] | 4207 |
|
---|
[186] | 4208 | # ennnhhhh.... if we're passed an id of 0, it will never be found. usual
|
---|
| 4209 | # case would be the UI creating a new <thing>, and so we don't have an ID for
|
---|
| 4210 | # <thing> to look up yet. in that case the UI should check the parent as well.
|
---|
| 4211 | return 0 if $id1 == 0; # nothing can have a parent id of 0
|
---|
| 4212 | return 1 if $id2 == 0; # anything could have a child id of 0 (or "unknown")
|
---|
| 4213 |
|
---|
[117] | 4214 | # group 1 is the ultimate root parent
|
---|
| 4215 | return 1 if $type1 eq 'group' && $id1 == 1;
|
---|
| 4216 |
|
---|
[155] | 4217 | # groups are always (a) parent of themselves
|
---|
| 4218 | return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2;
|
---|
| 4219 |
|
---|
[117] | 4220 | my $id = $id2;
|
---|
| 4221 | my $type = $type2;
|
---|
| 4222 | my $foundparent = 0;
|
---|
[155] | 4223 |
|
---|
[244] | 4224 | # Records are the only entity with two possible parents. We need to split the parent checks on
|
---|
| 4225 | # domain/rdns.
|
---|
| 4226 | if ($type eq 'record') {
|
---|
| 4227 | my ($dom,$rdns) = $dbh->selectrow_array("SELECT domain_id,rdns_id FROM records WHERE record_id=?",
|
---|
| 4228 | undef, ($id));
|
---|
| 4229 | # check immediate parent against request
|
---|
| 4230 | return 1 if $type1 eq 'domain' && $id1 == $dom;
|
---|
| 4231 | return 1 if $type1 eq 'revzone' && $id1 == $rdns;
|
---|
| 4232 | # if request is group, check *both* parents. Only check if the parent is nonzero though.
|
---|
[470] | 4233 | return 1 if $dom && $self->isParent($id1, $type1, $dom, 'domain');
|
---|
| 4234 | return 1 if $rdns && $self->isParent($id1, $type1, $rdns, 'revzone');
|
---|
[244] | 4235 | # exit here since we've executed the loop below by proxy in the above recursive calls.
|
---|
| 4236 | return 0;
|
---|
| 4237 | }
|
---|
| 4238 |
|
---|
| 4239 | # almost the same loop as getParents() above
|
---|
[186] | 4240 | my $limiter = 0;
|
---|
[117] | 4241 | while (1) {
|
---|
[155] | 4242 | my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
|
---|
[117] | 4243 | my $result = $dbh->selectrow_hashref($sql,
|
---|
[157] | 4244 | undef, ($id) );
|
---|
[186] | 4245 | if (!$result) {
|
---|
| 4246 | $limiter++;
|
---|
[244] | 4247 | ##fixme: how often will this happen on a live site? fail at max limiter <n>?
|
---|
[186] | 4248 | warn "no results looking for $sql with id $id (depth $limiter)\n";
|
---|
| 4249 | last;
|
---|
| 4250 | }
|
---|
[157] | 4251 | if ($result && $result->{$par_col{$type}} == $id1) {
|
---|
[117] | 4252 | $foundparent = 1;
|
---|
| 4253 | last;
|
---|
[157] | 4254 | } else {
|
---|
| 4255 | ##fixme: do we care about trying to return a "no such record/domain/user/group" error?
|
---|
[244] | 4256 | # should be impossible to create an inconsistent DB just with API calls.
|
---|
[157] | 4257 | warn $dbh->errstr." $sql, $id" if $dbh->errstr;
|
---|
[117] | 4258 | }
|
---|
| 4259 | # group 1 is its own parent. need this here more to break strange loops than for detecting a parent
|
---|
| 4260 | last if $result->{$par_col{$type}} == 1;
|
---|
[152] | 4261 | $id = $result->{$par_col{$type}};
|
---|
[117] | 4262 | $type = $par_type{$type};
|
---|
| 4263 | }
|
---|
| 4264 |
|
---|
| 4265 | return $foundparent;
|
---|
| 4266 | } # end isParent()
|
---|
| 4267 |
|
---|
| 4268 |
|
---|
[275] | 4269 | ## DNSDB::zoneStatus()
|
---|
| 4270 | # Returns and optionally sets a zone's status
|
---|
| 4271 | # Takes a database handle, domain/revzone ID, forward/reverse flag, and optionally a status argument
|
---|
| 4272 | # Returns status, or undef on errors.
|
---|
| 4273 | sub zoneStatus {
|
---|
[477] | 4274 | my $self = shift;
|
---|
| 4275 | my $dbh = $self->{dbh};
|
---|
[3] | 4276 | my $id = shift;
|
---|
[275] | 4277 | my $revrec = shift;
|
---|
| 4278 | my $newstatus = shift || 'mu';
|
---|
[3] | 4279 |
|
---|
| 4280 | return undef if $id !~ /^\d+$/;
|
---|
| 4281 |
|
---|
[283] | 4282 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4283 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4284 | local $dbh->{AutoCommit} = 0;
|
---|
| 4285 | local $dbh->{RaiseError} = 1;
|
---|
| 4286 |
|
---|
[275] | 4287 | if ($newstatus ne 'mu') {
|
---|
[283] | 4288 | # ooo, fun! let's see what we were passed for status
|
---|
| 4289 | eval {
|
---|
| 4290 | $newstatus = 0 if $newstatus eq 'domoff';
|
---|
| 4291 | $newstatus = 1 if $newstatus eq 'domon';
|
---|
| 4292 | $dbh->do("UPDATE ".($revrec eq 'n' ? 'domains' : 'revzones')." SET status=? WHERE ".
|
---|
[275] | 4293 | ($revrec eq 'n' ? 'domain_id' : 'rdns_id')."=?", undef, ($newstatus,$id) );
|
---|
[283] | 4294 |
|
---|
| 4295 | ##fixme switch to more consise "Enabled <domain"/"Disabled <domain>" as with users?
|
---|
[473] | 4296 | $resultstr = "Changed ".($revrec eq 'n' ? $self->domainName($id) : $self->revName($id)).
|
---|
[283] | 4297 | " state to ".($newstatus ? 'active' : 'inactive');
|
---|
| 4298 |
|
---|
| 4299 | my %loghash;
|
---|
| 4300 | $loghash{domain_id} = $id if $revrec eq 'n';
|
---|
| 4301 | $loghash{rdns_id} = $id if $revrec eq 'y';
|
---|
[473] | 4302 | $loghash{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec);
|
---|
[283] | 4303 | $loghash{entry} = $resultstr;
|
---|
[487] | 4304 | $self->_log(%loghash);
|
---|
[283] | 4305 |
|
---|
| 4306 | $dbh->commit;
|
---|
| 4307 | };
|
---|
| 4308 | if ($@) {
|
---|
| 4309 | my $msg = $@;
|
---|
| 4310 | eval { $dbh->rollback; };
|
---|
| 4311 | $resultstr = '';
|
---|
| 4312 | $errstr = $msg;
|
---|
| 4313 | return;
|
---|
| 4314 | }
|
---|
[3] | 4315 | }
|
---|
| 4316 |
|
---|
[275] | 4317 | my ($status) = $dbh->selectrow_array("SELECT status FROM ".
|
---|
| 4318 | ($revrec eq 'n' ? "domains WHERE domain_id=?" : "revzones WHERE rdns_id=?"),
|
---|
| 4319 | undef, ($id) );
|
---|
[3] | 4320 | return $status;
|
---|
[275] | 4321 | } # end zoneStatus()
|
---|
[3] | 4322 |
|
---|
| 4323 |
|
---|
[452] | 4324 | ## DNSDB::getZonesByCIDR()
|
---|
| 4325 | # Get a list of zone names and IDs that records for a passed CIDR block are within.
|
---|
| 4326 | sub getZonesByCIDR {
|
---|
[477] | 4327 | my $self = shift;
|
---|
| 4328 | my $dbh = $self->{dbh};
|
---|
[452] | 4329 | my %args = @_;
|
---|
| 4330 |
|
---|
| 4331 | my $result = $dbh->selectall_arrayref("SELECT rdns_id,revnet FROM revzones WHERE revnet >>= ? OR revnet <<= ?",
|
---|
| 4332 | { Slice => {} }, ($args{cidr}, $args{cidr}) );
|
---|
| 4333 | return $result;
|
---|
| 4334 | } # end getZonesByCIDR()
|
---|
| 4335 |
|
---|
| 4336 |
|
---|
[33] | 4337 | ## DNSDB::importAXFR
|
---|
| 4338 | # Import a domain via AXFR
|
---|
[37] | 4339 | # Takes AXFR host, domain to transfer, group to put the domain in,
|
---|
[484] | 4340 | # and an optional hash containing:
|
---|
| 4341 | # status - active/inactive state flag (defaults to active)
|
---|
| 4342 | # rwsoa - overwrite-SOA flag (defaults to off)
|
---|
| 4343 | # rwns - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
|
---|
| 4344 | # merge - flag to automerge A or AAAA records with matching PTR records
|
---|
[37] | 4345 | # Returns a status code (OK, WARN, or FAIL) and message - message should be blank
|
---|
| 4346 | # if status is OK, but WARN includes conditions that are not fatal but should
|
---|
| 4347 | # really be reported.
|
---|
[33] | 4348 | sub importAXFR {
|
---|
[484] | 4349 | my $self = shift;
|
---|
| 4350 | my $dbh = $self->{dbh};
|
---|
[35] | 4351 | my $ifrom_in = shift;
|
---|
[301] | 4352 | my $zone = shift;
|
---|
[33] | 4353 | my $group = shift;
|
---|
[484] | 4354 |
|
---|
| 4355 | my %args = @_;
|
---|
| 4356 |
|
---|
[33] | 4357 | ##fixme: add mode to delete&replace, merge+overwrite, merge new?
|
---|
| 4358 |
|
---|
[484] | 4359 | $args{status} = (defined($args{status}) ? $args{status} : 0);
|
---|
| 4360 | $args{status} = 1 if $args{status} eq 'on';
|
---|
| 4361 |
|
---|
[37] | 4362 | my $nrecs = 0;
|
---|
| 4363 | my $soaflag = 0;
|
---|
| 4364 | my $nsflag = 0;
|
---|
| 4365 | my $warnmsg = '';
|
---|
| 4366 | my $ifrom;
|
---|
[33] | 4367 |
|
---|
[301] | 4368 | my $rev = 'n';
|
---|
[302] | 4369 | my $code = 'OK';
|
---|
| 4370 | my $msg = 'foobar?';
|
---|
[301] | 4371 |
|
---|
[35] | 4372 | # choke on possible bad setting in ifrom
|
---|
[37] | 4373 | # IPv4 and v6, and valid hostnames!
|
---|
[35] | 4374 | ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
| 4375 | return ('FAIL', "Bad AXFR source host $ifrom")
|
---|
| 4376 | unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
| 4377 |
|
---|
[301] | 4378 | my $errmsg;
|
---|
| 4379 |
|
---|
| 4380 | my $zone_id;
|
---|
| 4381 | my $domain_id = 0;
|
---|
| 4382 | my $rdns_id = 0;
|
---|
| 4383 | my $cidr;
|
---|
| 4384 |
|
---|
| 4385 | # magic happens! detect if we're importing a domain or a reverse zone
|
---|
| 4386 | # while we're at it, figure out what the CIDR netblock is (if we got a .arpa)
|
---|
| 4387 | # or what the formal .arpa zone is (if we got a CIDR netblock)
|
---|
| 4388 | # Handles sub-octet v4 zones in the format specified in the Cricket Book, 2nd Ed, p217-218
|
---|
| 4389 |
|
---|
| 4390 | if ($zone =~ m{(?:\.arpa\.?|/\d+)$}) {
|
---|
| 4391 | # we seem to have a reverse zone
|
---|
| 4392 | $rev = 'y';
|
---|
| 4393 |
|
---|
| 4394 | if ($zone =~ /\.arpa\.?$/) {
|
---|
| 4395 | # we have a formal reverse zone. call _zone2cidr and get the CIDR block.
|
---|
| 4396 | ($code,$msg) = _zone2cidr($zone);
|
---|
| 4397 | return ($code, $msg) if $code eq 'FAIL';
|
---|
| 4398 | $cidr = $msg;
|
---|
| 4399 | } elsif ($zone =~ m|^[\d.]+/\d+$|) {
|
---|
| 4400 | # v4 revzone, CIDR netblock
|
---|
| 4401 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 4402 | $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
| 4403 | } elsif ($zone =~ m|^[a-fA-F\d:]+/\d+$|) {
|
---|
| 4404 | # v6 revzone, CIDR netblock
|
---|
| 4405 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 4406 | return ('FAIL', "$zone is not a nibble-aligned block") if $cidr->masklen % 4 != 0;
|
---|
| 4407 | $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.');
|
---|
| 4408 | } else {
|
---|
| 4409 | # there is. no. else!
|
---|
| 4410 | return ('FAIL', "Unknown zone name format");
|
---|
| 4411 | }
|
---|
| 4412 |
|
---|
| 4413 | # quick check to start to see if we've already got one
|
---|
| 4414 |
|
---|
| 4415 | ($zone_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?",
|
---|
| 4416 | undef, ("$cidr"));
|
---|
| 4417 | $rdns_id = $zone_id;
|
---|
| 4418 | } else {
|
---|
| 4419 | # default to domain
|
---|
[349] | 4420 | ($zone_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
[301] | 4421 | undef, ($zone));
|
---|
| 4422 | $domain_id = $zone_id;
|
---|
| 4423 | }
|
---|
| 4424 |
|
---|
| 4425 | return ('FAIL', ($rev eq 'n' ? 'Domain' : 'Reverse zone')." already exists") if $zone_id;
|
---|
| 4426 |
|
---|
[303] | 4427 | # little local utility sub to swap $val and $host for revzone records.
|
---|
| 4428 | sub _revswap {
|
---|
| 4429 | my $rechost = shift;
|
---|
| 4430 | my $recdata = shift;
|
---|
| 4431 |
|
---|
| 4432 | if ($rechost =~ /\.in-addr\.arpa\.?$/) {
|
---|
| 4433 | $rechost =~ s/\.in-addr\.arpa\.?$//;
|
---|
| 4434 | $rechost = join '.', reverse split /\./, $rechost;
|
---|
| 4435 | } else {
|
---|
| 4436 | $rechost =~ s/\.ip6\.arpa\.?$//;
|
---|
| 4437 | my @nibs = reverse split /\./, $rechost;
|
---|
| 4438 | $rechost = '';
|
---|
| 4439 | my $nc;
|
---|
| 4440 | foreach (@nibs) {
|
---|
| 4441 | $rechost.= $_;
|
---|
| 4442 | $rechost .= ":" if ++$nc % 4 == 0 && $nc < 32;
|
---|
| 4443 | }
|
---|
[307] | 4444 | $rechost .= ":" if $nc < 32 && $rechost !~ /\*$/; # close netblock records?
|
---|
| 4445 | ##fixme: there's a case that ends up with a partial entry here:
|
---|
| 4446 | # ip:add:re:ss::
|
---|
| 4447 | # can't reproduce after letting it sit overnight after discovery. :(
|
---|
| 4448 | #print "$rechost\n";
|
---|
[303] | 4449 | # canonicalize with NetAddr::IP
|
---|
| 4450 | $rechost = NetAddr::IP->new($rechost)->addr unless $rechost =~ /\*$/;
|
---|
| 4451 | }
|
---|
| 4452 | return ($recdata,$rechost)
|
---|
| 4453 | }
|
---|
| 4454 |
|
---|
| 4455 |
|
---|
[33] | 4456 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4457 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4458 | local $dbh->{AutoCommit} = 0;
|
---|
| 4459 | local $dbh->{RaiseError} = 1;
|
---|
| 4460 |
|
---|
[301] | 4461 | my $sth;
|
---|
| 4462 | eval {
|
---|
[34] | 4463 |
|
---|
[301] | 4464 | if ($rev eq 'n') {
|
---|
[33] | 4465 | ##fixme: serial
|
---|
[484] | 4466 | $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef,
|
---|
| 4467 | ($zone, $group, $args{status}) );
|
---|
[301] | 4468 | # get domain id so we can do the records
|
---|
| 4469 | ($zone_id) = $dbh->selectrow_array("SELECT currval('domains_domain_id_seq')");
|
---|
| 4470 | $domain_id = $zone_id;
|
---|
[487] | 4471 | $self->_log(group_id => $group, domain_id => $domain_id,
|
---|
| 4472 | entry => "[Added ".($args{status} ? 'active' : 'inactive')." domain $zone via AXFR]");
|
---|
[301] | 4473 | } else {
|
---|
| 4474 | ##fixme: serial
|
---|
[484] | 4475 | $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef,
|
---|
| 4476 | ($cidr,$group,$args{status}) );
|
---|
[301] | 4477 | # get revzone id so we can do the records
|
---|
| 4478 | ($zone_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
| 4479 | $rdns_id = $zone_id;
|
---|
[487] | 4480 | $self->_log(group_id => $group, rdns_id => $rdns_id,
|
---|
| 4481 | entry => "[Added ".($args{status} ? 'active' : 'inactive')." reverse zone $cidr via AXFR]");
|
---|
[301] | 4482 | }
|
---|
[33] | 4483 |
|
---|
[35] | 4484 | ## bizarre DBI<->Net::DNS interaction bug:
|
---|
| 4485 | ## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
|
---|
[37] | 4486 | ## fixed, apparently I was doing *something* odd, but not certain what it was that
|
---|
| 4487 | ## caused a commit instead of barfing
|
---|
[35] | 4488 |
|
---|
[34] | 4489 | my $res = Net::DNS::Resolver->new;
|
---|
[35] | 4490 | $res->nameservers($ifrom);
|
---|
[301] | 4491 | $res->axfr_start($zone)
|
---|
[35] | 4492 | or die "Couldn't begin AXFR\n";
|
---|
[34] | 4493 |
|
---|
[301] | 4494 | $sth = $dbh->prepare("INSERT INTO records (domain_id,rdns_id,host,type,val,distance,weight,port,ttl)".
|
---|
| 4495 | " VALUES (?,?,?,?,?,?,?,?,?)");
|
---|
| 4496 |
|
---|
[307] | 4497 | # Stash info about sub-octet v4 revzones here so we don't have
|
---|
| 4498 | # to store the CNAMEs used to delegate a suboctet zone
|
---|
| 4499 | # $suboct{zone}{ns}[] -> array of nameservers
|
---|
| 4500 | # $suboct{zone}{cname}[] -> array of extant CNAMEs (Just In Case someone did something bizarre)
|
---|
| 4501 | ## commented pending actual use of this data. for now, we'll just
|
---|
| 4502 | ## auto-(re)create the CNAMEs in revzones on export
|
---|
| 4503 | # my %suboct;
|
---|
| 4504 |
|
---|
[35] | 4505 | while (my $rr = $res->axfr_next()) {
|
---|
[301] | 4506 |
|
---|
| 4507 | my $val;
|
---|
| 4508 | my $distance = 0;
|
---|
| 4509 | my $weight = 0;
|
---|
| 4510 | my $port = 0;
|
---|
[303] | 4511 | my $logfrag = '';
|
---|
[301] | 4512 |
|
---|
[33] | 4513 | my $type = $rr->type;
|
---|
[301] | 4514 | my $host = $rr->name;
|
---|
[484] | 4515 | my $ttl = ($args{newttl} ? $args{newttl} : $rr->ttl); # allow force-override TTLs
|
---|
[35] | 4516 |
|
---|
[37] | 4517 | $soaflag = 1 if $type eq 'SOA';
|
---|
| 4518 | $nsflag = 1 if $type eq 'NS';
|
---|
[35] | 4519 |
|
---|
[34] | 4520 | # "Primary" types:
|
---|
| 4521 | # A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
|
---|
| 4522 | # maybe KEY
|
---|
| 4523 |
|
---|
[302] | 4524 | # BIND supports:
|
---|
| 4525 | # [standard]
|
---|
| 4526 | # A AAAA CNAME MX NS PTR SOA TXT
|
---|
| 4527 | # [variously experimental, obsolete, or obscure]
|
---|
| 4528 | # 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
|
---|
| 4529 | # ... if one can ever find the right magic to format them correctly
|
---|
| 4530 |
|
---|
| 4531 | # Net::DNS supports:
|
---|
| 4532 | # RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
|
---|
| 4533 | # EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
|
---|
| 4534 | # DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
|
---|
| 4535 |
|
---|
[35] | 4536 | # nasty big ugly case-like thing here, since we have to do *some* different
|
---|
| 4537 | # processing depending on the record. le sigh.
|
---|
| 4538 |
|
---|
[105] | 4539 | ##fixme: what record types other than TXT can/will have >255-byte payloads?
|
---|
| 4540 |
|
---|
[34] | 4541 | if ($type eq 'A') {
|
---|
[301] | 4542 | $val = $rr->address;
|
---|
[34] | 4543 | } elsif ($type eq 'NS') {
|
---|
[37] | 4544 | # hmm. should we warn here if subdomain NS'es are left alone?
|
---|
[484] | 4545 | next if ($args{rwns} && ($rr->name eq $zone));
|
---|
[302] | 4546 | if ($rev eq 'y') {
|
---|
| 4547 | # revzones have records more or less reversed from forward zones.
|
---|
| 4548 | my ($tmpcode,$tmpmsg) = _zone2cidr($host);
|
---|
[401] | 4549 | die "Error converting NS record: $tmpmsg\n" if $tmpcode eq 'FAIL'; # hmm. may not make sense...
|
---|
[302] | 4550 | $val = "$tmpmsg";
|
---|
| 4551 | $host = $rr->nsdname;
|
---|
[303] | 4552 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
[307] | 4553 | # Tag and preserve. For now this is commented for a no-op, but we have Ideas for
|
---|
| 4554 | # another custom storage type ("DELEGATE") that will use these subzone-delegation records
|
---|
| 4555 | #if ($val ne "$cidr") {
|
---|
| 4556 | # push @{$suboct{$val}{ns}}, $host;
|
---|
| 4557 | #}
|
---|
[302] | 4558 | } else {
|
---|
| 4559 | $val = $rr->nsdname;
|
---|
| 4560 | }
|
---|
[35] | 4561 | $nsflag = 1;
|
---|
[34] | 4562 | } elsif ($type eq 'CNAME') {
|
---|
[302] | 4563 | if ($rev eq 'y') {
|
---|
[303] | 4564 | # hmm. do we even want to bother with storing these at this level? Sub-octet delegation
|
---|
| 4565 | # by CNAME is essentially a record-publication hack, and we want to just represent the
|
---|
| 4566 | # "true" logical intentions as far down the stack as we can from the UI.
|
---|
| 4567 | ($host,$val) = _revswap($host,$rr->cname);
|
---|
| 4568 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
[307] | 4569 | # Tag and preserve in case we want to commit them as-is later, but mostly we don't care.
|
---|
| 4570 | # Commented pending actually doing something with possibly new type DELEGATE
|
---|
| 4571 | #my $tmprev = $host;
|
---|
| 4572 | #$tmprev =~ s/^\d+\.//;
|
---|
| 4573 | #($code,$tmprev) = _zone2cidr($tmprev);
|
---|
| 4574 | #push @{$suboct{"$tmprev"}{cname}}, $val;
|
---|
| 4575 | # Silently skip CNAMEs in revzones.
|
---|
| 4576 | next;
|
---|
[302] | 4577 | } else {
|
---|
| 4578 | $val = $rr->cname;
|
---|
| 4579 | }
|
---|
[34] | 4580 | } elsif ($type eq 'SOA') {
|
---|
[484] | 4581 | next if $args{rwsoa};
|
---|
[307] | 4582 | $host = $rr->rname.":".$rr->mname;
|
---|
[301] | 4583 | $val = $rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum;
|
---|
[35] | 4584 | $soaflag = 1;
|
---|
[34] | 4585 | } elsif ($type eq 'PTR') {
|
---|
[303] | 4586 | ($host,$val) = _revswap($host,$rr->ptrdname);
|
---|
| 4587 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
[34] | 4588 | # hmm. PTR records should not be in forward zones.
|
---|
| 4589 | } elsif ($type eq 'MX') {
|
---|
[301] | 4590 | $val = $rr->exchange;
|
---|
| 4591 | $distance = $rr->preference;
|
---|
[34] | 4592 | } elsif ($type eq 'TXT') {
|
---|
| 4593 | ##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
|
---|
| 4594 | ## but don't really seem enthusiastic about it.
|
---|
[303] | 4595 | #print "should use rdatastr:\n\t".$rr->rdatastr."\n or char_str_list:\n\t".join(' ',$rr->char_str_list())."\n";
|
---|
| 4596 | # rdatastr returns a BIND-targetted logical string, including opening and closing quotes
|
---|
| 4597 | # char_str_list returns a list of the individual string fragments in the record
|
---|
[307] | 4598 | # txtdata returns the more useful all-in-one form (since we want to push such protocol
|
---|
| 4599 | # details as far down the stack as we can)
|
---|
[303] | 4600 | # NB: this may turn out to be more troublesome if we ever have need of >512-byte TXT records.
|
---|
| 4601 | if ($rev eq 'y') {
|
---|
| 4602 | ($host,$val) = _revswap($host,$rr->txtdata);
|
---|
| 4603 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
| 4604 | } else {
|
---|
| 4605 | $val = $rr->txtdata;
|
---|
| 4606 | }
|
---|
[34] | 4607 | } elsif ($type eq 'SPF') {
|
---|
| 4608 | ##fixme: and the same caveat here, since it is apparently a clone of ::TXT
|
---|
[301] | 4609 | $val = $rr->txtdata;
|
---|
[34] | 4610 | } elsif ($type eq 'AAAA') {
|
---|
[301] | 4611 | $val = $rr->address;
|
---|
[34] | 4612 | } elsif ($type eq 'SRV') {
|
---|
[301] | 4613 | $val = $rr->target;
|
---|
| 4614 | $distance = $rr->priority;
|
---|
| 4615 | $weight = $rr->weight;
|
---|
| 4616 | $port = $rr->port;
|
---|
[34] | 4617 | } elsif ($type eq 'KEY') {
|
---|
[35] | 4618 | # we don't actually know what to do with these...
|
---|
[301] | 4619 | $val = $rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname;
|
---|
[35] | 4620 | } else {
|
---|
[301] | 4621 | $val = $rr->rdatastr;
|
---|
[35] | 4622 | # Finding a different record type is not fatal.... just problematic.
|
---|
[37] | 4623 | # We may not be able to export it correctly.
|
---|
[35] | 4624 | $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
|
---|
[33] | 4625 | }
|
---|
| 4626 |
|
---|
[303] | 4627 | my $logentry = "[AXFR ".($rev eq 'n' ? $zone : $cidr)."] ";
|
---|
[34] | 4628 |
|
---|
[484] | 4629 | if ($args{merge}) {
|
---|
[307] | 4630 | if ($rev eq 'n') {
|
---|
| 4631 | # importing a domain; we have A and AAAA records that could be merged with matching PTR records
|
---|
| 4632 | my $etype;
|
---|
| 4633 | my ($erdns,$erid,$ettl) = $dbh->selectrow_array("SELECT rdns_id,record_id,ttl FROM records ".
|
---|
| 4634 | "WHERE host=? AND val=? AND type=12",
|
---|
| 4635 | undef, ($host, $val) );
|
---|
| 4636 | if ($erid) {
|
---|
| 4637 | if ($type eq 'A') { # PTR -> A+PTR
|
---|
| 4638 | $etype = 65280;
|
---|
| 4639 | $logentry .= "Merged A record with existing PTR record '$host A+PTR $val', TTL $ettl";
|
---|
| 4640 | }
|
---|
| 4641 | if ($type eq 'AAAA') { # PTR -> AAAA+PTR
|
---|
| 4642 | $etype = 65281;
|
---|
| 4643 | $logentry .= "Merged AAAA record with existing PTR record '$host AAAA+PTR $val', TTL $ettl";
|
---|
| 4644 | }
|
---|
| 4645 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
| 4646 | $dbh->do("UPDATE records SET domain_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
| 4647 | ($domain_id, $ettl, $etype, $erid));
|
---|
| 4648 | $nrecs++;
|
---|
[487] | 4649 | $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $erdns, entry => $logentry);
|
---|
[307] | 4650 | next; # while axfr_next
|
---|
| 4651 | }
|
---|
| 4652 | } # $rev eq 'n'
|
---|
| 4653 | else {
|
---|
| 4654 | # importing a revzone, we have PTR records that could be merged with matching A/AAAA records
|
---|
| 4655 | my ($domid,$erid,$ettl,$etype) = $dbh->selectrow_array("SELECT domain_id,record_id,ttl,type FROM records ".
|
---|
| 4656 | "WHERE host=? AND val=? AND (type=1 OR type=28)",
|
---|
| 4657 | undef, ($host, $val) );
|
---|
| 4658 | if ($erid) {
|
---|
| 4659 | if ($etype == 1) { # A -> A+PTR
|
---|
| 4660 | $etype = 65280;
|
---|
| 4661 | $logentry .= "Merged PTR record with existing matching A record '$host A+PTR $val', TTL $ettl";
|
---|
| 4662 | }
|
---|
| 4663 | if ($etype == 28) { # AAAA -> AAAA+PTR
|
---|
| 4664 | $etype = 65281;
|
---|
| 4665 | $logentry .= "Merged PTR record with existing matching AAAA record '$host AAAA+PTR $val', TTL $ettl";
|
---|
| 4666 | }
|
---|
| 4667 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
| 4668 | $dbh->do("UPDATE records SET rdns_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
| 4669 | ($rdns_id, $ettl, $etype, $erid));
|
---|
| 4670 | $nrecs++;
|
---|
[487] | 4671 | $self->_log(group_id => $group, domain_id => $domid, rdns_id => $rdns_id, entry => $logentry);
|
---|
[307] | 4672 | next; # while axfr_next
|
---|
| 4673 | }
|
---|
| 4674 | } # $rev eq 'y'
|
---|
[484] | 4675 | } # if $args{merge}
|
---|
[34] | 4676 |
|
---|
[302] | 4677 | # Insert the new record
|
---|
[301] | 4678 | $sth->execute($domain_id, $rdns_id, $host, $reverse_typemap{$type}, $val,
|
---|
| 4679 | $distance, $weight, $port, $ttl);
|
---|
| 4680 |
|
---|
[37] | 4681 | $nrecs++;
|
---|
[34] | 4682 |
|
---|
[301] | 4683 | if ($type eq 'SOA') {
|
---|
[484] | 4684 | # also !$args{rwsoa}, but if that's set, it should be impossible to get here.
|
---|
[301] | 4685 | my @tmp1 = split /:/, $host;
|
---|
| 4686 | my @tmp2 = split /:/, $val;
|
---|
| 4687 | $logentry .= "Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
| 4688 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl";
|
---|
[303] | 4689 | } elsif ($logfrag) {
|
---|
| 4690 | # special case for log entries we need to meddle with a little.
|
---|
| 4691 | $logentry .= $logfrag;
|
---|
[301] | 4692 | } else {
|
---|
| 4693 | $logentry .= "Added record '$host $type";
|
---|
| 4694 | $logentry .= " [distance $distance]" if $type eq 'MX';
|
---|
| 4695 | $logentry .= " [priority $distance] [weight $weight] [port $port]" if $type eq 'SRV';
|
---|
| 4696 | $logentry .= " $val', TTL $ttl";
|
---|
| 4697 | }
|
---|
[487] | 4698 | $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $rdns_id, entry => $logentry);
|
---|
[301] | 4699 |
|
---|
[37] | 4700 | } # while axfr_next
|
---|
| 4701 |
|
---|
[307] | 4702 | # Detect and handle delegated subzones
|
---|
| 4703 | # Placeholder for when we decide what to actually do with this, see previous comments in NS and CNAME handling.
|
---|
| 4704 | #foreach (keys %suboct) {
|
---|
| 4705 | # print "found ".($suboct{$_}{ns} ? @{$suboct{$_}{ns}} : '0')." NS records and ".
|
---|
| 4706 | # ($suboct{$_}{cname} ? @{$suboct{$_}{cname}} : '0')." CNAMEs for $_\n";
|
---|
| 4707 | #}
|
---|
| 4708 |
|
---|
[37] | 4709 | # Overwrite SOA record
|
---|
[484] | 4710 | if ($args{rwsoa}) {
|
---|
[37] | 4711 | $soaflag = 1;
|
---|
| 4712 | my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
|
---|
| 4713 | my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
| 4714 | $sthgetsoa->execute($group,$reverse_typemap{SOA});
|
---|
| 4715 | while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
|
---|
[301] | 4716 | $host =~ s/DOMAIN/$zone/g;
|
---|
| 4717 | $val =~ s/DOMAIN/$zone/g;
|
---|
| 4718 | $sthputsoa->execute($zone_id,$host,$reverse_typemap{SOA},$val,$ttl);
|
---|
[34] | 4719 | }
|
---|
[37] | 4720 | }
|
---|
[34] | 4721 |
|
---|
[37] | 4722 | # Overwrite NS records
|
---|
[484] | 4723 | if ($args{rwns}) {
|
---|
[37] | 4724 | $nsflag = 1;
|
---|
| 4725 | my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
|
---|
| 4726 | my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
| 4727 | $sthgetns->execute($group,$reverse_typemap{NS});
|
---|
| 4728 | while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
|
---|
[301] | 4729 | $host =~ s/DOMAIN/$zone/g;
|
---|
| 4730 | $val =~ s/DOMAIN/$zone/g;
|
---|
| 4731 | $sthputns->execute($zone_id,$host,$reverse_typemap{NS},$val,$ttl);
|
---|
[37] | 4732 | }
|
---|
| 4733 | }
|
---|
[34] | 4734 |
|
---|
[35] | 4735 | die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
|
---|
| 4736 | die "Bad zone: No SOA record!\n" if !$soaflag;
|
---|
| 4737 | die "Bad zone: No NS records!\n" if !$nsflag;
|
---|
| 4738 |
|
---|
[37] | 4739 | $dbh->commit;
|
---|
[35] | 4740 |
|
---|
[33] | 4741 | };
|
---|
| 4742 |
|
---|
| 4743 | if ($@) {
|
---|
| 4744 | my $msg = $@;
|
---|
| 4745 | eval { $dbh->rollback; };
|
---|
[34] | 4746 | return ('FAIL',$msg." $warnmsg");
|
---|
[33] | 4747 | } else {
|
---|
[35] | 4748 | return ('WARN', $warnmsg) if $warnmsg;
|
---|
[91] | 4749 | return ('OK',"Imported OK");
|
---|
[33] | 4750 | }
|
---|
| 4751 |
|
---|
[37] | 4752 | # it should be impossible to get here.
|
---|
[34] | 4753 | return ('WARN',"OOOK!");
|
---|
[33] | 4754 | } # end importAXFR()
|
---|
| 4755 |
|
---|
| 4756 |
|
---|
[302] | 4757 | ## DNSDB::importBIND()
|
---|
| 4758 | sub importBIND {
|
---|
| 4759 | } # end importBIND()
|
---|
| 4760 |
|
---|
| 4761 |
|
---|
| 4762 | ## DNSDB::import_tinydns()
|
---|
| 4763 | sub import_tinydns {
|
---|
| 4764 | } # end import_tinydns()
|
---|
| 4765 |
|
---|
| 4766 |
|
---|
[103] | 4767 | ## DNSDB::export()
|
---|
| 4768 | # Export the DNS database, or a part of it
|
---|
[485] | 4769 | # Takes a string indicating the export type, plus optional arguments depending on type
|
---|
[103] | 4770 | # Writes zone data to targets as appropriate for type
|
---|
| 4771 | sub export {
|
---|
[485] | 4772 | my $self = shift;
|
---|
[103] | 4773 | my $target = shift;
|
---|
| 4774 |
|
---|
| 4775 | if ($target eq 'tiny') {
|
---|
[485] | 4776 | $self->__export_tiny(@_);
|
---|
[103] | 4777 | }
|
---|
| 4778 | # elsif ($target eq 'foo') {
|
---|
[485] | 4779 | # __export_foo(@_);
|
---|
[103] | 4780 | #}
|
---|
| 4781 | # etc
|
---|
| 4782 |
|
---|
| 4783 | } # end export()
|
---|
| 4784 |
|
---|
| 4785 |
|
---|
| 4786 | ## DNSDB::__export_tiny
|
---|
| 4787 | # Internal sub to implement tinyDNS (compatible) export
|
---|
[485] | 4788 | # Takes filehandle to write export to, optional argument(s)
|
---|
[103] | 4789 | # to determine which data gets exported
|
---|
| 4790 | sub __export_tiny {
|
---|
[485] | 4791 | my $self = shift;
|
---|
| 4792 | my $dbh = $self->{dbh};
|
---|
[103] | 4793 | my $datafile = shift;
|
---|
| 4794 |
|
---|
| 4795 | ##fixme: slurp up further options to specify particular zone(s) to export
|
---|
| 4796 |
|
---|
| 4797 | ##fixme: fail if $datafile isn't an open, writable file
|
---|
| 4798 |
|
---|
| 4799 | # easy case - export all evarything
|
---|
| 4800 | # not-so-easy case - export item(s) specified
|
---|
| 4801 | # todo: figure out what kind of list we use to export items
|
---|
| 4802 |
|
---|
[329] | 4803 | # raw packet in unknown format: first byte indicates length
|
---|
| 4804 | # of remaining data, allows up to 255 raw bytes
|
---|
| 4805 |
|
---|
[372] | 4806 | # Locations/views - worth including in the caching setup?
|
---|
| 4807 | my $lochash = $dbh->selectall_hashref("SELECT location,iplist FROM locations", 'location');
|
---|
| 4808 | foreach my $location (keys %$lochash) {
|
---|
[375] | 4809 | foreach my $ipprefix (split /[,\s]+/, $lochash->{$location}{iplist}) {
|
---|
| 4810 | $ipprefix =~ s/\s+//g;
|
---|
[449] | 4811 | $ipprefix = new NetAddr::IP $ipprefix;
|
---|
| 4812 | ##fixme: how to handle IPv6?
|
---|
| 4813 | next if $ipprefix->{isv6};
|
---|
| 4814 | # have to account for /nn CIDR entries. tinydns only speaks octet-sliced prefix.
|
---|
| 4815 | if ($ipprefix->masklen <= 8) {
|
---|
| 4816 | foreach ($ipprefix->split(8)) {
|
---|
| 4817 | my $tmp = $_->addr;
|
---|
| 4818 | $tmp =~ s/\.\d+\.\d+\.\d+$//;
|
---|
| 4819 | print $datafile "%$location:$tmp\n";
|
---|
| 4820 | }
|
---|
| 4821 | } elsif ($ipprefix->masklen <= 16) {
|
---|
| 4822 | foreach ($ipprefix->split(16)) {
|
---|
| 4823 | my $tmp = $_->addr;
|
---|
| 4824 | $tmp =~ s/\.\d+\.\d+$//;
|
---|
| 4825 | print $datafile "%$location:$tmp\n";
|
---|
| 4826 | }
|
---|
| 4827 | } elsif ($ipprefix->masklen <= 24) {
|
---|
| 4828 | foreach ($ipprefix->split(24)) {
|
---|
| 4829 | my $tmp = $_->addr;
|
---|
| 4830 | $tmp =~ s/\.\d+$//;
|
---|
| 4831 | print $datafile "%$location:$tmp\n";
|
---|
| 4832 | }
|
---|
| 4833 | } else {
|
---|
| 4834 | foreach ($ipprefix->split(32)) {
|
---|
| 4835 | print $datafile "%$location:".$_->addr."\n";
|
---|
| 4836 | }
|
---|
| 4837 | }
|
---|
[372] | 4838 | }
|
---|
| 4839 | print $datafile "%$location\n" if !$lochash->{$location}{iplist};
|
---|
| 4840 | }
|
---|
| 4841 |
|
---|
[329] | 4842 | # tracking hash so we don't double-export A+PTR or AAAA+PTR records.
|
---|
| 4843 | my %recflags;
|
---|
| 4844 |
|
---|
[368] | 4845 | my $domsth = $dbh->prepare("SELECT domain_id,domain,status,changed FROM domains WHERE status=1");
|
---|
[372] | 4846 | my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
[368] | 4847 | "FROM records WHERE domain_id=? AND type < 65280"); # Just exclude all types relating to rDNS
|
---|
[372] | 4848 | my $zonesth = $dbh->prepare("UPDATE domains SET changed='n' WHERE domain_id=?");
|
---|
[103] | 4849 | $domsth->execute();
|
---|
[368] | 4850 | while (my ($domid,$dom,$domstat,$changed) = $domsth->fetchrow_array) {
|
---|
| 4851 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
| 4852 | # O_NOFOLLOW
|
---|
| 4853 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
| 4854 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
| 4855 | # still be followed.
|
---|
| 4856 | # but that doesn't help other platforms. :/
|
---|
| 4857 | sysopen(ZONECACHE, "$config{exportcache}/$dom", O_RDWR|O_CREAT);
|
---|
| 4858 | flock(ZONECACHE, LOCK_EX);
|
---|
| 4859 | if ($changed || -s "$config{exportcache}/$dom" == 0) {
|
---|
| 4860 | $recsth->execute($domid);
|
---|
[372] | 4861 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc) = $recsth->fetchrow_array) {
|
---|
[368] | 4862 | next if $recflags{$recid};
|
---|
[108] | 4863 |
|
---|
[372] | 4864 | $loc = '' if !$loc; # de-nullify - just in case
|
---|
| 4865 | ##fixme: handle case of record-with-location-that-doesn't-exist better.
|
---|
| 4866 | # note this currently fails safe (tested) - records with a location that
|
---|
| 4867 | # doesn't exist will not be sent to any client
|
---|
| 4868 | # $loc = '' if !$lochash->{$loc};
|
---|
| 4869 |
|
---|
[108] | 4870 | ##fixme: record validity timestamp. tinydns supports fiddling with timestamps.
|
---|
| 4871 | # note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
|
---|
| 4872 | # timestamps are TAI64
|
---|
| 4873 | # ~~ 2^62 + time()
|
---|
[368] | 4874 | my $stamp = '';
|
---|
[108] | 4875 |
|
---|
[368] | 4876 | # support tinydns' auto-TTL
|
---|
| 4877 | $ttl = '' if $ttl == '0';
|
---|
[367] | 4878 |
|
---|
[417] | 4879 | # Spaces are evil.
|
---|
[441] | 4880 | $host =~ s/^\s+//;
|
---|
| 4881 | $host =~ s/\s+$//;
|
---|
| 4882 | if ($typemap{$type} ne 'TXT') {
|
---|
[417] | 4883 | # Leading or trailng spaces could be legit in TXT records.
|
---|
[441] | 4884 | $val =~ s/^\s+//;
|
---|
| 4885 | $val =~ s/\s+$//;
|
---|
[417] | 4886 | }
|
---|
| 4887 |
|
---|
[368] | 4888 | _printrec_tiny(*ZONECACHE, 'n', \%recflags,
|
---|
| 4889 | $dom, $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp)
|
---|
| 4890 | if *ZONECACHE;
|
---|
[450] | 4891 |
|
---|
[368] | 4892 | # in case the zone shrunk, get rid of garbage at the end of the file.
|
---|
| 4893 | truncate(ZONECACHE, tell(ZONECACHE));
|
---|
| 4894 |
|
---|
| 4895 | $recflags{$recid} = 1;
|
---|
| 4896 | } # while ($recsth)
|
---|
| 4897 | }
|
---|
[450] | 4898 | # stream from cache, whether freshly created or existing
|
---|
| 4899 | print $datafile $_ while <ZONECACHE>;
|
---|
[368] | 4900 | close ZONECACHE;
|
---|
| 4901 | # mark domain as unmodified
|
---|
| 4902 | $zonesth->execute($domid);
|
---|
[329] | 4903 | } # while ($domsth)
|
---|
| 4904 |
|
---|
[368] | 4905 | my $revsth = $dbh->prepare("SELECT rdns_id,revnet,status,changed FROM revzones WHERE status=1 ".
|
---|
[337] | 4906 | "ORDER BY masklen(revnet) DESC");
|
---|
[372] | 4907 |
|
---|
[344] | 4908 | # For reasons unknown, we can't sanely UNION these statements. Feh.
|
---|
| 4909 | # Supposedly it should work though (note last 3 lines):
|
---|
| 4910 | ## PG manual
|
---|
| 4911 | #UNION Clause
|
---|
| 4912 | #
|
---|
| 4913 | #The UNION clause has this general form:
|
---|
| 4914 | #
|
---|
| 4915 | # select_statement UNION [ ALL ] select_statement
|
---|
| 4916 | #
|
---|
| 4917 | #select_statement is any SELECT statement without an ORDER BY, LIMIT, FOR UPDATE, or FOR SHARE clause. (ORDER BY
|
---|
| 4918 | #and LIMIT can be attached to a subexpression if it is enclosed in parentheses. Without parentheses, these
|
---|
| 4919 | #clauses will be taken to apply to the result of the UNION, not to its right-hand input expression.)
|
---|
[372] | 4920 | my $soasth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
[344] | 4921 | "FROM records WHERE rdns_id=? AND type=6");
|
---|
[372] | 4922 | $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
[337] | 4923 | "FROM records WHERE rdns_id=? AND not type=6 ".
|
---|
[344] | 4924 | "ORDER BY masklen(CAST(val AS inet)) DESC, CAST(val AS inet)");
|
---|
[372] | 4925 | $zonesth = $dbh->prepare("UPDATE revzones SET changed='n' WHERE rdns_id=?");
|
---|
[329] | 4926 | $revsth->execute();
|
---|
[368] | 4927 | while (my ($revid,$revzone,$revstat,$changed) = $revsth->fetchrow_array) {
|
---|
| 4928 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
| 4929 | # O_NOFOLLOW
|
---|
| 4930 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
| 4931 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
| 4932 | # still be followed.
|
---|
| 4933 | # but that doesn't help other platforms. :/
|
---|
| 4934 | my $tmpzone = NetAddr::IP->new($revzone);
|
---|
| 4935 | sysopen(ZONECACHE, "$config{exportcache}/".$tmpzone->network->addr, O_RDWR|O_CREAT);
|
---|
| 4936 | flock(ZONECACHE, LOCK_EX);
|
---|
| 4937 | if ($changed || -s "$config{exportcache}/".$tmpzone->network->addr == 0) {
|
---|
| 4938 | # need to fetch this separately since the rest of the records all (should) have real IPs in val
|
---|
| 4939 | $soasth->execute($revid);
|
---|
| 4940 | my (@zsoa) = $soasth->fetchrow_array();
|
---|
[445] | 4941 | _printrec_tiny(*ZONECACHE,'y',\%recflags,$revzone,
|
---|
| 4942 | $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],'');
|
---|
[344] | 4943 |
|
---|
[368] | 4944 | $recsth->execute($revid);
|
---|
[372] | 4945 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc) = $recsth->fetchrow_array) {
|
---|
[368] | 4946 | next if $recflags{$recid};
|
---|
[329] | 4947 |
|
---|
[372] | 4948 | $loc = '' if !$loc; # de-nullify - just in case
|
---|
| 4949 | ##fixme: handle case of record-with-location-that-doesn't-exist better.
|
---|
| 4950 | # note this currently fails safe (tested) - records with a location that
|
---|
| 4951 | # doesn't exist will not be sent to any client
|
---|
| 4952 | # $loc = '' if !$lochash->{$loc};
|
---|
| 4953 |
|
---|
[329] | 4954 | ##fixme: record validity timestamp. tinydns supports fiddling with timestamps.
|
---|
| 4955 | # note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
|
---|
| 4956 | # timestamps are TAI64
|
---|
| 4957 | # ~~ 2^62 + time()
|
---|
[368] | 4958 | my $stamp = '';
|
---|
[329] | 4959 |
|
---|
[368] | 4960 | # support tinydns' auto-TTL
|
---|
| 4961 | $ttl = '' if $ttl == '0';
|
---|
[367] | 4962 |
|
---|
[368] | 4963 | _printrec_tiny(*ZONECACHE, 'y', \%recflags, $revzone,
|
---|
| 4964 | $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp)
|
---|
| 4965 | if *ZONECACHE;
|
---|
[329] | 4966 |
|
---|
[450] | 4967 | # in case the zone shrunk, get rid of garbage at the end of the file.
|
---|
| 4968 | truncate(ZONECACHE, tell(ZONECACHE));
|
---|
| 4969 |
|
---|
[368] | 4970 | $recflags{$recid} = 1;
|
---|
| 4971 | } # while ($recsth)
|
---|
| 4972 | }
|
---|
[450] | 4973 | # stream from cache, whether freshly created or existing
|
---|
| 4974 | print $datafile $_ while <ZONECACHE>;
|
---|
[368] | 4975 | close ZONECACHE;
|
---|
[450] | 4976 | # mark zone as unmodified
|
---|
[368] | 4977 | $zonesth->execute($revid);
|
---|
[329] | 4978 | } # while ($domsth)
|
---|
| 4979 |
|
---|
| 4980 | } # end __export_tiny()
|
---|
| 4981 |
|
---|
| 4982 |
|
---|
| 4983 | # Utility sub for __export_tiny above
|
---|
| 4984 | sub _printrec_tiny {
|
---|
| 4985 | my ($datafile,$revrec,$recflags,$zone,$host,$type,$val,$dist,$weight,$port,$ttl,$loc,$stamp) = @_;
|
---|
| 4986 |
|
---|
| 4987 | ## Convert a bare number into an octal-coded pair of octets.
|
---|
| 4988 | # Take optional arg to indicate a decimal or hex input. Defaults to hex.
|
---|
| 4989 | sub octalize {
|
---|
| 4990 | my $tmp = shift;
|
---|
| 4991 | my $srctype = shift || 'h'; # default assumes hex string
|
---|
| 4992 | $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
|
---|
| 4993 | $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
|
---|
| 4994 | my @o = ($tmp =~ /^(..)(..)$/); # split into octets
|
---|
| 4995 | return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);;
|
---|
| 4996 | }
|
---|
| 4997 |
|
---|
[339] | 4998 | ## WARNING: This works to export even the whole Internet's worth of IP space...
|
---|
| 4999 | ## if you have the disk/RAM to handle the dataset, and you call this sub based on /16-sized chunks
|
---|
| 5000 | ## A /16 took ~3 seconds with a handful of separate records; adding a /8 pushed export time out to ~13m:40s
|
---|
| 5001 | ## 0/0 is estimated to take ~54 hours and ~256G of disk
|
---|
| 5002 | ## RAM usage depends on how many non-template entries you have in the set.
|
---|
| 5003 | ## This should probably be done on record addition rather than export; large blocks may need to be done in a
|
---|
| 5004 | ## forked process
|
---|
| 5005 | sub __publish_subnet {
|
---|
| 5006 | my $sub = shift;
|
---|
| 5007 | my $recflags = shift;
|
---|
| 5008 | my $hpat = shift;
|
---|
| 5009 | my $fh = shift;
|
---|
| 5010 | my $ttl = shift;
|
---|
| 5011 | my $stamp = shift;
|
---|
| 5012 | my $loc = shift;
|
---|
| 5013 | my $ptronly = shift || 0;
|
---|
| 5014 |
|
---|
| 5015 | my $iplist = $sub->splitref(32);
|
---|
| 5016 | foreach (@$iplist) {
|
---|
| 5017 | my $ip = $_->addr;
|
---|
| 5018 | # make as if we split the non-octet-aligned block into octet-aligned blocks as with SOA
|
---|
| 5019 | next if $ip =~ /\.(0|255)$/;
|
---|
| 5020 | next if $$recflags{$ip};
|
---|
| 5021 | $$recflags{$ip}++;
|
---|
[463] | 5022 | next if $hpat eq '%blank%'; # Allows blanking a subnet so no records are published.
|
---|
[339] | 5023 | my $rec = $hpat; # start fresh with the template for each IP
|
---|
| 5024 | _template4_expand(\$rec, $ip);
|
---|
| 5025 | print $fh ($ptronly ? "^"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$rec" : "=$rec:$ip").
|
---|
| 5026 | ":$ttl:$stamp:$loc\n";
|
---|
| 5027 | }
|
---|
| 5028 | }
|
---|
| 5029 |
|
---|
[103] | 5030 | ##fixme? append . to all host/val hostnames
|
---|
| 5031 | if ($typemap{$type} eq 'SOA') {
|
---|
| 5032 |
|
---|
| 5033 | # host contains pri-ns:responsible
|
---|
| 5034 | # val is abused to contain refresh:retry:expire:minttl
|
---|
| 5035 | ##fixme: "manual" serial vs tinydns-autoserial
|
---|
[202] | 5036 | # let's be explicit about abusing $host and $val
|
---|
| 5037 | my ($email, $primary) = (split /:/, $host)[0,1];
|
---|
| 5038 | my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
|
---|
[330] | 5039 | if ($revrec eq 'y') {
|
---|
[337] | 5040 | ##fixme: have to publish SOA records for each v4 /24 in sub-/16, and each /16 in sub-/8
|
---|
| 5041 | # what about v6?
|
---|
| 5042 | # -> only need SOA for local chunks offset from reverse delegation boundaries, so v6 is fine
|
---|
[330] | 5043 | $zone = NetAddr::IP->new($zone);
|
---|
[337] | 5044 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
| 5045 | if (!$zone->{isv6} && ($zone->masklen < 24) && ($zone->masklen % 8 != 0)) {
|
---|
| 5046 | foreach my $szone ($zone->split($zone->masklen + (8 - $zone->masklen % 8))) {
|
---|
| 5047 | $szone = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
| 5048 | print $datafile "Z$szone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
|
---|
| 5049 | }
|
---|
| 5050 | return; # skips "default" bits just below
|
---|
| 5051 | }
|
---|
[330] | 5052 | $zone = _ZONE($zone, 'ZONE', 'r', '.').($zone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 5053 | }
|
---|
[329] | 5054 | print $datafile "Z$zone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
|
---|
[103] | 5055 |
|
---|
| 5056 | } elsif ($typemap{$type} eq 'A') {
|
---|
| 5057 |
|
---|
[108] | 5058 | print $datafile "+$host:$val:$ttl:$stamp:$loc\n";
|
---|
[103] | 5059 |
|
---|
| 5060 | } elsif ($typemap{$type} eq 'NS') {
|
---|
| 5061 |
|
---|
[330] | 5062 | if ($revrec eq 'y') {
|
---|
| 5063 | $val = NetAddr::IP->new($val);
|
---|
[345] | 5064 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
| 5065 | if (!$val->{isv6} && ($val->masklen < 24) && ($val->masklen % 8 != 0)) {
|
---|
[346] | 5066 | foreach my $szone ($val->split($val->masklen + (8 - $val->masklen % 8))) {
|
---|
[345] | 5067 | my $szone2 = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
[346] | 5068 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
[345] | 5069 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n";
|
---|
[346] | 5070 | $$recflags{$szone2} = $val->masklen;
|
---|
[345] | 5071 | }
|
---|
[346] | 5072 | } elsif ($val->{isv6} && ($val->masklen < 64) && ($val->masklen % 4 !=0)) {
|
---|
| 5073 | foreach my $szone ($val->split($val->masklen + (4 - $val->masklen % 4))) {
|
---|
| 5074 | my $szone2 = _ZONE($szone, 'ZONE.ip6.arpa', 'r', '.');
|
---|
| 5075 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
| 5076 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n";
|
---|
| 5077 | $$recflags{$szone2} = $val->masklen;
|
---|
| 5078 | }
|
---|
| 5079 | } else {
|
---|
| 5080 | my $val2 = _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 5081 | print $datafile "\&$val2"."::$host:$ttl:$stamp:$loc\n";
|
---|
| 5082 | $$recflags{$val2} = $val->masklen;
|
---|
[345] | 5083 | }
|
---|
[330] | 5084 | } else {
|
---|
| 5085 | print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n";
|
---|
| 5086 | }
|
---|
[103] | 5087 |
|
---|
| 5088 | } elsif ($typemap{$type} eq 'AAAA') {
|
---|
| 5089 |
|
---|
| 5090 | print $datafile ":$host:28:";
|
---|
| 5091 | my $altgrp = 0;
|
---|
| 5092 | my @altconv;
|
---|
[108] | 5093 | # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
|
---|
[103] | 5094 | foreach (split /:/, $val) {
|
---|
| 5095 | if (/^$/) {
|
---|
| 5096 | # flag blank entry; this is a series of 0's of (currently) unknown length
|
---|
| 5097 | $altconv[$altgrp++] = 's';
|
---|
| 5098 | } else {
|
---|
| 5099 | # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
|
---|
| 5100 | $altconv[$altgrp++] = octalize($_)
|
---|
| 5101 | }
|
---|
| 5102 | }
|
---|
| 5103 | foreach my $octet (@altconv) {
|
---|
| 5104 | # if not 's', output
|
---|
| 5105 | print $datafile $octet unless $octet =~ /^s$/;
|
---|
| 5106 | # if 's', output (9-array length)x literal '\000\000'
|
---|
| 5107 | print $datafile '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
|
---|
| 5108 | }
|
---|
[108] | 5109 | print $datafile ":$ttl:$stamp:$loc\n";
|
---|
[103] | 5110 |
|
---|
| 5111 | } elsif ($typemap{$type} eq 'MX') {
|
---|
| 5112 |
|
---|
[108] | 5113 | print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n";
|
---|
[103] | 5114 |
|
---|
| 5115 | } elsif ($typemap{$type} eq 'TXT') {
|
---|
| 5116 |
|
---|
| 5117 | ##fixme: split v-e-r-y long TXT strings? will need to do so for BIND export, at least
|
---|
[350] | 5118 | if ($revrec eq 'n') {
|
---|
| 5119 | $val =~ s/:/\\072/g; # may need to replace other symbols
|
---|
| 5120 | print $datafile "'$host:$val:$ttl:$stamp:$loc\n";
|
---|
| 5121 | } else {
|
---|
| 5122 | $host =~ s/:/\\072/g; # may need to replace other symbols
|
---|
| 5123 | my $val2 = NetAddr::IP->new($val);
|
---|
| 5124 | print $datafile "'"._ZONE($val2, 'ZONE', 'r', '.').($val2->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
| 5125 | ":$host:$ttl:$stamp:$loc\n";
|
---|
| 5126 | }
|
---|
[103] | 5127 |
|
---|
| 5128 | # by-hand TXT
|
---|
| 5129 | #:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
|
---|
| 5130 | #@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
|
---|
| 5131 | #'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
|
---|
| 5132 |
|
---|
| 5133 | #txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
|
---|
| 5134 | #: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
|
---|
| 5135 |
|
---|
| 5136 | # very long TXT record as brought in by axfr-get
|
---|
| 5137 | # note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
|
---|
| 5138 | # also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
|
---|
| 5139 | #:longtxt.deepnet.cx:16:
|
---|
| 5140 | #\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
|
---|
| 5141 | #\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.
|
---|
| 5142 | #\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.
|
---|
| 5143 | #:3600
|
---|
| 5144 |
|
---|
| 5145 | } elsif ($typemap{$type} eq 'CNAME') {
|
---|
| 5146 |
|
---|
[372] | 5147 | if ($revrec eq 'n') {
|
---|
| 5148 | print $datafile "C$host:$val:$ttl:$stamp:$loc\n";
|
---|
| 5149 | } else {
|
---|
| 5150 | my $val2 = NetAddr::IP->new($val);
|
---|
| 5151 | print $datafile "C"._ZONE($val2, 'ZONE', 'r', '.').($val2->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
| 5152 | ":$host:$ttl:$stamp:$loc\n";
|
---|
| 5153 | }
|
---|
[103] | 5154 |
|
---|
| 5155 | } elsif ($typemap{$type} eq 'SRV') {
|
---|
| 5156 |
|
---|
| 5157 | # data is two-byte values for priority, weight, port, in that order,
|
---|
| 5158 | # followed by length/string data
|
---|
| 5159 |
|
---|
| 5160 | print $datafile ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
|
---|
| 5161 |
|
---|
| 5162 | $val .= '.' if $val !~ /\.$/;
|
---|
| 5163 | foreach (split /\./, $val) {
|
---|
| 5164 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
| 5165 | }
|
---|
[108] | 5166 | print $datafile "\\000:$ttl:$stamp:$loc\n";
|
---|
[103] | 5167 |
|
---|
| 5168 | } elsif ($typemap{$type} eq 'RP') {
|
---|
| 5169 |
|
---|
| 5170 | # RP consists of two mostly free-form strings.
|
---|
| 5171 | # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
|
---|
| 5172 | # The second is the "hostname" of a TXT record with more info.
|
---|
| 5173 | print $datafile ":$host:17:";
|
---|
| 5174 | my ($who,$what) = split /\s/, $val;
|
---|
| 5175 | foreach (split /\./, $who) {
|
---|
| 5176 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
| 5177 | }
|
---|
| 5178 | print $datafile '\000';
|
---|
| 5179 | foreach (split /\./, $what) {
|
---|
| 5180 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
| 5181 | }
|
---|
[108] | 5182 | print $datafile "\\000:$ttl:$stamp:$loc\n";
|
---|
[103] | 5183 |
|
---|
| 5184 | } elsif ($typemap{$type} eq 'PTR') {
|
---|
| 5185 |
|
---|
[332] | 5186 | $zone = NetAddr::IP->new($zone);
|
---|
[337] | 5187 | $$recflags{$val}++;
|
---|
[332] | 5188 | if (!$zone->{isv6} && $zone->masklen > 24) {
|
---|
| 5189 | ($val) = ($val =~ /\.(\d+)$/);
|
---|
| 5190 | print $datafile "^$val."._ZONE($zone, 'ZONE', 'r', '.').'.in-addr.arpa'.
|
---|
| 5191 | ":$host:ttl:$stamp:$loc\n";
|
---|
| 5192 | } else {
|
---|
| 5193 | $val = NetAddr::IP->new($val);
|
---|
| 5194 | print $datafile "^".
|
---|
| 5195 | _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
[334] | 5196 | ":$host:$ttl:$stamp:$loc\n";
|
---|
[332] | 5197 | }
|
---|
[103] | 5198 |
|
---|
[333] | 5199 | } elsif ($type == 65280) { # A+PTR
|
---|
[334] | 5200 |
|
---|
[337] | 5201 | $$recflags{$val}++;
|
---|
[334] | 5202 | print $datafile "=$host:$val:$ttl:$stamp:$loc\n";
|
---|
| 5203 |
|
---|
[333] | 5204 | } elsif ($type == 65281) { # AAAA+PTR
|
---|
| 5205 |
|
---|
[337] | 5206 | #$$recflags{$val}++;
|
---|
[333] | 5207 | # treat these as two separate records. since tinydns doesn't have
|
---|
| 5208 | # a native combined type, we have to create them separately anyway.
|
---|
| 5209 | if ($revrec eq 'n') {
|
---|
| 5210 | $type = 28;
|
---|
| 5211 | } else {
|
---|
| 5212 | $type = 12;
|
---|
| 5213 | }
|
---|
[334] | 5214 | _printrec_tiny($datafile,$revrec,$recflags,$zone,$host,$type,$val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
[335] | 5215 | ##fixme: add a config flag to indicate use of the patch from http://www.fefe.de/dns/
|
---|
| 5216 | # type 6 is for AAAA+PTR, type 3 is for AAAA
|
---|
[333] | 5217 |
|
---|
| 5218 | } elsif ($type == 65282) { # PTR template
|
---|
[335] | 5219 |
|
---|
| 5220 | # only useful for v4 with standard DNS software, since this expands all
|
---|
| 5221 | # IPs in $zone (or possibly $val?) with autogenerated records
|
---|
[337] | 5222 | $val = NetAddr::IP->new($val);
|
---|
| 5223 | return if $val->{isv6};
|
---|
[336] | 5224 |
|
---|
[339] | 5225 | if ($val->masklen <= 16) {
|
---|
| 5226 | foreach my $sub ($val->split(16)) {
|
---|
| 5227 | __publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, 1);
|
---|
| 5228 | }
|
---|
| 5229 | } else {
|
---|
| 5230 | __publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, 1);
|
---|
[337] | 5231 | }
|
---|
[335] | 5232 |
|
---|
[333] | 5233 | } elsif ($type == 65283) { # A+PTR template
|
---|
[335] | 5234 |
|
---|
[337] | 5235 | $val = NetAddr::IP->new($val);
|
---|
| 5236 | # Just In Case. An A+PTR should be impossible to add to a v6 revzone via API.
|
---|
| 5237 | return if $val->{isv6};
|
---|
[339] | 5238 |
|
---|
| 5239 | if ($val->masklen <= 16) {
|
---|
| 5240 | foreach my $sub ($val->split(16)) {
|
---|
| 5241 | __publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, 0);
|
---|
| 5242 | }
|
---|
| 5243 | } else {
|
---|
| 5244 | __publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, 0);
|
---|
[337] | 5245 | }
|
---|
[335] | 5246 |
|
---|
[333] | 5247 | } elsif ($type == 65284) { # AAAA+PTR template
|
---|
[335] | 5248 | # Stub for completeness. Could be exported to DNS software that supports
|
---|
| 5249 | # some degree of internal automagic in generic-record-creation
|
---|
| 5250 | # (eg http://search.cpan.org/dist/AllKnowingDNS/ )
|
---|
[333] | 5251 |
|
---|
[345] | 5252 | } elsif ($type == 65285) { # Delegation
|
---|
| 5253 | # This is intended for reverse zones, but may prove useful in forward zones.
|
---|
| 5254 |
|
---|
[346] | 5255 | # All delegations need to create one or more NS records. The NS record handler knows what to do.
|
---|
| 5256 | _printrec_tiny($datafile,$revrec,$recflags,$zone,$host,$reverse_typemap{'NS'},
|
---|
| 5257 | $val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
| 5258 | if ($revrec eq 'y') {
|
---|
| 5259 | # In the case of a sub-/24 v4 reverse delegation, we need to generate CNAMEs
|
---|
| 5260 | # to redirect all of the individual IP lookups as well.
|
---|
| 5261 | # Not sure how this would actually resolve if a /24 or larger was delegated
|
---|
| 5262 | # one way, and a sub-/24 in that >=/24 was delegated elsewhere...
|
---|
| 5263 | my $dblock = NetAddr::IP->new($val);
|
---|
| 5264 | if (!$dblock->{isv6} && $dblock->masklen > 24) {
|
---|
| 5265 | my @subs = $dblock->split;
|
---|
| 5266 | foreach (@subs) {
|
---|
| 5267 | next if $$recflags{"$_"};
|
---|
| 5268 | my ($oct) = ($_->addr =~ /(\d+)$/);
|
---|
| 5269 | print $datafile "C"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$oct.".
|
---|
| 5270 | _ZONE($dblock, 'ZONE.in-addr.arpa', 'r', '.').":$ttl:$stamp:$loc\n";
|
---|
| 5271 | $$recflags{"$_"}++;
|
---|
| 5272 | }
|
---|
| 5273 | }
|
---|
| 5274 | }
|
---|
[345] | 5275 |
|
---|
[364] | 5276 | ##
|
---|
| 5277 | ## Uncommon types. These will need better UI support Any Day Sometime Maybe(TM).
|
---|
| 5278 | ##
|
---|
| 5279 |
|
---|
| 5280 | } elsif ($type == 44) { # SSHFP
|
---|
| 5281 | my ($algo,$fpt,$fp) = split /\s+/, $val;
|
---|
| 5282 |
|
---|
| 5283 | my $rec = sprintf ":$host:44:\\%0.3o\\%0.3o", $algo, $fpt;
|
---|
| 5284 | while (my ($byte) = ($fp =~ /^(..)/) ) {
|
---|
| 5285 | $rec .= sprintf "\\%0.3o", hex($byte);
|
---|
| 5286 | $fp =~ s/^..//;
|
---|
| 5287 | }
|
---|
| 5288 | print $datafile "$rec:$ttl:$stamp:$loc\n";
|
---|
| 5289 |
|
---|
[345] | 5290 | } else {
|
---|
[108] | 5291 | # raw record. we don't know what's in here, so we ASS-U-ME the user has
|
---|
| 5292 | # put it in correctly, since either the user is messing directly with the
|
---|
| 5293 | # database, or the record was imported via AXFR
|
---|
| 5294 | # <split by char>
|
---|
| 5295 | # convert anything not a-zA-Z0-9.- to octal coding
|
---|
| 5296 |
|
---|
| 5297 | ##fixme: add flag to export "unknown" record types - note we'll probably end up
|
---|
| 5298 | # mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
|
---|
| 5299 | #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
|
---|
| 5300 |
|
---|
[103] | 5301 | } # record type if-else
|
---|
| 5302 |
|
---|
[329] | 5303 | } # end _printrec_tiny()
|
---|
[103] | 5304 |
|
---|
| 5305 |
|
---|
[197] | 5306 | ## DNSDB::mailNotify()
|
---|
[283] | 5307 | # Sends notification mail to recipients regarding a DNSDB operation
|
---|
[197] | 5308 | sub mailNotify {
|
---|
[483] | 5309 | my $self = shift;
|
---|
| 5310 | my $dbh = $self->{dbh};
|
---|
[197] | 5311 | my ($subj,$message) = @_;
|
---|
| 5312 |
|
---|
| 5313 | return if $config{mailhost} eq 'smtp.example.com'; # do nothing if still using default SMTP host.
|
---|
| 5314 |
|
---|
| 5315 | my $mailer = Net::SMTP->new($config{mailhost}, Hello => "dnsadmin.$config{domain}");
|
---|
| 5316 |
|
---|
| 5317 | my $mailsender = ($config{mailsender} ? $config{mailsender} : $config{mailnotify});
|
---|
| 5318 |
|
---|
| 5319 | $mailer->mail($mailsender);
|
---|
| 5320 | $mailer->to($config{mailnotify});
|
---|
[198] | 5321 | $mailer->data("From: \"$config{mailname}\" <$mailsender>\n",
|
---|
| 5322 | "To: <$config{mailnotify}>\n",
|
---|
[197] | 5323 | "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
|
---|
| 5324 | "Subject: $subj\n",
|
---|
| 5325 | "X-Mailer: DNSAdmin Notify v".sprintf("%.1d",$DNSDB::VERSION)."\n",
|
---|
| 5326 | "Organization: $config{orgname}\n",
|
---|
| 5327 | "\n$message\n");
|
---|
| 5328 | $mailer->quit;
|
---|
| 5329 | }
|
---|
| 5330 |
|
---|
[2] | 5331 | # shut Perl up
|
---|
| 5332 | 1;
|
---|