[2] | 1 | # dns/trunk/DNSDB.pm
|
---|
| 2 | # Abstraction functions for DNS administration
|
---|
[262] | 3 | ##
|
---|
| 4 | # $Id: DNSDB.pm 485 2013-03-15 16:19:59Z 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 |
|
---|
| 65 | @EXPORT = (); # Export nothing by default.
|
---|
| 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 |
|
---|
[278] | 178 | # Username, full name, ID - mainly for logging
|
---|
| 179 | my %userdata;
|
---|
[228] | 180 |
|
---|
[295] | 181 | # Entity-relationship reference hashes.
|
---|
| 182 | my %par_tbl = (
|
---|
| 183 | group => 'groups',
|
---|
| 184 | user => 'users',
|
---|
| 185 | defrec => 'default_records',
|
---|
| 186 | defrevrec => 'default_rev_records',
|
---|
| 187 | domain => 'domains',
|
---|
| 188 | revzone => 'revzones',
|
---|
| 189 | record => 'records'
|
---|
| 190 | );
|
---|
| 191 | my %id_col = (
|
---|
| 192 | group => 'group_id',
|
---|
| 193 | user => 'user_id',
|
---|
| 194 | defrec => 'record_id',
|
---|
| 195 | defrevrec => 'record_id',
|
---|
| 196 | domain => 'domain_id',
|
---|
| 197 | revzone => 'rdns_id',
|
---|
| 198 | record => 'record_id'
|
---|
| 199 | );
|
---|
| 200 | my %par_col = (
|
---|
| 201 | group => 'parent_group_id',
|
---|
| 202 | user => 'group_id',
|
---|
| 203 | defrec => 'group_id',
|
---|
| 204 | defrevrec => 'group_id',
|
---|
| 205 | domain => 'group_id',
|
---|
| 206 | revzone => 'group_id',
|
---|
| 207 | record => 'domain_id'
|
---|
| 208 | );
|
---|
| 209 | my %par_type = (
|
---|
| 210 | group => 'group',
|
---|
| 211 | user => 'group',
|
---|
| 212 | defrec => 'group',
|
---|
| 213 | defrevrec => 'group',
|
---|
| 214 | domain => 'group',
|
---|
| 215 | revzone => 'group',
|
---|
| 216 | record => 'domain'
|
---|
| 217 | );
|
---|
[278] | 218 |
|
---|
[2] | 219 | ##
|
---|
[465] | 220 | ## Constructor and destructor
|
---|
| 221 | ##
|
---|
| 222 |
|
---|
| 223 | sub new {
|
---|
| 224 | my $this = shift;
|
---|
| 225 | my $class = ref($this) || $this;
|
---|
| 226 | my %args = @_;
|
---|
| 227 | ##fixme? to ponder: do we do some magic if the caller sets eg dbname to prevent parsing of the config file?
|
---|
| 228 | if (!loadConfig(basename => $args{configfile})) {
|
---|
| 229 | warn "Using default configuration; unable to load custom settings: $errstr\n";
|
---|
| 230 | }
|
---|
| 231 | my $self = \%config;
|
---|
| 232 | $self->{configfile} = $args{configfile};
|
---|
| 233 | bless $self, $class;
|
---|
| 234 | $self->{dbh} = connectDB($self->{dbname}, $self->{dbuser}, $self->{dbpass}, $self->{dbhost}) or return;
|
---|
| 235 | $self->initGlobals();
|
---|
| 236 |
|
---|
| 237 | return $self;
|
---|
| 238 | }
|
---|
| 239 |
|
---|
| 240 | sub DESTROY {
|
---|
| 241 | my $self = shift;
|
---|
| 242 | $self->{dbh}->disconnect;
|
---|
| 243 | }
|
---|
| 244 |
|
---|
| 245 | ##
|
---|
[225] | 246 | ## utility functions
|
---|
[281] | 247 | ##
|
---|
| 248 |
|
---|
| 249 | ## DNSDB::_rectable()
|
---|
[224] | 250 | # Takes default+rdns flags, returns appropriate table name
|
---|
| 251 | sub _rectable {
|
---|
| 252 | my $def = shift;
|
---|
| 253 | my $rev = shift;
|
---|
| 254 |
|
---|
| 255 | return 'records' if $def ne 'y';
|
---|
| 256 | return 'default_records' if $rev ne 'y';
|
---|
| 257 | return 'default_rev_records';
|
---|
| 258 | } # end _rectable()
|
---|
| 259 |
|
---|
[281] | 260 | ## DNSDB::_recparent()
|
---|
[224] | 261 | # Takes default+rdns flags, returns appropriate parent-id column name
|
---|
| 262 | sub _recparent {
|
---|
| 263 | my $def = shift;
|
---|
| 264 | my $rev = shift;
|
---|
| 265 |
|
---|
| 266 | return 'group_id' if $def eq 'y';
|
---|
| 267 | return 'rdns_id' if $rev eq 'y';
|
---|
| 268 | return 'domain_id';
|
---|
| 269 | } # end _recparent()
|
---|
| 270 |
|
---|
[281] | 271 | ## DNSDB::_ipparent()
|
---|
[226] | 272 | # Check an IP to be added in a reverse zone to see if it's really in the requested parent.
|
---|
[466] | 273 | # Takes default and reverse flags, IP (fragment) to check, parent zone ID,
|
---|
[226] | 274 | # and a reference to a NetAddr::IP object (also used to pass back a fully-reconstructed IP for
|
---|
| 275 | # database insertion)
|
---|
| 276 | sub _ipparent {
|
---|
[466] | 277 | my $self = shift;
|
---|
| 278 | my $dbh = $self->{dbh};
|
---|
[226] | 279 | my $defrec = shift;
|
---|
| 280 | my $revrec = shift;
|
---|
| 281 | my $val = shift;
|
---|
| 282 | my $id = shift;
|
---|
| 283 | my $addr = shift;
|
---|
[224] | 284 |
|
---|
[232] | 285 | return if $revrec ne 'y'; # this sub not useful in forward zones
|
---|
| 286 |
|
---|
| 287 | $$addr = NetAddr::IP->new($$val); #necessary?
|
---|
| 288 |
|
---|
[226] | 289 | # subsub to split, reverse, and overlay an IP fragment on a netblock
|
---|
| 290 | sub __rev_overlay {
|
---|
| 291 | my $splitme = shift; # ':' or '.', m'lud?
|
---|
| 292 | my $parnet = shift;
|
---|
| 293 | my $val = shift;
|
---|
| 294 | my $addr = shift;
|
---|
| 295 |
|
---|
| 296 | my $joinme = $splitme;
|
---|
| 297 | $splitme = '\.' if $splitme eq '.';
|
---|
[232] | 298 | my @working = reverse(split($splitme, $parnet->addr));
|
---|
| 299 | my @parts = reverse(split($splitme, $$val));
|
---|
[226] | 300 | for (my $i = 0; $i <= $#parts; $i++) {
|
---|
| 301 | $working[$i] = $parts[$i];
|
---|
| 302 | }
|
---|
[232] | 303 | my $checkme = NetAddr::IP->new(join($joinme, reverse(@working))) or return 0;
|
---|
| 304 | return 0 unless $checkme->within($parnet);
|
---|
[226] | 305 | $$addr = $checkme; # force "correct" IP to be recorded.
|
---|
| 306 | return 1;
|
---|
| 307 | }
|
---|
| 308 |
|
---|
| 309 | my ($parstr) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id = ?", undef, ($id));
|
---|
| 310 | my $parnet = NetAddr::IP->new($parstr);
|
---|
| 311 |
|
---|
| 312 | # Fail early on v6-in-v4 or v4-in-v6. We're not accepting these ATM.
|
---|
[232] | 313 | return 0 if $parnet->addr =~ /\./ && $$val =~ /:/;
|
---|
| 314 | return 0 if $parnet->addr =~ /:/ && $$val =~ /\./;
|
---|
[226] | 315 |
|
---|
[340] | 316 | if ($$addr && ($$val =~ /^[\da-fA-F][\da-fA-F:]+[\da-fA-F]$/ || $$val =~ m|/\d+$|)) {
|
---|
| 317 | # the only case where NetAddr::IP's acceptance of legitimate IPs is "correct" is for a proper IPv6 address,
|
---|
| 318 | # or a netblock (only expected on templates)
|
---|
[232] | 319 | # the rest we have to restructure before fiddling. *sigh*
|
---|
| 320 | return 1 if $$addr->within($parnet);
|
---|
| 321 | } else {
|
---|
[340] | 322 | # We don't have a complete IP in $$val (yet)... unless we have a netblock
|
---|
[232] | 323 | if ($parnet->addr =~ /:/) {
|
---|
| 324 | $$val =~ s/^:+//; # gotta strip'em all...
|
---|
[226] | 325 | return __rev_overlay(':', $parnet, $val, $addr);
|
---|
| 326 | }
|
---|
[232] | 327 | if ($parnet->addr =~ /\./) {
|
---|
| 328 | $$val =~ s/^\.+//;
|
---|
| 329 | return __rev_overlay('.', $parnet, $val, $addr);
|
---|
| 330 | }
|
---|
[226] | 331 | # should be impossible to get here...
|
---|
| 332 | }
|
---|
| 333 | # ... and here.
|
---|
| 334 | # can't do nuttin' in forward zones
|
---|
| 335 | } # end _ipparent()
|
---|
| 336 |
|
---|
[281] | 337 | ## DNSDB::_hostparent()
|
---|
[232] | 338 | # A little different than _ipparent above; this tries to *find* the parent zone of a hostname
|
---|
[466] | 339 | # Takes a hostname.
|
---|
[281] | 340 | # Returns the domain ID of the parent domain if one was found.
|
---|
[232] | 341 | sub _hostparent {
|
---|
[466] | 342 | my $self = shift;
|
---|
| 343 | my $dbh = $self->{dbh};
|
---|
[232] | 344 | my $hname = shift;
|
---|
[347] | 345 |
|
---|
| 346 | $hname =~ s/^\*\.//; # this should be impossible to find in the domains table.
|
---|
[232] | 347 | my @hostbits = split /\./, $hname;
|
---|
[349] | 348 | my $sth = $dbh->prepare("SELECT count(*),domain_id FROM domains WHERE lower(domain) = lower(?) GROUP BY domain_id");
|
---|
[232] | 349 | foreach (@hostbits) {
|
---|
| 350 | $sth->execute($hname);
|
---|
| 351 | my ($found, $parid) = $sth->fetchrow_array;
|
---|
| 352 | if ($found) {
|
---|
| 353 | return $parid;
|
---|
| 354 | }
|
---|
| 355 | $hname =~ s/^$_\.//;
|
---|
| 356 | }
|
---|
| 357 | } # end _hostparent()
|
---|
[228] | 358 |
|
---|
[281] | 359 | ## DNSDB::_log()
|
---|
| 360 | # Log an action
|
---|
[466] | 361 | # Takes a log entry hash containing at least:
|
---|
[282] | 362 | # group_id, log entry
|
---|
[281] | 363 | # and optionally one or more of:
|
---|
| 364 | # domain_id, rdns_id
|
---|
[282] | 365 | # The %userdata hash provides the user ID, username, and fullname
|
---|
[281] | 366 | sub _log {
|
---|
[466] | 367 | my $self = shift;
|
---|
| 368 | my $dbh = $self->{dbh};
|
---|
[281] | 369 |
|
---|
| 370 | my %args = @_;
|
---|
| 371 |
|
---|
| 372 | $args{rdns_id} = 0 if !$args{rdns_id};
|
---|
| 373 | $args{domain_id} = 0 if !$args{domain_id};
|
---|
| 374 |
|
---|
| 375 | ##fixme: farm out the actual logging to different subs for file, syslog, internal, etc based on config
|
---|
| 376 | # if ($config{log_channel} eq 'sql') {
|
---|
| 377 | $dbh->do("INSERT INTO log (domain_id,rdns_id,group_id,entry,user_id,email,name) VALUES (?,?,?,?,?,?,?)",
|
---|
| 378 | undef,
|
---|
| 379 | ($args{domain_id}, $args{rdns_id}, $args{group_id}, $args{entry},
|
---|
| 380 | $userdata{userid}, $userdata{username}, $userdata{fullname}) );
|
---|
| 381 | # } elsif ($config{log_channel} eq 'file') {
|
---|
| 382 | # } elsif ($config{log_channel} eq 'syslog') {
|
---|
| 383 | # }
|
---|
| 384 | } # end _log
|
---|
| 385 |
|
---|
| 386 |
|
---|
[224] | 387 | ##
|
---|
[228] | 388 | ## Record validation subs.
|
---|
| 389 | ##
|
---|
| 390 |
|
---|
[281] | 391 | ## All of these subs take substantially the same arguments:
|
---|
| 392 | # a hash containing at least the following keys:
|
---|
| 393 | # - defrec (default/live flag)
|
---|
| 394 | # - revrec (forward/reverse flag)
|
---|
| 395 | # - id (parent entity ID)
|
---|
| 396 | # - host (hostname)
|
---|
| 397 | # - rectype
|
---|
| 398 | # - val (IP, hostname [CNAME/MX/SRV] or text)
|
---|
| 399 | # - addr (NetAddr::IP object from val. May be undef.)
|
---|
| 400 | # MX and SRV record validation also expect distance, and SRV records expect weight and port as well.
|
---|
| 401 | # host, rectype, and addr should be references as these may be modified in validation
|
---|
| 402 |
|
---|
[228] | 403 | # A record
|
---|
| 404 | sub _validate_1 {
|
---|
[467] | 405 | my $self = shift;
|
---|
| 406 | my $dbh = $self->{dbh};
|
---|
[229] | 407 |
|
---|
[230] | 408 | my %args = @_;
|
---|
[229] | 409 |
|
---|
[230] | 410 | return ('FAIL', 'Reverse zones cannot contain A records') if $args{revrec} eq 'y';
|
---|
[229] | 411 |
|
---|
| 412 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 413 | # or the intended parent domain for live records.
|
---|
[467] | 414 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[230] | 415 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
[229] | 416 |
|
---|
| 417 | # Check IP is well-formed, and that it's a v4 address
|
---|
[234] | 418 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
|
---|
[232] | 419 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
[234] | 420 | unless ${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/;
|
---|
| 421 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
[230] | 422 | unless $args{addr} && !$args{addr}->{isv6};
|
---|
[229] | 423 | # coerce IP/value to normalized form for storage
|
---|
[230] | 424 | ${$args{val}} = $args{addr}->addr;
|
---|
[229] | 425 |
|
---|
[228] | 426 | return ('OK','OK');
|
---|
| 427 | } # done A record
|
---|
| 428 |
|
---|
| 429 | # NS record
|
---|
| 430 | sub _validate_2 {
|
---|
[467] | 431 | my $self = shift;
|
---|
| 432 | my $dbh = $self->{dbh};
|
---|
[230] | 433 |
|
---|
| 434 | my %args = @_;
|
---|
| 435 |
|
---|
[328] | 436 | # Check that the target of the record is within the parent.
|
---|
| 437 | # Yes, host<->val are mixed up here; can't see a way to avoid it. :(
|
---|
| 438 | if ($args{defrec} eq 'n') {
|
---|
| 439 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
| 440 | if ($args{revrec} eq 'y') {
|
---|
| 441 | my $tmpip = NetAddr::IP->new(${$args{val}});
|
---|
[467] | 442 | my $pname = $self->revName($args{id});
|
---|
[328] | 443 | return ('FAIL',"${$args{val}} not within $pname")
|
---|
[467] | 444 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$tmpip);
|
---|
[328] | 445 | # Sub the returned thing for ZONE? This could get stupid if you have typos...
|
---|
| 446 | ${$args{val}} =~ s/ZONE/$tmpip->address/;
|
---|
| 447 | } else {
|
---|
[467] | 448 | my $pname = $self->domainName($args{id});
|
---|
[328] | 449 | ${$args{host}} = $pname if ${$args{host}} !~ /\.$pname$/;
|
---|
| 450 | }
|
---|
[230] | 451 | } else {
|
---|
[328] | 452 | # Default reverse NS records should always refer to the implied parent
|
---|
| 453 | ${$args{host}} = 'DOMAIN' if $args{revrec} eq 'n';
|
---|
| 454 | ${$args{val}} = 'ZONE' if $args{revrec} eq 'y';
|
---|
[230] | 455 | }
|
---|
| 456 |
|
---|
| 457 | # Let this lie for now. Needs more magic.
|
---|
| 458 | # # Check IP is well-formed, and that it's a v4 address
|
---|
| 459 | # return ('FAIL',"A record must be a valid IPv4 address")
|
---|
| 460 | # unless $addr && !$addr->{isv6};
|
---|
| 461 | # # coerce IP/value to normalized form for storage
|
---|
| 462 | # $$val = $addr->addr;
|
---|
| 463 |
|
---|
[228] | 464 | return ('OK','OK');
|
---|
| 465 | } # done NS record
|
---|
| 466 |
|
---|
| 467 | # CNAME record
|
---|
| 468 | sub _validate_5 {
|
---|
[467] | 469 | my $self = shift;
|
---|
| 470 | my $dbh = $self->{dbh};
|
---|
[230] | 471 |
|
---|
| 472 | my %args = @_;
|
---|
| 473 |
|
---|
| 474 | # Not really true, but these are only useful for delegating smaller-than-/24 IP blocks.
|
---|
| 475 | # This is fundamentally a messy operation and should really just be taken care of by the
|
---|
| 476 | # export process, not manual maintenance of the necessary records.
|
---|
| 477 | return ('FAIL', 'Reverse zones cannot contain CNAME records') if $args{revrec} eq 'y';
|
---|
| 478 |
|
---|
| 479 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 480 | # or the intended parent domain for live records.
|
---|
[467] | 481 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[230] | 482 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 483 |
|
---|
[228] | 484 | return ('OK','OK');
|
---|
| 485 | } # done CNAME record
|
---|
| 486 |
|
---|
| 487 | # SOA record
|
---|
| 488 | sub _validate_6 {
|
---|
[230] | 489 | # Smart monkeys won't stick their fingers in here; we have
|
---|
| 490 | # separate dedicated routines to deal with SOA records.
|
---|
[228] | 491 | return ('OK','OK');
|
---|
| 492 | } # done SOA record
|
---|
| 493 |
|
---|
| 494 | # PTR record
|
---|
| 495 | sub _validate_12 {
|
---|
[467] | 496 | my $self = shift;
|
---|
| 497 | my $dbh = $self->{dbh};
|
---|
[232] | 498 |
|
---|
| 499 | my %args = @_;
|
---|
| 500 |
|
---|
| 501 | if ($args{revrec} eq 'y') {
|
---|
| 502 | if ($args{defrec} eq 'n') {
|
---|
[467] | 503 | return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
| 504 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
[232] | 505 | ${$args{val}} = $args{addr}->addr;
|
---|
| 506 | } else {
|
---|
[234] | 507 | if (${$args{val}} =~ /\./) {
|
---|
| 508 | # looks like a v4 or fragment
|
---|
| 509 | if (${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/) {
|
---|
| 510 | # woo! a complete IP! validate it and normalize, or fail.
|
---|
| 511 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
| 512 | or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
|
---|
| 513 | ${$args{val}} = $args{addr}->addr;
|
---|
| 514 | } else {
|
---|
[249] | 515 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
[234] | 516 | }
|
---|
| 517 | } elsif (${$args{val}} =~ /[a-f:]/) {
|
---|
| 518 | # looks like a v6 or fragment
|
---|
[251] | 519 | ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
|
---|
[234] | 520 | if ($args{addr}) {
|
---|
| 521 | if ($args{addr}->addr =~ /^0/) {
|
---|
[251] | 522 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
[234] | 523 | } else {
|
---|
| 524 | ${$args{val}} = $args{addr}->addr;
|
---|
| 525 | }
|
---|
| 526 | }
|
---|
| 527 | } else {
|
---|
| 528 | # bare number (probably). These could be v4 or v6, so we'll
|
---|
| 529 | # expand on these on creation of a reverse zone.
|
---|
[251] | 530 | ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
|
---|
[234] | 531 | }
|
---|
[249] | 532 | ${$args{host}} =~ s/\.*$/\.$config{domain}/ if ${$args{host}} !~ /(?:$config{domain}|ADMINDOMAIN)$/;
|
---|
[232] | 533 | }
|
---|
| 534 |
|
---|
| 535 | # Multiple PTR records do NOT generally do what most people believe they do,
|
---|
| 536 | # and tend to fail in the most awkward way possible. Check and warn.
|
---|
| 537 | # We use $val instead of $addr->addr since we may be in a defrec, and may have eg "ZONE::42" or "ZONE.12"
|
---|
[249] | 538 |
|
---|
| 539 | my @checkvals = (${$args{val}});
|
---|
| 540 | if (${$args{val}} =~ /,/) {
|
---|
| 541 | # push . and :: variants into checkvals if val has ,
|
---|
| 542 | my $tmp;
|
---|
| 543 | ($tmp = ${$args{val}}) =~ s/,/./;
|
---|
| 544 | push @checkvals, $tmp;
|
---|
| 545 | ($tmp = ${$args{val}}) =~ s/,/::/;
|
---|
| 546 | push @checkvals, $tmp;
|
---|
| 547 | }
|
---|
| 548 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ?");
|
---|
| 549 | foreach my $checkme (@checkvals) {
|
---|
[272] | 550 | if ($args{update}) {
|
---|
| 551 | # Record update. There should usually be an existing PTR (the record being updated)
|
---|
| 552 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 553 | " WHERE val = ?", undef, ($checkme)) };
|
---|
| 554 | return ('WARN', "PTR record for $checkme already exists; adding another will probably not do what you want")
|
---|
[273] | 555 | if @ptrs && (!grep /^$args{update}$/, @ptrs);
|
---|
[272] | 556 | } else {
|
---|
| 557 | # New record. Always warn if a PTR exists
|
---|
| 558 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 559 | " WHERE val = ?", undef, ($checkme));
|
---|
| 560 | return ('WARN', "PTR record for $checkme already exists; adding another will probably not do what you want")
|
---|
| 561 | if $ptrcount;
|
---|
| 562 | }
|
---|
[249] | 563 | }
|
---|
[272] | 564 |
|
---|
[232] | 565 | } else {
|
---|
| 566 | # Not absolutely true but only useful if you hack things up for sub-/24 v4 reverse delegations
|
---|
| 567 | # Simpler to just create the reverse zone and grant access for the customer to edit it, and create direct
|
---|
| 568 | # PTR records on export
|
---|
| 569 | return ('FAIL',"Forward zones cannot contain PTR records");
|
---|
| 570 | }
|
---|
| 571 |
|
---|
[228] | 572 | return ('OK','OK');
|
---|
| 573 | } # done PTR record
|
---|
| 574 |
|
---|
| 575 | # MX record
|
---|
| 576 | sub _validate_15 {
|
---|
[467] | 577 | my $self = shift;
|
---|
| 578 | my $dbh = $self->{dbh};
|
---|
[230] | 579 |
|
---|
| 580 | my %args = @_;
|
---|
| 581 |
|
---|
| 582 | # Not absolutely true but WTF use is an MX record for a reverse zone?
|
---|
| 583 | return ('FAIL', 'Reverse zones cannot contain MX records') if $args{revrec} eq 'y';
|
---|
| 584 |
|
---|
| 585 | return ('FAIL', "Distance is required for MX records") unless defined(${$args{dist}});
|
---|
| 586 | ${$args{dist}} =~ s/\s*//g;
|
---|
| 587 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
|
---|
| 588 |
|
---|
| 589 | ${$args{fields}} = "distance,";
|
---|
| 590 | push @{$args{vallist}}, ${$args{dist}};
|
---|
| 591 |
|
---|
| 592 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 593 | # or the intended parent domain for live records.
|
---|
[467] | 594 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[230] | 595 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 596 |
|
---|
[273] | 597 | # hmm.. this might work. except possibly for something pointing to "deadbeef.ca". <g>
|
---|
| 598 | # if ($type == $reverse_typemap{NS} || $type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
|
---|
| 599 | # if ($val =~ /^\s*[\da-f:.]+\s*$/) {
|
---|
| 600 | # return ('FAIL',"$val is not a valid IP address") if !$addr;
|
---|
| 601 | # }
|
---|
| 602 | # }
|
---|
| 603 |
|
---|
[228] | 604 | return ('OK','OK');
|
---|
| 605 | } # done MX record
|
---|
| 606 |
|
---|
| 607 | # TXT record
|
---|
| 608 | sub _validate_16 {
|
---|
[231] | 609 | # Could arguably put a WARN return here on very long (>512) records
|
---|
[228] | 610 | return ('OK','OK');
|
---|
| 611 | } # done TXT record
|
---|
| 612 |
|
---|
| 613 | # RP record
|
---|
| 614 | sub _validate_17 {
|
---|
[231] | 615 | # Probably have to validate these some day
|
---|
[228] | 616 | return ('OK','OK');
|
---|
| 617 | } # done RP record
|
---|
| 618 |
|
---|
| 619 | # AAAA record
|
---|
| 620 | sub _validate_28 {
|
---|
[467] | 621 | my $self = shift;
|
---|
| 622 | my $dbh = $self->{dbh};
|
---|
[229] | 623 |
|
---|
[230] | 624 | my %args = @_;
|
---|
[229] | 625 |
|
---|
[230] | 626 | return ('FAIL', 'Reverse zones cannot contain AAAA records') if $args{revrec} eq 'y';
|
---|
[229] | 627 |
|
---|
| 628 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 629 | # or the intended parent domain for live records.
|
---|
[467] | 630 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[230] | 631 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
[229] | 632 |
|
---|
| 633 | # Check IP is well-formed, and that it's a v6 address
|
---|
[232] | 634 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
|
---|
[230] | 635 | unless $args{addr} && $args{addr}->{isv6};
|
---|
[229] | 636 | # coerce IP/value to normalized form for storage
|
---|
[230] | 637 | ${$args{val}} = $args{addr}->addr;
|
---|
[229] | 638 |
|
---|
[228] | 639 | return ('OK','OK');
|
---|
| 640 | } # done AAAA record
|
---|
| 641 |
|
---|
| 642 | # SRV record
|
---|
| 643 | sub _validate_33 {
|
---|
[467] | 644 | my $self = shift;
|
---|
| 645 | my $dbh = $self->{dbh};
|
---|
[231] | 646 |
|
---|
| 647 | my %args = @_;
|
---|
| 648 |
|
---|
| 649 | # Not absolutely true but WTF use is an SRV record for a reverse zone?
|
---|
| 650 | return ('FAIL', 'Reverse zones cannot contain SRV records') if $args{revrec} eq 'y';
|
---|
| 651 |
|
---|
| 652 | return ('FAIL', "Distance is required for SRV records") unless defined(${$args{dist}});
|
---|
| 653 | ${$args{dist}} =~ s/\s*//g;
|
---|
| 654 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
|
---|
| 655 |
|
---|
| 656 | return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]")
|
---|
| 657 | unless ${$args{host}} =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/;
|
---|
| 658 | return ('FAIL',"Port and weight are required for SRV records")
|
---|
| 659 | unless defined(${$args{weight}}) && defined(${$args{port}});
|
---|
| 660 | ${$args{weight}} =~ s/\s*//g;
|
---|
| 661 | ${$args{port}} =~ s/\s*//g;
|
---|
| 662 |
|
---|
| 663 | return ('FAIL',"Port and weight are required, and must be numeric")
|
---|
| 664 | unless ${$args{weight}} =~ /^\d+$/ && ${$args{port}} =~ /^\d+$/;
|
---|
| 665 |
|
---|
| 666 | ${$args{fields}} = "distance,weight,port,";
|
---|
| 667 | push @{$args{vallist}}, (${$args{dist}}, ${$args{weight}}, ${$args{port}});
|
---|
| 668 |
|
---|
| 669 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 670 | # or the intended parent domain for live records.
|
---|
[467] | 671 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
[231] | 672 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 673 |
|
---|
[228] | 674 | return ('OK','OK');
|
---|
| 675 | } # done SRV record
|
---|
| 676 |
|
---|
| 677 | # Now the custom types
|
---|
| 678 |
|
---|
[232] | 679 | # A+PTR record. With a very little bit of magic we can also use this sub to validate AAAA+PTR. Whee!
|
---|
[228] | 680 | sub _validate_65280 {
|
---|
[467] | 681 | my $self = shift;
|
---|
| 682 | my $dbh = $self->{dbh};
|
---|
[232] | 683 |
|
---|
| 684 | my %args = @_;
|
---|
| 685 |
|
---|
| 686 | my $code = 'OK';
|
---|
| 687 | my $msg = 'OK';
|
---|
| 688 |
|
---|
| 689 | if ($args{defrec} eq 'n') {
|
---|
| 690 | # live record; revrec determines whether we validate the PTR or A component first.
|
---|
[233] | 691 |
|
---|
[232] | 692 | if ($args{revrec} eq 'y') {
|
---|
[467] | 693 | ($code,$msg) = $self->_validate_12(%args);
|
---|
[232] | 694 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 695 |
|
---|
[467] | 696 | # check A+PTR is really v4
|
---|
| 697 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
| 698 | if ${$args{rectype}} == 65280 && $args{addr}->{isv6};
|
---|
| 699 | # check AAAA+PTR is really v6
|
---|
| 700 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
|
---|
| 701 | if ${$args{rectype}} == 65281 && !$args{addr}->{isv6};
|
---|
| 702 |
|
---|
[232] | 703 | # Check if the reqested domain exists. If not, coerce the type down to PTR and warn.
|
---|
[467] | 704 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) {
|
---|
[272] | 705 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
| 706 | " as PTR instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
[232] | 707 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
| 708 | $msg = $addmsg if $code eq 'OK';
|
---|
| 709 | ${$args{rectype}} = $reverse_typemap{PTR};
|
---|
| 710 | return ('WARN', $msg);
|
---|
| 711 | }
|
---|
| 712 |
|
---|
[242] | 713 | # Add domain ID to field list and values
|
---|
| 714 | ${$args{fields}} .= "domain_id,";
|
---|
| 715 | push @{$args{vallist}}, ${$args{domid}};
|
---|
| 716 |
|
---|
[232] | 717 | } else {
|
---|
[467] | 718 | ($code,$msg) = $self->_validate_1(%args) if ${$args{rectype}} == 65280;
|
---|
| 719 | ($code,$msg) = $self->_validate_28(%args) if ${$args{rectype}} == 65281;
|
---|
[232] | 720 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 721 |
|
---|
| 722 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
| 723 | # work here since we don't *know* which parent to put it in.
|
---|
[233] | 724 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
[232] | 725 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
| 726 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
| 727 | if (!$revid) {
|
---|
[272] | 728 | $msg = "Record ".($args{update} ? 'updated' : 'added')." as ".(${$args{rectype}} == 65280 ? 'A' : 'AAAA').
|
---|
[232] | 729 | " instead of $typemap{${$args{rectype}}}; reverse zone not found for ${$args{val}}";
|
---|
| 730 | ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
| 731 | return ('WARN', $msg);
|
---|
| 732 | }
|
---|
| 733 |
|
---|
| 734 | # Check for duplicate PTRs. Note we don't have to play games with $code and $msg, because
|
---|
| 735 | # by definition there can't be duplicate PTRs if the reverse zone isn't managed here.
|
---|
[272] | 736 | if ($args{update}) {
|
---|
| 737 | # Record update. There should usually be an existing PTR (the record being updated)
|
---|
| 738 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 739 | " WHERE val = ?", undef, (${$args{val}})) };
|
---|
[273] | 740 | if (@ptrs && (!grep /^$args{update}$/, @ptrs)) {
|
---|
[272] | 741 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
|
---|
| 742 | $code = 'WARN';
|
---|
| 743 | }
|
---|
| 744 | } else {
|
---|
| 745 | # New record. Always warn if a PTR exists
|
---|
| 746 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 747 | " WHERE val = ?", undef, (${$args{val}}));
|
---|
| 748 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want"
|
---|
| 749 | if $ptrcount;
|
---|
| 750 | $code = 'WARN' if $ptrcount;
|
---|
[232] | 751 | }
|
---|
| 752 |
|
---|
[272] | 753 | # my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 754 | # " WHERE val = ?", undef, ${$args{val}});
|
---|
| 755 | # if ($ptrcount) {
|
---|
| 756 | # my $curid = $dbh->selectrow_array("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 757 | # " WHERE val = ?
|
---|
| 758 | # $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
|
---|
| 759 | # $code = 'WARN';
|
---|
| 760 | # }
|
---|
| 761 |
|
---|
[232] | 762 | ${$args{fields}} .= "rdns_id,";
|
---|
| 763 | push @{$args{vallist}}, $revid;
|
---|
| 764 | }
|
---|
| 765 |
|
---|
[233] | 766 | } else { # defrec eq 'y'
|
---|
| 767 | if ($args{revrec} eq 'y') {
|
---|
[467] | 768 | ($code,$msg) = $self->_validate_12(%args);
|
---|
[233] | 769 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 770 | if (${$args{rectype}} == 65280) {
|
---|
| 771 | return ('FAIL',"A+PTR record must be a valid IPv4 address or fragment")
|
---|
| 772 | if ${$args{val}} =~ /:/;
|
---|
[234] | 773 | ${$args{val}} =~ s/^ZONE,/ZONE./; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
[233] | 774 | } elsif (${$args{rectype}} == 65281) {
|
---|
| 775 | return ('FAIL',"AAAA+PTR record must be a valid IPv6 address or fragment")
|
---|
| 776 | if ${$args{val}} =~ /\./;
|
---|
[234] | 777 | ${$args{val}} =~ s/^ZONE,/ZONE::/; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
[233] | 778 | }
|
---|
| 779 | } else {
|
---|
| 780 | # This is easy. I also can't see a real use-case for A/AAAA+PTR in *all* forward
|
---|
| 781 | # domains, since you wouldn't be able to substitute both domain and reverse zone
|
---|
| 782 | # sanely, and you'd end up with guaranteed over-replicated PTR records that would
|
---|
| 783 | # confuse the hell out of pretty much anything that uses them.
|
---|
[234] | 784 | ##fixme: make this a config flag?
|
---|
[233] | 785 | return ('FAIL', "$typemap{${$args{rectype}}} records not allowed in default domains");
|
---|
| 786 | }
|
---|
[232] | 787 | }
|
---|
| 788 |
|
---|
| 789 | return ($code, $msg);
|
---|
[228] | 790 | } # done A+PTR record
|
---|
| 791 |
|
---|
| 792 | # AAAA+PTR record
|
---|
[232] | 793 | # A+PTR above has been magicked to handle AAAA+PTR as well.
|
---|
[228] | 794 | sub _validate_65281 {
|
---|
[232] | 795 | return _validate_65280(@_);
|
---|
[228] | 796 | } # done AAAA+PTR record
|
---|
| 797 |
|
---|
| 798 | # PTR template record
|
---|
| 799 | sub _validate_65282 {
|
---|
[467] | 800 | my $self = shift;
|
---|
| 801 | my $dbh = $self->{dbh};
|
---|
[340] | 802 |
|
---|
| 803 | my %args = @_;
|
---|
| 804 |
|
---|
| 805 | # we're *this* >.< close to being able to just call _validate_12... unfortunately we can't, quite.
|
---|
| 806 | if ($args{revrec} eq 'y') {
|
---|
| 807 | if ($args{defrec} eq 'n') {
|
---|
[467] | 808 | return ('FAIL', "Template block ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
| 809 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
[340] | 810 | ##fixme: warn if $args{val} is not /31 or larger block?
|
---|
| 811 | ${$args{val}} = "$args{addr}";
|
---|
| 812 | } else {
|
---|
| 813 | if (${$args{val}} =~ /\./) {
|
---|
| 814 | # looks like a v4 or fragment
|
---|
| 815 | if (${$args{val}} =~ m|^\d+\.\d+\.\d+\.\d+(?:/\d+)?$|) {
|
---|
| 816 | # woo! a complete IP! validate it and normalize, or fail.
|
---|
| 817 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
| 818 | or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
|
---|
| 819 | ${$args{val}} = "$args{addr}";
|
---|
| 820 | } else {
|
---|
| 821 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
| 822 | }
|
---|
| 823 | } elsif (${$args{val}} =~ /[a-f:]/) {
|
---|
| 824 | # looks like a v6 or fragment
|
---|
| 825 | ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
|
---|
| 826 | if ($args{addr}) {
|
---|
| 827 | if ($args{addr}->addr =~ /^0/) {
|
---|
| 828 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
| 829 | } else {
|
---|
| 830 | ${$args{val}} = "$args{addr}";
|
---|
| 831 | }
|
---|
| 832 | }
|
---|
| 833 | } else {
|
---|
| 834 | # bare number (probably). These could be v4 or v6, so we'll
|
---|
| 835 | # expand on these on creation of a reverse zone.
|
---|
| 836 | ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
|
---|
| 837 | }
|
---|
| 838 | }
|
---|
| 839 | ##fixme: validate %-patterns?
|
---|
| 840 |
|
---|
| 841 | # Unlike single PTR records, there is absolutely no way to sanely support multiple
|
---|
| 842 | # PTR templates for the same block, since they expect to expand to all the individual
|
---|
| 843 | # IPs on export. Nested templates should be supported though.
|
---|
| 844 |
|
---|
| 845 | my @checkvals = (${$args{val}});
|
---|
| 846 | if (${$args{val}} =~ /,/) {
|
---|
| 847 | # push . and :: variants into checkvals if val has ,
|
---|
| 848 | my $tmp;
|
---|
| 849 | ($tmp = ${$args{val}}) =~ s/,/./;
|
---|
| 850 | push @checkvals, $tmp;
|
---|
| 851 | ($tmp = ${$args{val}}) =~ s/,/::/;
|
---|
| 852 | push @checkvals, $tmp;
|
---|
| 853 | }
|
---|
| 854 | ##fixme: this feels wrong still - need to restrict template pseudorecords to One Of Each
|
---|
| 855 | # Per Netblock such that they don't conflict on export
|
---|
| 856 | my $typeck;
|
---|
| 857 | # type 65282 -> ptr template -> look for any of 65282, 65283, 65284
|
---|
| 858 | $typeck = 'type=65283 OR type=65284' if ${$args{rectype}} == 65282;
|
---|
| 859 | # type 65283 -> a+ptr template -> v4 -> look for 65282 or 65283
|
---|
| 860 | $typeck = 'type=65283' if ${$args{rectype}} == 65282;
|
---|
| 861 | # type 65284 -> aaaa+ptr template -> v6 -> look for 65282 or 65284
|
---|
| 862 | $typeck = 'type=65284' if ${$args{rectype}} == 65282;
|
---|
| 863 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ? ".
|
---|
| 864 | "AND (type=65282 OR $typeck)");
|
---|
| 865 | foreach my $checkme (@checkvals) {
|
---|
| 866 | $pcsth->execute($checkme);
|
---|
| 867 | my ($rc) = $pcsth->fetchrow_array;
|
---|
[442] | 868 | return ('FAIL', "Only one template pseudorecord may exist for a given IP block") if $rc > 1;
|
---|
[340] | 869 | }
|
---|
| 870 |
|
---|
| 871 | } else {
|
---|
| 872 | return ('FAIL', "Forward zones cannot contain PTR records");
|
---|
| 873 | }
|
---|
| 874 |
|
---|
[228] | 875 | return ('OK','OK');
|
---|
| 876 | } # done PTR template record
|
---|
| 877 |
|
---|
| 878 | # A+PTR template record
|
---|
| 879 | sub _validate_65283 {
|
---|
[467] | 880 | my $self = shift;
|
---|
| 881 | my $dbh = $self->{dbh};
|
---|
[340] | 882 |
|
---|
| 883 | my %args = @_;
|
---|
| 884 |
|
---|
| 885 | my ($code,$msg) = ('OK','OK');
|
---|
| 886 |
|
---|
| 887 | ##fixme: need to fiddle things since A+PTR templates are acceptable in live
|
---|
| 888 | # forward zones but not default records
|
---|
| 889 | if ($args{defrec} eq 'n') {
|
---|
| 890 | if ($args{revrec} eq 'n') {
|
---|
[467] | 891 | ($code,$msg) = $self->_validate_1(%args) if ${$args{rectype}} == 65280;
|
---|
| 892 | ($code,$msg) = $self->_validate_28(%args) if ${$args{rectype}} == 65281;
|
---|
[340] | 893 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 894 |
|
---|
| 895 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
| 896 | # work here since we don't *know* which parent to put it in.
|
---|
| 897 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
| 898 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
| 899 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
| 900 | # Fail if no match; we can't coerce a PTR-template type down to not include the PTR bit currently.
|
---|
| 901 | if (!$revid) {
|
---|
| 902 | $msg = "Can't ".($args{update} ? 'update' : 'add')." ${$args{host}}/${$args{val}} as ".
|
---|
| 903 | "$typemap{${$args{rectype}}}: reverse zone not found for ${$args{val}}";
|
---|
| 904 | ##fixme: add A template, AAAA template types?
|
---|
| 905 | # ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
| 906 | return ('FAIL', $msg);
|
---|
| 907 | }
|
---|
| 908 |
|
---|
| 909 | # Add reverse zone ID to field list and values
|
---|
| 910 | ${$args{fields}} .= "rdns_id,";
|
---|
| 911 | push @{$args{vallist}}, $revid;
|
---|
| 912 |
|
---|
| 913 | } else {
|
---|
[467] | 914 | return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
| 915 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
[340] | 916 | ${$args{val}} = "$args{addr}";
|
---|
| 917 |
|
---|
[467] | 918 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) {
|
---|
[340] | 919 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
| 920 | " as PTR template instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
| 921 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
| 922 | $msg = $addmsg if $code eq 'OK';
|
---|
| 923 | ${$args{rectype}} = 65282;
|
---|
| 924 | return ('WARN', $msg);
|
---|
| 925 | }
|
---|
| 926 |
|
---|
| 927 | # Add domain ID to field list and values
|
---|
| 928 | ${$args{fields}} .= "domain_id,";
|
---|
| 929 | push @{$args{vallist}}, ${$args{domid}};
|
---|
| 930 | }
|
---|
| 931 |
|
---|
| 932 | } else {
|
---|
[467] | 933 | my ($code,$msg) = $self->_validate_65282(%args);
|
---|
[340] | 934 | return ($code, $msg) if $code eq 'FAIL';
|
---|
| 935 | # get domain, check against ${$args{name}}
|
---|
| 936 | }
|
---|
| 937 |
|
---|
[228] | 938 | return ('OK','OK');
|
---|
| 939 | } # done AAAA+PTR template record
|
---|
| 940 |
|
---|
| 941 | # AAAA+PTR template record
|
---|
| 942 | sub _validate_65284 {
|
---|
| 943 | return ('OK','OK');
|
---|
| 944 | } # done AAAA+PTR template record
|
---|
| 945 |
|
---|
[342] | 946 | # Delegation record
|
---|
[345] | 947 | # This is essentially a specialized clone of the NS record, primarily useful
|
---|
| 948 | # for delegating IPv4 sub-/24 reverse blocks
|
---|
[342] | 949 | sub _validate_65285 {
|
---|
[467] | 950 | my $self = shift;
|
---|
| 951 | my $dbh = $self->{dbh};
|
---|
[345] | 952 |
|
---|
| 953 | my %args = @_;
|
---|
| 954 |
|
---|
| 955 | # Almost, but not quite, identical to NS record validation.
|
---|
| 956 |
|
---|
| 957 | # Check that the target of the record is within the parent.
|
---|
| 958 | # Yes, host<->val are mixed up here; can't see a way to avoid it. :(
|
---|
| 959 | if ($args{defrec} eq 'n') {
|
---|
| 960 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
| 961 | if ($args{revrec} eq 'y') {
|
---|
| 962 | my $tmpip = NetAddr::IP->new(${$args{val}});
|
---|
[467] | 963 | my $pname = $self->revName($args{id});
|
---|
[345] | 964 | return ('FAIL',"${$args{val}} not within $pname")
|
---|
[467] | 965 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$tmpip);
|
---|
[345] | 966 | # Normalize
|
---|
| 967 | ${$args{val}} = "$tmpip";
|
---|
| 968 | } else {
|
---|
[467] | 969 | my $pname = $self->domainName($args{id});
|
---|
[345] | 970 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 971 | }
|
---|
| 972 | } else {
|
---|
| 973 | return ('FAIL',"Delegation records are not permitted in default record sets");
|
---|
| 974 | }
|
---|
[342] | 975 | return ('OK','OK');
|
---|
| 976 | }
|
---|
[228] | 977 |
|
---|
[342] | 978 |
|
---|
[265] | 979 | ##
|
---|
| 980 | ## Record data substitution subs
|
---|
| 981 | ##
|
---|
[228] | 982 |
|
---|
[298] | 983 | # Replace ZONE in hostname, or create (most of) the actual proper zone name
|
---|
[265] | 984 | sub _ZONE {
|
---|
| 985 | my $zone = shift;
|
---|
| 986 | my $string = shift;
|
---|
| 987 | my $fr = shift || 'f'; # flag for forward/reverse order? nb: ignored for IP
|
---|
[298] | 988 | my $sep = shift || '-'; # Separator character - unlikely we'll ever need more than . or -
|
---|
[265] | 989 |
|
---|
[298] | 990 | my $prefix;
|
---|
[265] | 991 |
|
---|
| 992 | $string =~ s/,/./ if !$zone->{isv6};
|
---|
| 993 | $string =~ s/,/::/ if $zone->{isv6};
|
---|
| 994 |
|
---|
[298] | 995 | # Subbing ZONE in the host. We need to properly ID the netblock range
|
---|
| 996 | # The subbed text should have "network IP with trailing zeros stripped" for
|
---|
| 997 | # blocks lined up on octet (for v4) or hex-quad (for v6) boundaries
|
---|
| 998 | # For blocks that do NOT line up on these boundaries, we take the most
|
---|
| 999 | # significant octet or 16-bit chunk of the "broadcast" IP and append it
|
---|
| 1000 | # after a double-dash
|
---|
| 1001 | # ie:
|
---|
| 1002 | # 8.0.0.0/6 -> 8.0.0.0 -> 11.255.255.255; sub should be 8--11
|
---|
| 1003 | # 10.0.0.0/12 -> 10.0.0.0 -> 10.0.0.0 -> 10.15.255.255; sub should be 10-0--15
|
---|
| 1004 | # 192.168.4.0/22 -> 192.168.4.0 -> 192.168.7.255; sub should be 192-168-4--7
|
---|
| 1005 | # 192.168.0.8/29 -> 192.168.0.8 -> 192.168.0.15; sub should be 192-168-0-8--15
|
---|
| 1006 | # Similar for v6
|
---|
[265] | 1007 |
|
---|
[298] | 1008 | if (!$zone->{isv6}) { # IPv4
|
---|
| 1009 |
|
---|
| 1010 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
| 1011 | # a funky subnet that had host bits set.
|
---|
| 1012 | my $bc = $zone->broadcast->addr;
|
---|
| 1013 |
|
---|
| 1014 | if ($zone->masklen > 24) {
|
---|
| 1015 | $bc =~ s/^\d+\.\d+\.\d+\.//;
|
---|
| 1016 | } elsif ($zone->masklen > 16) {
|
---|
| 1017 | $prefix =~ s/\.0$//;
|
---|
| 1018 | $bc =~ s/^\d+\.\d+\.//;
|
---|
| 1019 | } elsif ($zone->masklen > 8) {
|
---|
| 1020 | $bc =~ s/^\d+\.//;
|
---|
| 1021 | $prefix =~ s/\.0\.0$//;
|
---|
| 1022 | } else {
|
---|
| 1023 | $prefix =~ s/\.0\.0\.0$//;
|
---|
| 1024 | }
|
---|
| 1025 | if ($zone->masklen % 8) {
|
---|
| 1026 | $bc =~ s/(\.255)+$//;
|
---|
| 1027 | $prefix .= "--$bc"; #"--".zone->masklen; # use range or mask length?
|
---|
| 1028 | }
|
---|
| 1029 | if ($fr eq 'f') {
|
---|
| 1030 | $prefix =~ s/\.+/$sep/g;
|
---|
| 1031 | } else {
|
---|
| 1032 | $prefix = join($sep, reverse(split(/\./, $prefix)));
|
---|
| 1033 | }
|
---|
| 1034 |
|
---|
| 1035 | } else { # IPv6
|
---|
| 1036 |
|
---|
| 1037 | if ($fr eq 'f') {
|
---|
| 1038 |
|
---|
| 1039 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
| 1040 | # a funky subnet that had host bits set.
|
---|
[265] | 1041 | my $bc = $zone->broadcast->addr;
|
---|
| 1042 | if (($zone->masklen % 16) != 0) {
|
---|
[298] | 1043 | # Strip trailing :0 off $prefix, and :ffff off the broadcast IP
|
---|
| 1044 | for (my $i=0; $i<(7-int($zone->masklen / 16)); $i++) {
|
---|
| 1045 | $prefix =~ s/:0$//;
|
---|
| 1046 | $bc =~ s/:ffff$//;
|
---|
| 1047 | }
|
---|
| 1048 | # Strip the leading 16-bit chunks off the front of the broadcast IP
|
---|
| 1049 | $bc =~ s/^([a-f0-9]+:)+//;
|
---|
| 1050 | # Append the remaining 16-bit chunk to the prefix after "--"
|
---|
| 1051 | $prefix .= "--$bc";
|
---|
[265] | 1052 | } else {
|
---|
[298] | 1053 | # Strip off :0 from the end until we reach the netblock length.
|
---|
| 1054 | for (my $i=0; $i<(8-$zone->masklen / 16); $i++) {
|
---|
[265] | 1055 | $prefix =~ s/:0$//;
|
---|
[298] | 1056 | }
|
---|
[265] | 1057 | }
|
---|
[298] | 1058 | # Actually deal with the separator
|
---|
| 1059 | $prefix =~ s/:/$sep/g;
|
---|
| 1060 |
|
---|
| 1061 | } else { # $fr eq 'f'
|
---|
| 1062 |
|
---|
| 1063 | $prefix = $zone->network->full; # Just In Case someone managed to slip in
|
---|
| 1064 | # a funky subnet that had host bits set.
|
---|
| 1065 | my $bc = $zone->broadcast->full;
|
---|
| 1066 | $prefix =~ s/://g; # clean these out since they're not spaced right for this case
|
---|
| 1067 | $bc =~ s/://g;
|
---|
| 1068 | # Strip trailing 0 off $prefix, and f off the broadcast IP, to match the mask length
|
---|
| 1069 | for (my $i=0; $i<(31-int($zone->masklen / 4)); $i++) {
|
---|
| 1070 | $prefix =~ s/0$//;
|
---|
| 1071 | $bc =~ s/f$//;
|
---|
| 1072 | }
|
---|
| 1073 | # Split and reverse the order of the nibbles in the network/broadcast IPs
|
---|
[332] | 1074 | # trim another 0 for nibble-aligned blocks first, but only if we really have a block, not an IP
|
---|
| 1075 | $prefix =~ s/0$// if $zone->masklen % 4 == 0 && $zone->masklen != 128;
|
---|
[298] | 1076 | my @nbits = reverse split //, $prefix;
|
---|
| 1077 | my @bbits = reverse split //, $bc;
|
---|
| 1078 | # Handle the sub-nibble case. Eww. I feel dirty supporting this...
|
---|
| 1079 | $nbits[0] = "$nbits[0]-$bbits[0]" if ($zone->masklen % 4) != 0;
|
---|
| 1080 | # Glue it back together
|
---|
| 1081 | $prefix = join($sep, @nbits);
|
---|
| 1082 |
|
---|
| 1083 | } # $fr ne 'f'
|
---|
| 1084 |
|
---|
| 1085 | } # $zone->{isv6}
|
---|
| 1086 |
|
---|
| 1087 | # Do the substitution, finally
|
---|
| 1088 | $string =~ s/ZONE/$prefix/;
|
---|
| 1089 | $string =~ s/--/-/ if $sep ne '-'; # - as separator needs extra help for sub-octet v4 netblocks
|
---|
| 1090 | return $string;
|
---|
| 1091 | } # done _ZONE()
|
---|
| 1092 |
|
---|
| 1093 | # Not quite a substitution sub, but placed here as it's basically the inverse of above;
|
---|
| 1094 | # given the .arpa zone name, return the CIDR netblock the zone is for.
|
---|
[304] | 1095 | # Supports v4 non-octet/non-classful netblocks as per the method outlined in the Grasshopper Book (2nd Ed p217-218)
|
---|
[298] | 1096 | # Does NOT support non-quad v6 netblocks via the same scheme; it shouldn't ever be necessary.
|
---|
| 1097 | # Takes a nominal .arpa zone name, returns a success code and NetAddr::IP, or a fail code and message
|
---|
| 1098 | sub _zone2cidr {
|
---|
| 1099 | my $zone = shift;
|
---|
| 1100 |
|
---|
| 1101 | my $cidr;
|
---|
[301] | 1102 | my $tmpcidr;
|
---|
| 1103 | my $warnmsg = '';
|
---|
[298] | 1104 |
|
---|
| 1105 | if ($zone =~ /\.in-addr\.arpa\.?$/) {
|
---|
| 1106 | # v4 revzone, formal zone name type
|
---|
| 1107 | my $tmpzone = $zone;
|
---|
| 1108 | $tmpzone =~ s/\.in-addr\.arpa\.?//;
|
---|
[301] | 1109 | return ('FAIL', "Non-numerics in apparent IPv4 reverse zone name") if $tmpzone !~ /^(?:\d+-)?[\d\.]+$/;
|
---|
[298] | 1110 |
|
---|
| 1111 | # Snag the octet pieces
|
---|
| 1112 | my @octs = split /\./, $tmpzone;
|
---|
| 1113 |
|
---|
| 1114 | # Map result of a range manipulation to a mask length change. Cheaper than finding the 2-root of $octets[0]+1.
|
---|
[304] | 1115 | # Note we will not support /31 blocks, mostly due to issues telling "24-31" -> .24/29 apart from
|
---|
| 1116 | # "24-31" -> .24/31", with a litte bit of "/31 is icky".
|
---|
| 1117 | my %maskmap = ( 3 => 2, 7 => 3, 15 => 4, 31 => 5, 63 => 6, 127 => 7,
|
---|
| 1118 | 30 => 2, 29 => 3, 28 => 4, 27 => 5, 26 => 6, 25 => 7
|
---|
| 1119 | );
|
---|
[298] | 1120 |
|
---|
| 1121 | # Handle "range" blocks, eg, 80-83.168.192.in-addr.arpa (192.168.80.0/22)
|
---|
| 1122 | # Need to take the size of the range to offset the basic octet-based mask length,
|
---|
| 1123 | # and make sure the first number in the range gets used as the network address for the block
|
---|
[304] | 1124 | # Alternate form: The second number is actually the real netmask, not the end of the range.
|
---|
[298] | 1125 | my $masklen = 0;
|
---|
[307] | 1126 | if ($octs[0] =~ /^((\d+)-(\d+))$/) { # take the range...
|
---|
| 1127 | if (24 < $3 && $3 < 31) {
|
---|
[304] | 1128 | # we have a real netmask
|
---|
[307] | 1129 | $masklen = -$maskmap{$3};
|
---|
[304] | 1130 | } else {
|
---|
| 1131 | # we have a range. NB: only real CIDR ranges are supported
|
---|
[307] | 1132 | $masklen -= $maskmap{-(eval $1)}; # find the mask base...
|
---|
[304] | 1133 | }
|
---|
[307] | 1134 | $octs[0] = $2; # set the base octet of the range...
|
---|
[265] | 1135 | }
|
---|
[298] | 1136 | @octs = reverse @octs; # We can reverse the octet pieces now that we've extracted and munged any ranges
|
---|
[265] | 1137 |
|
---|
[304] | 1138 | # arguably we should only allow sub-octet range/mask in-addr.arpa
|
---|
| 1139 | # specifications in the least significant octet, but the code is
|
---|
| 1140 | # simpler if we deal with sub-octet delegations at any level.
|
---|
| 1141 |
|
---|
[298] | 1142 | # Now we find the "true" mask with the aid of the "base" calculated above
|
---|
| 1143 | if ($#octs == 0) {
|
---|
| 1144 | $masklen += 8;
|
---|
| 1145 | $tmpcidr = "$octs[0].0.0.0/$masklen"; # really hope we don't see one of these very often.
|
---|
| 1146 | } elsif ($#octs == 1) {
|
---|
| 1147 | $masklen += 16;
|
---|
| 1148 | $tmpcidr = "$octs[0].$octs[1].0.0/$masklen";
|
---|
| 1149 | } elsif ($#octs == 2) {
|
---|
| 1150 | $masklen += 24;
|
---|
| 1151 | $tmpcidr = "$octs[0].$octs[1].$octs[2].0/$masklen";
|
---|
[265] | 1152 | } else {
|
---|
[298] | 1153 | $masklen += 32;
|
---|
| 1154 | $tmpcidr = "$octs[0].$octs[1].$octs[2].$octs[3]/$masklen";
|
---|
[265] | 1155 | }
|
---|
| 1156 |
|
---|
[298] | 1157 | } elsif ($zone =~ /\.ip6\.arpa$/) {
|
---|
| 1158 | # v6 revzone, formal zone name type
|
---|
| 1159 | my $tmpzone = $zone;
|
---|
| 1160 | $tmpzone =~ s/\.ip6\.arpa\.?//;
|
---|
[301] | 1161 | ##fixme: if-n-when we decide we can support sub-nibble v6 zone names, we'll need to change this segment
|
---|
| 1162 | return ('FAIL', "Non-hexadecimals in apparent IPv6 reverse zone name") if $tmpzone !~ /^[a-fA-F\d\.]+$/;
|
---|
[298] | 1163 | my @quads = reverse(split(/\./, $tmpzone));
|
---|
| 1164 | $warnmsg .= "Apparent sub-/64 IPv6 reverse zone\n" if $#quads > 15;
|
---|
| 1165 | my $nc;
|
---|
| 1166 | foreach (@quads) {
|
---|
[301] | 1167 | $tmpcidr .= $_;
|
---|
| 1168 | $tmpcidr .= ":" if ++$nc % 4 == 0;
|
---|
[298] | 1169 | }
|
---|
| 1170 | my $nq = 1 if $nc % 4 != 0;
|
---|
| 1171 | my $mask = $nc * 4; # need to do this here because we probably increment it below
|
---|
| 1172 | while ($nc++ % 4 != 0) {
|
---|
[301] | 1173 | $tmpcidr .= "0";
|
---|
[298] | 1174 | }
|
---|
[301] | 1175 | $tmpcidr .= ($nq ? '::' : ':')."/$mask";
|
---|
[298] | 1176 | }
|
---|
[301] | 1177 |
|
---|
| 1178 | # Just to be sure, use NetAddr::IP to validate. Saves a lot of nasty regex watching for valid octet values.
|
---|
| 1179 | return ('FAIL', "Invalid zone $zone (apparent netblock $tmpcidr)")
|
---|
| 1180 | unless $cidr = NetAddr::IP->new($tmpcidr);
|
---|
| 1181 |
|
---|
| 1182 | if ($warnmsg) {
|
---|
| 1183 | $errstr = $warnmsg;
|
---|
| 1184 | return ('WARN', $cidr);
|
---|
| 1185 | }
|
---|
| 1186 | return ('OK', $cidr);
|
---|
[298] | 1187 | } # done _zone2cidr()
|
---|
[265] | 1188 |
|
---|
[337] | 1189 | # Record template %-parameter expansion, IPv4. Note that IPv6 doesn't
|
---|
| 1190 | # really have a sane way to handle this type of expansion at the moment
|
---|
| 1191 | # due to the size of the address space.
|
---|
| 1192 | # Takes a reference to a template string to be expanded, and an IP to use in the replacement.
|
---|
| 1193 | sub _template4_expand {
|
---|
| 1194 | my $tmpl = shift;
|
---|
| 1195 | my $ip = shift;
|
---|
[298] | 1196 |
|
---|
[337] | 1197 | my @ipparts = split /\./, $ip;
|
---|
| 1198 | my @iphex;
|
---|
| 1199 | my @ippad;
|
---|
| 1200 | for (@ipparts) {
|
---|
| 1201 | push @iphex, sprintf("%x", $_);
|
---|
[443] | 1202 | push @ippad, sprintf("%0.3u", $_);
|
---|
[337] | 1203 | }
|
---|
| 1204 |
|
---|
| 1205 | # IP substitutions in template records:
|
---|
| 1206 | #major patterns:
|
---|
| 1207 | #dashed IP, forward and reverse
|
---|
| 1208 | #dotted IP, forward and reverse (even if forward is... dumb)
|
---|
| 1209 | # -> %r for reverse, %i for forward, leading - or . to indicate separator, defaults to -
|
---|
| 1210 | # %r or %-r => %4d-%3d-%2d-%1d
|
---|
| 1211 | # %.r => %4d.%3d.%2d.%1d
|
---|
| 1212 | # %i or %-i => %1d-%2d-%3d-%4d
|
---|
| 1213 | # %.i => %1d.%2d.%3d.%4d
|
---|
| 1214 | $$tmpl =~ s/\%r/\%4d-\%3d-\%2d-\%1d/g;
|
---|
| 1215 | $$tmpl =~ s/\%([-.])r/\%4d$1\%3d$1\%2d$1\%1d/g;
|
---|
| 1216 | $$tmpl =~ s/\%i/\%1d-\%2d-\%3d-\%4d/g;
|
---|
| 1217 | $$tmpl =~ s/\%([-.])i/\%1d$1\%2d$1\%3d$1\%4d/g;
|
---|
| 1218 |
|
---|
| 1219 | #hex-coded IP
|
---|
| 1220 | # %h
|
---|
| 1221 | $$tmpl =~ s/\%h/$iphex[0]$iphex[1]$iphex[2]$iphex[3]/g;
|
---|
| 1222 |
|
---|
| 1223 | #IP as decimal-coded 32-bit value
|
---|
| 1224 | # %d
|
---|
| 1225 | my $iptmp = $ipparts[0]*256*256*256 + $ipparts[1]*256*256 + $ipparts[2]*256 + $ipparts[3];
|
---|
| 1226 | $$tmpl =~ s/\%d/$iptmp/g;
|
---|
| 1227 |
|
---|
| 1228 | #minor patterns (per-octet)
|
---|
| 1229 | # %[1234][dh0]
|
---|
| 1230 | #octet
|
---|
| 1231 | #hex-coded octet
|
---|
| 1232 | #0-padded octet
|
---|
| 1233 | $$tmpl =~ s/\%([1234])d/$ipparts[$1-1]/g;
|
---|
| 1234 | $$tmpl =~ s/\%([1234])h/$iphex[$1-1]/g;
|
---|
[443] | 1235 | $$tmpl =~ s/\%([1234])0/$ippad[$1-1]/g;
|
---|
[337] | 1236 | } # _template4_expand()
|
---|
| 1237 |
|
---|
| 1238 |
|
---|
[228] | 1239 | ##
|
---|
[2] | 1240 | ## Initialization and cleanup subs
|
---|
| 1241 | ##
|
---|
| 1242 |
|
---|
[128] | 1243 | ## DNSDB::loadConfig()
|
---|
| 1244 | # Load the minimum required initial state (DB connect info) from a config file
|
---|
| 1245 | # Load misc other bits while we're at it.
|
---|
[400] | 1246 | # Takes an optional hash that may contain:
|
---|
| 1247 | # - basename and config path to look for
|
---|
[128] | 1248 | # Populates the %config and %def hashes
|
---|
| 1249 | sub loadConfig {
|
---|
[400] | 1250 | my %args = @_;
|
---|
[465] | 1251 | $args{configfile} = '' if !$args{configfile};
|
---|
[128] | 1252 |
|
---|
[465] | 1253 | ##fixme this is *intended* to load a system-default config template, and allow
|
---|
| 1254 | # overriding on a per-tool or per-web-UI-instance basis with a secondary config
|
---|
| 1255 | # file. The "default" config file can't be deleted in the current form.
|
---|
| 1256 |
|
---|
[128] | 1257 | my $deferr = ''; # place to put error from default config file in case we can't find either one
|
---|
| 1258 |
|
---|
[219] | 1259 | my $configroot = "/etc/dnsdb"; ##CFG_LEAF##
|
---|
[465] | 1260 | $configroot = '' if $args{configfile} =~ m|^/|; # allow passed siteconfig to specify an arbitrary absolute path
|
---|
| 1261 | $args{configfile} .= ".conf" if $args{configfile} !~ /\.conf$/;
|
---|
[128] | 1262 | my $defconfig = "$configroot/dnsdb.conf";
|
---|
[465] | 1263 | my $siteconfig = "$configroot/$args{configfile}";
|
---|
[128] | 1264 |
|
---|
| 1265 | # System defaults
|
---|
[465] | 1266 | __cfgload("$defconfig") or $deferr = $errstr;
|
---|
[128] | 1267 |
|
---|
[131] | 1268 | # Per-site-ish settings.
|
---|
[465] | 1269 | if ($args{configfile} ne '.conf') {
|
---|
| 1270 | unless (__cfgload("$siteconfig")) {
|
---|
[131] | 1271 | $errstr = ($deferr ? "Error opening default config file $defconfig: $deferr\n" : '').
|
---|
[128] | 1272 | "Error opening site config file $siteconfig";
|
---|
[131] | 1273 | return;
|
---|
| 1274 | }
|
---|
[128] | 1275 | }
|
---|
| 1276 |
|
---|
[195] | 1277 | # Munge log_failures.
|
---|
| 1278 | if ($config{log_failures} ne '1' && $config{log_failures} ne '0') {
|
---|
| 1279 | # true/false, on/off, yes/no all valid.
|
---|
| 1280 | if ($config{log_failures} =~ /^(?:true|false|on|off|yes|no)$/) {
|
---|
| 1281 | if ($config{log_failures} =~ /(?:true|on|yes)/) {
|
---|
| 1282 | $config{log_failures} = 1;
|
---|
| 1283 | } else {
|
---|
| 1284 | $config{log_failures} = 0;
|
---|
| 1285 | }
|
---|
| 1286 | } else {
|
---|
| 1287 | $errstr = "Bad log_failures setting $config{log_failures}";
|
---|
| 1288 | $config{log_failures} = 1;
|
---|
| 1289 | # Bad setting shouldn't be fatal.
|
---|
| 1290 | # return 2;
|
---|
| 1291 | }
|
---|
| 1292 | }
|
---|
| 1293 |
|
---|
[128] | 1294 | # All good, clear the error and go home.
|
---|
| 1295 | $errstr = '';
|
---|
| 1296 | return 1;
|
---|
| 1297 | } # end loadConfig()
|
---|
| 1298 |
|
---|
| 1299 |
|
---|
| 1300 | ## DNSDB::__cfgload()
|
---|
| 1301 | # Private sub to parse a config file and load it into %config
|
---|
[465] | 1302 | # Takes a filename
|
---|
[128] | 1303 | sub __cfgload {
|
---|
| 1304 | $errstr = '';
|
---|
| 1305 | my $cfgfile = shift;
|
---|
[131] | 1306 |
|
---|
[128] | 1307 | if (open CFG, "<$cfgfile") {
|
---|
| 1308 | while (<CFG>) {
|
---|
| 1309 | chomp;
|
---|
| 1310 | s/^\s*//;
|
---|
| 1311 | next if /^#/;
|
---|
| 1312 | next if /^$/;
|
---|
| 1313 | # hmm. more complex bits in this file might require [heading] headers, maybe?
|
---|
| 1314 | # $mode = $1 if /^\[(a-z)+]/;
|
---|
| 1315 | # DB connect info
|
---|
| 1316 | $config{dbname} = $1 if /^dbname\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1317 | $config{dbuser} = $1 if /^dbuser\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1318 | $config{dbpass} = $1 if /^dbpass\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1319 | $config{dbhost} = $1 if /^dbhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1320 | # SOA defaults
|
---|
| 1321 | $def{contact} = $1 if /^contact\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1322 | $def{prins} = $1 if /^prins\s*=\s*([a-z0-9_.-]+)/i;
|
---|
[201] | 1323 | $def{soattl} = $1 if /^soattl\s*=\s*(\d+)/i;
|
---|
| 1324 | $def{refresh} = $1 if /^refresh\s*=\s*(\d+)/i;
|
---|
| 1325 | $def{retry} = $1 if /^retry\s*=\s*(\d+)/i;
|
---|
| 1326 | $def{expire} = $1 if /^expire\s*=\s*(\d+)/i;
|
---|
| 1327 | $def{minttl} = $1 if /^minttl\s*=\s*(\d+)/i;
|
---|
| 1328 | $def{ttl} = $1 if /^ttl\s*=\s*(\d+)/i;
|
---|
[128] | 1329 | # Mail settings
|
---|
| 1330 | $config{mailhost} = $1 if /^mailhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
[198] | 1331 | $config{mailnotify} = $1 if /^mailnotify\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
| 1332 | $config{mailsender} = $1 if /^mailsender\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
[128] | 1333 | $config{mailname} = $1 if /^mailname\s*=\s*([a-z0-9\s_.-]+)/i;
|
---|
[195] | 1334 | $config{orgname} = $1 if /^orgname\s*=\s*([a-z0-9\s_.,'-]+)/i;
|
---|
| 1335 | $config{domain} = $1 if /^domain\s*=\s*([a-z0-9_.-]+)/i;
|
---|
[163] | 1336 | # session - note this is fed directly to CGI::Session
|
---|
[216] | 1337 | $config{timeout} = $1 if /^[tT][iI][mM][eE][oO][uU][tT]\s*=\s*(\d+[smhdwMy]?)/;
|
---|
| 1338 | $config{sessiondir} = $1 if m{^sessiondir\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
[201] | 1339 | # misc
|
---|
[195] | 1340 | $config{log_failures} = $1 if /^log_failures\s*=\s*([a-z01]+)/i;
|
---|
[201] | 1341 | $config{perpage} = $1 if /^perpage\s*=\s*(\d+)/i;
|
---|
[368] | 1342 | $config{exportcache} = $1 if m{^exportcache\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
[400] | 1343 | # RPC options
|
---|
[465] | 1344 | $config{rpcmode} = $1 if /^rpc_mode\s*=\s*(socket|HTTP|XMLRPC)\s*$/i;
|
---|
| 1345 | if (my ($tmp) = /^rpc_iplist\s*=\s*(.+)/i) {
|
---|
| 1346 | my @ips = split /[,\s]+/, $tmp;
|
---|
| 1347 | my $rpcsys = shift @ips;
|
---|
| 1348 | push @{$config{rpcacl}{$rpcsys}}, @ips;
|
---|
[400] | 1349 | }
|
---|
[128] | 1350 | }
|
---|
| 1351 | close CFG;
|
---|
| 1352 | } else {
|
---|
| 1353 | $errstr = $!;
|
---|
| 1354 | return;
|
---|
| 1355 | }
|
---|
| 1356 | return 1;
|
---|
| 1357 | } # end __cfgload()
|
---|
| 1358 |
|
---|
| 1359 |
|
---|
[2] | 1360 | ## DNSDB::connectDB()
|
---|
| 1361 | # Creates connection to DNS database.
|
---|
| 1362 | # Requires the database name, username, and password.
|
---|
[465] | 1363 | # Returns a handle to the db or undef on failure.
|
---|
[2] | 1364 | # Set up for a PostgreSQL db; could be any transactional DBMS with the
|
---|
| 1365 | # right changes.
|
---|
[465] | 1366 | # Called by new(); not intended to be called publicly.
|
---|
[2] | 1367 | sub connectDB {
|
---|
| 1368 | $errstr = '';
|
---|
[15] | 1369 | my $dbname = shift;
|
---|
| 1370 | my $user = shift;
|
---|
| 1371 | my $pass = shift;
|
---|
[2] | 1372 | my $dbh;
|
---|
| 1373 | my $DSN = "DBI:Pg:dbname=$dbname";
|
---|
| 1374 |
|
---|
| 1375 | my $host = shift;
|
---|
| 1376 | $DSN .= ";host=$host" if $host;
|
---|
| 1377 |
|
---|
| 1378 | # Note that we want to autocommit by default, and we will turn it off locally as necessary.
|
---|
| 1379 | # We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
|
---|
| 1380 | $dbh = DBI->connect($DSN, $user, $pass, {
|
---|
| 1381 | AutoCommit => 1,
|
---|
| 1382 | PrintError => 0
|
---|
[465] | 1383 | });
|
---|
| 1384 | if (!$dbh) {
|
---|
| 1385 | $errstr = $DBI::errstr;
|
---|
| 1386 | return;
|
---|
| 1387 | }
|
---|
| 1388 | #) if(!$dbh);
|
---|
[2] | 1389 |
|
---|
[465] | 1390 | local $dbh->{RaiseError} = 1;
|
---|
| 1391 |
|
---|
| 1392 | eval {
|
---|
[212] | 1393 | ##fixme: initialize the DB if we can't find the table (since, by definition, there's
|
---|
| 1394 | # nothing there if we can't select from it...)
|
---|
[465] | 1395 | my $tblsth = $dbh->prepare("SELECT count(*) FROM pg_catalog.pg_class WHERE relkind='r' AND relname=?");
|
---|
| 1396 | my ($tblcount) = $dbh->selectrow_array($tblsth, undef, ('misc'));
|
---|
| 1397 | # return (undef,$DBI::errstr) if $dbh->err;
|
---|
[212] | 1398 |
|
---|
| 1399 | #if ($tblcount == 0) {
|
---|
| 1400 | # # create tables one at a time, checking for each.
|
---|
| 1401 | # return (undef, "check table misc missing");
|
---|
| 1402 | #}
|
---|
| 1403 |
|
---|
| 1404 | # Return here if we can't select.
|
---|
| 1405 | # This should retrieve the dbversion key.
|
---|
[465] | 1406 | my $sth = $dbh->prepare("SELECT key,value FROM misc WHERE misc_id=1");
|
---|
| 1407 | $sth->execute();
|
---|
| 1408 | # return (undef,$DBI::errstr) if ($sth->err);
|
---|
[2] | 1409 |
|
---|
[212] | 1410 | ##fixme: do stuff to the DB on version mismatch
|
---|
| 1411 | # x.y series should upgrade on $DNSDB::VERSION > misc(key=>version)
|
---|
| 1412 | # DB should be downward-compatible; column defaults should give sane (if possibly
|
---|
| 1413 | # useless-and-needs-help) values in columns an older software stack doesn't know about.
|
---|
| 1414 |
|
---|
[2] | 1415 | # See if the select returned anything (or null data). This should
|
---|
| 1416 | # succeed if the select executed, but...
|
---|
[465] | 1417 | $sth->fetchrow();
|
---|
| 1418 | # return (undef,$DBI::errstr) if ($sth->err);
|
---|
[2] | 1419 |
|
---|
[465] | 1420 | $sth->finish;
|
---|
[2] | 1421 |
|
---|
[465] | 1422 | }; # wrapped DB checks
|
---|
| 1423 | if ($@) {
|
---|
| 1424 | $errstr = $@;
|
---|
| 1425 | return;
|
---|
| 1426 | }
|
---|
| 1427 |
|
---|
[2] | 1428 | # If we get here, we should be OK.
|
---|
[465] | 1429 | return $dbh;
|
---|
[2] | 1430 | } # end connectDB
|
---|
| 1431 |
|
---|
| 1432 |
|
---|
| 1433 | ## DNSDB::finish()
|
---|
| 1434 | # Cleans up after database handles and so on.
|
---|
| 1435 | # Requires a database handle
|
---|
| 1436 | sub finish {
|
---|
[465] | 1437 | my $self = shift;
|
---|
| 1438 | $self->{dbh}->disconnect;
|
---|
[2] | 1439 | } # end finish
|
---|
| 1440 |
|
---|
| 1441 |
|
---|
| 1442 | ## DNSDB::initGlobals()
|
---|
| 1443 | # Initialize global variables
|
---|
| 1444 | # NB: this does NOT include web-specific session variables!
|
---|
| 1445 | sub initGlobals {
|
---|
[465] | 1446 | my $self = shift;
|
---|
| 1447 | my $dbh = $self->{dbh};
|
---|
[2] | 1448 |
|
---|
[208] | 1449 | # load record types from database
|
---|
[228] | 1450 | my $sth = $dbh->prepare("SELECT val,name,stdflag FROM rectypes");
|
---|
[2] | 1451 | $sth->execute;
|
---|
[228] | 1452 | while (my ($recval,$recname,$stdflag) = $sth->fetchrow_array()) {
|
---|
[2] | 1453 | $typemap{$recval} = $recname;
|
---|
| 1454 | $reverse_typemap{$recname} = $recval;
|
---|
[228] | 1455 | # now we fill the record validation function hash
|
---|
| 1456 | if ($stdflag < 5) {
|
---|
| 1457 | my $fn = "_validate_$recval";
|
---|
| 1458 | $validators{$recval} = \&$fn;
|
---|
| 1459 | } else {
|
---|
| 1460 | my $fn = "sub { return ('FAIL','Type $recval ($recname) not supported'); }";
|
---|
| 1461 | $validators{$recval} = eval $fn;
|
---|
| 1462 | }
|
---|
[2] | 1463 | }
|
---|
| 1464 | } # end initGlobals
|
---|
| 1465 |
|
---|
| 1466 |
|
---|
[401] | 1467 | ## DNSDB::initRPC()
|
---|
[469] | 1468 | # Takes a remote username and remote fullname.
|
---|
[401] | 1469 | # Sets up the RPC logging-pseudouser if needed.
|
---|
| 1470 | # Sets the %userdata hash for logging.
|
---|
| 1471 | # Returns undef on failure
|
---|
| 1472 | sub initRPC {
|
---|
[469] | 1473 | my $self = shift;
|
---|
| 1474 | my $dbh = $self->{dbh};
|
---|
[401] | 1475 | my %args = @_;
|
---|
| 1476 |
|
---|
| 1477 | return if !$args{username};
|
---|
| 1478 | return if !$args{fullname};
|
---|
| 1479 |
|
---|
[406] | 1480 | $args{username} = "$args{username}/$args{rpcsys}";
|
---|
| 1481 |
|
---|
| 1482 | my $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
|
---|
[404] | 1483 | " FROM users WHERE username=?", undef, ($args{username}) );
|
---|
[406] | 1484 | if (!$tmpuser) {
|
---|
[401] | 1485 | $dbh->do("INSERT INTO users (username,password,firstname,type) VALUES (?,'RPC',?,'R')", undef,
|
---|
| 1486 | ($args{username}, $args{fullname}) );
|
---|
[406] | 1487 | $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
|
---|
[404] | 1488 | " FROM users WHERE username=?", undef, ($args{username}) );
|
---|
[401] | 1489 | }
|
---|
[404] | 1490 | %userdata = %{$tmpuser};
|
---|
[410] | 1491 | $userdata{lastname} = '' if !$userdata{lastname};
|
---|
[404] | 1492 | $userdata{fullname} = "$userdata{firstname} $userdata{lastname} ($args{rpcsys})";
|
---|
[406] | 1493 | return 1 if $tmpuser;
|
---|
[401] | 1494 | } # end initRPC()
|
---|
| 1495 |
|
---|
| 1496 |
|
---|
[278] | 1497 | ## DNSDB::login()
|
---|
| 1498 | # Takes a database handle, username and password
|
---|
[316] | 1499 | # Returns a userdata hash (UID, GID, username, fullname parts) if username exists,
|
---|
| 1500 | # password matches the one on file, and account is not disabled
|
---|
[278] | 1501 | # Returns undef otherwise
|
---|
| 1502 | sub login {
|
---|
[469] | 1503 | my $self = shift;
|
---|
| 1504 | my $dbh = $self->{dbh};
|
---|
[278] | 1505 | my $user = shift;
|
---|
| 1506 | my $pass = shift;
|
---|
| 1507 |
|
---|
[316] | 1508 | my $userinfo = $dbh->selectrow_hashref("SELECT user_id,group_id,password,firstname,lastname,status".
|
---|
| 1509 | " FROM users WHERE username=?",
|
---|
[279] | 1510 | undef, ($user) );
|
---|
| 1511 | return if !$userinfo;
|
---|
[316] | 1512 | return if !$userinfo->{status};
|
---|
[278] | 1513 |
|
---|
[279] | 1514 | if ($userinfo->{password} =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
|
---|
[278] | 1515 | # native passwords (crypt-md5)
|
---|
[279] | 1516 | return if $userinfo->{password} ne unix_md5_crypt($pass,$1);
|
---|
| 1517 | } elsif ($userinfo->{password} =~ /^[0-9a-f]{32}$/) {
|
---|
[278] | 1518 | # VegaDNS import (hex-coded MD5)
|
---|
[279] | 1519 | return if $userinfo->{password} ne md5_hex($pass);
|
---|
[278] | 1520 | } else {
|
---|
| 1521 | # plaintext (convenient now and then)
|
---|
[279] | 1522 | return if $userinfo->{password} ne $pass;
|
---|
[278] | 1523 | }
|
---|
| 1524 |
|
---|
[279] | 1525 | return $userinfo;
|
---|
[278] | 1526 | } # end login()
|
---|
| 1527 |
|
---|
| 1528 |
|
---|
[279] | 1529 | ## DNSDB::initActionLog()
|
---|
| 1530 | # Set up action logging. Takes a database handle and user ID
|
---|
| 1531 | # Sets some internal globals and Does The Right Thing to set up a logging channel.
|
---|
| 1532 | # This sets up _log() to spew out log entries to the defined channel without worrying
|
---|
| 1533 | # about having to open a file or a syslog channel
|
---|
| 1534 | ##fixme Need to call _initActionLog_blah() for various logging channels, configured
|
---|
| 1535 | # via dnsdb.conf, in $config{log_channel} or something
|
---|
| 1536 | # See https://secure.deepnet.cx/trac/dnsadmin/ticket/21
|
---|
| 1537 | sub initActionLog {
|
---|
[469] | 1538 | my $self = shift;
|
---|
| 1539 | my $dbh = $self->{dbh};
|
---|
[279] | 1540 | my $uid = shift;
|
---|
| 1541 |
|
---|
| 1542 | return if !$uid;
|
---|
| 1543 |
|
---|
| 1544 | # snag user info for logging. there's got to be a way to not have to pass this back
|
---|
| 1545 | # and forth from a caller, but web usage means no persistence we can rely on from
|
---|
| 1546 | # the server side.
|
---|
| 1547 | my ($username,$fullname) = $dbh->selectrow_array("SELECT username, firstname || ' ' || lastname".
|
---|
| 1548 | " FROM users WHERE user_id=?", undef, ($uid));
|
---|
| 1549 | ##fixme: errors are unpossible!
|
---|
| 1550 |
|
---|
| 1551 | $userdata{username} = $username;
|
---|
| 1552 | $userdata{userid} = $uid;
|
---|
| 1553 | $userdata{fullname} = $fullname;
|
---|
| 1554 |
|
---|
| 1555 | # convert to real check once we have other logging channels
|
---|
| 1556 | # if ($config{log_channel} eq 'sql') {
|
---|
| 1557 | # Open Log, Sez Me!
|
---|
| 1558 | # }
|
---|
| 1559 |
|
---|
| 1560 | } # end initActionLog
|
---|
| 1561 |
|
---|
| 1562 |
|
---|
[65] | 1563 | ## DNSDB::initPermissions()
|
---|
| 1564 | # Set up permissions global
|
---|
| 1565 | # Takes database handle and UID
|
---|
| 1566 | sub initPermissions {
|
---|
[469] | 1567 | my $self = shift;
|
---|
| 1568 | my $dbh = $self->{dbh};
|
---|
[65] | 1569 | my $uid = shift;
|
---|
| 1570 |
|
---|
[469] | 1571 | # %permissions = $(getPermissions('user',$uid));
|
---|
| 1572 | $self->getPermissions('user', $uid, \%permissions);
|
---|
[65] | 1573 |
|
---|
| 1574 | } # end initPermissions()
|
---|
| 1575 |
|
---|
| 1576 |
|
---|
| 1577 | ## DNSDB::getPermissions()
|
---|
| 1578 | # Get permissions from DB
|
---|
| 1579 | # Requires DB handle, group or user flag, ID, and hashref.
|
---|
| 1580 | sub getPermissions {
|
---|
[469] | 1581 | my $self = shift;
|
---|
| 1582 | my $dbh = $self->{dbh};
|
---|
| 1583 |
|
---|
[65] | 1584 | my $type = shift;
|
---|
| 1585 | my $id = shift;
|
---|
| 1586 | my $hash = shift;
|
---|
| 1587 |
|
---|
| 1588 | my $sql = qq(
|
---|
| 1589 | SELECT
|
---|
| 1590 | p.admin,p.self_edit,
|
---|
| 1591 | p.group_create,p.group_edit,p.group_delete,
|
---|
| 1592 | p.user_create,p.user_edit,p.user_delete,
|
---|
| 1593 | p.domain_create,p.domain_edit,p.domain_delete,
|
---|
[387] | 1594 | p.record_create,p.record_edit,p.record_delete,p.record_locchg,
|
---|
[382] | 1595 | p.location_create,p.location_edit,p.location_delete,p.location_view
|
---|
[65] | 1596 | FROM permissions p
|
---|
| 1597 | );
|
---|
| 1598 | if ($type eq 'group') {
|
---|
| 1599 | $sql .= qq(
|
---|
| 1600 | JOIN groups g ON g.permission_id=p.permission_id
|
---|
| 1601 | WHERE g.group_id=?
|
---|
| 1602 | );
|
---|
| 1603 | } else {
|
---|
| 1604 | $sql .= qq(
|
---|
| 1605 | JOIN users u ON u.permission_id=p.permission_id
|
---|
| 1606 | WHERE u.user_id=?
|
---|
| 1607 | );
|
---|
| 1608 | }
|
---|
| 1609 |
|
---|
| 1610 | my $sth = $dbh->prepare($sql);
|
---|
| 1611 |
|
---|
| 1612 | $sth->execute($id) or die "argh: ".$sth->errstr;
|
---|
| 1613 |
|
---|
| 1614 | # my $permref = $sth->fetchrow_hashref;
|
---|
| 1615 | # return $permref;
|
---|
| 1616 | # $hash = $permref;
|
---|
| 1617 | # Eww. Need to learn how to forcibly drop a hashref onto an existing hash.
|
---|
| 1618 | ($hash->{admin},$hash->{self_edit},
|
---|
| 1619 | $hash->{group_create},$hash->{group_edit},$hash->{group_delete},
|
---|
| 1620 | $hash->{user_create},$hash->{user_edit},$hash->{user_delete},
|
---|
| 1621 | $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete},
|
---|
[387] | 1622 | $hash->{record_create},$hash->{record_edit},$hash->{record_delete},$hash->{record_locchg},
|
---|
[382] | 1623 | $hash->{location_create},$hash->{location_edit},$hash->{location_delete},$hash->{location_view}
|
---|
| 1624 | ) = $sth->fetchrow_array;
|
---|
[65] | 1625 |
|
---|
| 1626 | } # end getPermissions()
|
---|
| 1627 |
|
---|
| 1628 |
|
---|
| 1629 | ## DNSDB::changePermissions()
|
---|
| 1630 | # Update an ACL entry
|
---|
| 1631 | # Takes a db handle, type, owner-id, and hashref for the changed permissions.
|
---|
| 1632 | sub changePermissions {
|
---|
[474] | 1633 | my $self = shift;
|
---|
| 1634 | my $dbh = $self->{dbh};
|
---|
[65] | 1635 | my $type = shift;
|
---|
| 1636 | my $id = shift;
|
---|
| 1637 | my $newperms = shift;
|
---|
[87] | 1638 | my $inherit = shift || 0;
|
---|
[65] | 1639 |
|
---|
[294] | 1640 | my $resultmsg = '';
|
---|
[66] | 1641 |
|
---|
[87] | 1642 | # see if we're switching from inherited to custom. for bonus points,
|
---|
| 1643 | # snag the permid and parent permid anyway, since we'll need the permid
|
---|
| 1644 | # to set/alter custom perms, and both if we're switching from custom to
|
---|
| 1645 | # inherited.
|
---|
[294] | 1646 | my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id,".
|
---|
| 1647 | ($type eq 'user' ? 'u.group_id,u.username' : 'u.parent_group_id,u.group_name').
|
---|
[65] | 1648 | " FROM ".($type eq 'user' ? 'users' : 'groups')." u ".
|
---|
[66] | 1649 | " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ".
|
---|
[65] | 1650 | " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?");
|
---|
| 1651 | $sth->execute($id);
|
---|
| 1652 |
|
---|
[294] | 1653 | my ($wasinherited,$permid,$parpermid,$parid,$name) = $sth->fetchrow_array;
|
---|
[66] | 1654 |
|
---|
[78] | 1655 | # hack phtoui
|
---|
| 1656 | # group id 1 is "special" in that it's it's own parent (err... possibly.)
|
---|
| 1657 | # may make its parent id 0 which doesn't exist, and as a bonus is Perl-false.
|
---|
| 1658 | $wasinherited = 0 if ($type eq 'group' && $id == 1);
|
---|
| 1659 |
|
---|
[66] | 1660 | local $dbh->{AutoCommit} = 0;
|
---|
| 1661 | local $dbh->{RaiseError} = 1;
|
---|
| 1662 |
|
---|
| 1663 | # Wrap all the SQL in a transaction
|
---|
| 1664 | eval {
|
---|
[87] | 1665 | if ($inherit) {
|
---|
| 1666 |
|
---|
| 1667 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ".
|
---|
| 1668 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) );
|
---|
| 1669 | $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) );
|
---|
| 1670 |
|
---|
| 1671 | } else {
|
---|
| 1672 |
|
---|
| 1673 | if ($wasinherited) { # munge new permission entry in if we're switching from inherited perms
|
---|
[66] | 1674 | ##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users
|
---|
[87] | 1675 | # ... if'n'when we have groups with fully inherited permissions.
|
---|
| 1676 | # SQL is coo
|
---|
| 1677 | $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ".
|
---|
| 1678 | "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) );
|
---|
| 1679 | ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ".
|
---|
| 1680 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) );
|
---|
| 1681 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ".
|
---|
| 1682 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) );
|
---|
[66] | 1683 | }
|
---|
[78] | 1684 |
|
---|
[87] | 1685 | # and now set the permissions we were passed
|
---|
| 1686 | foreach (@permtypes) {
|
---|
| 1687 | if (defined ($newperms->{$_})) {
|
---|
| 1688 | $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) );
|
---|
| 1689 | }
|
---|
| 1690 | }
|
---|
| 1691 |
|
---|
| 1692 | } # (inherited->)? custom
|
---|
| 1693 |
|
---|
[294] | 1694 | if ($type eq 'user') {
|
---|
| 1695 | $resultmsg = "Updated permissions for user $name";
|
---|
| 1696 | } else {
|
---|
| 1697 | $resultmsg = "Updated default permissions for group $name";
|
---|
| 1698 | }
|
---|
| 1699 | _log($dbh, (group_id => ($type eq 'user' ? $parid : $id), entry => $resultmsg));
|
---|
[66] | 1700 | $dbh->commit;
|
---|
| 1701 | }; # end eval
|
---|
| 1702 | if ($@) {
|
---|
| 1703 | my $msg = $@;
|
---|
| 1704 | eval { $dbh->rollback; };
|
---|
[294] | 1705 | return ('FAIL',"Error changing permissions: $msg");
|
---|
[66] | 1706 | }
|
---|
| 1707 |
|
---|
[294] | 1708 | return ('OK',$resultmsg);
|
---|
[65] | 1709 | } # end changePermissions()
|
---|
| 1710 |
|
---|
| 1711 |
|
---|
[67] | 1712 | ## DNSDB::comparePermissions()
|
---|
| 1713 | # Compare two permission hashes
|
---|
| 1714 | # Returns '>', '<', '=', '!'
|
---|
| 1715 | sub comparePermissions {
|
---|
| 1716 | my $p1 = shift;
|
---|
| 1717 | my $p2 = shift;
|
---|
| 1718 |
|
---|
| 1719 | my $retval = '='; # assume equality until proven otherwise
|
---|
| 1720 |
|
---|
| 1721 | no warnings "uninitialized";
|
---|
| 1722 |
|
---|
| 1723 | foreach (@permtypes) {
|
---|
| 1724 | next if $p1->{$_} == $p2->{$_}; # equal is good
|
---|
| 1725 | if ($p1->{$_} && !$p2->{$_}) {
|
---|
| 1726 | if ($retval eq '<') { # if we've already found an unequal pair where
|
---|
| 1727 | $retval = '!'; # $p2 has more access, and we now find a pair
|
---|
| 1728 | last; # where $p1 has more access, the overall access
|
---|
| 1729 | } # is neither greater or lesser, it's unequal.
|
---|
| 1730 | $retval = '>';
|
---|
| 1731 | }
|
---|
| 1732 | if (!$p1->{$_} && $p2->{$_}) {
|
---|
| 1733 | if ($retval eq '>') { # if we've already found an unequal pair where
|
---|
| 1734 | $retval = '!'; # $p1 has more access, and we now find a pair
|
---|
| 1735 | last; # where $p2 has more access, the overall access
|
---|
| 1736 | } # is neither greater or lesser, it's unequal.
|
---|
| 1737 | $retval = '<';
|
---|
| 1738 | }
|
---|
| 1739 | }
|
---|
| 1740 | return $retval;
|
---|
| 1741 | } # end comparePermissions()
|
---|
| 1742 |
|
---|
| 1743 |
|
---|
[112] | 1744 | ## DNSDB::changeGroup()
|
---|
| 1745 | # Change group ID of an entity
|
---|
| 1746 | # Takes a database handle, entity type, entity ID, and new group ID
|
---|
| 1747 | sub changeGroup {
|
---|
[476] | 1748 | my $self = shift;
|
---|
| 1749 | my $dbh = $self->{dbh};
|
---|
[112] | 1750 | my $type = shift;
|
---|
| 1751 | my $id = shift;
|
---|
| 1752 | my $newgrp = shift;
|
---|
| 1753 |
|
---|
| 1754 | ##fixme: fail on not enough args
|
---|
| 1755 | #return ('FAIL', "Missing
|
---|
| 1756 |
|
---|
[295] | 1757 | return ('FAIL', "Can't change the group of a $type")
|
---|
| 1758 | unless grep /^$type$/, ('domain','revzone','user','group'); # could be extended for defrecs?
|
---|
| 1759 |
|
---|
| 1760 | # Collect some names for logging and messages
|
---|
| 1761 | my $entname;
|
---|
[112] | 1762 | if ($type eq 'domain') {
|
---|
[473] | 1763 | $entname = $self->domainName($id);
|
---|
[295] | 1764 | } elsif ($type eq 'revzone') {
|
---|
[473] | 1765 | $entname = $self->revName($id);
|
---|
[112] | 1766 | } elsif ($type eq 'user') {
|
---|
[473] | 1767 | $entname = $self->userFullName($id, '%u');
|
---|
[112] | 1768 | } elsif ($type eq 'group') {
|
---|
[473] | 1769 | $entname = $self->groupName($id);
|
---|
[112] | 1770 | }
|
---|
[295] | 1771 |
|
---|
| 1772 | my ($oldgid) = $dbh->selectrow_array("SELECT group_id FROM $par_tbl{$type} WHERE $id_col{$type}=?",
|
---|
| 1773 | undef, ($id));
|
---|
[473] | 1774 | my $oldgname = $self->groupName($oldgid);
|
---|
| 1775 | my $newgname = $self->groupName($newgrp);
|
---|
[295] | 1776 |
|
---|
| 1777 | return ('FAIL', "Can't move things into a group that doesn't exist") if !$newgname;
|
---|
| 1778 |
|
---|
| 1779 | return ('WARN', "Nothing to do, new group is the same as the old group") if $oldgid == $newgrp;
|
---|
| 1780 |
|
---|
| 1781 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 1782 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 1783 | local $dbh->{AutoCommit} = 0;
|
---|
| 1784 | local $dbh->{RaiseError} = 1;
|
---|
| 1785 |
|
---|
| 1786 | eval {
|
---|
| 1787 | $dbh->do("UPDATE $par_tbl{$type} SET group_id=? WHERE $id_col{$type}=?", undef, ($newgrp, $id));
|
---|
| 1788 | # Log the change in both the old and new groups
|
---|
| 1789 | _log($dbh, (group_id => $oldgid, entry => "Moved $type $entname from $oldgname to $newgname"));
|
---|
| 1790 | _log($dbh, (group_id => $newgrp, entry => "Moved $type $entname from $oldgname to $newgname"));
|
---|
| 1791 | $dbh->commit;
|
---|
| 1792 | };
|
---|
| 1793 | if ($@) {
|
---|
| 1794 | my $msg = $@;
|
---|
| 1795 | eval { $dbh->rollback; };
|
---|
| 1796 | if ($config{log_failures}) {
|
---|
| 1797 | _log($dbh, (group_id => $oldgid, entry => "Error moving $type $entname to $newgname: $msg"));
|
---|
| 1798 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 1799 | }
|
---|
| 1800 | return ('FAIL',"Error moving $type $entname to $newgname: $msg");
|
---|
| 1801 | }
|
---|
| 1802 |
|
---|
| 1803 | return ('OK',"Moved $type $entname from $oldgname to $newgname");
|
---|
[112] | 1804 | } # end changeGroup()
|
---|
| 1805 |
|
---|
| 1806 |
|
---|
[2] | 1807 | ##
|
---|
| 1808 | ## Processing subs
|
---|
| 1809 | ##
|
---|
| 1810 |
|
---|
| 1811 | ## DNSDB::addDomain()
|
---|
| 1812 | # Add a domain
|
---|
[190] | 1813 | # Takes a database handle, domain name, numeric group, boolean(ish) state (active/inactive),
|
---|
| 1814 | # and user info hash (for logging).
|
---|
[2] | 1815 | # Returns a status code and message
|
---|
| 1816 | sub addDomain {
|
---|
| 1817 | $errstr = '';
|
---|
[477] | 1818 | my $self = shift;
|
---|
| 1819 | my $dbh = $self->{dbh};
|
---|
[2] | 1820 | return ('FAIL',"Need database handle") if !$dbh;
|
---|
| 1821 | my $domain = shift;
|
---|
[91] | 1822 | return ('FAIL',"Domain must not be blank") if !$domain;
|
---|
[2] | 1823 | my $group = shift;
|
---|
| 1824 | return ('FAIL',"Need group") if !defined($group);
|
---|
| 1825 | my $state = shift;
|
---|
| 1826 | return ('FAIL',"Need domain status") if !defined($state);
|
---|
| 1827 |
|
---|
[116] | 1828 | $state = 1 if $state =~ /^active$/;
|
---|
| 1829 | $state = 1 if $state =~ /^on$/;
|
---|
| 1830 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 1831 | $state = 0 if $state =~ /^off$/;
|
---|
| 1832 |
|
---|
| 1833 | return ('FAIL',"Invalid domain status") if $state !~ /^\d+$/;
|
---|
| 1834 |
|
---|
[190] | 1835 | return ('FAIL', "Invalid characters in domain") if $domain !~ /^[a-zA-Z0-9_.-]+$/;
|
---|
| 1836 |
|
---|
[349] | 1837 | my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)");
|
---|
[3] | 1838 | my $dom_id;
|
---|
| 1839 |
|
---|
[38] | 1840 | # quick check to start to see if we've already got one
|
---|
| 1841 | $sth->execute($domain);
|
---|
| 1842 | ($dom_id) = $sth->fetchrow_array;
|
---|
| 1843 |
|
---|
| 1844 | return ('FAIL', "Domain already exists") if $dom_id;
|
---|
| 1845 |
|
---|
[2] | 1846 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 1847 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 1848 | local $dbh->{AutoCommit} = 0;
|
---|
| 1849 | local $dbh->{RaiseError} = 1;
|
---|
| 1850 |
|
---|
| 1851 | # Wrap all the SQL in a transaction
|
---|
| 1852 | eval {
|
---|
| 1853 | # insert the domain...
|
---|
[190] | 1854 | $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef, ($domain, $group, $state));
|
---|
[2] | 1855 |
|
---|
| 1856 | # get the ID...
|
---|
[349] | 1857 | ($dom_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
| 1858 | undef, ($domain));
|
---|
[2] | 1859 |
|
---|
[284] | 1860 | _log($dbh, (domain_id => $dom_id, group_id => $group,
|
---|
[259] | 1861 | entry => "Added ".($state ? 'active' : 'inactive')." domain $domain"));
|
---|
[190] | 1862 |
|
---|
[2] | 1863 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
[190] | 1864 | my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
| 1865 | my $sth_in = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,distance,weight,port,ttl)".
|
---|
| 1866 | " VALUES ($dom_id,?,?,?,?,?,?,?)");
|
---|
| 1867 | $sth->execute($group);
|
---|
[3] | 1868 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $sth->fetchrow_array()) {
|
---|
[2] | 1869 | $host =~ s/DOMAIN/$domain/g;
|
---|
[37] | 1870 | $val =~ s/DOMAIN/$domain/g;
|
---|
[3] | 1871 | $sth_in->execute($host,$type,$val,$dist,$weight,$port,$ttl);
|
---|
[190] | 1872 | if ($typemap{$type} eq 'SOA') {
|
---|
| 1873 | my @tmp1 = split /:/, $host;
|
---|
| 1874 | my @tmp2 = split /:/, $val;
|
---|
[284] | 1875 | _log($dbh, (domain_id => $dom_id, group_id => $group,
|
---|
| 1876 | entry => "[new $domain] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
[257] | 1877 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"));
|
---|
[190] | 1878 | } else {
|
---|
| 1879 | my $logentry = "[new $domain] Added record '$host $typemap{$type}";
|
---|
| 1880 | $logentry .= " [distance $dist]" if $typemap{$type} eq 'MX';
|
---|
| 1881 | $logentry .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$type} eq 'SRV';
|
---|
[284] | 1882 | _log($dbh, (domain_id => $dom_id, group_id => $group,
|
---|
| 1883 | entry => $logentry." $val', TTL $ttl"));
|
---|
[190] | 1884 | }
|
---|
[2] | 1885 | }
|
---|
| 1886 |
|
---|
| 1887 | # once we get here, we should have suceeded.
|
---|
| 1888 | $dbh->commit;
|
---|
| 1889 | }; # end eval
|
---|
| 1890 |
|
---|
| 1891 | if ($@) {
|
---|
| 1892 | my $msg = $@;
|
---|
| 1893 | eval { $dbh->rollback; };
|
---|
[286] | 1894 | _log($dbh, (group_id => $group, entry => "Failed adding domain $domain ($msg)"))
|
---|
[284] | 1895 | if $config{log_failures};
|
---|
| 1896 | $dbh->commit; # since we enabled transactions earlier
|
---|
[193] | 1897 | return ('FAIL',$msg);
|
---|
[2] | 1898 | } else {
|
---|
[3] | 1899 | return ('OK',$dom_id);
|
---|
[2] | 1900 | }
|
---|
| 1901 | } # end addDomain
|
---|
| 1902 |
|
---|
| 1903 |
|
---|
[274] | 1904 | ## DNSDB::delZone()
|
---|
| 1905 | # Delete a forward or reverse zone.
|
---|
| 1906 | # Takes a database handle, zone ID, and forward/reverse flag.
|
---|
[3] | 1907 | # for now, just delete the records, then the domain.
|
---|
| 1908 | # later we may want to archive it in some way instead (status code 2, for example?)
|
---|
[274] | 1909 | sub delZone {
|
---|
[477] | 1910 | my $self = shift;
|
---|
| 1911 | my $dbh = $self->{dbh};
|
---|
[274] | 1912 | my $zoneid = shift;
|
---|
| 1913 | my $revrec = shift;
|
---|
[3] | 1914 |
|
---|
| 1915 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 1916 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 1917 | local $dbh->{AutoCommit} = 0;
|
---|
| 1918 | local $dbh->{RaiseError} = 1;
|
---|
| 1919 |
|
---|
[285] | 1920 | my $msg = '';
|
---|
[23] | 1921 | my $failmsg = '';
|
---|
[473] | 1922 | my $zone = ($revrec eq 'n' ? $self->domainName($zoneid) : $self->revName($zoneid));
|
---|
[23] | 1923 |
|
---|
[343] | 1924 | return ('FAIL', ($revrec eq 'n' ? 'Domain' : 'Reverse zone')." ID $zoneid doesn't exist") if !$zone;
|
---|
| 1925 |
|
---|
[285] | 1926 | # Set this up here since we may use if if $config{log_failures} is enabled
|
---|
| 1927 | my %loghash;
|
---|
| 1928 | $loghash{domain_id} = $zoneid if $revrec eq 'n';
|
---|
| 1929 | $loghash{rdns_id} = $zoneid if $revrec eq 'y';
|
---|
[473] | 1930 | $loghash{group_id} = $self->parentID(
|
---|
| 1931 | id => $zoneid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec);
|
---|
[285] | 1932 |
|
---|
[3] | 1933 | # Wrap all the SQL in a transaction
|
---|
| 1934 | eval {
|
---|
[274] | 1935 | # Disentangle custom record types before removing the
|
---|
| 1936 | # ones that are only in the zone to be deleted
|
---|
| 1937 | if ($revrec eq 'n') {
|
---|
| 1938 | my $sth = $dbh->prepare("UPDATE records SET type=?,domain_id=0 WHERE domain_id=? AND type=?");
|
---|
| 1939 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
| 1940 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65280);
|
---|
| 1941 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65281);
|
---|
| 1942 | $sth->execute(65282, $zoneid, 65283);
|
---|
| 1943 | $sth->execute(65282, $zoneid, 65284);
|
---|
| 1944 | $failmsg = "Failure removing domain records";
|
---|
| 1945 | $dbh->do("DELETE FROM records WHERE domain_id=?", undef, ($zoneid));
|
---|
| 1946 | $failmsg = "Failure removing domain";
|
---|
| 1947 | $dbh->do("DELETE FROM domains WHERE domain_id=?", undef, ($zoneid));
|
---|
| 1948 | } else {
|
---|
| 1949 | my $sth = $dbh->prepare("UPDATE records SET type=?,rdns_id=0 WHERE rdns_id=? AND type=?");
|
---|
| 1950 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
| 1951 | $sth->execute($reverse_typemap{A}, $zoneid, 65280);
|
---|
| 1952 | $sth->execute($reverse_typemap{AAAA}, $zoneid, 65281);
|
---|
| 1953 | # We don't have an "A template" or "AAAA template" type, although it might be useful for symmetry.
|
---|
[345] | 1954 | # $sth->execute(65286?, $zoneid, 65283);
|
---|
| 1955 | # $sth->execute(65286?, $zoneid, 65284);
|
---|
[274] | 1956 | $failmsg = "Failure removing reverse records";
|
---|
| 1957 | $dbh->do("DELETE FROM records WHERE rdns_id=?", undef, ($zoneid));
|
---|
| 1958 | $failmsg = "Failure removing reverse zone";
|
---|
| 1959 | $dbh->do("DELETE FROM revzones WHERE rdns_id=?", undef, ($zoneid));
|
---|
| 1960 | }
|
---|
[3] | 1961 |
|
---|
[285] | 1962 | $msg = "Deleted ".($revrec eq 'n' ? 'domain' : 'reverse zone')." $zone";
|
---|
| 1963 | $loghash{entry} = $msg;
|
---|
| 1964 | _log($dbh, %loghash);
|
---|
| 1965 |
|
---|
[3] | 1966 | # once we get here, we should have suceeded.
|
---|
[23] | 1967 | $dbh->commit;
|
---|
[3] | 1968 | }; # end eval
|
---|
| 1969 |
|
---|
| 1970 | if ($@) {
|
---|
[285] | 1971 | $msg = $@;
|
---|
[3] | 1972 | eval { $dbh->rollback; };
|
---|
[295] | 1973 | $loghash{entry} = "Error deleting $zone: $msg ($failmsg)";
|
---|
| 1974 | if ($config{log_failures}) {
|
---|
| 1975 | _log($dbh, %loghash);
|
---|
| 1976 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 1977 | }
|
---|
| 1978 | return ('FAIL', $loghash{entry});
|
---|
[3] | 1979 | } else {
|
---|
[295] | 1980 | return ('OK', $msg);
|
---|
[3] | 1981 | }
|
---|
| 1982 |
|
---|
[274] | 1983 | } # end delZone()
|
---|
[3] | 1984 |
|
---|
| 1985 |
|
---|
[2] | 1986 | ## DNSDB::domainName()
|
---|
| 1987 | # Return the domain name based on a domain ID
|
---|
| 1988 | # Takes a database handle and the domain ID
|
---|
| 1989 | # Returns the domain name or undef on failure
|
---|
| 1990 | sub domainName {
|
---|
| 1991 | $errstr = '';
|
---|
[473] | 1992 | my $self = shift;
|
---|
| 1993 | my $dbh = $self->{dbh};
|
---|
[2] | 1994 | my $domid = shift;
|
---|
[91] | 1995 | my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
|
---|
[2] | 1996 | $errstr = $DBI::errstr if !$domname;
|
---|
| 1997 | return $domname if $domname;
|
---|
[91] | 1998 | } # end domainName()
|
---|
[2] | 1999 |
|
---|
| 2000 |
|
---|
[224] | 2001 | ## DNSDB::revName()
|
---|
| 2002 | # Return the reverse zone name based on an rDNS ID
|
---|
| 2003 | # Takes a database handle and the rDNS ID
|
---|
| 2004 | # Returns the reverse zone name or undef on failure
|
---|
| 2005 | sub revName {
|
---|
| 2006 | $errstr = '';
|
---|
[473] | 2007 | my $self = shift;
|
---|
| 2008 | my $dbh = $self->{dbh};
|
---|
[224] | 2009 | my $revid = shift;
|
---|
| 2010 | my ($revname) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id=?", undef, ($revid) );
|
---|
| 2011 | $errstr = $DBI::errstr if !$revname;
|
---|
| 2012 | return $revname if $revname;
|
---|
| 2013 | } # end revName()
|
---|
| 2014 |
|
---|
| 2015 |
|
---|
[91] | 2016 | ## DNSDB::domainID()
|
---|
| 2017 | # Takes a database handle and domain name
|
---|
| 2018 | # Returns the domain ID number
|
---|
| 2019 | sub domainID {
|
---|
| 2020 | $errstr = '';
|
---|
[473] | 2021 | my $self = shift;
|
---|
| 2022 | my $dbh = $self->{dbh};
|
---|
[91] | 2023 | my $domain = shift;
|
---|
[349] | 2024 | my ($domid) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
| 2025 | undef, ($domain) );
|
---|
[91] | 2026 | $errstr = $DBI::errstr if !$domid;
|
---|
| 2027 | return $domid if $domid;
|
---|
| 2028 | } # end domainID()
|
---|
| 2029 |
|
---|
| 2030 |
|
---|
[276] | 2031 | ## DNSDB::revID()
|
---|
| 2032 | # Takes a database handle and reverse zone name
|
---|
| 2033 | # Returns the rDNS ID number
|
---|
| 2034 | sub revID {
|
---|
| 2035 | $errstr = '';
|
---|
[473] | 2036 | my $self = shift;
|
---|
| 2037 | my $dbh = $self->{dbh};
|
---|
[276] | 2038 | my $revzone = shift;
|
---|
| 2039 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ($revzone) );
|
---|
| 2040 | $errstr = $DBI::errstr if !$revid;
|
---|
| 2041 | return $revid if $revid;
|
---|
| 2042 | } # end revID()
|
---|
| 2043 |
|
---|
| 2044 |
|
---|
[260] | 2045 | ## DNSDB::addRDNS
|
---|
| 2046 | # Adds a reverse DNS zone
|
---|
[286] | 2047 | # Takes a database handle, CIDR block, reverse DNS pattern, numeric group,
|
---|
| 2048 | # and boolean(ish) state (active/inactive)
|
---|
[260] | 2049 | # Returns a status code and message
|
---|
| 2050 | sub addRDNS {
|
---|
[477] | 2051 | my $self = shift;
|
---|
| 2052 | my $dbh = $self->{dbh};
|
---|
[260] | 2053 | my $zone = NetAddr::IP->new(shift);
|
---|
[446] | 2054 |
|
---|
[260] | 2055 | return ('FAIL',"Zone name must be a valid CIDR netblock") unless ($zone && $zone->addr !~ /^0/);
|
---|
[270] | 2056 | my $revpatt = shift; # construct a custom (A/AAAA+)? PTR template record
|
---|
[260] | 2057 | my $group = shift;
|
---|
| 2058 | my $state = shift;
|
---|
[446] | 2059 | my $defloc = shift || '';
|
---|
[260] | 2060 |
|
---|
| 2061 | $state = 1 if $state =~ /^active$/;
|
---|
| 2062 | $state = 1 if $state =~ /^on$/;
|
---|
| 2063 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 2064 | $state = 0 if $state =~ /^off$/;
|
---|
| 2065 |
|
---|
| 2066 | return ('FAIL',"Invalid zone status") if $state !~ /^\d+$/;
|
---|
| 2067 |
|
---|
| 2068 | # quick check to start to see if we've already got one
|
---|
[299] | 2069 | my ($rdns_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ("$zone"));
|
---|
[260] | 2070 |
|
---|
| 2071 | return ('FAIL', "Zone already exists") if $rdns_id;
|
---|
| 2072 |
|
---|
| 2073 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2074 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2075 | local $dbh->{AutoCommit} = 0;
|
---|
| 2076 | local $dbh->{RaiseError} = 1;
|
---|
| 2077 |
|
---|
[264] | 2078 | my $warnstr = '';
|
---|
[270] | 2079 | my $defttl = 3600; # 1 hour should be reasonable. And unless things have gone horribly
|
---|
| 2080 | # wrong, we should have a value to override this anyway.
|
---|
[264] | 2081 |
|
---|
[260] | 2082 | # Wrap all the SQL in a transaction
|
---|
| 2083 | eval {
|
---|
[446] | 2084 | # insert the zone...
|
---|
| 2085 | $dbh->do("INSERT INTO revzones (revnet,group_id,status,default_location) VALUES (?,?,?,?)", undef,
|
---|
| 2086 | ($zone, $group, $state, $defloc) );
|
---|
[260] | 2087 |
|
---|
| 2088 | # get the ID...
|
---|
| 2089 | ($rdns_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
| 2090 |
|
---|
[286] | 2091 | _log($dbh, (rdns_id => $rdns_id, group_id => $group,
|
---|
[260] | 2092 | entry => "Added ".($state ? 'active' : 'inactive')." reverse zone $zone"));
|
---|
| 2093 |
|
---|
| 2094 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
| 2095 | my $sth = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
[446] | 2096 | my $sth_in = $dbh->prepare("INSERT INTO records (rdns_id,domain_id,host,type,val,ttl,location)".
|
---|
| 2097 | " VALUES ($rdns_id,?,?,?,?,?,?)");
|
---|
[260] | 2098 | $sth->execute($group);
|
---|
| 2099 | while (my ($host,$type,$val,$ttl) = $sth->fetchrow_array()) {
|
---|
[264] | 2100 | # Silently skip v4/v6 mismatches. This is not an error, this is expected.
|
---|
| 2101 | if ($zone->{isv6}) {
|
---|
| 2102 | next if ($type == 65280 || $type == 65283);
|
---|
| 2103 | } else {
|
---|
| 2104 | next if ($type == 65281 || $type == 65284);
|
---|
| 2105 | }
|
---|
[269] | 2106 |
|
---|
[260] | 2107 | $host =~ s/ADMINDOMAIN/$config{domain}/g;
|
---|
[264] | 2108 |
|
---|
[265] | 2109 | # Check to make sure the IP stubs will fit in the zone. Under most usage failures here should be rare.
|
---|
| 2110 | # On failure, tack a note on to a warning string and continue without adding this record.
|
---|
| 2111 | # While we're at it, we substitute $zone for ZONE in the value.
|
---|
| 2112 | if ($val eq 'ZONE') {
|
---|
[444] | 2113 | # If we've got a pattern, we skip the default record version on (A+)PTR-template types
|
---|
| 2114 | next if $revpatt && ($type == 65282 || $type == 65283);
|
---|
[269] | 2115 | ##fixme? do we care if we have multiple whole-zone templates?
|
---|
[265] | 2116 | $val = $zone->network;
|
---|
| 2117 | } elsif ($val =~ /ZONE/) {
|
---|
| 2118 | my $tmpval = $val;
|
---|
| 2119 | $tmpval =~ s/ZONE//;
|
---|
[269] | 2120 | # Bend the rules and allow single-trailing-number PTR or PTR template records to be inserted
|
---|
| 2121 | # as either v4 or v6. May make this an off-by-default config flag
|
---|
| 2122 | # Note that the origin records that may trigger this **SHOULD** already have ZONE,\d
|
---|
| 2123 | if ($type == 12 || $type == 65282) {
|
---|
| 2124 | $tmpval =~ s/[,.]/::/ if ($tmpval =~ /^[,.]\d+$/ && $zone->{isv6});
|
---|
| 2125 | $tmpval =~ s/[,:]+/./ if ($tmpval =~ /^(?:,|::)\d+$/ && !$zone->{isv6});
|
---|
| 2126 | }
|
---|
[265] | 2127 | my $addr;
|
---|
[471] | 2128 | if ($self->_ipparent('n', 'y', \$tmpval, $rdns_id, \$addr)) {
|
---|
[265] | 2129 | $val = $addr->addr;
|
---|
| 2130 | } else {
|
---|
[269] | 2131 | $warnstr .= "\nDefault record '$val $typemap{$type} $host' doesn't fit in $zone, skipping";
|
---|
[264] | 2132 | next;
|
---|
| 2133 | }
|
---|
| 2134 | }
|
---|
| 2135 |
|
---|
[328] | 2136 | # Substitute $zone for ZONE in the hostname, but only for non-NS records.
|
---|
| 2137 | # NS records get this substitution on the value instead.
|
---|
| 2138 | $host = _ZONE($zone, $host) if $type != 2;
|
---|
[265] | 2139 |
|
---|
[269] | 2140 | # Fill in the forward domain ID if we can find it, otherwise:
|
---|
| 2141 | # Coerce type down to PTR or PTR template if we can't
|
---|
| 2142 | my $domid = 0;
|
---|
| 2143 | if ($type >= 65280) {
|
---|
[471] | 2144 | if (!($domid = $self->_hostparent($host))) {
|
---|
[269] | 2145 | $warnstr .= "\nRecord added as PTR instead of $typemap{$type}; domain not found for $host";
|
---|
| 2146 | $type = $reverse_typemap{PTR};
|
---|
| 2147 | $domid = 0; # just to be explicit.
|
---|
| 2148 | }
|
---|
| 2149 | }
|
---|
| 2150 |
|
---|
[446] | 2151 | $sth_in->execute($domid,$host,$type,$val,$ttl,$defloc);
|
---|
[269] | 2152 |
|
---|
[260] | 2153 | if ($typemap{$type} eq 'SOA') {
|
---|
| 2154 | my @tmp1 = split /:/, $host;
|
---|
| 2155 | my @tmp2 = split /:/, $val;
|
---|
[286] | 2156 | _log($dbh, (rdns_id => $rdns_id, group_id => $group,
|
---|
| 2157 | entry => "[new $zone] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
[260] | 2158 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"));
|
---|
[270] | 2159 | $defttl = $tmp2[3];
|
---|
[260] | 2160 | } else {
|
---|
[446] | 2161 | my $logentry = "[new $zone] Added record '$host $typemap{$type} $val', TTL $ttl";
|
---|
[480] | 2162 | $logentry .= ", default location ".$self->getLoc($defloc)->{description} if $defloc;
|
---|
[446] | 2163 | _log($dbh, (rdns_id => $rdns_id, domain_id => $domid, group_id => $group, entry => $logentry) );
|
---|
[260] | 2164 | }
|
---|
| 2165 | }
|
---|
| 2166 |
|
---|
[270] | 2167 | # Generate record based on provided pattern.
|
---|
| 2168 | if ($revpatt) {
|
---|
| 2169 | my $host;
|
---|
| 2170 | my $type = ($zone->{isv6} ? 65284 : 65283);
|
---|
| 2171 | my $val = $zone->network;
|
---|
[269] | 2172 |
|
---|
[270] | 2173 | # Substitute $zone for ZONE in the hostname.
|
---|
| 2174 | $host = _ZONE($zone, $revpatt);
|
---|
| 2175 |
|
---|
| 2176 | my $domid = 0;
|
---|
[471] | 2177 | if (!($domid = $self->_hostparent($host))) {
|
---|
[270] | 2178 | $warnstr .= "\nDefault pattern added as PTR template instead of $typemap{$type}; domain not found for $host";
|
---|
| 2179 | $type = 65282;
|
---|
| 2180 | $domid = 0; # just to be explicit.
|
---|
| 2181 | }
|
---|
| 2182 |
|
---|
[446] | 2183 | $sth_in->execute($domid,$host,$type,$val,$defttl,$defloc);
|
---|
[286] | 2184 | my $logentry = "[new $zone] Added record '$host $typemap{$type}";
|
---|
| 2185 | _log($dbh, (rdns_id => $rdns_id, domain_id => $domid, group_id => $group,
|
---|
| 2186 | entry => $logentry." $val', TTL $defttl from pattern"));
|
---|
[270] | 2187 | }
|
---|
| 2188 |
|
---|
[264] | 2189 | # If there are warnings (presumably about default records skipped for cause) log them
|
---|
[286] | 2190 | _log($dbh, (rdns_id => $rdns_id, group_id => $group, entry => "Warning(s) adding $zone:$warnstr"))
|
---|
[264] | 2191 | if $warnstr;
|
---|
[269] | 2192 |
|
---|
[260] | 2193 | # once we get here, we should have suceeded.
|
---|
| 2194 | $dbh->commit;
|
---|
| 2195 | }; # end eval
|
---|
| 2196 |
|
---|
| 2197 | if ($@) {
|
---|
| 2198 | my $msg = $@;
|
---|
| 2199 | eval { $dbh->rollback; };
|
---|
[286] | 2200 | _log($dbh, (group_id => $group, entry => "Failed adding reverse zone $zone ($msg)"))
|
---|
| 2201 | if $config{log_failures};
|
---|
| 2202 | $dbh->commit; # since we enabled transactions earlier
|
---|
[260] | 2203 | return ('FAIL',$msg);
|
---|
| 2204 | } else {
|
---|
[286] | 2205 | my $retcode = 'OK';
|
---|
| 2206 | if ($warnstr) {
|
---|
| 2207 | $resultstr = $warnstr;
|
---|
| 2208 | $retcode = 'WARN';
|
---|
| 2209 | }
|
---|
| 2210 | return ($retcode, $rdns_id);
|
---|
[260] | 2211 | }
|
---|
| 2212 |
|
---|
| 2213 | } # end addRDNS()
|
---|
| 2214 |
|
---|
| 2215 |
|
---|
[237] | 2216 | ## DNSDB::getZoneCount
|
---|
| 2217 | # Get count of zones in group or groups
|
---|
| 2218 | # Takes a database handle and hash containing:
|
---|
| 2219 | # - the "current" group
|
---|
| 2220 | # - an array of "acceptable" groups
|
---|
| 2221 | # - a flag for forward/reverse zones
|
---|
| 2222 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
| 2223 | # Returns an integer count of the resulting zone list.
|
---|
| 2224 | sub getZoneCount {
|
---|
[477] | 2225 | my $self = shift;
|
---|
| 2226 | my $dbh = $self->{dbh};
|
---|
[237] | 2227 |
|
---|
| 2228 | my %args = @_;
|
---|
| 2229 |
|
---|
| 2230 | my @filterargs;
|
---|
[239] | 2231 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2232 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2233 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
[237] | 2234 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2235 |
|
---|
| 2236 | my $sql;
|
---|
| 2237 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
| 2238 | if ($args{revrec} eq 'n') {
|
---|
| 2239 | $sql = "SELECT count(*) FROM domains".
|
---|
| 2240 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2241 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
| 2242 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
| 2243 | } else {
|
---|
| 2244 | $sql = "SELECT count(*) FROM revzones".
|
---|
| 2245 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2246 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
|
---|
| 2247 | ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2248 | }
|
---|
| 2249 | my ($count) = $dbh->selectrow_array($sql, undef, @filterargs);
|
---|
| 2250 | return $count;
|
---|
| 2251 | } # end getZoneCount()
|
---|
| 2252 |
|
---|
| 2253 |
|
---|
| 2254 | ## DNSDB::getZoneList()
|
---|
| 2255 | # Get a list of zones in the specified group(s)
|
---|
| 2256 | # Takes the same arguments as getZoneCount() above
|
---|
| 2257 | # Returns a reference to an array of hashrefs suitable for feeding to HTML::Template
|
---|
| 2258 | sub getZoneList {
|
---|
[477] | 2259 | my $self = shift;
|
---|
| 2260 | my $dbh = $self->{dbh};
|
---|
[237] | 2261 |
|
---|
| 2262 | my %args = @_;
|
---|
| 2263 |
|
---|
| 2264 | my @zonelist;
|
---|
| 2265 |
|
---|
[475] | 2266 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
[239] | 2267 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[237] | 2268 |
|
---|
| 2269 | my @filterargs;
|
---|
[239] | 2270 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2271 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2272 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
[237] | 2273 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2274 |
|
---|
| 2275 | my $sql;
|
---|
| 2276 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
| 2277 | if ($args{revrec} eq 'n') {
|
---|
[475] | 2278 | $args{sortby} = 'domain' if !$args{sortby} || !grep /^$args{sortby}$/, ('domain','group','status');
|
---|
[237] | 2279 | $sql = "SELECT domain_id,domain,status,groups.group_name AS group FROM domains".
|
---|
| 2280 | " INNER JOIN groups ON domains.group_id=groups.group_id".
|
---|
| 2281 | " WHERE domains.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2282 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
| 2283 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
| 2284 | } else {
|
---|
[239] | 2285 | ##fixme: arguably startwith here is irrelevant. depends on the UI though.
|
---|
[475] | 2286 | $args{sortby} = 'revnet' if !$args{sortby} || !grep /^$args{sortby}$/, ('revnet','group','status');
|
---|
[237] | 2287 | $sql = "SELECT rdns_id,revnet,status,groups.group_name AS group FROM revzones".
|
---|
| 2288 | " INNER JOIN groups ON revzones.group_id=groups.group_id".
|
---|
| 2289 | " WHERE revzones.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2290 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
|
---|
| 2291 | ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2292 | }
|
---|
| 2293 | # A common tail.
|
---|
[239] | 2294 | $sql .= " ORDER BY ".($args{sortby} eq 'group' ? 'groups.group_name' : $args{sortby})." $args{sortorder} ".
|
---|
| 2295 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage}".
|
---|
[237] | 2296 | " OFFSET ".$args{offset}*$config{perpage});
|
---|
[402] | 2297 | my $sth = $dbh->prepare($sql);
|
---|
| 2298 | $sth->execute(@filterargs);
|
---|
| 2299 | my $rownum = 0;
|
---|
[237] | 2300 |
|
---|
[402] | 2301 | while (my @data = $sth->fetchrow_array) {
|
---|
| 2302 | my %row;
|
---|
| 2303 | $row{domain_id} = $data[0];
|
---|
| 2304 | $row{domain} = $data[1];
|
---|
| 2305 | $row{status} = $data[2];
|
---|
| 2306 | $row{group} = $data[3];
|
---|
| 2307 | push @zonelist, \%row;
|
---|
| 2308 | }
|
---|
| 2309 |
|
---|
| 2310 | return \@zonelist;
|
---|
[237] | 2311 | } # end getZoneList()
|
---|
| 2312 |
|
---|
| 2313 |
|
---|
[383] | 2314 | ## DNSDB::getZoneLocation()
|
---|
[387] | 2315 | # Retrieve the default location for a zone.
|
---|
[383] | 2316 | # Takes a database handle, forward/reverse flag, and zone ID
|
---|
| 2317 | sub getZoneLocation {
|
---|
[477] | 2318 | my $self = shift;
|
---|
| 2319 | my $dbh = $self->{dbh};
|
---|
[383] | 2320 | my $revrec = shift;
|
---|
| 2321 | my $zoneid = shift;
|
---|
| 2322 |
|
---|
| 2323 | my ($loc) = $dbh->selectrow_array("SELECT default_location FROM ".
|
---|
| 2324 | ($revrec eq 'n' ? 'domains WHERE domain_id = ?' : 'revzones WHERE rdns_id = ?'),
|
---|
| 2325 | undef, ($zoneid));
|
---|
| 2326 | return $loc;
|
---|
| 2327 | } # end getZoneLocation()
|
---|
| 2328 |
|
---|
| 2329 |
|
---|
[18] | 2330 | ## DNSDB::addGroup()
|
---|
| 2331 | # Add a group
|
---|
[66] | 2332 | # Takes a database handle, group name, parent group, hashref for permissions,
|
---|
[292] | 2333 | # and optional template-vs-cloneme flag for the default records
|
---|
[18] | 2334 | # Returns a status code and message
|
---|
| 2335 | sub addGroup {
|
---|
| 2336 | $errstr = '';
|
---|
[476] | 2337 | my $self = shift;
|
---|
| 2338 | my $dbh = $self->{dbh};
|
---|
[20] | 2339 | my $groupname = shift;
|
---|
| 2340 | my $pargroup = shift;
|
---|
[66] | 2341 | my $permissions = shift;
|
---|
[18] | 2342 |
|
---|
[66] | 2343 | # 0 indicates "custom", hardcoded.
|
---|
[18] | 2344 | # Any other value clones that group's default records, if it exists.
|
---|
[66] | 2345 | my $inherit = shift || 0;
|
---|
| 2346 | ##fixme: need a flag to indicate clone records or <?> ?
|
---|
[18] | 2347 |
|
---|
| 2348 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2349 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2350 | local $dbh->{AutoCommit} = 0;
|
---|
| 2351 | local $dbh->{RaiseError} = 1;
|
---|
| 2352 |
|
---|
[292] | 2353 | my ($group_id) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($groupname));
|
---|
[38] | 2354 |
|
---|
| 2355 | return ('FAIL', "Group already exists") if $group_id;
|
---|
| 2356 |
|
---|
[18] | 2357 | # Wrap all the SQL in a transaction
|
---|
| 2358 | eval {
|
---|
[292] | 2359 | $dbh->do("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)", undef, ($pargroup, $groupname) );
|
---|
[18] | 2360 |
|
---|
[292] | 2361 | my ($groupid) = $dbh->selectrow_array("SELECT currval('groups_group_id_seq')");
|
---|
[18] | 2362 |
|
---|
[292] | 2363 | # We work through the whole set of permissions instead of specifying them so
|
---|
| 2364 | # that when we add a new permission, we don't have to change the code anywhere
|
---|
| 2365 | # that doesn't explicitly deal with that specific permission.
|
---|
| 2366 | my @permvals;
|
---|
| 2367 | foreach (@permtypes) {
|
---|
| 2368 | if (!defined ($permissions->{$_})) {
|
---|
| 2369 | push @permvals, 0;
|
---|
| 2370 | } else {
|
---|
| 2371 | push @permvals, $permissions->{$_};
|
---|
[66] | 2372 | }
|
---|
[292] | 2373 | }
|
---|
| 2374 | $dbh->do("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")",
|
---|
| 2375 | undef, ($groupid, @permvals) );
|
---|
| 2376 | my ($permid) = $dbh->selectrow_array("SELECT currval('permissions_permission_id_seq')");
|
---|
| 2377 | $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
|
---|
[66] | 2378 |
|
---|
[292] | 2379 | # Default records
|
---|
[255] | 2380 | my $sthf = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
|
---|
[20] | 2381 | "VALUES ($groupid,?,?,?,?,?,?,?)");
|
---|
[255] | 2382 | my $sthr = $dbh->prepare("INSERT INTO default_rev_records (group_id,host,type,val,ttl) ".
|
---|
| 2383 | "VALUES ($groupid,?,?,?,?)");
|
---|
[66] | 2384 | if ($inherit) {
|
---|
[87] | 2385 | # Duplicate records from parent. Actually relying on inherited records feels
|
---|
| 2386 | # very fragile, and it would be problematic to roll over at a later time.
|
---|
[18] | 2387 | my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
[87] | 2388 | $sth2->execute($pargroup);
|
---|
[18] | 2389 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
[255] | 2390 | $sthf->execute(@clonedata);
|
---|
[18] | 2391 | }
|
---|
[255] | 2392 | # And now the reverse records
|
---|
[292] | 2393 | $sth2 = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
[255] | 2394 | $sth2->execute($pargroup);
|
---|
| 2395 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
| 2396 | $sthr->execute(@clonedata);
|
---|
| 2397 | }
|
---|
[18] | 2398 | } else {
|
---|
[66] | 2399 | ##fixme: Hardcoding is Bad, mmmmkaaaay?
|
---|
[18] | 2400 | # reasonable basic defaults for SOA, MX, NS, and minimal hosting
|
---|
| 2401 | # could load from a config file, but somewhere along the line we need hardcoded bits.
|
---|
[255] | 2402 | $sthf->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
|
---|
| 2403 | $sthf->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
|
---|
| 2404 | $sthf->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
|
---|
| 2405 | $sthf->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
|
---|
| 2406 | $sthf->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
|
---|
| 2407 | $sthf->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
|
---|
| 2408 | # reasonable basic defaults for generic reverse zone. Same as initial SQL tabledef.
|
---|
| 2409 | $sthr->execute('hostmaster.ADMINDOMAIN:ns1.ADMINDOMAIN', 6, '10800:3600:604800:10800', 86400);
|
---|
| 2410 | $sthr->execute('unused-%r.ADMINDOMAIN', 65283, 'ZONE', 3600);
|
---|
[18] | 2411 | }
|
---|
| 2412 |
|
---|
[292] | 2413 | _log($dbh, (group_id => $pargroup, entry => "Added group $groupname") );
|
---|
| 2414 |
|
---|
[18] | 2415 | # once we get here, we should have suceeded.
|
---|
| 2416 | $dbh->commit;
|
---|
| 2417 | }; # end eval
|
---|
| 2418 |
|
---|
| 2419 | if ($@) {
|
---|
| 2420 | my $msg = $@;
|
---|
| 2421 | eval { $dbh->rollback; };
|
---|
[292] | 2422 | if ($config{log_failures}) {
|
---|
| 2423 | _log($dbh, (group_id => $pargroup, entry => "Failed to add group $groupname: $msg") );
|
---|
| 2424 | $dbh->commit;
|
---|
| 2425 | }
|
---|
[18] | 2426 | return ('FAIL',$msg);
|
---|
| 2427 | }
|
---|
| 2428 |
|
---|
[292] | 2429 | return ('OK','OK');
|
---|
[18] | 2430 | } # end addGroup()
|
---|
| 2431 |
|
---|
| 2432 |
|
---|
[22] | 2433 | ## DNSDB::delGroup()
|
---|
| 2434 | # Delete a group.
|
---|
| 2435 | # Takes a group ID
|
---|
| 2436 | # Returns a status code and message
|
---|
| 2437 | sub delGroup {
|
---|
[476] | 2438 | my $self = shift;
|
---|
| 2439 | my $dbh = $self->{dbh};
|
---|
[22] | 2440 | my $groupid = shift;
|
---|
| 2441 |
|
---|
| 2442 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2443 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2444 | local $dbh->{AutoCommit} = 0;
|
---|
| 2445 | local $dbh->{RaiseError} = 1;
|
---|
| 2446 |
|
---|
| 2447 | ##fixme: locate "knowable" error conditions and deal with them before the eval
|
---|
[23] | 2448 | # ... or inside, whatever.
|
---|
[22] | 2449 | # -> domains still exist in group
|
---|
| 2450 | # -> ...
|
---|
[23] | 2451 | my $failmsg = '';
|
---|
[293] | 2452 | my $resultmsg = '';
|
---|
[22] | 2453 |
|
---|
[293] | 2454 | # collect some pieces for logging and error messages
|
---|
[473] | 2455 | my $groupname = $self->groupName($groupid);
|
---|
| 2456 | my $parid = $self->parentID(id => $groupid, type => 'group');
|
---|
[293] | 2457 |
|
---|
[22] | 2458 | # Wrap all the SQL in a transaction
|
---|
| 2459 | eval {
|
---|
[293] | 2460 | # Check for Things in the group
|
---|
| 2461 | $failmsg = "Can't remove group $groupname";
|
---|
| 2462 | my ($grpcnt) = $dbh->selectrow_array("SELECT count(*) FROM groups WHERE parent_group_id=?", undef, ($groupid));
|
---|
| 2463 | die "$grpcnt groups still in group\n" if $grpcnt;
|
---|
| 2464 | my ($domcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($groupid));
|
---|
[23] | 2465 | die "$domcnt domains still in group\n" if $domcnt;
|
---|
[293] | 2466 | my ($usercnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($groupid));
|
---|
| 2467 | die "$usercnt users still in group\n" if $usercnt;
|
---|
[23] | 2468 |
|
---|
[293] | 2469 | $failmsg = "Failed to delete default records for $groupname";
|
---|
| 2470 | $dbh->do("DELETE from default_records WHERE group_id=?", undef, ($groupid));
|
---|
| 2471 | $failmsg = "Failed to delete default reverse records for $groupname";
|
---|
| 2472 | $dbh->do("DELETE from default_rev_records WHERE group_id=?", undef, ($groupid));
|
---|
| 2473 | $failmsg = "Failed to remove group $groupname";
|
---|
| 2474 | $dbh->do("DELETE from groups WHERE group_id=?", undef, ($groupid));
|
---|
[22] | 2475 |
|
---|
[293] | 2476 | _log($dbh, (group_id => $parid, entry => "Deleted group $groupname"));
|
---|
| 2477 | $resultmsg = "Deleted group $groupname";
|
---|
| 2478 |
|
---|
[22] | 2479 | # once we get here, we should have suceeded.
|
---|
| 2480 | $dbh->commit;
|
---|
| 2481 | }; # end eval
|
---|
| 2482 |
|
---|
| 2483 | if ($@) {
|
---|
| 2484 | my $msg = $@;
|
---|
| 2485 | eval { $dbh->rollback; };
|
---|
[293] | 2486 | if ($config{log_failures}) {
|
---|
| 2487 | _log($dbh, (group_id => $parid, entry => "$failmsg: $msg"));
|
---|
| 2488 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2489 | }
|
---|
[23] | 2490 | return ('FAIL',"$failmsg: $msg");
|
---|
[22] | 2491 | }
|
---|
[293] | 2492 |
|
---|
| 2493 | return ('OK',$resultmsg);
|
---|
[22] | 2494 | } # end delGroup()
|
---|
| 2495 |
|
---|
| 2496 |
|
---|
[19] | 2497 | ## DNSDB::getChildren()
|
---|
| 2498 | # Get a list of all groups whose parent^n is group <n>
|
---|
[24] | 2499 | # Takes a database handle, group ID, reference to an array to put the group IDs in,
|
---|
| 2500 | # and an optional flag to return only immediate children or all children-of-children
|
---|
| 2501 | # default to returning all children
|
---|
[19] | 2502 | # Calls itself
|
---|
| 2503 | sub getChildren {
|
---|
| 2504 | $errstr = '';
|
---|
[476] | 2505 | my $self = shift;
|
---|
| 2506 | my $dbh = $self->{dbh};
|
---|
[20] | 2507 | my $rootgroup = shift;
|
---|
| 2508 | my $groupdest = shift;
|
---|
[24] | 2509 | my $immed = shift || 'all';
|
---|
[19] | 2510 |
|
---|
| 2511 | # special break for default group; otherwise we get stuck.
|
---|
[20] | 2512 | if ($rootgroup == 1) {
|
---|
[19] | 2513 | # by definition, group 1 is the Root Of All Groups
|
---|
[24] | 2514 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
|
---|
[331] | 2515 | ($immed ne 'all' ? " AND parent_group_id=1" : '')." ORDER BY group_name");
|
---|
[19] | 2516 | $sth->execute;
|
---|
| 2517 | while (my @this = $sth->fetchrow_array) {
|
---|
[20] | 2518 | push @$groupdest, @this;
|
---|
[19] | 2519 | }
|
---|
| 2520 | } else {
|
---|
[331] | 2521 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=? ORDER BY group_name");
|
---|
[20] | 2522 | $sth->execute($rootgroup);
|
---|
[19] | 2523 | return if $sth->rows == 0;
|
---|
[20] | 2524 | my @grouplist;
|
---|
| 2525 | while (my ($group) = $sth->fetchrow_array) {
|
---|
| 2526 | push @$groupdest, $group;
|
---|
[476] | 2527 | $self->getChildren($group, $groupdest) if $immed eq 'all';
|
---|
[19] | 2528 | }
|
---|
| 2529 | }
|
---|
| 2530 | } # end getChildren()
|
---|
| 2531 |
|
---|
| 2532 |
|
---|
[20] | 2533 | ## DNSDB::groupName()
|
---|
[17] | 2534 | # Return the group name based on a group ID
|
---|
| 2535 | # Takes a database handle and the group ID
|
---|
| 2536 | # Returns the group name or undef on failure
|
---|
[20] | 2537 | sub groupName {
|
---|
[13] | 2538 | $errstr = '';
|
---|
[473] | 2539 | my $self = shift;
|
---|
| 2540 | my $dbh = $self->{dbh};
|
---|
[20] | 2541 | my $groupid = shift;
|
---|
| 2542 | my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
|
---|
| 2543 | $sth->execute($groupid);
|
---|
| 2544 | my ($groupname) = $sth->fetchrow_array();
|
---|
| 2545 | $errstr = $DBI::errstr if !$groupname;
|
---|
| 2546 | return $groupname if $groupname;
|
---|
| 2547 | } # end groupName
|
---|
[13] | 2548 |
|
---|
| 2549 |
|
---|
[314] | 2550 | ## DNSDB::getGroupCount()
|
---|
| 2551 | # Get count of subgroups in group or groups
|
---|
| 2552 | # Takes a database handle and hash containing:
|
---|
| 2553 | # - the "current" group
|
---|
| 2554 | # - an array of "acceptable" groups
|
---|
| 2555 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
| 2556 | # Returns an integer count of the resulting group list.
|
---|
| 2557 | sub getGroupCount {
|
---|
[476] | 2558 | my $self = shift;
|
---|
| 2559 | my $dbh = $self->{dbh};
|
---|
[314] | 2560 |
|
---|
| 2561 | my %args = @_;
|
---|
| 2562 |
|
---|
| 2563 | my @filterargs;
|
---|
| 2564 |
|
---|
| 2565 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2566 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2567 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2568 |
|
---|
| 2569 | my $sql = "SELECT count(*) FROM groups ".
|
---|
| 2570 | "WHERE parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2571 | ($args{startwith} ? " AND group_name ~* ?" : '').
|
---|
| 2572 | ($args{filter} ? " AND group_name ~* ?" : '');
|
---|
| 2573 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 2574 | $errstr = $dbh->errstr if !$count;
|
---|
| 2575 | return $count;
|
---|
| 2576 | } # end getGroupCount
|
---|
| 2577 |
|
---|
| 2578 |
|
---|
| 2579 | ## DNSDB::getGroupList()
|
---|
| 2580 | # Get a list of sub^n-groups in the specified group(s)
|
---|
| 2581 | # Takes the same arguments as getGroupCount() above
|
---|
| 2582 | # Returns an arrayref containing hashrefs suitable for feeding straight to HTML::Template
|
---|
| 2583 | sub getGroupList {
|
---|
[476] | 2584 | my $self = shift;
|
---|
| 2585 | my $dbh = $self->{dbh};
|
---|
[314] | 2586 |
|
---|
| 2587 | my %args = @_;
|
---|
| 2588 |
|
---|
| 2589 | my @filterargs;
|
---|
| 2590 |
|
---|
| 2591 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2592 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2593 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2594 |
|
---|
| 2595 | # protection against bad or missing arguments
|
---|
| 2596 | $args{sortorder} = 'ASC' if !$args{sortorder};
|
---|
[397] | 2597 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[314] | 2598 |
|
---|
| 2599 | # munge sortby for columns in database
|
---|
| 2600 | $args{sortby} = 'g.group_name' if $args{sortby} eq 'group';
|
---|
| 2601 | $args{sortby} = 'g2.group_name' if $args{sortby} eq 'parent';
|
---|
| 2602 |
|
---|
[385] | 2603 | my $sql = q(SELECT g.group_id AS groupid, g.group_name AS groupname, g2.group_name AS pgroup
|
---|
[314] | 2604 | FROM groups g
|
---|
| 2605 | INNER JOIN groups g2 ON g2.group_id=g.parent_group_id
|
---|
| 2606 | ).
|
---|
[385] | 2607 | " WHERE g.parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
[314] | 2608 | ($args{startwith} ? " AND g.group_name ~* ?" : '').
|
---|
| 2609 | ($args{filter} ? " AND g.group_name ~* ?" : '').
|
---|
| 2610 | " GROUP BY g.group_id, g.group_name, g2.group_name ".
|
---|
| 2611 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
| 2612 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
| 2613 | my $glist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 2614 | $errstr = $dbh->errstr if !$glist;
|
---|
[385] | 2615 |
|
---|
| 2616 | # LEFT JOINs make the result set balloon beyond sanity just to include counts;
|
---|
| 2617 | # this means there's lots of crunching needed to trim the result set back down.
|
---|
| 2618 | # So instead we track the order of the groups, and push the counts into the
|
---|
| 2619 | # arrayref result separately.
|
---|
| 2620 | ##fixme: put this whole sub in a transaction? might be
|
---|
| 2621 | # needed for accurate results on very busy systems.
|
---|
[386] | 2622 | ##fixme: large group lists need prepared statements?
|
---|
| 2623 | #my $ucsth = $dbh->prepare("SELECT count(*) FROM users WHERE group_id=?");
|
---|
| 2624 | #my $dcsth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
|
---|
| 2625 | #my $rcsth = $dbh->prepare("SELECT count(*) FROM revzones WHERE group_id=?");
|
---|
[385] | 2626 | foreach (@{$glist}) {
|
---|
[386] | 2627 | my ($ucnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 2628 | $$_{nusers} = $ucnt;
|
---|
| 2629 | my ($dcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 2630 | $$_{ndomains} = $dcnt;
|
---|
| 2631 | my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 2632 | $$_{nrevzones} = $rcnt;
|
---|
[385] | 2633 | }
|
---|
| 2634 |
|
---|
[314] | 2635 | return $glist;
|
---|
| 2636 | } # end getGroupList
|
---|
| 2637 |
|
---|
| 2638 |
|
---|
[118] | 2639 | ## DNSDB::groupID()
|
---|
| 2640 | # Return the group ID based on the group name
|
---|
| 2641 | # Takes a database handle and the group name
|
---|
| 2642 | # Returns the group ID or undef on failure
|
---|
| 2643 | sub groupID {
|
---|
| 2644 | $errstr = '';
|
---|
[473] | 2645 | my $self = shift;
|
---|
| 2646 | my $dbh = $self->{dbh};
|
---|
[118] | 2647 | my $group = shift;
|
---|
[406] | 2648 | my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($group) );
|
---|
[118] | 2649 | $errstr = $DBI::errstr if !$grpid;
|
---|
| 2650 | return $grpid if $grpid;
|
---|
| 2651 | } # end groupID()
|
---|
| 2652 |
|
---|
| 2653 |
|
---|
[24] | 2654 | ## DNSDB::addUser()
|
---|
[87] | 2655 | # Add a user.
|
---|
| 2656 | # Takes a DB handle, username, group ID, password, state (active/inactive).
|
---|
| 2657 | # Optionally accepts:
|
---|
| 2658 | # user type (user/admin) - defaults to user
|
---|
| 2659 | # permissions string - defaults to inherit from group
|
---|
| 2660 | # three valid forms:
|
---|
| 2661 | # i - Inherit permissions
|
---|
| 2662 | # c:<user_id> - Clone permissions from <user_id>
|
---|
| 2663 | # C:<permission list> - Set these specific permissions
|
---|
| 2664 | # first name - defaults to username
|
---|
| 2665 | # last name - defaults to blank
|
---|
| 2666 | # phone - defaults to blank (could put other data within column def)
|
---|
[90] | 2667 | # Returns (OK,<uid>) on success, (FAIL,<message>) on failure
|
---|
[24] | 2668 | sub addUser {
|
---|
| 2669 | $errstr = '';
|
---|
[479] | 2670 | my $self = shift;
|
---|
| 2671 | my $dbh = $self->{dbh};
|
---|
[24] | 2672 | my $username = shift;
|
---|
| 2673 | my $group = shift;
|
---|
| 2674 | my $pass = shift;
|
---|
| 2675 | my $state = shift;
|
---|
[25] | 2676 |
|
---|
[90] | 2677 | return ('FAIL', "Missing one or more required entries") if !defined($state);
|
---|
| 2678 | return ('FAIL', "Username must not be blank") if !$username;
|
---|
[87] | 2679 |
|
---|
[408] | 2680 | # Munge in some alternate state values
|
---|
| 2681 | $state = 1 if $state =~ /^active$/;
|
---|
| 2682 | $state = 1 if $state =~ /^on$/;
|
---|
| 2683 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 2684 | $state = 0 if $state =~ /^off$/;
|
---|
| 2685 |
|
---|
[25] | 2686 | my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
|
---|
| 2687 |
|
---|
[67] | 2688 | my $permstring = shift || 'i'; # default is to inhert permissions from group
|
---|
| 2689 |
|
---|
[25] | 2690 | my $fname = shift || $username;
|
---|
[24] | 2691 | my $lname = shift || '';
|
---|
[25] | 2692 | my $phone = shift || ''; # not going format-check
|
---|
[24] | 2693 |
|
---|
[38] | 2694 | my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
|
---|
[24] | 2695 | my $user_id;
|
---|
| 2696 |
|
---|
[38] | 2697 | # quick check to start to see if we've already got one
|
---|
| 2698 | $sth->execute($username);
|
---|
| 2699 | ($user_id) = $sth->fetchrow_array;
|
---|
| 2700 |
|
---|
| 2701 | return ('FAIL', "User already exists") if $user_id;
|
---|
| 2702 |
|
---|
[24] | 2703 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2704 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2705 | local $dbh->{AutoCommit} = 0;
|
---|
| 2706 | local $dbh->{RaiseError} = 1;
|
---|
| 2707 |
|
---|
| 2708 | # Wrap all the SQL in a transaction
|
---|
| 2709 | eval {
|
---|
[87] | 2710 | # insert the user... note we set inherited perms by default since
|
---|
| 2711 | # it's simple and cleans up some other bits of state
|
---|
| 2712 | my $sth = $dbh->prepare("INSERT INTO users ".
|
---|
| 2713 | "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
|
---|
| 2714 | "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
|
---|
| 2715 | $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);
|
---|
[24] | 2716 |
|
---|
| 2717 | # get the ID...
|
---|
[94] | 2718 | ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");
|
---|
[24] | 2719 |
|
---|
[87] | 2720 | # Permissions! Gotta set'em all!
|
---|
[401] | 2721 | die "Invalid permission string $permstring\n"
|
---|
[87] | 2722 | if $permstring !~ /^(?:
|
---|
| 2723 | i # inherit
|
---|
| 2724 | |c:\d+ # clone
|
---|
| 2725 | # custom. no, the leading , is not a typo
|
---|
[391] | 2726 | |C:(?:,(?:group|user|domain|record|location|self)_(?:edit|create|delete|locchg|view))*
|
---|
[87] | 2727 | )$/x;
|
---|
| 2728 | # bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
|
---|
| 2729 | if ($permstring ne 'i') {
|
---|
| 2730 | # for cloned or custom permissions, we have to create a new permissions entry.
|
---|
| 2731 | my $clonesrc = $group;
|
---|
| 2732 | if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
|
---|
| 2733 | $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
|
---|
| 2734 | "SELECT $permlist,? FROM permissions WHERE permission_id=".
|
---|
| 2735 | "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
|
---|
| 2736 | undef, ($user_id,$clonesrc) );
|
---|
| 2737 | $dbh->do("UPDATE users SET permission_id=".
|
---|
| 2738 | "(SELECT permission_id FROM permissions WHERE user_id=?) ".
|
---|
| 2739 | "WHERE user_id=?", undef, ($user_id, $user_id) );
|
---|
| 2740 | }
|
---|
| 2741 | if ($permstring =~ /^C:/) {
|
---|
| 2742 | # finally for custom permissions, we set the passed-in permissions (and unset
|
---|
| 2743 | # any that might have been brought in by the clone operation above)
|
---|
| 2744 | my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
|
---|
| 2745 | undef, ($user_id) );
|
---|
| 2746 | foreach (@permtypes) {
|
---|
| 2747 | if ($permstring =~ /,$_/) {
|
---|
| 2748 | $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
|
---|
| 2749 | } else {
|
---|
| 2750 | $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
|
---|
| 2751 | }
|
---|
| 2752 | }
|
---|
| 2753 | }
|
---|
| 2754 |
|
---|
| 2755 | $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
|
---|
| 2756 |
|
---|
[25] | 2757 | ##fixme: add another table to hold name/email for log table?
|
---|
| 2758 |
|
---|
[294] | 2759 | _log($dbh, (group_id => $group, entry => "Added user $username ($fname $lname)"));
|
---|
[24] | 2760 | # once we get here, we should have suceeded.
|
---|
| 2761 | $dbh->commit;
|
---|
| 2762 | }; # end eval
|
---|
| 2763 |
|
---|
| 2764 | if ($@) {
|
---|
| 2765 | my $msg = $@;
|
---|
| 2766 | eval { $dbh->rollback; };
|
---|
[294] | 2767 | if ($config{log_failures}) {
|
---|
| 2768 | _log($dbh, (group_id => $group, entry => "Error adding user $username: $msg"));
|
---|
| 2769 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2770 | }
|
---|
| 2771 | return ('FAIL',"Error adding user $username: $msg");
|
---|
[24] | 2772 | }
|
---|
[294] | 2773 |
|
---|
| 2774 | return ('OK',"User $username ($fname $lname) added");
|
---|
[24] | 2775 | } # end addUser
|
---|
| 2776 |
|
---|
| 2777 |
|
---|
[325] | 2778 | ## DNSDB::getUserCount()
|
---|
| 2779 | # Get count of users in group
|
---|
| 2780 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
| 2781 | # - a reference list of secondary groups
|
---|
| 2782 | # - a filter string
|
---|
| 2783 | # - a "Starts with" string
|
---|
| 2784 | sub getUserCount {
|
---|
[479] | 2785 | my $self = shift;
|
---|
| 2786 | my $dbh = $self->{dbh};
|
---|
[325] | 2787 |
|
---|
| 2788 | my %args = @_;
|
---|
| 2789 |
|
---|
| 2790 | my @filterargs;
|
---|
| 2791 |
|
---|
| 2792 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2793 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2794 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2795 |
|
---|
| 2796 |
|
---|
| 2797 | my $sql = "SELECT count(*) FROM users ".
|
---|
| 2798 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2799 | ($args{startwith} ? " AND username ~* ?" : '').
|
---|
| 2800 | ($args{filter} ? " AND username ~* ?" : '');
|
---|
| 2801 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 2802 | $errstr = $dbh->errstr if !$count;
|
---|
| 2803 | return $count;
|
---|
| 2804 | } # end getUserCount()
|
---|
| 2805 |
|
---|
| 2806 |
|
---|
| 2807 | ## DNSDB::getUserList()
|
---|
| 2808 | # Get list of users
|
---|
| 2809 | # Takes the same arguments as getUserCount() above, plus optional:
|
---|
| 2810 | # - sort field
|
---|
| 2811 | # - sort order
|
---|
| 2812 | # - offset/return-all-everything flag (defaults to $perpage records)
|
---|
| 2813 | sub getUserList {
|
---|
[479] | 2814 | my $self = shift;
|
---|
| 2815 | my $dbh = $self->{dbh};
|
---|
[325] | 2816 |
|
---|
| 2817 | my %args = @_;
|
---|
| 2818 |
|
---|
| 2819 | my @filterargs;
|
---|
| 2820 |
|
---|
| 2821 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2822 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2823 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2824 |
|
---|
| 2825 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
| 2826 | my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
| 2827 | fname => 'fname');
|
---|
| 2828 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 2829 |
|
---|
| 2830 | # protection against bad or missing arguments
|
---|
| 2831 | $args{sortorder} = 'ASC' if !$args{sortorder};
|
---|
| 2832 | $args{sortby} = 'u.username' if !$args{sortby};
|
---|
[397] | 2833 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[325] | 2834 |
|
---|
| 2835 | my $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ".
|
---|
| 2836 | "FROM users u ".
|
---|
| 2837 | "INNER JOIN groups g ON u.group_id=g.group_id ".
|
---|
| 2838 | "WHERE u.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2839 | ($args{startwith} ? " AND u.username ~* ?" : '').
|
---|
| 2840 | ($args{filter} ? " AND u.username ~* ?" : '').
|
---|
[401] | 2841 | " AND NOT u.type = 'R' ".
|
---|
[325] | 2842 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
| 2843 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
| 2844 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 2845 | $errstr = $dbh->errstr if !$ulist;
|
---|
| 2846 | return $ulist;
|
---|
| 2847 | } # end getUserList()
|
---|
| 2848 |
|
---|
| 2849 |
|
---|
[326] | 2850 | ## DNSDB::getUserDropdown()
|
---|
| 2851 | # Get a list of usernames for use in a dropdown menu.
|
---|
| 2852 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
| 2853 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
| 2854 | sub getUserDropdown {
|
---|
[479] | 2855 | my $self = shift;
|
---|
| 2856 | my $dbh = $self->{dbh};
|
---|
[326] | 2857 | my $grp = shift;
|
---|
| 2858 | my $sel = shift || 0;
|
---|
| 2859 |
|
---|
| 2860 | my $sth = $dbh->prepare("SELECT username,user_id FROM users WHERE group_id=?");
|
---|
| 2861 | $sth->execute($grp);
|
---|
| 2862 |
|
---|
| 2863 | my @userlist;
|
---|
| 2864 | while (my ($username,$uid) = $sth->fetchrow_array) {
|
---|
| 2865 | my %row = (
|
---|
| 2866 | username => $username,
|
---|
| 2867 | uid => $uid,
|
---|
| 2868 | selected => ($sel == $uid ? 1 : 0)
|
---|
| 2869 | );
|
---|
| 2870 | push @userlist, \%row;
|
---|
| 2871 | }
|
---|
| 2872 | return \@userlist;
|
---|
| 2873 | } # end getUserDropdown()
|
---|
| 2874 |
|
---|
| 2875 |
|
---|
[83] | 2876 | ## DNSDB:: updateUser()
|
---|
[90] | 2877 | # Update general data about user
|
---|
[83] | 2878 | sub updateUser {
|
---|
[479] | 2879 | my $self = shift;
|
---|
| 2880 | my $dbh = $self->{dbh};
|
---|
[118] | 2881 |
|
---|
| 2882 | ##fixme: tweak calling convention so that we can update any given bit of data
|
---|
[83] | 2883 | my $uid = shift;
|
---|
| 2884 | my $username = shift;
|
---|
| 2885 | my $group = shift;
|
---|
| 2886 | my $pass = shift;
|
---|
| 2887 | my $state = shift;
|
---|
[87] | 2888 | my $type = shift || 'u';
|
---|
[83] | 2889 | my $fname = shift || $username;
|
---|
| 2890 | my $lname = shift || '';
|
---|
| 2891 | my $phone = shift || ''; # not going format-check
|
---|
| 2892 |
|
---|
[294] | 2893 | my $resultmsg = '';
|
---|
[83] | 2894 |
|
---|
[411] | 2895 | # Munge in some alternate state values
|
---|
| 2896 | $state = 1 if $state =~ /^active$/;
|
---|
| 2897 | $state = 1 if $state =~ /^on$/;
|
---|
| 2898 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 2899 | $state = 0 if $state =~ /^off$/;
|
---|
| 2900 |
|
---|
[83] | 2901 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2902 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2903 | local $dbh->{AutoCommit} = 0;
|
---|
| 2904 | local $dbh->{RaiseError} = 1;
|
---|
| 2905 |
|
---|
| 2906 | my $sth;
|
---|
| 2907 |
|
---|
| 2908 | # Password can be left blank; if so we assume there's one on file.
|
---|
| 2909 | # Actual blank passwords are bad, mm'kay?
|
---|
| 2910 | if (!$pass) {
|
---|
[294] | 2911 | ($pass) = $dbh->selectrow_array("SELECT password FROM users WHERE user_id=?", undef, ($uid));
|
---|
[83] | 2912 | } else {
|
---|
| 2913 | $pass = unix_md5_crypt($pass);
|
---|
| 2914 | }
|
---|
| 2915 |
|
---|
| 2916 | eval {
|
---|
[294] | 2917 | $dbh->do("UPDATE users SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?".
|
---|
| 2918 | " WHERE user_id=?", undef, ($username, $pass, $fname, $lname, $phone, $type, $state, $uid));
|
---|
| 2919 | $resultmsg = "Updated user info for $username ($fname $lname)";
|
---|
| 2920 | _log($dbh, group_id => $group, entry => $resultmsg);
|
---|
[83] | 2921 | $dbh->commit;
|
---|
| 2922 | };
|
---|
| 2923 | if ($@) {
|
---|
| 2924 | my $msg = $@;
|
---|
| 2925 | eval { $dbh->rollback; };
|
---|
[294] | 2926 | if ($config{log_failures}) {
|
---|
| 2927 | _log($dbh, (group_id => $group, entry => "Error updating user $username: $msg"));
|
---|
| 2928 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2929 | }
|
---|
| 2930 | return ('FAIL',"Error updating user $username: $msg");
|
---|
[83] | 2931 | }
|
---|
[294] | 2932 |
|
---|
| 2933 | return ('OK',$resultmsg);
|
---|
[83] | 2934 | } # end updateUser()
|
---|
| 2935 |
|
---|
| 2936 |
|
---|
[24] | 2937 | ## DNSDB::delUser()
|
---|
[297] | 2938 | # Delete a user.
|
---|
| 2939 | # Takes a database handle and user ID
|
---|
| 2940 | # Returns a success/failure code and matching message
|
---|
[24] | 2941 | sub delUser {
|
---|
[479] | 2942 | my $self = shift;
|
---|
| 2943 | my $dbh = $self->{dbh};
|
---|
[25] | 2944 | my $userid = shift;
|
---|
| 2945 |
|
---|
[297] | 2946 | return ('FAIL',"Bad userid") if !defined($userid);
|
---|
[25] | 2947 |
|
---|
[479] | 2948 | my $userdata = $self->getUserData($userid);
|
---|
[25] | 2949 |
|
---|
[297] | 2950 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2951 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2952 | local $dbh->{AutoCommit} = 0;
|
---|
| 2953 | local $dbh->{RaiseError} = 1;
|
---|
[25] | 2954 |
|
---|
[297] | 2955 | eval {
|
---|
| 2956 | $dbh->do("DELETE FROM users WHERE user_id=?", undef, ($userid));
|
---|
| 2957 | _log($dbh, (group_id => $userdata->{group_id},
|
---|
| 2958 | entry => "Deleted user ID $userid/".$userdata->{username}.
|
---|
| 2959 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")") );
|
---|
| 2960 | $dbh->commit;
|
---|
| 2961 | };
|
---|
| 2962 | if ($@) {
|
---|
| 2963 | my $msg = $@;
|
---|
| 2964 | eval { $dbh->rollback; };
|
---|
| 2965 | if ($config{log_failures}) {
|
---|
| 2966 | _log($dbh, (group_id => $userdata->{group_id}, entry => "Error deleting user ID ".
|
---|
| 2967 | "$userid/".$userdata->{username}.": $msg") );
|
---|
| 2968 | $dbh->commit;
|
---|
| 2969 | }
|
---|
| 2970 | return ('FAIL',"Error deleting user $userid/".$userdata->{username}.": $msg");
|
---|
| 2971 | }
|
---|
| 2972 |
|
---|
| 2973 | return ('OK',"Deleted user ".$userdata->{username}." (".$userdata->{firstname}." ".$userdata->{lastname}.")");
|
---|
[24] | 2974 | } # end delUser
|
---|
| 2975 |
|
---|
| 2976 |
|
---|
[25] | 2977 | ## DNSDB::userFullName()
|
---|
| 2978 | # Return a pretty string!
|
---|
| 2979 | # Takes a user_id and optional printf-ish string to indicate which pieces where:
|
---|
| 2980 | # %u for the username
|
---|
| 2981 | # %f for the first name
|
---|
| 2982 | # %l for the last name
|
---|
| 2983 | # All other text in the passed string will be left as-is.
|
---|
| 2984 | ##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
|
---|
| 2985 | sub userFullName {
|
---|
| 2986 | $errstr = '';
|
---|
[473] | 2987 | my $self = shift;
|
---|
| 2988 | my $dbh = $self->{dbh};
|
---|
[25] | 2989 | my $userid = shift;
|
---|
| 2990 | my $fullformat = shift || '%f %l (%u)';
|
---|
| 2991 | my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
|
---|
| 2992 | $sth->execute($userid);
|
---|
| 2993 | my ($uname,$fname,$lname) = $sth->fetchrow_array();
|
---|
| 2994 | $errstr = $DBI::errstr if !$uname;
|
---|
| 2995 |
|
---|
| 2996 | $fullformat =~ s/\%u/$uname/g;
|
---|
| 2997 | $fullformat =~ s/\%f/$fname/g;
|
---|
| 2998 | $fullformat =~ s/\%l/$lname/g;
|
---|
| 2999 |
|
---|
| 3000 | return $fullformat;
|
---|
| 3001 | } # end userFullName
|
---|
| 3002 |
|
---|
| 3003 |
|
---|
[51] | 3004 | ## DNSDB::userStatus()
|
---|
| 3005 | # Sets and/or returns a user's status
|
---|
| 3006 | # Takes a database handle, user ID and optionally a status argument
|
---|
| 3007 | # Returns undef on errors.
|
---|
| 3008 | sub userStatus {
|
---|
[479] | 3009 | my $self = shift;
|
---|
| 3010 | my $dbh = $self->{dbh};
|
---|
[51] | 3011 | my $id = shift;
|
---|
[296] | 3012 | my $newstatus = shift || 'mu';
|
---|
[51] | 3013 |
|
---|
| 3014 | return undef if $id !~ /^\d+$/;
|
---|
| 3015 |
|
---|
[479] | 3016 | my $userdata = $self->getUserData($id);
|
---|
[51] | 3017 |
|
---|
[296] | 3018 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3019 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3020 | local $dbh->{AutoCommit} = 0;
|
---|
| 3021 | local $dbh->{RaiseError} = 1;
|
---|
| 3022 |
|
---|
| 3023 | if ($newstatus ne 'mu') {
|
---|
| 3024 | # ooo, fun! let's see what we were passed for status
|
---|
| 3025 | eval {
|
---|
| 3026 | $newstatus = 0 if $newstatus eq 'useroff';
|
---|
| 3027 | $newstatus = 1 if $newstatus eq 'useron';
|
---|
| 3028 | $dbh->do("UPDATE users SET status=? WHERE user_id=?", undef, ($newstatus, $id));
|
---|
| 3029 |
|
---|
[297] | 3030 | $resultstr = ($newstatus ? 'Enabled' : 'Disabled')." user ".$userdata->{username}.
|
---|
| 3031 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")";
|
---|
[296] | 3032 |
|
---|
| 3033 | my %loghash;
|
---|
[473] | 3034 | $loghash{group_id} = $self->parentID(id => $id, type => 'user');
|
---|
[296] | 3035 | $loghash{entry} = $resultstr;
|
---|
| 3036 | _log($dbh, %loghash);
|
---|
| 3037 |
|
---|
| 3038 | $dbh->commit;
|
---|
| 3039 | };
|
---|
| 3040 | if ($@) {
|
---|
| 3041 | my $msg = $@;
|
---|
| 3042 | eval { $dbh->rollback; };
|
---|
| 3043 | $resultstr = '';
|
---|
| 3044 | $errstr = $msg;
|
---|
| 3045 | ##fixme: failure logging?
|
---|
| 3046 | return;
|
---|
[51] | 3047 | }
|
---|
| 3048 | }
|
---|
| 3049 |
|
---|
[296] | 3050 | my ($status) = $dbh->selectrow_array("SELECT status FROM users WHERE user_id=?", undef, ($id));
|
---|
[51] | 3051 | return $status;
|
---|
| 3052 | } # end userStatus()
|
---|
| 3053 |
|
---|
| 3054 |
|
---|
[83] | 3055 | ## DNSDB::getUserData()
|
---|
| 3056 | # Get misc user data for display
|
---|
| 3057 | sub getUserData {
|
---|
[479] | 3058 | my $self = shift;
|
---|
| 3059 | my $dbh = $self->{dbh};
|
---|
[83] | 3060 | my $uid = shift;
|
---|
| 3061 |
|
---|
| 3062 | my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
|
---|
| 3063 | "FROM users WHERE user_id=?");
|
---|
| 3064 | $sth->execute($uid);
|
---|
| 3065 | return $sth->fetchrow_hashref();
|
---|
| 3066 | } # end getUserData()
|
---|
| 3067 |
|
---|
| 3068 |
|
---|
[370] | 3069 | ## DNSDB::addLoc()
|
---|
[375] | 3070 | # Add a new location.
|
---|
| 3071 | # Takes a database handle, group ID, short and long description, and a comma-separated
|
---|
| 3072 | # list of IP addresses.
|
---|
| 3073 | # Returns ('OK',<location>) on success, ('FAIL',<failmsg>) on failure
|
---|
| 3074 | sub addLoc {
|
---|
[480] | 3075 | my $self = shift;
|
---|
| 3076 | my $dbh = $self->{dbh};
|
---|
[375] | 3077 | my $grp = shift;
|
---|
| 3078 | my $shdesc = shift;
|
---|
| 3079 | my $comments = shift;
|
---|
| 3080 | my $iplist = shift;
|
---|
[370] | 3081 |
|
---|
[375] | 3082 | # $shdesc gets set to the generated location ID if possible, but these can be de-undefined here.
|
---|
| 3083 | $comments = '' if !$comments;
|
---|
| 3084 | $iplist = '' if !$iplist;
|
---|
| 3085 |
|
---|
| 3086 | my $loc;
|
---|
| 3087 |
|
---|
| 3088 | # Generate a location ID. This is, by spec, a two-character widget. We'll use [a-z][a-z]
|
---|
| 3089 | # for now; 676 locations should satisfy all but the largest of the huge networks.
|
---|
| 3090 | # Not sure whether these are case-sensitive, or what other rules might apply - in any case
|
---|
| 3091 | # the absolute maximum is 16K (256*256) since it's parsed by tinydns as a two-character field.
|
---|
| 3092 |
|
---|
| 3093 | # add just after "my $origloc = $loc;":
|
---|
| 3094 | # # These expand the possible space from 26^2 to 52^2 [* note in testing only 2052 were achieved],
|
---|
| 3095 | # # and wrap it around.
|
---|
| 3096 | # # Yes, they skip a couple of possibles. No, I don't care.
|
---|
| 3097 | # $loc = 'aA' if $loc eq 'zz';
|
---|
| 3098 | # $loc = 'Aa' if $loc eq 'zZ';
|
---|
| 3099 | # $loc = 'ZA' if $loc eq 'Zz';
|
---|
| 3100 | # $loc = 'aa' if $loc eq 'ZZ';
|
---|
| 3101 |
|
---|
| 3102 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3103 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3104 | local $dbh->{AutoCommit} = 0;
|
---|
| 3105 | local $dbh->{RaiseError} = 1;
|
---|
| 3106 |
|
---|
| 3107 | ##fixme: There is probably a far better way to do this. Sequential increments
|
---|
| 3108 | # are marginally less stupid that pure random generation though, and the existence
|
---|
| 3109 | # check makes sure we don't stomp on an imported one.
|
---|
| 3110 |
|
---|
| 3111 | eval {
|
---|
| 3112 | # Get the "last" location. Note this is the only use for loc_id, because selecting on location Does Funky Things
|
---|
| 3113 | ($loc) = $dbh->selectrow_array("SELECT location FROM locations ORDER BY loc_id DESC LIMIT 1");
|
---|
[478] | 3114 | ($loc) = ($loc =~ /^(..)/) if $loc;
|
---|
[375] | 3115 | my $origloc = $loc;
|
---|
[446] | 3116 | $loc = 'aa' if !$loc;
|
---|
[375] | 3117 | # Make a change...
|
---|
| 3118 | $loc++;
|
---|
| 3119 | # ... and keep changing if it exists
|
---|
| 3120 | while ($dbh->selectrow_array("SELECT count(*) FROM locations WHERE location LIKE ?", undef, ($loc.'%'))) {
|
---|
| 3121 | $loc++;
|
---|
| 3122 | ($loc) = ($loc =~ /^(..)/);
|
---|
| 3123 | die "too many locations in use, can't add another one\n" if $loc eq $origloc;
|
---|
| 3124 | ##fixme: really need to handle this case faster somehow
|
---|
| 3125 | #if $loc eq $origloc die "<thwap> bad admin: all locations used, your network is too fragmented";
|
---|
| 3126 | }
|
---|
| 3127 | # And now we should have a unique location. tinydns fundamentally limits the
|
---|
| 3128 | # number of these but there's no doc on what characters are valid.
|
---|
| 3129 | $shdesc = $loc if !$shdesc;
|
---|
| 3130 | $dbh->do("INSERT INTO locations (location, group_id, iplist, description, comments) VALUES (?,?,?,?,?)",
|
---|
| 3131 | undef, ($loc, $grp, $iplist, $shdesc, $comments) );
|
---|
[377] | 3132 | _log($dbh, entry => "Added location ($shdesc, '$iplist')");
|
---|
| 3133 | $dbh->commit;
|
---|
[375] | 3134 | };
|
---|
| 3135 | if ($@) {
|
---|
| 3136 | my $msg = $@;
|
---|
| 3137 | eval { $dbh->rollback; };
|
---|
| 3138 | if ($config{log_failures}) {
|
---|
| 3139 | $shdesc = $loc if !$shdesc;
|
---|
| 3140 | _log($dbh, (entry => "Failed adding location ($shdesc, '$iplist'): $msg"));
|
---|
| 3141 | $dbh->commit;
|
---|
| 3142 | }
|
---|
| 3143 | return ('FAIL',$msg);
|
---|
| 3144 | }
|
---|
| 3145 |
|
---|
| 3146 | return ('OK',$loc);
|
---|
[377] | 3147 | } # end addLoc()
|
---|
[375] | 3148 |
|
---|
| 3149 |
|
---|
[370] | 3150 | ## DNSDB::updateLoc()
|
---|
[428] | 3151 | # Update details of a location.
|
---|
| 3152 | # Takes a database handle, location ID, group ID, short description,
|
---|
| 3153 | # long comments/notes, and comma/space-separated IP list
|
---|
| 3154 | # Returns a result code and message
|
---|
[377] | 3155 | sub updateLoc {
|
---|
[480] | 3156 | my $self = shift;
|
---|
| 3157 | my $dbh = $self->{dbh};
|
---|
[377] | 3158 | my $loc = shift;
|
---|
| 3159 | my $grp = shift;
|
---|
| 3160 | my $shdesc = shift;
|
---|
| 3161 | my $comments = shift;
|
---|
| 3162 | my $iplist = shift;
|
---|
[370] | 3163 |
|
---|
[377] | 3164 | $shdesc = '' if !$shdesc;
|
---|
| 3165 | $comments = '' if !$comments;
|
---|
| 3166 | $iplist = '' if !$iplist;
|
---|
| 3167 |
|
---|
| 3168 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3169 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3170 | local $dbh->{AutoCommit} = 0;
|
---|
| 3171 | local $dbh->{RaiseError} = 1;
|
---|
| 3172 |
|
---|
[480] | 3173 | my $oldloc = $self->getLoc($loc);
|
---|
[377] | 3174 | my $okmsg = "Updated location (".$oldloc->{description}.", '".$oldloc->{iplist}."') to ($shdesc, '$iplist')";
|
---|
| 3175 |
|
---|
| 3176 | eval {
|
---|
| 3177 | $dbh->do("UPDATE locations SET group_id=?,iplist=?,description=?,comments=? WHERE location=?",
|
---|
| 3178 | undef, ($grp, $iplist, $shdesc, $comments, $loc) );
|
---|
| 3179 | _log($dbh, entry => $okmsg);
|
---|
| 3180 | $dbh->commit;
|
---|
| 3181 | };
|
---|
| 3182 | if ($@) {
|
---|
| 3183 | my $msg = $@;
|
---|
| 3184 | eval { $dbh->rollback; };
|
---|
| 3185 | if ($config{log_failures}) {
|
---|
| 3186 | $shdesc = $loc if !$shdesc;
|
---|
| 3187 | _log($dbh, (entry => "Failed updating location ($shdesc, '$iplist'): $msg"));
|
---|
| 3188 | $dbh->commit;
|
---|
| 3189 | }
|
---|
| 3190 | return ('FAIL',$msg);
|
---|
| 3191 | }
|
---|
| 3192 |
|
---|
| 3193 | return ('OK',$okmsg);
|
---|
| 3194 | } # end updateLoc()
|
---|
| 3195 |
|
---|
| 3196 |
|
---|
[370] | 3197 | ## DNSDB::delLoc()
|
---|
[428] | 3198 | sub delLoc {
|
---|
[480] | 3199 | my $self = shift;
|
---|
| 3200 | my $dbh = $self->{dbh};
|
---|
[428] | 3201 | my $loc = shift;
|
---|
[370] | 3202 |
|
---|
[428] | 3203 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3204 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3205 | local $dbh->{AutoCommit} = 0;
|
---|
| 3206 | local $dbh->{RaiseError} = 1;
|
---|
[370] | 3207 |
|
---|
[480] | 3208 | my $oldloc = $self->getLoc($loc);
|
---|
[428] | 3209 | my $olddesc = ($oldloc->{description} ? $oldloc->{description} : $loc);
|
---|
| 3210 | my $okmsg = "Deleted location ($olddesc, '".$oldloc->{iplist}."')";
|
---|
| 3211 |
|
---|
| 3212 | eval {
|
---|
| 3213 | # Check for records with this location first. Deleting a location without deleting records
|
---|
| 3214 | # tagged for that location will render them unpublished without other warning.
|
---|
| 3215 | my ($r) = $dbh->selectrow_array("SELECT record_id FROM records WHERE location=? LIMIT 1", undef, ($loc) );
|
---|
| 3216 | die "Records still exist in location $olddesc\n" if $r;
|
---|
| 3217 | $dbh->do("DELETE FROM locations WHERE location=?", undef, ($loc) );
|
---|
| 3218 | _log($dbh, entry => $okmsg);
|
---|
| 3219 | $dbh->commit;
|
---|
| 3220 | };
|
---|
| 3221 | if ($@) {
|
---|
| 3222 | my $msg = $@;
|
---|
| 3223 | eval { $dbh->rollback; };
|
---|
| 3224 | if ($config{log_failures}) {
|
---|
| 3225 | _log($dbh, (entry => "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg"));
|
---|
| 3226 | $dbh->commit;
|
---|
| 3227 | }
|
---|
| 3228 | return ('FAIL', "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
|
---|
| 3229 | }
|
---|
| 3230 |
|
---|
| 3231 | return ('OK',$okmsg);
|
---|
| 3232 | } # end delLoc()
|
---|
| 3233 |
|
---|
| 3234 |
|
---|
[375] | 3235 | ## DNSDB::getLoc()
|
---|
[428] | 3236 | # Get details about a location/view
|
---|
| 3237 | # Takes a database handle and location ID.
|
---|
| 3238 | # Returns a reference to a hash containing the group ID, IP list, description, and comments/notes
|
---|
[375] | 3239 | sub getLoc {
|
---|
[480] | 3240 | my $self = shift;
|
---|
| 3241 | my $dbh = $self->{dbh};
|
---|
[375] | 3242 | my $loc = shift;
|
---|
| 3243 |
|
---|
| 3244 | my $sth = $dbh->prepare("SELECT group_id,iplist,description,comments FROM locations WHERE location=?");
|
---|
| 3245 | $sth->execute($loc);
|
---|
| 3246 | return $sth->fetchrow_hashref();
|
---|
| 3247 | } # end getLoc()
|
---|
| 3248 |
|
---|
| 3249 |
|
---|
[370] | 3250 | ## DNSDB::getLocCount()
|
---|
| 3251 | # Get count of locations/views
|
---|
| 3252 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
| 3253 | # - a reference list of secondary groups
|
---|
| 3254 | # - a filter string
|
---|
| 3255 | # - a "Starts with" string
|
---|
| 3256 | sub getLocCount {
|
---|
[480] | 3257 | my $self = shift;
|
---|
| 3258 | my $dbh = $self->{dbh};
|
---|
[370] | 3259 |
|
---|
| 3260 | my %args = @_;
|
---|
| 3261 |
|
---|
| 3262 | my @filterargs;
|
---|
| 3263 |
|
---|
| 3264 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3265 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3266 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3267 |
|
---|
| 3268 |
|
---|
| 3269 | my $sql = "SELECT count(*) FROM locations ".
|
---|
| 3270 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3271 | ($args{startwith} ? " AND description ~* ?" : '').
|
---|
| 3272 | ($args{filter} ? " AND description ~* ?" : '');
|
---|
| 3273 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 3274 | $errstr = $dbh->errstr if !$count;
|
---|
| 3275 | return $count;
|
---|
| 3276 | } # end getLocCount()
|
---|
| 3277 |
|
---|
| 3278 |
|
---|
| 3279 | ## DNSDB::getLocList()
|
---|
| 3280 | sub getLocList {
|
---|
[480] | 3281 | my $self = shift;
|
---|
| 3282 | my $dbh = $self->{dbh};
|
---|
[370] | 3283 |
|
---|
| 3284 | my %args = @_;
|
---|
| 3285 |
|
---|
| 3286 | my @filterargs;
|
---|
| 3287 |
|
---|
| 3288 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3289 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3290 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3291 |
|
---|
| 3292 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
| 3293 | # my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
| 3294 | # fname => 'fname');
|
---|
| 3295 | # $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 3296 |
|
---|
| 3297 | # protection against bad or missing arguments
|
---|
| 3298 | $args{sortorder} = 'ASC' if !$args{sortorder};
|
---|
| 3299 | $args{sortby} = 'l.description' if !$args{sortby};
|
---|
[397] | 3300 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[370] | 3301 |
|
---|
| 3302 | my $sql = "SELECT l.location, l.description, l.iplist, g.group_name ".
|
---|
| 3303 | "FROM locations l ".
|
---|
| 3304 | "INNER JOIN groups g ON l.group_id=g.group_id ".
|
---|
| 3305 | "WHERE l.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3306 | ($args{startwith} ? " AND l.description ~* ?" : '').
|
---|
| 3307 | ($args{filter} ? " AND l.description ~* ?" : '').
|
---|
| 3308 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
| 3309 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
| 3310 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 3311 | $errstr = $dbh->errstr if !$ulist;
|
---|
| 3312 | return $ulist;
|
---|
| 3313 | } # end getLocList()
|
---|
| 3314 |
|
---|
| 3315 |
|
---|
| 3316 | ## DNSDB::getLocDropdown()
|
---|
[383] | 3317 | # Get a list of location names for use in a dropdown menu.
|
---|
| 3318 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
| 3319 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
| 3320 | sub getLocDropdown {
|
---|
[480] | 3321 | my $self = shift;
|
---|
| 3322 | my $dbh = $self->{dbh};
|
---|
[383] | 3323 | my $grp = shift;
|
---|
| 3324 | my $sel = shift || '';
|
---|
[370] | 3325 |
|
---|
[383] | 3326 | my $sth = $dbh->prepare(qq(
|
---|
| 3327 | SELECT description,location FROM locations
|
---|
| 3328 | WHERE group_id=?
|
---|
| 3329 | ORDER BY description
|
---|
| 3330 | ) );
|
---|
| 3331 | $sth->execute($grp);
|
---|
[370] | 3332 |
|
---|
[383] | 3333 | my @loclist;
|
---|
[446] | 3334 | push @loclist, { locname => "(Default/All)", loc => '', selected => ($sel ? 0 : ($sel eq '' ? 1 : 0)) };
|
---|
[383] | 3335 | while (my ($locname, $loc) = $sth->fetchrow_array) {
|
---|
| 3336 | my %row = (
|
---|
| 3337 | locname => $locname,
|
---|
| 3338 | loc => $loc,
|
---|
| 3339 | selected => ($sel eq $loc ? 1 : 0)
|
---|
| 3340 | );
|
---|
| 3341 | push @loclist, \%row;
|
---|
| 3342 | }
|
---|
| 3343 | return \@loclist;
|
---|
| 3344 | } # end getLocDropdown()
|
---|
| 3345 |
|
---|
| 3346 |
|
---|
[2] | 3347 | ## DNSDB::getSOA()
|
---|
| 3348 | # Return all suitable fields from an SOA record in separate elements of a hash
|
---|
[224] | 3349 | # Takes a database handle, default/live flag, domain/reverse flag, and parent ID
|
---|
[2] | 3350 | sub getSOA {
|
---|
| 3351 | $errstr = '';
|
---|
[481] | 3352 | my $self = shift;
|
---|
| 3353 | my $dbh = $self->{dbh};
|
---|
[2] | 3354 | my $def = shift;
|
---|
[224] | 3355 | my $rev = shift;
|
---|
[2] | 3356 | my $id = shift;
|
---|
| 3357 |
|
---|
[224] | 3358 | # (ab)use distance and weight columns to store SOA data? can't for default_rev_records...
|
---|
| 3359 | # - should really attach serial to the zone parent somewhere
|
---|
[101] | 3360 |
|
---|
[224] | 3361 | my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev).
|
---|
| 3362 | " WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}";
|
---|
[311] | 3363 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
| 3364 | return if !$ret;
|
---|
[246] | 3365 | ##fixme: stick a flag somewhere if the record doesn't exist. by the API, this is an impossible case, but...
|
---|
[2] | 3366 |
|
---|
[311] | 3367 | ($ret->{contact},$ret->{prins}) = split /:/, $ret->{host};
|
---|
| 3368 | delete $ret->{host};
|
---|
| 3369 | ($ret->{refresh},$ret->{retry},$ret->{expire},$ret->{minttl}) = split /:/, $ret->{val};
|
---|
| 3370 | delete $ret->{val};
|
---|
[2] | 3371 |
|
---|
[311] | 3372 | return $ret;
|
---|
[2] | 3373 | } # end getSOA()
|
---|
| 3374 |
|
---|
| 3375 |
|
---|
[246] | 3376 | ## DNSDB::updateSOA()
|
---|
| 3377 | # Update the specified SOA record
|
---|
| 3378 | # Takes a database handle, default/live flag, forward/reverse flag, and SOA data hash
|
---|
[277] | 3379 | # Returns a two-element list with a result code and message
|
---|
[246] | 3380 | sub updateSOA {
|
---|
[473] | 3381 | my $self = shift;
|
---|
| 3382 | my $dbh = $self->{dbh};
|
---|
[246] | 3383 | my $defrec = shift;
|
---|
[248] | 3384 | my $revrec = shift;
|
---|
[246] | 3385 |
|
---|
| 3386 | my %soa = @_;
|
---|
| 3387 |
|
---|
[473] | 3388 | my $oldsoa = $self->getSOA($defrec, $revrec, $soa{id});
|
---|
[277] | 3389 |
|
---|
[311] | 3390 | my $msg;
|
---|
| 3391 | my %logdata;
|
---|
| 3392 | if ($defrec eq 'n') {
|
---|
| 3393 | $logdata{domain_id} = $soa{id} if $revrec eq 'n';
|
---|
| 3394 | $logdata{rdns_id} = $soa{id} if $revrec eq 'y';
|
---|
[473] | 3395 | $logdata{group_id} = $self->parentID(id => $soa{id}, revrec => $revrec,
|
---|
| 3396 | type => ($revrec eq 'n' ? 'domain' : 'revzone') );
|
---|
[311] | 3397 | } else {
|
---|
| 3398 | $logdata{group_id} = $soa{id};
|
---|
| 3399 | }
|
---|
[473] | 3400 | my $parname = ($defrec eq 'y' ? $self->groupName($soa{id}) :
|
---|
| 3401 | ($revrec eq 'n' ? $self->domainName($soa{id}) : $self->revName($soa{id})) );
|
---|
[311] | 3402 |
|
---|
[277] | 3403 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3404 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3405 | local $dbh->{AutoCommit} = 0;
|
---|
| 3406 | local $dbh->{RaiseError} = 1;
|
---|
| 3407 |
|
---|
| 3408 | eval {
|
---|
| 3409 | my $sql = "UPDATE "._rectable($defrec, $revrec)." SET host=?, val=?, ttl=? WHERE record_id=? AND type=6";
|
---|
| 3410 | $dbh->do($sql, undef, ("$soa{contact}:$soa{prins}", "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}",
|
---|
[311] | 3411 | $soa{ttl}, $oldsoa->{record_id}) );
|
---|
| 3412 | $msg = "Updated ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse ' : 'default ') : '').
|
---|
| 3413 | "SOA for $parname: ".
|
---|
| 3414 | "(ns $oldsoa->{prins}, contact $oldsoa->{contact}, refresh $oldsoa->{refresh},".
|
---|
| 3415 | " retry $oldsoa->{retry}, expire $oldsoa->{expire}, minTTL $oldsoa->{minttl}, TTL $oldsoa->{ttl}) to ".
|
---|
[277] | 3416 | "(ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
|
---|
| 3417 | " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})";
|
---|
| 3418 |
|
---|
[311] | 3419 | $logdata{entry} = $msg;
|
---|
| 3420 | _log($dbh, %logdata);
|
---|
[277] | 3421 |
|
---|
| 3422 | $dbh->commit;
|
---|
| 3423 | };
|
---|
| 3424 | if ($@) {
|
---|
| 3425 | $msg = $@;
|
---|
| 3426 | eval { $dbh->rollback; };
|
---|
[311] | 3427 | $logdata{entry} = "Error updating ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse zone ' : 'default ') : '').
|
---|
| 3428 | "SOA record for $parname: $msg";
|
---|
| 3429 | if ($config{log_failures}) {
|
---|
| 3430 | _log($dbh, %logdata);
|
---|
| 3431 | $dbh->commit;
|
---|
| 3432 | }
|
---|
| 3433 | return ('FAIL', $logdata{entry});
|
---|
[277] | 3434 | } else {
|
---|
| 3435 | return ('OK', $msg);
|
---|
| 3436 | }
|
---|
[246] | 3437 | } # end updateSOA()
|
---|
| 3438 |
|
---|
| 3439 |
|
---|
[2] | 3440 | ## DNSDB::getRecLine()
|
---|
| 3441 | # Return all data fields for a zone record in separate elements of a hash
|
---|
[243] | 3442 | # Takes a database handle, default/live flag, forward/reverse flag, and record ID
|
---|
[2] | 3443 | sub getRecLine {
|
---|
| 3444 | $errstr = '';
|
---|
[481] | 3445 | my $self = shift;
|
---|
| 3446 | my $dbh = $self->{dbh};
|
---|
[243] | 3447 | my $defrec = shift;
|
---|
| 3448 | my $revrec = shift;
|
---|
[2] | 3449 | my $id = shift;
|
---|
| 3450 |
|
---|
[429] | 3451 | my $sql = "SELECT record_id,host,type,val,ttl".
|
---|
| 3452 | ($defrec eq 'n' ? ',location' : '').
|
---|
| 3453 | ($revrec eq 'n' ? ',distance,weight,port' : '').
|
---|
[243] | 3454 | (($defrec eq 'y') ? ',group_id FROM ' : ',domain_id,rdns_id FROM ').
|
---|
| 3455 | _rectable($defrec,$revrec)." WHERE record_id=?";
|
---|
[123] | 3456 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
[2] | 3457 |
|
---|
[90] | 3458 | if ($dbh->err) {
|
---|
[2] | 3459 | $errstr = $DBI::errstr;
|
---|
| 3460 | return undef;
|
---|
| 3461 | }
|
---|
| 3462 |
|
---|
[123] | 3463 | if (!$ret) {
|
---|
| 3464 | $errstr = "No such record";
|
---|
| 3465 | return undef;
|
---|
| 3466 | }
|
---|
| 3467 |
|
---|
[243] | 3468 | # explicitly set a parent id
|
---|
| 3469 | if ($defrec eq 'y') {
|
---|
| 3470 | $ret->{parid} = $ret->{group_id};
|
---|
| 3471 | } else {
|
---|
| 3472 | $ret->{parid} = (($revrec eq 'n') ? $ret->{domain_id} : $ret->{rdns_id});
|
---|
| 3473 | # and a secondary if we have a custom type that lives in both a forward and reverse zone
|
---|
| 3474 | $ret->{secid} = (($revrec eq 'y') ? $ret->{domain_id} : $ret->{rdns_id}) if $ret->{type} > 65279;
|
---|
| 3475 | }
|
---|
[451] | 3476 | $ret->{address} = $ret->{val}; # because.
|
---|
[90] | 3477 |
|
---|
| 3478 | return $ret;
|
---|
[2] | 3479 | }
|
---|
| 3480 |
|
---|
| 3481 |
|
---|
| 3482 | ##fixme: should use above (getRecLine()) to get lines for below?
|
---|
| 3483 | ## DNSDB::getDomRecs()
|
---|
| 3484 | # Return records for a domain
|
---|
| 3485 | # Takes a database handle, default/live flag, group/domain ID, start,
|
---|
| 3486 | # number of records, sort field, and sort order
|
---|
| 3487 | # Returns a reference to an array of hashes
|
---|
| 3488 | sub getDomRecs {
|
---|
| 3489 | $errstr = '';
|
---|
[481] | 3490 | my $self = shift;
|
---|
| 3491 | my $dbh = $self->{dbh};
|
---|
[2] | 3492 |
|
---|
[397] | 3493 | my %args = @_;
|
---|
[4] | 3494 |
|
---|
[397] | 3495 | my @filterargs;
|
---|
[135] | 3496 |
|
---|
[397] | 3497 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3498 |
|
---|
| 3499 | # protection against bad or missing arguments
|
---|
| 3500 | $args{sortorder} = 'ASC' if !$args{sortorder};
|
---|
[399] | 3501 | $args{sortby} = 'host' if !$args{sortby} && $args{revrec} eq 'n'; # default sort by host on domain record list
|
---|
| 3502 | $args{sortby} = 'val' if !$args{sortby} && $args{revrec} eq 'y'; # default sort by IP on revzone record list
|
---|
[397] | 3503 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
| 3504 |
|
---|
[352] | 3505 | # sort reverse zones on IP, correctly
|
---|
[397] | 3506 | # do other fiddling with $args{sortby} while we're at it.
|
---|
[420] | 3507 | # whee! multisort means just passing comma-separated fields in sortby!
|
---|
| 3508 | my $newsort = '';
|
---|
| 3509 | foreach my $sf (split /,/, $args{sortby}) {
|
---|
| 3510 | $sf = "r.$sf";
|
---|
| 3511 | $sf =~ s/r\.val/CAST (r.val AS inet)/
|
---|
| 3512 | if $args{revrec} eq 'y' && $args{defrec} eq 'n';
|
---|
| 3513 | $sf =~ s/r\.type/t.alphaorder/;
|
---|
| 3514 | $newsort .= ",$sf";
|
---|
| 3515 | }
|
---|
| 3516 | $newsort =~ s/^,//;
|
---|
[352] | 3517 |
|
---|
[224] | 3518 | my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.ttl";
|
---|
[397] | 3519 | $sql .= ",l.description AS locname" if $args{defrec} eq 'n';
|
---|
| 3520 | $sql .= ",r.distance,r.weight,r.port" if $args{revrec} eq 'n';
|
---|
| 3521 | $sql .= " FROM "._rectable($args{defrec},$args{revrec})." r ";
|
---|
[104] | 3522 | $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
|
---|
[397] | 3523 | $sql .= "LEFT JOIN locations l ON r.location=l.location " if $args{defrec} eq 'n';
|
---|
| 3524 | $sql .= "WHERE "._recparent($args{defrec},$args{revrec})." = ?";
|
---|
[104] | 3525 | $sql .= " AND NOT r.type=$reverse_typemap{SOA}";
|
---|
[439] | 3526 | $sql .= " AND (r.host ~* ? OR r.val ~* ?)" if $args{filter};
|
---|
[420] | 3527 | $sql .= " ORDER BY $newsort $args{sortorder}";
|
---|
[324] | 3528 | # ensure consistent ordering by sorting on record_id too
|
---|
[397] | 3529 | $sql .= ", record_id $args{sortorder}";
|
---|
| 3530 | $sql .= ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
[4] | 3531 |
|
---|
[397] | 3532 | my @bindvars = ($args{id});
|
---|
[439] | 3533 | push @bindvars, ($args{filter},$args{filter}) if $args{filter};
|
---|
[224] | 3534 |
|
---|
[397] | 3535 | my $ret = $dbh->selectall_arrayref($sql, { Slice => {} }, (@bindvars) );
|
---|
[2] | 3536 | return $ret;
|
---|
| 3537 | } # end getDomRecs()
|
---|
| 3538 |
|
---|
| 3539 |
|
---|
[91] | 3540 | ## DNSDB::getRecCount()
|
---|
[224] | 3541 | # Return count of non-SOA records in zone (or default records in a group)
|
---|
| 3542 | # Takes a database handle, default/live flag, reverse/forward flag, group/domain ID,
|
---|
| 3543 | # and optional filtering modifier
|
---|
[91] | 3544 | # Returns the count
|
---|
| 3545 | sub getRecCount {
|
---|
[481] | 3546 | my $self = shift;
|
---|
| 3547 | my $dbh = $self->{dbh};
|
---|
[91] | 3548 | my $defrec = shift;
|
---|
[224] | 3549 | my $revrec = shift;
|
---|
[91] | 3550 | my $id = shift;
|
---|
[135] | 3551 | my $filter = shift || '';
|
---|
[91] | 3552 |
|
---|
[135] | 3553 | # keep the nasties down, since we can't ?-sub this bit. :/
|
---|
| 3554 | # note this is chars allowed in DNS hostnames
|
---|
| 3555 | $filter =~ s/[^a-zA-Z0-9_.:-]//g;
|
---|
| 3556 |
|
---|
[222] | 3557 | my @bindvars = ($id);
|
---|
| 3558 | push @bindvars, $filter if $filter;
|
---|
[224] | 3559 | my $sql = "SELECT count(*) FROM ".
|
---|
| 3560 | _rectable($defrec,$revrec).
|
---|
| 3561 | " WHERE "._recparent($defrec,$revrec)."=? ".
|
---|
| 3562 | "AND NOT type=$reverse_typemap{SOA}".
|
---|
| 3563 | ($filter ? " AND host ~* ?" : '');
|
---|
| 3564 | my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) );
|
---|
[91] | 3565 |
|
---|
| 3566 | return $count;
|
---|
| 3567 |
|
---|
| 3568 | } # end getRecCount()
|
---|
| 3569 |
|
---|
| 3570 |
|
---|
[3] | 3571 | ## DNSDB::addRec()
|
---|
[2] | 3572 | # Add a new record to a domain or a group's default records
|
---|
| 3573 | # Takes a database handle, default/live flag, group/domain ID,
|
---|
| 3574 | # host, type, value, and TTL
|
---|
| 3575 | # Some types require additional detail: "distance" for MX and SRV,
|
---|
| 3576 | # and weight/port for SRV
|
---|
| 3577 | # Returns a status code and detail message in case of error
|
---|
[234] | 3578 | ##fixme: pass a hash with the record data, not a series of separate values
|
---|
[2] | 3579 | sub addRec {
|
---|
| 3580 | $errstr = '';
|
---|
[481] | 3581 | my $self = shift;
|
---|
| 3582 | my $dbh = $self->{dbh};
|
---|
[2] | 3583 | my $defrec = shift;
|
---|
[226] | 3584 | my $revrec = shift;
|
---|
| 3585 | my $id = shift; # parent (group_id for defrecs, rdns_id for reverse records,
|
---|
| 3586 | # domain_id for domain records)
|
---|
[2] | 3587 |
|
---|
| 3588 | my $host = shift;
|
---|
[234] | 3589 | my $rectype = shift; # reference so we can coerce it if "+"-types can't find both zones
|
---|
[2] | 3590 | my $val = shift;
|
---|
| 3591 | my $ttl = shift;
|
---|
[389] | 3592 | my $location = shift;
|
---|
| 3593 | $location = '' if !$location;
|
---|
[2] | 3594 |
|
---|
[417] | 3595 | # Spaces are evil.
|
---|
| 3596 | $$host =~ s/^\s+//;
|
---|
| 3597 | $$host =~ s/\s+$//;
|
---|
[418] | 3598 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
[417] | 3599 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 3600 | $$val =~ s/^\s+//;
|
---|
| 3601 | $$val =~ s/\s+$//;
|
---|
| 3602 | }
|
---|
| 3603 |
|
---|
[226] | 3604 | # prep for validation
|
---|
[252] | 3605 | my $addr = NetAddr::IP->new($$val);
|
---|
| 3606 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
[226] | 3607 |
|
---|
| 3608 | my $domid = 0;
|
---|
| 3609 | my $revid = 0;
|
---|
| 3610 |
|
---|
| 3611 | my $retcode = 'OK'; # assume everything will go OK
|
---|
| 3612 | my $retmsg = '';
|
---|
| 3613 |
|
---|
| 3614 | # do simple validation first
|
---|
| 3615 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
|
---|
| 3616 |
|
---|
[234] | 3617 | # Quick check on hostname parts. Note the regex is more forgiving than the error message;
|
---|
| 3618 | # domain names technically are case-insensitive, and we use printf-like % codes for a couple
|
---|
| 3619 | # of types. Other things may also be added to validate default records of several flavours.
|
---|
| 3620 | return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z . _)")
|
---|
[350] | 3621 | if $defrec eq 'n' && ($revrec eq 'y' ? $$rectype != $reverse_typemap{TXT} : 1) &&
|
---|
| 3622 | $$host !~ /^[0-9a-z_%.-]+$/i;
|
---|
[226] | 3623 |
|
---|
[234] | 3624 | # Collect these even if we're only doing a simple A record so we can call *any* validation sub
|
---|
| 3625 | my $dist = shift;
|
---|
[281] | 3626 | my $weight = shift;
|
---|
[234] | 3627 | my $port = shift;
|
---|
[226] | 3628 |
|
---|
[234] | 3629 | my $fields;
|
---|
| 3630 | my @vallist;
|
---|
[226] | 3631 |
|
---|
[234] | 3632 | # Call the validation sub for the type requested.
|
---|
[481] | 3633 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec, id => $id,
|
---|
[249] | 3634 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
[234] | 3635 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
[481] | 3636 | fields => \$fields, vallist => \@vallist);
|
---|
[129] | 3637 |
|
---|
[234] | 3638 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
[209] | 3639 |
|
---|
[234] | 3640 | # Set up database fields and bind parameters
|
---|
[481] | 3641 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
| 3642 | push @vallist, ($$host,$$rectype,$$val,$ttl,$id);
|
---|
| 3643 |
|
---|
| 3644 | # locations are not for default records, silly coder!
|
---|
| 3645 | if ($defrec eq 'n') {
|
---|
| 3646 | $fields .= ",location";
|
---|
| 3647 | push @vallist, $location;
|
---|
| 3648 | }
|
---|
[234] | 3649 | my $vallen = '?'.(',?'x$#vallist);
|
---|
[2] | 3650 |
|
---|
[287] | 3651 | # Put together the success log entry. We have to use this horrible kludge
|
---|
| 3652 | # because domain_id and rdns_id may or may not be present, and if they are,
|
---|
| 3653 | # they're not at a guaranteed consistent index in the array. wheee!
|
---|
| 3654 | my %logdata;
|
---|
| 3655 | my @ftmp = split /,/, $fields;
|
---|
| 3656 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
| 3657 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
| 3658 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
| 3659 | }
|
---|
| 3660 | $logdata{group_id} = $id if $defrec eq 'y';
|
---|
[473] | 3661 | $logdata{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec)
|
---|
[287] | 3662 | if $defrec eq 'n';
|
---|
[328] | 3663 | $logdata{entry} = "Added ".($defrec eq 'y' ? 'default record' : 'record');
|
---|
| 3664 | # NS records for revzones get special treatment
|
---|
| 3665 | if ($revrec eq 'y' && $$rectype == 2) {
|
---|
| 3666 | $logdata{entry} .= " '$$val $typemap{$$rectype} $$host";
|
---|
| 3667 | } else {
|
---|
| 3668 | $logdata{entry} .= " '$$host $typemap{$$rectype} $$val";
|
---|
| 3669 | }
|
---|
| 3670 |
|
---|
[287] | 3671 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
| 3672 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]"
|
---|
| 3673 | if $typemap{$$rectype} eq 'SRV';
|
---|
[425] | 3674 | $logdata{entry} .= "', TTL $ttl";
|
---|
[480] | 3675 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location;
|
---|
[287] | 3676 |
|
---|
[90] | 3677 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3678 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3679 | local $dbh->{AutoCommit} = 0;
|
---|
| 3680 | local $dbh->{RaiseError} = 1;
|
---|
[2] | 3681 |
|
---|
[90] | 3682 | eval {
|
---|
[236] | 3683 | $dbh->do("INSERT INTO "._rectable($defrec, $revrec)." ($fields) VALUES ($vallen)",
|
---|
[90] | 3684 | undef, @vallist);
|
---|
[287] | 3685 | _log($dbh, %logdata);
|
---|
[90] | 3686 | $dbh->commit;
|
---|
| 3687 | };
|
---|
| 3688 | if ($@) {
|
---|
| 3689 | my $msg = $@;
|
---|
| 3690 | eval { $dbh->rollback; };
|
---|
[289] | 3691 | if ($config{log_failures}) {
|
---|
| 3692 | $logdata{entry} = "Failed adding ".($defrec eq 'y' ? 'default ' : '').
|
---|
| 3693 | "record '$$host $typemap{$$rectype} $$val', TTL $ttl ($msg)";
|
---|
| 3694 | _log($dbh, %logdata);
|
---|
| 3695 | $dbh->commit;
|
---|
| 3696 | }
|
---|
[90] | 3697 | return ('FAIL',$msg);
|
---|
| 3698 | }
|
---|
[2] | 3699 |
|
---|
[287] | 3700 | $resultstr = $logdata{entry};
|
---|
[226] | 3701 | return ($retcode, $retmsg);
|
---|
[90] | 3702 |
|
---|
[2] | 3703 | } # end addRec()
|
---|
| 3704 |
|
---|
| 3705 |
|
---|
[16] | 3706 | ## DNSDB::updateRec()
|
---|
| 3707 | # Update a record
|
---|
[273] | 3708 | # Takes a database handle, default and reverse flags, record ID, immediate parent ID, and new record data.
|
---|
| 3709 | # Returns a status code and message
|
---|
[16] | 3710 | sub updateRec {
|
---|
| 3711 | $errstr = '';
|
---|
[17] | 3712 |
|
---|
[481] | 3713 | my $self = shift;
|
---|
| 3714 | my $dbh = $self->{dbh};
|
---|
[16] | 3715 | my $defrec = shift;
|
---|
[272] | 3716 | my $revrec = shift;
|
---|
[16] | 3717 | my $id = shift;
|
---|
[272] | 3718 | my $parid = shift; # immediate parent entity that we're descending from to update the record
|
---|
[16] | 3719 |
|
---|
[273] | 3720 | # all records have these
|
---|
[16] | 3721 | my $host = shift;
|
---|
[272] | 3722 | my $hostbk = $$host; # Keep a backup copy of the original, so we can WARN if the update mangles the domain
|
---|
| 3723 | my $rectype = shift;
|
---|
[16] | 3724 | my $val = shift;
|
---|
| 3725 | my $ttl = shift;
|
---|
[389] | 3726 | my $location = shift; # may be empty/null/undef depending on caller
|
---|
| 3727 | $location = '' if !$location;
|
---|
[16] | 3728 |
|
---|
[417] | 3729 | # Spaces are evil.
|
---|
| 3730 | $$host =~ s/^\s+//;
|
---|
| 3731 | $$host =~ s/\s+$//;
|
---|
[418] | 3732 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
[417] | 3733 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 3734 | $$val =~ s/^\s+//;
|
---|
| 3735 | $$val =~ s/\s+$//;
|
---|
| 3736 | }
|
---|
| 3737 |
|
---|
[272] | 3738 | # prep for validation
|
---|
| 3739 | my $addr = NetAddr::IP->new($$val);
|
---|
| 3740 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
[16] | 3741 |
|
---|
[272] | 3742 | my $domid = 0;
|
---|
| 3743 | my $revid = 0;
|
---|
| 3744 |
|
---|
| 3745 | my $retcode = 'OK'; # assume everything will go OK
|
---|
| 3746 | my $retmsg = '';
|
---|
| 3747 |
|
---|
[273] | 3748 | # do simple validation first
|
---|
[272] | 3749 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
|
---|
| 3750 |
|
---|
| 3751 | # Quick check on hostname parts. Note the regex is more forgiving than the error message;
|
---|
| 3752 | # domain names technically are case-insensitive, and we use printf-like % codes for a couple
|
---|
| 3753 | # of types. Other things may also be added to validate default records of several flavours.
|
---|
[273] | 3754 | return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z - . _)")
|
---|
[350] | 3755 | if $defrec eq 'n' && ($revrec eq 'y' ? $$rectype != $reverse_typemap{TXT} : 1) &&
|
---|
| 3756 | $$host !~ /^[0-9a-z_%.-]+$/i;
|
---|
[272] | 3757 |
|
---|
[273] | 3758 | # only MX and SRV will use these
|
---|
[288] | 3759 | my $dist = shift || 0;
|
---|
| 3760 | my $weight = shift || 0;
|
---|
| 3761 | my $port = shift || 0;
|
---|
[16] | 3762 |
|
---|
[272] | 3763 | my $fields;
|
---|
| 3764 | my @vallist;
|
---|
[16] | 3765 |
|
---|
[273] | 3766 | # get old record data so we have the right parent ID
|
---|
| 3767 | # and for logging (eventually)
|
---|
[481] | 3768 | my $oldrec = $self->getRecLine($defrec, $revrec, $id);
|
---|
[223] | 3769 |
|
---|
[272] | 3770 | # Call the validation sub for the type requested.
|
---|
| 3771 | # Note the ID to pass here is the *parent*, not the record
|
---|
[481] | 3772 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec,
|
---|
[272] | 3773 | id => ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})),
|
---|
| 3774 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
| 3775 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
| 3776 | fields => \$fields, vallist => \@vallist,
|
---|
[481] | 3777 | update => $id);
|
---|
[272] | 3778 |
|
---|
| 3779 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
| 3780 |
|
---|
[273] | 3781 | # Set up database fields and bind parameters. Note only the optional fields
|
---|
| 3782 | # (distance, weight, port, secondary parent ID) are added in the validation call above
|
---|
[448] | 3783 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
| 3784 | push @vallist, ($$host,$$rectype,$$val,$ttl,
|
---|
[273] | 3785 | ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})) );
|
---|
[272] | 3786 |
|
---|
[448] | 3787 | # locations are not for default records, silly coder!
|
---|
| 3788 | if ($defrec eq 'n') {
|
---|
| 3789 | $fields .= ",location";
|
---|
| 3790 | push @vallist, $location;
|
---|
| 3791 | }
|
---|
| 3792 |
|
---|
[273] | 3793 | # hack hack PTHUI
|
---|
| 3794 | # need to forcibly make sure we disassociate a record with a parent it's no longer related to.
|
---|
| 3795 | # eg, PTR records may not have a domain parent, or A/AAAA records may not have a revzone parent.
|
---|
| 3796 | # mainly needed for crossover types that got coerced down to "standard" types
|
---|
| 3797 | if ($defrec eq 'n') {
|
---|
| 3798 | if ($$rectype == $reverse_typemap{PTR}) {
|
---|
| 3799 | $fields .= ",domain_id";
|
---|
| 3800 | push @vallist, 0;
|
---|
| 3801 | }
|
---|
| 3802 | if ($$rectype == $reverse_typemap{A} || $$rectype == $reverse_typemap{AAAA}) {
|
---|
| 3803 | $fields .= ",rdns_id";
|
---|
| 3804 | push @vallist, 0;
|
---|
| 3805 | }
|
---|
| 3806 | }
|
---|
[345] | 3807 | # fix fat-finger-originated record type changes
|
---|
| 3808 | if ($$rectype == 65285) {
|
---|
| 3809 | $fields .= ",rdns_id" if $revrec eq 'n';
|
---|
| 3810 | $fields .= ",domain_id" if $revrec eq 'y';
|
---|
| 3811 | push @vallist, 0;
|
---|
| 3812 | }
|
---|
[341] | 3813 | if ($defrec eq 'n') {
|
---|
| 3814 | $domid = $parid if $revrec eq 'n';
|
---|
| 3815 | $revid = $parid if $revrec eq 'y';
|
---|
| 3816 | }
|
---|
[272] | 3817 |
|
---|
[288] | 3818 | # Put together the success log entry. Horrible kludge from addRec() copied as-is since
|
---|
| 3819 | # we don't know whether the passed arguments or retrieved values for domain_id and rdns_id
|
---|
| 3820 | # will be maintained (due to "not-in-zone" validation changes)
|
---|
| 3821 | my %logdata;
|
---|
[341] | 3822 | $logdata{domain_id} = $domid;
|
---|
| 3823 | $logdata{rdns_id} = $revid;
|
---|
[288] | 3824 | my @ftmp = split /,/, $fields;
|
---|
| 3825 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
| 3826 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
| 3827 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
| 3828 | }
|
---|
| 3829 | $logdata{group_id} = $parid if $defrec eq 'y';
|
---|
[473] | 3830 | $logdata{group_id} = $self->parentID(id => $parid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec)
|
---|
[288] | 3831 | if $defrec eq 'n';
|
---|
[328] | 3832 | $logdata{entry} = "Updated ".($defrec eq 'y' ? 'default record' : 'record')." from\n";
|
---|
| 3833 | # NS records for revzones get special treatment
|
---|
| 3834 | if ($revrec eq 'y' && $$rectype == 2) {
|
---|
| 3835 | $logdata{entry} .= " '$oldrec->{val} $typemap{$oldrec->{type}} $oldrec->{host}";
|
---|
| 3836 | } else {
|
---|
| 3837 | $logdata{entry} .= " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
| 3838 | }
|
---|
[288] | 3839 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
| 3840 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
| 3841 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
[425] | 3842 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
[480] | 3843 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location};
|
---|
[425] | 3844 | $logdata{entry} .= "\nto\n";
|
---|
[328] | 3845 | # More NS special
|
---|
| 3846 | if ($revrec eq 'y' && $$rectype == 2) {
|
---|
| 3847 | $logdata{entry} .= "'$$val $typemap{$$rectype} $$host";
|
---|
| 3848 | } else {
|
---|
| 3849 | $logdata{entry} .= "'$$host $typemap{$$rectype} $$val";
|
---|
| 3850 | }
|
---|
[288] | 3851 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
| 3852 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$$rectype} eq 'SRV';
|
---|
[425] | 3853 | $logdata{entry} .= "', TTL $ttl";
|
---|
[480] | 3854 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location;
|
---|
[288] | 3855 |
|
---|
[90] | 3856 | local $dbh->{AutoCommit} = 0;
|
---|
| 3857 | local $dbh->{RaiseError} = 1;
|
---|
| 3858 |
|
---|
[341] | 3859 | # Fiddle the field list into something suitable for updates
|
---|
| 3860 | $fields =~ s/,/=?,/g;
|
---|
| 3861 | $fields .= "=?";
|
---|
| 3862 |
|
---|
[90] | 3863 | eval {
|
---|
[273] | 3864 | $dbh->do("UPDATE "._rectable($defrec,$revrec)." SET $fields WHERE record_id=?", undef, (@vallist, $id) );
|
---|
[288] | 3865 | _log($dbh, %logdata);
|
---|
[130] | 3866 | $dbh->commit;
|
---|
[90] | 3867 | };
|
---|
| 3868 | if ($@) {
|
---|
| 3869 | my $msg = $@;
|
---|
[288] | 3870 | eval { $dbh->rollback; };
|
---|
[289] | 3871 | if ($config{log_failures}) {
|
---|
| 3872 | $logdata{entry} = "Failed updating ".($defrec eq 'y' ? 'default ' : '').
|
---|
| 3873 | "record '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
| 3874 | _log($dbh, %logdata);
|
---|
| 3875 | $dbh->commit;
|
---|
| 3876 | }
|
---|
[90] | 3877 | return ('FAIL', $msg);
|
---|
| 3878 | }
|
---|
| 3879 |
|
---|
[288] | 3880 | $resultstr = $logdata{entry};
|
---|
[272] | 3881 | return ($retcode, $retmsg);
|
---|
[16] | 3882 | } # end updateRec()
|
---|
| 3883 |
|
---|
| 3884 |
|
---|
[459] | 3885 | ## DNSDB::downconvert()
|
---|
| 3886 | # A mostly internal (not exported) semiutilty sub to downconvert from pseudotype <x>
|
---|
| 3887 | # to a compatible component type. Only a handful of operations are valid, anything
|
---|
| 3888 | # else is a null-op.
|
---|
| 3889 | # Takes the record ID and the new type. Returns boolean.
|
---|
| 3890 | sub downconvert {
|
---|
[481] | 3891 | my $self = shift;
|
---|
| 3892 | my $dbh = $self->{dbh};
|
---|
[459] | 3893 | my $recid = shift;
|
---|
| 3894 | my $newtype = shift;
|
---|
| 3895 |
|
---|
| 3896 | # also, only work on live records; little to no value trying to do this on default records.
|
---|
[481] | 3897 | my $rec = $self->getRecLine('n', 'y', $recid);
|
---|
[459] | 3898 |
|
---|
| 3899 | # hm?
|
---|
| 3900 | #return 1 if !$rec;
|
---|
| 3901 |
|
---|
| 3902 | return 1 if $rec->{type} < 65000; # Only the reverse-record pseudotypes can be downconverted
|
---|
| 3903 | return 1 if $rec->{type} == 65282; # Nowhere to go
|
---|
| 3904 |
|
---|
| 3905 | my $delpar;
|
---|
| 3906 | my @sqlargs;
|
---|
| 3907 | if ($rec->{type} == 65280) {
|
---|
| 3908 | return 1 if $newtype != 1 && $newtype != 12;
|
---|
| 3909 | $delpar = ($newtype == 1 ? 'rdns_id' : 'domain_id');
|
---|
| 3910 | push @sqlargs, 0, $newtype, $recid;
|
---|
| 3911 | } elsif ($rec->{type} == 65281) {
|
---|
| 3912 | return 1 if $newtype != 28 && $newtype != 12;
|
---|
| 3913 | $delpar = ($newtype == 28 ? 'rdns_id' : 'domain_id');
|
---|
| 3914 | push @sqlargs, 0, $newtype, $recid;
|
---|
| 3915 | } elsif ($rec->{type} == 65283) {
|
---|
| 3916 | return 1 if $newtype != 65282;
|
---|
| 3917 | $delpar = 'rdns_id';
|
---|
| 3918 | } elsif ($rec->{type} == 65284) {
|
---|
| 3919 | return 1 if $newtype != 65282;
|
---|
| 3920 | $delpar = 'rdns_id';
|
---|
| 3921 | } else {
|
---|
| 3922 | # Your llama is on fire.
|
---|
| 3923 | }
|
---|
| 3924 |
|
---|
| 3925 | local $dbh->{AutoCommit} = 0;
|
---|
| 3926 | local $dbh->{RaiseError} = 1;
|
---|
| 3927 |
|
---|
| 3928 | eval {
|
---|
| 3929 | $dbh->do("UPDATE records SET $delpar = ?, type = ? WHERE record_id = ?", undef, @sqlargs);
|
---|
| 3930 | $dbh->commit;
|
---|
| 3931 | };
|
---|
| 3932 | if ($@) {
|
---|
| 3933 | $errstr = $@;
|
---|
| 3934 | eval { $dbh->rollback; };
|
---|
| 3935 | return 0;
|
---|
| 3936 | }
|
---|
| 3937 | return 1;
|
---|
| 3938 | } # end downconvert()
|
---|
| 3939 |
|
---|
| 3940 |
|
---|
[3] | 3941 | ## DNSDB::delRec()
|
---|
| 3942 | # Delete a record.
|
---|
| 3943 | sub delRec {
|
---|
| 3944 | $errstr = '';
|
---|
[481] | 3945 | my $self = shift;
|
---|
| 3946 | my $dbh = $self->{dbh};
|
---|
[3] | 3947 | my $defrec = shift;
|
---|
[243] | 3948 | my $revrec = shift;
|
---|
[3] | 3949 | my $id = shift;
|
---|
| 3950 |
|
---|
[481] | 3951 | my $oldrec = $self->getRecLine($defrec, $revrec, $id);
|
---|
[3] | 3952 |
|
---|
[290] | 3953 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3954 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3955 | local $dbh->{AutoCommit} = 0;
|
---|
| 3956 | local $dbh->{RaiseError} = 1;
|
---|
[3] | 3957 |
|
---|
[290] | 3958 | # Put together the log entry
|
---|
| 3959 | my %logdata;
|
---|
| 3960 | $logdata{domain_id} = $oldrec->{domain_id};
|
---|
| 3961 | $logdata{rdns_id} = $oldrec->{rdns_id};
|
---|
| 3962 | $logdata{group_id} = $oldrec->{group_id} if $defrec eq 'y';
|
---|
[473] | 3963 | $logdata{group_id} = $self->parentID(id => $oldrec->{domain_id}, type => ($revrec eq 'n' ? 'domain' : 'revzone'),
|
---|
| 3964 | revrec => $revrec)
|
---|
[290] | 3965 | if $defrec eq 'n';
|
---|
| 3966 | $logdata{entry} = "Deleted ".($defrec eq 'y' ? 'default record ' : 'record ').
|
---|
| 3967 | "'$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
| 3968 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
| 3969 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
| 3970 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
[425] | 3971 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
[480] | 3972 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location};
|
---|
[290] | 3973 |
|
---|
| 3974 | eval {
|
---|
| 3975 | my $sth = $dbh->do("DELETE FROM "._rectable($defrec,$revrec)." WHERE record_id=?", undef, ($id));
|
---|
| 3976 | _log($dbh, %logdata);
|
---|
| 3977 | $dbh->commit;
|
---|
| 3978 | };
|
---|
| 3979 | if ($@) {
|
---|
| 3980 | my $msg = $@;
|
---|
| 3981 | eval { $dbh->rollback; };
|
---|
| 3982 | if ($config{log_failures}) {
|
---|
| 3983 | $logdata{entry} = "Error deleting ".($defrec eq 'y' ? 'default record' : 'record').
|
---|
| 3984 | " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
| 3985 | _log($dbh, %logdata);
|
---|
| 3986 | $dbh->commit;
|
---|
| 3987 | }
|
---|
| 3988 | return ('FAIL', $msg);
|
---|
| 3989 | }
|
---|
| 3990 |
|
---|
| 3991 | return ('OK',$logdata{entry});
|
---|
[3] | 3992 | } # end delRec()
|
---|
| 3993 |
|
---|
| 3994 |
|
---|
[323] | 3995 | ## DNSDB::getLogCount()
|
---|
| 3996 | # Get a count of log entries
|
---|
| 3997 | # Takes a database handle and a hash containing at least:
|
---|
| 3998 | # - Entity ID and entity type as the primary log "slice"
|
---|
| 3999 | sub getLogCount {
|
---|
[483] | 4000 | my $self = shift;
|
---|
| 4001 | my $dbh = $self->{dbh};
|
---|
[323] | 4002 |
|
---|
| 4003 | my %args = @_;
|
---|
| 4004 |
|
---|
| 4005 | my @filterargs;
|
---|
| 4006 | ##fixme: which fields do we want to filter on?
|
---|
| 4007 | # push @filterargs,
|
---|
| 4008 |
|
---|
| 4009 | $errstr = 'Missing primary parent ID and/or type';
|
---|
| 4010 | # fail early if we don't have a "prime" ID to look for log entries for
|
---|
| 4011 | return if !$args{id};
|
---|
| 4012 |
|
---|
| 4013 | # or if the prime id type is missing or invalid
|
---|
| 4014 | return if !$args{logtype};
|
---|
| 4015 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
| 4016 | $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
|
---|
| 4017 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
|
---|
| 4018 |
|
---|
| 4019 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
| 4020 |
|
---|
| 4021 | my $sql = "SELECT count(*) FROM log ".
|
---|
| 4022 | "WHERE $id_col{$args{logtype}}=?".
|
---|
| 4023 | ($args{filter} ? " AND entry ~* ?" : '');
|
---|
| 4024 | my ($count) = $dbh->selectrow_array($sql, undef, ($args{id}, @filterargs) );
|
---|
| 4025 | $errstr = $dbh->errstr if !$count;
|
---|
| 4026 | return $count;
|
---|
| 4027 | } # end getLogCount()
|
---|
| 4028 |
|
---|
| 4029 |
|
---|
| 4030 | ## DNSDB::getLogEntries()
|
---|
| 4031 | # Get a list of log entries
|
---|
| 4032 | # Takes arguments as with getLogCount() above, plus optional:
|
---|
| 4033 | # - sort field
|
---|
| 4034 | # - sort order
|
---|
| 4035 | # - offset for pagination
|
---|
| 4036 | sub getLogEntries {
|
---|
[483] | 4037 | my $self = shift;
|
---|
| 4038 | my $dbh = $self->{dbh};
|
---|
[323] | 4039 |
|
---|
| 4040 | my %args = @_;
|
---|
| 4041 |
|
---|
| 4042 | my @filterargs;
|
---|
| 4043 |
|
---|
| 4044 | # fail early if we don't have a "prime" ID to look for log entries for
|
---|
| 4045 | return if !$args{id};
|
---|
| 4046 |
|
---|
| 4047 | # or if the prime id type is missing or invalid
|
---|
| 4048 | return if !$args{logtype};
|
---|
| 4049 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
| 4050 | $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
|
---|
| 4051 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
|
---|
| 4052 |
|
---|
| 4053 | # Sorting defaults
|
---|
| 4054 | $args{sortby} = 'stamp' if !$args{sortby};
|
---|
| 4055 | $args{sortorder} = 'DESC' if !$args{sortorder};
|
---|
[397] | 4056 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[323] | 4057 |
|
---|
[324] | 4058 | my %sortmap = (fname => 'name', username => 'email', entry => 'entry', stamp => 'stamp');
|
---|
[323] | 4059 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 4060 |
|
---|
| 4061 | my $sql = "SELECT user_id AS userid, email AS useremail, name AS userfname, entry AS logentry, ".
|
---|
| 4062 | "date_trunc('second',stamp) AS logtime ".
|
---|
| 4063 | "FROM log ".
|
---|
| 4064 | "WHERE $id_col{$args{logtype}}=?".
|
---|
| 4065 | ($args{filter} ? " AND entry ~* ?" : '').
|
---|
[324] | 4066 | " ORDER BY $args{sortby} $args{sortorder}, log_id $args{sortorder}".
|
---|
[323] | 4067 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
| 4068 | my $loglist = $dbh->selectall_arrayref($sql, { Slice => {} }, ($args{id}, @filterargs) );
|
---|
| 4069 | $errstr = $dbh->errstr if !$loglist;
|
---|
| 4070 | return $loglist;
|
---|
| 4071 | } # end getLogEntries()
|
---|
| 4072 |
|
---|
| 4073 |
|
---|
[452] | 4074 | ## IPDB::getRevPattern()
|
---|
| 4075 | # Get the narrowest template pattern applicable to a passed CIDR address (may be a netblock or an IP)
|
---|
| 4076 | sub getRevPattern {
|
---|
[483] | 4077 | my $self = shift;
|
---|
| 4078 | my $dbh = $self->{dbh};
|
---|
[452] | 4079 | my $cidr = shift;
|
---|
| 4080 | my $group = shift || 1; # just in case
|
---|
| 4081 |
|
---|
[462] | 4082 | # for speed! Casting and comparing even ~7K records takes ~2.5s, so narrow it down to one revzone first.
|
---|
| 4083 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >>= ? AND group_id = ?",
|
---|
| 4084 | undef, ($cidr, $group) );
|
---|
| 4085 |
|
---|
| 4086 | ##fixme? may need to narrow things down more by octet-chopping and doing text comparisons before casting.
|
---|
| 4087 | my ($revpatt) = $dbh->selectrow_array("SELECT host FROM records ".
|
---|
| 4088 | "WHERE (type in (12,65280,65281,65282,65283,65284)) AND rdns_id = ? AND CAST (val AS inet) >>= ? ".
|
---|
| 4089 | "ORDER BY CAST (val AS inet) DESC LIMIT 1", undef, ($revid, $cidr) );
|
---|
[452] | 4090 | return $revpatt;
|
---|
| 4091 | } # end getRevPattern()
|
---|
| 4092 |
|
---|
| 4093 |
|
---|
[225] | 4094 | ## DNSDB::getTypelist()
|
---|
| 4095 | # Get a list of record types for various UI dropdowns
|
---|
| 4096 | # Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A)
|
---|
| 4097 | # Returns an arrayref to list of hashrefs perfect for HTML::Template
|
---|
| 4098 | sub getTypelist {
|
---|
[483] | 4099 | my $self = shift;
|
---|
| 4100 | my $dbh = $self->{dbh};
|
---|
[225] | 4101 | my $recgroup = shift;
|
---|
| 4102 | my $type = shift || $reverse_typemap{A};
|
---|
| 4103 |
|
---|
| 4104 | # also accepting $webvar{revrec}!
|
---|
| 4105 | $recgroup = 'f' if $recgroup eq 'n';
|
---|
| 4106 | $recgroup = 'r' if $recgroup eq 'y';
|
---|
| 4107 |
|
---|
| 4108 | my $sql = "SELECT val,name FROM rectypes WHERE ";
|
---|
| 4109 | if ($recgroup eq 'r') {
|
---|
| 4110 | # reverse zone types
|
---|
| 4111 | $sql .= "stdflag=2 OR stdflag=3";
|
---|
| 4112 | } elsif ($recgroup eq 'l') {
|
---|
| 4113 | # DNS lookup types. Note we avoid our custom types >= 65280, since those are entirely internal.
|
---|
| 4114 | $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280";
|
---|
| 4115 | } else {
|
---|
| 4116 | # default; forward zone types. technically $type eq 'f' but not worth the error message.
|
---|
| 4117 | $sql .= "stdflag=1 OR stdflag=2";
|
---|
| 4118 | }
|
---|
| 4119 | $sql .= " ORDER BY listorder";
|
---|
| 4120 |
|
---|
| 4121 | my $sth = $dbh->prepare($sql);
|
---|
| 4122 | $sth->execute;
|
---|
| 4123 | my @typelist;
|
---|
| 4124 | while (my ($rval,$rname) = $sth->fetchrow_array()) {
|
---|
| 4125 | my %row = ( recval => $rval, recname => $rname );
|
---|
| 4126 | $row{tselect} = 1 if $rval == $type;
|
---|
| 4127 | push @typelist, \%row;
|
---|
| 4128 | }
|
---|
| 4129 |
|
---|
| 4130 | # Add SOA on lookups since it's not listed in other dropdowns.
|
---|
| 4131 | if ($recgroup eq 'l') {
|
---|
| 4132 | my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
|
---|
| 4133 | $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
|
---|
| 4134 | push @typelist, \%row;
|
---|
| 4135 | }
|
---|
| 4136 |
|
---|
| 4137 | return \@typelist;
|
---|
| 4138 | } # end getTypelist()
|
---|
| 4139 |
|
---|
| 4140 |
|
---|
[254] | 4141 | ## DNSDB::parentID()
|
---|
| 4142 | # Get ID of entity that is nearest parent to requested id
|
---|
| 4143 | # Takes a database handle and a hash of entity ID, entity type, optional parent type flag
|
---|
| 4144 | # (domain/reverse zone or group), and optional default/live and forward/reverse flags
|
---|
| 4145 | # Returns the ID or undef on failure
|
---|
| 4146 | sub parentID {
|
---|
[473] | 4147 | my $self = shift;
|
---|
| 4148 | my $dbh = $self->{dbh};
|
---|
[116] | 4149 |
|
---|
[254] | 4150 | my %args = @_;
|
---|
[116] | 4151 |
|
---|
[254] | 4152 | # clean up the parent-type. Set it to group if not set; coerce revzone to domain for simpler logic
|
---|
| 4153 | $args{partype} = 'group' if !$args{partype};
|
---|
| 4154 | $args{partype} = 'domain' if $args{partype} eq 'revzone';
|
---|
[116] | 4155 |
|
---|
[254] | 4156 | # clean up defrec and revrec. default to live record, forward zone
|
---|
| 4157 | $args{defrec} = 'n' if !$args{defrec};
|
---|
| 4158 | $args{revrec} = 'n' if !$args{revrec};
|
---|
[116] | 4159 |
|
---|
[254] | 4160 | if ($par_type{$args{partype}} eq 'domain') {
|
---|
| 4161 | # only live records can have a domain/zone parent
|
---|
| 4162 | return unless ($args{type} eq 'record' && $args{defrec} eq 'n');
|
---|
| 4163 | my $result = $dbh->selectrow_hashref("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
| 4164 | " FROM records WHERE record_id = ?",
|
---|
| 4165 | undef, ($args{id}) ) or return;
|
---|
| 4166 | return $result;
|
---|
| 4167 | } else {
|
---|
| 4168 | # snag some arguments that will either fall through or be overwritten to save some code duplication
|
---|
| 4169 | my $tmpid = $args{id};
|
---|
| 4170 | my $type = $args{type};
|
---|
| 4171 | if ($type eq 'record' && $args{defrec} eq 'n') {
|
---|
| 4172 | # Live records go through the records table first.
|
---|
| 4173 | ($tmpid) = $dbh->selectrow_array("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
| 4174 | " FROM records WHERE record_id = ?",
|
---|
| 4175 | undef, ($args{id}) ) or return;
|
---|
| 4176 | $type = ($args{revrec} eq 'n' ? 'domain' : 'revzone');
|
---|
| 4177 | }
|
---|
| 4178 | my ($result) = $dbh->selectrow_array("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
|
---|
| 4179 | undef, ($tmpid) );
|
---|
| 4180 | return $result;
|
---|
| 4181 | }
|
---|
| 4182 | # should be impossible to get here with even remotely sane arguments
|
---|
| 4183 | return;
|
---|
| 4184 | } # end parentID()
|
---|
[116] | 4185 |
|
---|
| 4186 |
|
---|
[117] | 4187 | ## DNSDB::isParent()
|
---|
| 4188 | # Returns true if $id1 is a parent of $id2, false otherwise
|
---|
| 4189 | sub isParent {
|
---|
[470] | 4190 | my $self = shift;
|
---|
| 4191 | my $dbh = $self->{dbh};
|
---|
[117] | 4192 | my $id1 = shift;
|
---|
| 4193 | my $type1 = shift;
|
---|
| 4194 | my $id2 = shift;
|
---|
| 4195 | my $type2 = shift;
|
---|
| 4196 | ##todo: immediate, secondary, full (default)
|
---|
| 4197 |
|
---|
[157] | 4198 | # Return false on invalid types
|
---|
[244] | 4199 | return 0 if !grep /^$type1$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
| 4200 | return 0 if !grep /^$type2$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
[157] | 4201 |
|
---|
[117] | 4202 | # Return false on impossible relations
|
---|
| 4203 | return 0 if $type1 eq 'record'; # nothing may be a child of a record
|
---|
| 4204 | return 0 if $type1 eq 'defrec'; # nothing may be a child of a record
|
---|
[244] | 4205 | return 0 if $type1 eq 'defrevrec'; # nothing may be a child of a record
|
---|
[117] | 4206 | return 0 if $type1 eq 'user'; # nothing may be child of a user
|
---|
| 4207 | return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record
|
---|
[244] | 4208 | return 0 if $type1 eq 'revzone' && $type2 ne 'record';# reverse zone may not be a parent of anything other than a record
|
---|
[117] | 4209 |
|
---|
[186] | 4210 | # ennnhhhh.... if we're passed an id of 0, it will never be found. usual
|
---|
| 4211 | # case would be the UI creating a new <thing>, and so we don't have an ID for
|
---|
| 4212 | # <thing> to look up yet. in that case the UI should check the parent as well.
|
---|
| 4213 | return 0 if $id1 == 0; # nothing can have a parent id of 0
|
---|
| 4214 | return 1 if $id2 == 0; # anything could have a child id of 0 (or "unknown")
|
---|
| 4215 |
|
---|
[117] | 4216 | # group 1 is the ultimate root parent
|
---|
| 4217 | return 1 if $type1 eq 'group' && $id1 == 1;
|
---|
| 4218 |
|
---|
[155] | 4219 | # groups are always (a) parent of themselves
|
---|
| 4220 | return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2;
|
---|
| 4221 |
|
---|
[117] | 4222 | my $id = $id2;
|
---|
| 4223 | my $type = $type2;
|
---|
| 4224 | my $foundparent = 0;
|
---|
[155] | 4225 |
|
---|
[244] | 4226 | # Records are the only entity with two possible parents. We need to split the parent checks on
|
---|
| 4227 | # domain/rdns.
|
---|
| 4228 | if ($type eq 'record') {
|
---|
| 4229 | my ($dom,$rdns) = $dbh->selectrow_array("SELECT domain_id,rdns_id FROM records WHERE record_id=?",
|
---|
| 4230 | undef, ($id));
|
---|
| 4231 | # check immediate parent against request
|
---|
| 4232 | return 1 if $type1 eq 'domain' && $id1 == $dom;
|
---|
| 4233 | return 1 if $type1 eq 'revzone' && $id1 == $rdns;
|
---|
| 4234 | # if request is group, check *both* parents. Only check if the parent is nonzero though.
|
---|
[470] | 4235 | return 1 if $dom && $self->isParent($id1, $type1, $dom, 'domain');
|
---|
| 4236 | return 1 if $rdns && $self->isParent($id1, $type1, $rdns, 'revzone');
|
---|
[244] | 4237 | # exit here since we've executed the loop below by proxy in the above recursive calls.
|
---|
| 4238 | return 0;
|
---|
| 4239 | }
|
---|
| 4240 |
|
---|
| 4241 | # almost the same loop as getParents() above
|
---|
[186] | 4242 | my $limiter = 0;
|
---|
[117] | 4243 | while (1) {
|
---|
[155] | 4244 | my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
|
---|
[117] | 4245 | my $result = $dbh->selectrow_hashref($sql,
|
---|
[157] | 4246 | undef, ($id) );
|
---|
[186] | 4247 | if (!$result) {
|
---|
| 4248 | $limiter++;
|
---|
[244] | 4249 | ##fixme: how often will this happen on a live site? fail at max limiter <n>?
|
---|
[186] | 4250 | warn "no results looking for $sql with id $id (depth $limiter)\n";
|
---|
| 4251 | last;
|
---|
| 4252 | }
|
---|
[157] | 4253 | if ($result && $result->{$par_col{$type}} == $id1) {
|
---|
[117] | 4254 | $foundparent = 1;
|
---|
| 4255 | last;
|
---|
[157] | 4256 | } else {
|
---|
| 4257 | ##fixme: do we care about trying to return a "no such record/domain/user/group" error?
|
---|
[244] | 4258 | # should be impossible to create an inconsistent DB just with API calls.
|
---|
[157] | 4259 | warn $dbh->errstr." $sql, $id" if $dbh->errstr;
|
---|
[117] | 4260 | }
|
---|
| 4261 | # group 1 is its own parent. need this here more to break strange loops than for detecting a parent
|
---|
| 4262 | last if $result->{$par_col{$type}} == 1;
|
---|
[152] | 4263 | $id = $result->{$par_col{$type}};
|
---|
[117] | 4264 | $type = $par_type{$type};
|
---|
| 4265 | }
|
---|
| 4266 |
|
---|
| 4267 | return $foundparent;
|
---|
| 4268 | } # end isParent()
|
---|
| 4269 |
|
---|
| 4270 |
|
---|
[275] | 4271 | ## DNSDB::zoneStatus()
|
---|
| 4272 | # Returns and optionally sets a zone's status
|
---|
| 4273 | # Takes a database handle, domain/revzone ID, forward/reverse flag, and optionally a status argument
|
---|
| 4274 | # Returns status, or undef on errors.
|
---|
| 4275 | sub zoneStatus {
|
---|
[477] | 4276 | my $self = shift;
|
---|
| 4277 | my $dbh = $self->{dbh};
|
---|
[3] | 4278 | my $id = shift;
|
---|
[275] | 4279 | my $revrec = shift;
|
---|
| 4280 | my $newstatus = shift || 'mu';
|
---|
[3] | 4281 |
|
---|
| 4282 | return undef if $id !~ /^\d+$/;
|
---|
| 4283 |
|
---|
[283] | 4284 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4285 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4286 | local $dbh->{AutoCommit} = 0;
|
---|
| 4287 | local $dbh->{RaiseError} = 1;
|
---|
| 4288 |
|
---|
[275] | 4289 | if ($newstatus ne 'mu') {
|
---|
[283] | 4290 | # ooo, fun! let's see what we were passed for status
|
---|
| 4291 | eval {
|
---|
| 4292 | $newstatus = 0 if $newstatus eq 'domoff';
|
---|
| 4293 | $newstatus = 1 if $newstatus eq 'domon';
|
---|
| 4294 | $dbh->do("UPDATE ".($revrec eq 'n' ? 'domains' : 'revzones')." SET status=? WHERE ".
|
---|
[275] | 4295 | ($revrec eq 'n' ? 'domain_id' : 'rdns_id')."=?", undef, ($newstatus,$id) );
|
---|
[283] | 4296 |
|
---|
| 4297 | ##fixme switch to more consise "Enabled <domain"/"Disabled <domain>" as with users?
|
---|
[473] | 4298 | $resultstr = "Changed ".($revrec eq 'n' ? $self->domainName($id) : $self->revName($id)).
|
---|
[283] | 4299 | " state to ".($newstatus ? 'active' : 'inactive');
|
---|
| 4300 |
|
---|
| 4301 | my %loghash;
|
---|
| 4302 | $loghash{domain_id} = $id if $revrec eq 'n';
|
---|
| 4303 | $loghash{rdns_id} = $id if $revrec eq 'y';
|
---|
[473] | 4304 | $loghash{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec);
|
---|
[283] | 4305 | $loghash{entry} = $resultstr;
|
---|
| 4306 | _log($dbh, %loghash);
|
---|
| 4307 |
|
---|
| 4308 | $dbh->commit;
|
---|
| 4309 | };
|
---|
| 4310 | if ($@) {
|
---|
| 4311 | my $msg = $@;
|
---|
| 4312 | eval { $dbh->rollback; };
|
---|
| 4313 | $resultstr = '';
|
---|
| 4314 | $errstr = $msg;
|
---|
| 4315 | return;
|
---|
| 4316 | }
|
---|
[3] | 4317 | }
|
---|
| 4318 |
|
---|
[275] | 4319 | my ($status) = $dbh->selectrow_array("SELECT status FROM ".
|
---|
| 4320 | ($revrec eq 'n' ? "domains WHERE domain_id=?" : "revzones WHERE rdns_id=?"),
|
---|
| 4321 | undef, ($id) );
|
---|
[3] | 4322 | return $status;
|
---|
[275] | 4323 | } # end zoneStatus()
|
---|
[3] | 4324 |
|
---|
| 4325 |
|
---|
[452] | 4326 | ## DNSDB::getZonesByCIDR()
|
---|
| 4327 | # Get a list of zone names and IDs that records for a passed CIDR block are within.
|
---|
| 4328 | sub getZonesByCIDR {
|
---|
[477] | 4329 | my $self = shift;
|
---|
| 4330 | my $dbh = $self->{dbh};
|
---|
[452] | 4331 | my %args = @_;
|
---|
| 4332 |
|
---|
| 4333 | my $result = $dbh->selectall_arrayref("SELECT rdns_id,revnet FROM revzones WHERE revnet >>= ? OR revnet <<= ?",
|
---|
| 4334 | { Slice => {} }, ($args{cidr}, $args{cidr}) );
|
---|
| 4335 | return $result;
|
---|
| 4336 | } # end getZonesByCIDR()
|
---|
| 4337 |
|
---|
| 4338 |
|
---|
[33] | 4339 | ## DNSDB::importAXFR
|
---|
| 4340 | # Import a domain via AXFR
|
---|
[37] | 4341 | # Takes AXFR host, domain to transfer, group to put the domain in,
|
---|
[484] | 4342 | # and an optional hash containing:
|
---|
| 4343 | # status - active/inactive state flag (defaults to active)
|
---|
| 4344 | # rwsoa - overwrite-SOA flag (defaults to off)
|
---|
| 4345 | # rwns - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
|
---|
| 4346 | # merge - flag to automerge A or AAAA records with matching PTR records
|
---|
[37] | 4347 | # Returns a status code (OK, WARN, or FAIL) and message - message should be blank
|
---|
| 4348 | # if status is OK, but WARN includes conditions that are not fatal but should
|
---|
| 4349 | # really be reported.
|
---|
[33] | 4350 | sub importAXFR {
|
---|
[484] | 4351 | my $self = shift;
|
---|
| 4352 | my $dbh = $self->{dbh};
|
---|
[35] | 4353 | my $ifrom_in = shift;
|
---|
[301] | 4354 | my $zone = shift;
|
---|
[33] | 4355 | my $group = shift;
|
---|
[484] | 4356 |
|
---|
| 4357 | my %args = @_;
|
---|
| 4358 |
|
---|
[33] | 4359 | ##fixme: add mode to delete&replace, merge+overwrite, merge new?
|
---|
| 4360 |
|
---|
[484] | 4361 | $args{status} = (defined($args{status}) ? $args{status} : 0);
|
---|
| 4362 | $args{status} = 1 if $args{status} eq 'on';
|
---|
| 4363 |
|
---|
[37] | 4364 | my $nrecs = 0;
|
---|
| 4365 | my $soaflag = 0;
|
---|
| 4366 | my $nsflag = 0;
|
---|
| 4367 | my $warnmsg = '';
|
---|
| 4368 | my $ifrom;
|
---|
[33] | 4369 |
|
---|
[301] | 4370 | my $rev = 'n';
|
---|
[302] | 4371 | my $code = 'OK';
|
---|
| 4372 | my $msg = 'foobar?';
|
---|
[301] | 4373 |
|
---|
[35] | 4374 | # choke on possible bad setting in ifrom
|
---|
[37] | 4375 | # IPv4 and v6, and valid hostnames!
|
---|
[35] | 4376 | ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
| 4377 | return ('FAIL', "Bad AXFR source host $ifrom")
|
---|
| 4378 | unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
| 4379 |
|
---|
[301] | 4380 | my $errmsg;
|
---|
| 4381 |
|
---|
| 4382 | my $zone_id;
|
---|
| 4383 | my $domain_id = 0;
|
---|
| 4384 | my $rdns_id = 0;
|
---|
| 4385 | my $cidr;
|
---|
| 4386 |
|
---|
| 4387 | # magic happens! detect if we're importing a domain or a reverse zone
|
---|
| 4388 | # while we're at it, figure out what the CIDR netblock is (if we got a .arpa)
|
---|
| 4389 | # or what the formal .arpa zone is (if we got a CIDR netblock)
|
---|
| 4390 | # Handles sub-octet v4 zones in the format specified in the Cricket Book, 2nd Ed, p217-218
|
---|
| 4391 |
|
---|
| 4392 | if ($zone =~ m{(?:\.arpa\.?|/\d+)$}) {
|
---|
| 4393 | # we seem to have a reverse zone
|
---|
| 4394 | $rev = 'y';
|
---|
| 4395 |
|
---|
| 4396 | if ($zone =~ /\.arpa\.?$/) {
|
---|
| 4397 | # we have a formal reverse zone. call _zone2cidr and get the CIDR block.
|
---|
| 4398 | ($code,$msg) = _zone2cidr($zone);
|
---|
| 4399 | return ($code, $msg) if $code eq 'FAIL';
|
---|
| 4400 | $cidr = $msg;
|
---|
| 4401 | } elsif ($zone =~ m|^[\d.]+/\d+$|) {
|
---|
| 4402 | # v4 revzone, CIDR netblock
|
---|
| 4403 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 4404 | $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
| 4405 | } elsif ($zone =~ m|^[a-fA-F\d:]+/\d+$|) {
|
---|
| 4406 | # v6 revzone, CIDR netblock
|
---|
| 4407 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 4408 | return ('FAIL', "$zone is not a nibble-aligned block") if $cidr->masklen % 4 != 0;
|
---|
| 4409 | $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.');
|
---|
| 4410 | } else {
|
---|
| 4411 | # there is. no. else!
|
---|
| 4412 | return ('FAIL', "Unknown zone name format");
|
---|
| 4413 | }
|
---|
| 4414 |
|
---|
| 4415 | # quick check to start to see if we've already got one
|
---|
| 4416 |
|
---|
| 4417 | ($zone_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?",
|
---|
| 4418 | undef, ("$cidr"));
|
---|
| 4419 | $rdns_id = $zone_id;
|
---|
| 4420 | } else {
|
---|
| 4421 | # default to domain
|
---|
[349] | 4422 | ($zone_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
[301] | 4423 | undef, ($zone));
|
---|
| 4424 | $domain_id = $zone_id;
|
---|
| 4425 | }
|
---|
| 4426 |
|
---|
| 4427 | return ('FAIL', ($rev eq 'n' ? 'Domain' : 'Reverse zone')." already exists") if $zone_id;
|
---|
| 4428 |
|
---|
[303] | 4429 | # little local utility sub to swap $val and $host for revzone records.
|
---|
| 4430 | sub _revswap {
|
---|
| 4431 | my $rechost = shift;
|
---|
| 4432 | my $recdata = shift;
|
---|
| 4433 |
|
---|
| 4434 | if ($rechost =~ /\.in-addr\.arpa\.?$/) {
|
---|
| 4435 | $rechost =~ s/\.in-addr\.arpa\.?$//;
|
---|
| 4436 | $rechost = join '.', reverse split /\./, $rechost;
|
---|
| 4437 | } else {
|
---|
| 4438 | $rechost =~ s/\.ip6\.arpa\.?$//;
|
---|
| 4439 | my @nibs = reverse split /\./, $rechost;
|
---|
| 4440 | $rechost = '';
|
---|
| 4441 | my $nc;
|
---|
| 4442 | foreach (@nibs) {
|
---|
| 4443 | $rechost.= $_;
|
---|
| 4444 | $rechost .= ":" if ++$nc % 4 == 0 && $nc < 32;
|
---|
| 4445 | }
|
---|
[307] | 4446 | $rechost .= ":" if $nc < 32 && $rechost !~ /\*$/; # close netblock records?
|
---|
| 4447 | ##fixme: there's a case that ends up with a partial entry here:
|
---|
| 4448 | # ip:add:re:ss::
|
---|
| 4449 | # can't reproduce after letting it sit overnight after discovery. :(
|
---|
| 4450 | #print "$rechost\n";
|
---|
[303] | 4451 | # canonicalize with NetAddr::IP
|
---|
| 4452 | $rechost = NetAddr::IP->new($rechost)->addr unless $rechost =~ /\*$/;
|
---|
| 4453 | }
|
---|
| 4454 | return ($recdata,$rechost)
|
---|
| 4455 | }
|
---|
| 4456 |
|
---|
| 4457 |
|
---|
[33] | 4458 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4459 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4460 | local $dbh->{AutoCommit} = 0;
|
---|
| 4461 | local $dbh->{RaiseError} = 1;
|
---|
| 4462 |
|
---|
[301] | 4463 | my $sth;
|
---|
| 4464 | eval {
|
---|
[34] | 4465 |
|
---|
[301] | 4466 | if ($rev eq 'n') {
|
---|
[33] | 4467 | ##fixme: serial
|
---|
[484] | 4468 | $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef,
|
---|
| 4469 | ($zone, $group, $args{status}) );
|
---|
[301] | 4470 | # get domain id so we can do the records
|
---|
| 4471 | ($zone_id) = $dbh->selectrow_array("SELECT currval('domains_domain_id_seq')");
|
---|
| 4472 | $domain_id = $zone_id;
|
---|
| 4473 | _log($dbh, (group_id => $group, domain_id => $domain_id,
|
---|
| 4474 | entry => "[Added ".($status ? 'active' : 'inactive')." domain $zone via AXFR]") );
|
---|
| 4475 | } else {
|
---|
| 4476 | ##fixme: serial
|
---|
[484] | 4477 | $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef,
|
---|
| 4478 | ($cidr,$group,$args{status}) );
|
---|
[301] | 4479 | # get revzone id so we can do the records
|
---|
| 4480 | ($zone_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
| 4481 | $rdns_id = $zone_id;
|
---|
| 4482 | _log($dbh, (group_id => $group, rdns_id => $rdns_id,
|
---|
[303] | 4483 | entry => "[Added ".($status ? 'active' : 'inactive')." reverse zone $cidr via AXFR]") );
|
---|
[301] | 4484 | }
|
---|
[33] | 4485 |
|
---|
[35] | 4486 | ## bizarre DBI<->Net::DNS interaction bug:
|
---|
| 4487 | ## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
|
---|
[37] | 4488 | ## fixed, apparently I was doing *something* odd, but not certain what it was that
|
---|
| 4489 | ## caused a commit instead of barfing
|
---|
[35] | 4490 |
|
---|
[34] | 4491 | my $res = Net::DNS::Resolver->new;
|
---|
[35] | 4492 | $res->nameservers($ifrom);
|
---|
[301] | 4493 | $res->axfr_start($zone)
|
---|
[35] | 4494 | or die "Couldn't begin AXFR\n";
|
---|
[34] | 4495 |
|
---|
[301] | 4496 | $sth = $dbh->prepare("INSERT INTO records (domain_id,rdns_id,host,type,val,distance,weight,port,ttl)".
|
---|
| 4497 | " VALUES (?,?,?,?,?,?,?,?,?)");
|
---|
| 4498 |
|
---|
[307] | 4499 | # Stash info about sub-octet v4 revzones here so we don't have
|
---|
| 4500 | # to store the CNAMEs used to delegate a suboctet zone
|
---|
| 4501 | # $suboct{zone}{ns}[] -> array of nameservers
|
---|
| 4502 | # $suboct{zone}{cname}[] -> array of extant CNAMEs (Just In Case someone did something bizarre)
|
---|
| 4503 | ## commented pending actual use of this data. for now, we'll just
|
---|
| 4504 | ## auto-(re)create the CNAMEs in revzones on export
|
---|
| 4505 | # my %suboct;
|
---|
| 4506 |
|
---|
[35] | 4507 | while (my $rr = $res->axfr_next()) {
|
---|
[301] | 4508 |
|
---|
| 4509 | my $val;
|
---|
| 4510 | my $distance = 0;
|
---|
| 4511 | my $weight = 0;
|
---|
| 4512 | my $port = 0;
|
---|
[303] | 4513 | my $logfrag = '';
|
---|
[301] | 4514 |
|
---|
[33] | 4515 | my $type = $rr->type;
|
---|
[301] | 4516 | my $host = $rr->name;
|
---|
[484] | 4517 | my $ttl = ($args{newttl} ? $args{newttl} : $rr->ttl); # allow force-override TTLs
|
---|
[35] | 4518 |
|
---|
[37] | 4519 | $soaflag = 1 if $type eq 'SOA';
|
---|
| 4520 | $nsflag = 1 if $type eq 'NS';
|
---|
[35] | 4521 |
|
---|
[34] | 4522 | # "Primary" types:
|
---|
| 4523 | # A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
|
---|
| 4524 | # maybe KEY
|
---|
| 4525 |
|
---|
[302] | 4526 | # BIND supports:
|
---|
| 4527 | # [standard]
|
---|
| 4528 | # A AAAA CNAME MX NS PTR SOA TXT
|
---|
| 4529 | # [variously experimental, obsolete, or obscure]
|
---|
| 4530 | # 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
|
---|
| 4531 | # ... if one can ever find the right magic to format them correctly
|
---|
| 4532 |
|
---|
| 4533 | # Net::DNS supports:
|
---|
| 4534 | # RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
|
---|
| 4535 | # EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
|
---|
| 4536 | # DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
|
---|
| 4537 |
|
---|
[35] | 4538 | # nasty big ugly case-like thing here, since we have to do *some* different
|
---|
| 4539 | # processing depending on the record. le sigh.
|
---|
| 4540 |
|
---|
[105] | 4541 | ##fixme: what record types other than TXT can/will have >255-byte payloads?
|
---|
| 4542 |
|
---|
[34] | 4543 | if ($type eq 'A') {
|
---|
[301] | 4544 | $val = $rr->address;
|
---|
[34] | 4545 | } elsif ($type eq 'NS') {
|
---|
[37] | 4546 | # hmm. should we warn here if subdomain NS'es are left alone?
|
---|
[484] | 4547 | next if ($args{rwns} && ($rr->name eq $zone));
|
---|
[302] | 4548 | if ($rev eq 'y') {
|
---|
| 4549 | # revzones have records more or less reversed from forward zones.
|
---|
| 4550 | my ($tmpcode,$tmpmsg) = _zone2cidr($host);
|
---|
[401] | 4551 | die "Error converting NS record: $tmpmsg\n" if $tmpcode eq 'FAIL'; # hmm. may not make sense...
|
---|
[302] | 4552 | $val = "$tmpmsg";
|
---|
| 4553 | $host = $rr->nsdname;
|
---|
[303] | 4554 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
[307] | 4555 | # Tag and preserve. For now this is commented for a no-op, but we have Ideas for
|
---|
| 4556 | # another custom storage type ("DELEGATE") that will use these subzone-delegation records
|
---|
| 4557 | #if ($val ne "$cidr") {
|
---|
| 4558 | # push @{$suboct{$val}{ns}}, $host;
|
---|
| 4559 | #}
|
---|
[302] | 4560 | } else {
|
---|
| 4561 | $val = $rr->nsdname;
|
---|
| 4562 | }
|
---|
[35] | 4563 | $nsflag = 1;
|
---|
[34] | 4564 | } elsif ($type eq 'CNAME') {
|
---|
[302] | 4565 | if ($rev eq 'y') {
|
---|
[303] | 4566 | # hmm. do we even want to bother with storing these at this level? Sub-octet delegation
|
---|
| 4567 | # by CNAME is essentially a record-publication hack, and we want to just represent the
|
---|
| 4568 | # "true" logical intentions as far down the stack as we can from the UI.
|
---|
| 4569 | ($host,$val) = _revswap($host,$rr->cname);
|
---|
| 4570 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
[307] | 4571 | # Tag and preserve in case we want to commit them as-is later, but mostly we don't care.
|
---|
| 4572 | # Commented pending actually doing something with possibly new type DELEGATE
|
---|
| 4573 | #my $tmprev = $host;
|
---|
| 4574 | #$tmprev =~ s/^\d+\.//;
|
---|
| 4575 | #($code,$tmprev) = _zone2cidr($tmprev);
|
---|
| 4576 | #push @{$suboct{"$tmprev"}{cname}}, $val;
|
---|
| 4577 | # Silently skip CNAMEs in revzones.
|
---|
| 4578 | next;
|
---|
[302] | 4579 | } else {
|
---|
| 4580 | $val = $rr->cname;
|
---|
| 4581 | }
|
---|
[34] | 4582 | } elsif ($type eq 'SOA') {
|
---|
[484] | 4583 | next if $args{rwsoa};
|
---|
[307] | 4584 | $host = $rr->rname.":".$rr->mname;
|
---|
[301] | 4585 | $val = $rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum;
|
---|
[35] | 4586 | $soaflag = 1;
|
---|
[34] | 4587 | } elsif ($type eq 'PTR') {
|
---|
[303] | 4588 | ($host,$val) = _revswap($host,$rr->ptrdname);
|
---|
| 4589 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
[34] | 4590 | # hmm. PTR records should not be in forward zones.
|
---|
| 4591 | } elsif ($type eq 'MX') {
|
---|
[301] | 4592 | $val = $rr->exchange;
|
---|
| 4593 | $distance = $rr->preference;
|
---|
[34] | 4594 | } elsif ($type eq 'TXT') {
|
---|
| 4595 | ##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
|
---|
| 4596 | ## but don't really seem enthusiastic about it.
|
---|
[303] | 4597 | #print "should use rdatastr:\n\t".$rr->rdatastr."\n or char_str_list:\n\t".join(' ',$rr->char_str_list())."\n";
|
---|
| 4598 | # rdatastr returns a BIND-targetted logical string, including opening and closing quotes
|
---|
| 4599 | # char_str_list returns a list of the individual string fragments in the record
|
---|
[307] | 4600 | # txtdata returns the more useful all-in-one form (since we want to push such protocol
|
---|
| 4601 | # details as far down the stack as we can)
|
---|
[303] | 4602 | # NB: this may turn out to be more troublesome if we ever have need of >512-byte TXT records.
|
---|
| 4603 | if ($rev eq 'y') {
|
---|
| 4604 | ($host,$val) = _revswap($host,$rr->txtdata);
|
---|
| 4605 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
| 4606 | } else {
|
---|
| 4607 | $val = $rr->txtdata;
|
---|
| 4608 | }
|
---|
[34] | 4609 | } elsif ($type eq 'SPF') {
|
---|
| 4610 | ##fixme: and the same caveat here, since it is apparently a clone of ::TXT
|
---|
[301] | 4611 | $val = $rr->txtdata;
|
---|
[34] | 4612 | } elsif ($type eq 'AAAA') {
|
---|
[301] | 4613 | $val = $rr->address;
|
---|
[34] | 4614 | } elsif ($type eq 'SRV') {
|
---|
[301] | 4615 | $val = $rr->target;
|
---|
| 4616 | $distance = $rr->priority;
|
---|
| 4617 | $weight = $rr->weight;
|
---|
| 4618 | $port = $rr->port;
|
---|
[34] | 4619 | } elsif ($type eq 'KEY') {
|
---|
[35] | 4620 | # we don't actually know what to do with these...
|
---|
[301] | 4621 | $val = $rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname;
|
---|
[35] | 4622 | } else {
|
---|
[301] | 4623 | $val = $rr->rdatastr;
|
---|
[35] | 4624 | # Finding a different record type is not fatal.... just problematic.
|
---|
[37] | 4625 | # We may not be able to export it correctly.
|
---|
[35] | 4626 | $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
|
---|
[33] | 4627 | }
|
---|
| 4628 |
|
---|
[303] | 4629 | my $logentry = "[AXFR ".($rev eq 'n' ? $zone : $cidr)."] ";
|
---|
[34] | 4630 |
|
---|
[484] | 4631 | if ($args{merge}) {
|
---|
[307] | 4632 | if ($rev eq 'n') {
|
---|
| 4633 | # importing a domain; we have A and AAAA records that could be merged with matching PTR records
|
---|
| 4634 | my $etype;
|
---|
| 4635 | my ($erdns,$erid,$ettl) = $dbh->selectrow_array("SELECT rdns_id,record_id,ttl FROM records ".
|
---|
| 4636 | "WHERE host=? AND val=? AND type=12",
|
---|
| 4637 | undef, ($host, $val) );
|
---|
| 4638 | if ($erid) {
|
---|
| 4639 | if ($type eq 'A') { # PTR -> A+PTR
|
---|
| 4640 | $etype = 65280;
|
---|
| 4641 | $logentry .= "Merged A record with existing PTR record '$host A+PTR $val', TTL $ettl";
|
---|
| 4642 | }
|
---|
| 4643 | if ($type eq 'AAAA') { # PTR -> AAAA+PTR
|
---|
| 4644 | $etype = 65281;
|
---|
| 4645 | $logentry .= "Merged AAAA record with existing PTR record '$host AAAA+PTR $val', TTL $ettl";
|
---|
| 4646 | }
|
---|
| 4647 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
| 4648 | $dbh->do("UPDATE records SET domain_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
| 4649 | ($domain_id, $ettl, $etype, $erid));
|
---|
| 4650 | $nrecs++;
|
---|
| 4651 | _log($dbh, (group_id => $group, domain_id => $domain_id, rdns_id => $erdns, entry => $logentry) );
|
---|
| 4652 | next; # while axfr_next
|
---|
| 4653 | }
|
---|
| 4654 | } # $rev eq 'n'
|
---|
| 4655 | else {
|
---|
| 4656 | # importing a revzone, we have PTR records that could be merged with matching A/AAAA records
|
---|
| 4657 | my ($domid,$erid,$ettl,$etype) = $dbh->selectrow_array("SELECT domain_id,record_id,ttl,type FROM records ".
|
---|
| 4658 | "WHERE host=? AND val=? AND (type=1 OR type=28)",
|
---|
| 4659 | undef, ($host, $val) );
|
---|
| 4660 | if ($erid) {
|
---|
| 4661 | if ($etype == 1) { # A -> A+PTR
|
---|
| 4662 | $etype = 65280;
|
---|
| 4663 | $logentry .= "Merged PTR record with existing matching A record '$host A+PTR $val', TTL $ettl";
|
---|
| 4664 | }
|
---|
| 4665 | if ($etype == 28) { # AAAA -> AAAA+PTR
|
---|
| 4666 | $etype = 65281;
|
---|
| 4667 | $logentry .= "Merged PTR record with existing matching AAAA record '$host AAAA+PTR $val', TTL $ettl";
|
---|
| 4668 | }
|
---|
| 4669 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
| 4670 | $dbh->do("UPDATE records SET rdns_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
| 4671 | ($rdns_id, $ettl, $etype, $erid));
|
---|
| 4672 | $nrecs++;
|
---|
| 4673 | _log($dbh, (group_id => $group, domain_id => $domid, rdns_id => $rdns_id, entry => $logentry) );
|
---|
| 4674 | next; # while axfr_next
|
---|
| 4675 | }
|
---|
| 4676 | } # $rev eq 'y'
|
---|
[484] | 4677 | } # if $args{merge}
|
---|
[34] | 4678 |
|
---|
[302] | 4679 | # Insert the new record
|
---|
[301] | 4680 | $sth->execute($domain_id, $rdns_id, $host, $reverse_typemap{$type}, $val,
|
---|
| 4681 | $distance, $weight, $port, $ttl);
|
---|
| 4682 |
|
---|
[37] | 4683 | $nrecs++;
|
---|
[34] | 4684 |
|
---|
[301] | 4685 | if ($type eq 'SOA') {
|
---|
[484] | 4686 | # also !$args{rwsoa}, but if that's set, it should be impossible to get here.
|
---|
[301] | 4687 | my @tmp1 = split /:/, $host;
|
---|
| 4688 | my @tmp2 = split /:/, $val;
|
---|
| 4689 | $logentry .= "Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
| 4690 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl";
|
---|
[303] | 4691 | } elsif ($logfrag) {
|
---|
| 4692 | # special case for log entries we need to meddle with a little.
|
---|
| 4693 | $logentry .= $logfrag;
|
---|
[301] | 4694 | } else {
|
---|
| 4695 | $logentry .= "Added record '$host $type";
|
---|
| 4696 | $logentry .= " [distance $distance]" if $type eq 'MX';
|
---|
| 4697 | $logentry .= " [priority $distance] [weight $weight] [port $port]" if $type eq 'SRV';
|
---|
| 4698 | $logentry .= " $val', TTL $ttl";
|
---|
| 4699 | }
|
---|
| 4700 | _log($dbh, (group_id => $group, domain_id => $domain_id, rdns_id => $rdns_id, entry => $logentry) );
|
---|
| 4701 |
|
---|
[37] | 4702 | } # while axfr_next
|
---|
| 4703 |
|
---|
[307] | 4704 | # Detect and handle delegated subzones
|
---|
| 4705 | # Placeholder for when we decide what to actually do with this, see previous comments in NS and CNAME handling.
|
---|
| 4706 | #foreach (keys %suboct) {
|
---|
| 4707 | # print "found ".($suboct{$_}{ns} ? @{$suboct{$_}{ns}} : '0')." NS records and ".
|
---|
| 4708 | # ($suboct{$_}{cname} ? @{$suboct{$_}{cname}} : '0')." CNAMEs for $_\n";
|
---|
| 4709 | #}
|
---|
| 4710 |
|
---|
[37] | 4711 | # Overwrite SOA record
|
---|
[484] | 4712 | if ($args{rwsoa}) {
|
---|
[37] | 4713 | $soaflag = 1;
|
---|
| 4714 | my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
|
---|
| 4715 | my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
| 4716 | $sthgetsoa->execute($group,$reverse_typemap{SOA});
|
---|
| 4717 | while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
|
---|
[301] | 4718 | $host =~ s/DOMAIN/$zone/g;
|
---|
| 4719 | $val =~ s/DOMAIN/$zone/g;
|
---|
| 4720 | $sthputsoa->execute($zone_id,$host,$reverse_typemap{SOA},$val,$ttl);
|
---|
[34] | 4721 | }
|
---|
[37] | 4722 | }
|
---|
[34] | 4723 |
|
---|
[37] | 4724 | # Overwrite NS records
|
---|
[484] | 4725 | if ($args{rwns}) {
|
---|
[37] | 4726 | $nsflag = 1;
|
---|
| 4727 | my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
|
---|
| 4728 | my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
| 4729 | $sthgetns->execute($group,$reverse_typemap{NS});
|
---|
| 4730 | while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
|
---|
[301] | 4731 | $host =~ s/DOMAIN/$zone/g;
|
---|
| 4732 | $val =~ s/DOMAIN/$zone/g;
|
---|
| 4733 | $sthputns->execute($zone_id,$host,$reverse_typemap{NS},$val,$ttl);
|
---|
[37] | 4734 | }
|
---|
| 4735 | }
|
---|
[34] | 4736 |
|
---|
[35] | 4737 | die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
|
---|
| 4738 | die "Bad zone: No SOA record!\n" if !$soaflag;
|
---|
| 4739 | die "Bad zone: No NS records!\n" if !$nsflag;
|
---|
| 4740 |
|
---|
[37] | 4741 | $dbh->commit;
|
---|
[35] | 4742 |
|
---|
[33] | 4743 | };
|
---|
| 4744 |
|
---|
| 4745 | if ($@) {
|
---|
| 4746 | my $msg = $@;
|
---|
| 4747 | eval { $dbh->rollback; };
|
---|
[34] | 4748 | return ('FAIL',$msg." $warnmsg");
|
---|
[33] | 4749 | } else {
|
---|
[35] | 4750 | return ('WARN', $warnmsg) if $warnmsg;
|
---|
[91] | 4751 | return ('OK',"Imported OK");
|
---|
[33] | 4752 | }
|
---|
| 4753 |
|
---|
[37] | 4754 | # it should be impossible to get here.
|
---|
[34] | 4755 | return ('WARN',"OOOK!");
|
---|
[33] | 4756 | } # end importAXFR()
|
---|
| 4757 |
|
---|
| 4758 |
|
---|
[302] | 4759 | ## DNSDB::importBIND()
|
---|
| 4760 | sub importBIND {
|
---|
| 4761 | } # end importBIND()
|
---|
| 4762 |
|
---|
| 4763 |
|
---|
| 4764 | ## DNSDB::import_tinydns()
|
---|
| 4765 | sub import_tinydns {
|
---|
| 4766 | } # end import_tinydns()
|
---|
| 4767 |
|
---|
| 4768 |
|
---|
[103] | 4769 | ## DNSDB::export()
|
---|
| 4770 | # Export the DNS database, or a part of it
|
---|
[485] | 4771 | # Takes a string indicating the export type, plus optional arguments depending on type
|
---|
[103] | 4772 | # Writes zone data to targets as appropriate for type
|
---|
| 4773 | sub export {
|
---|
[485] | 4774 | my $self = shift;
|
---|
[103] | 4775 | my $target = shift;
|
---|
| 4776 |
|
---|
| 4777 | if ($target eq 'tiny') {
|
---|
[485] | 4778 | $self->__export_tiny(@_);
|
---|
[103] | 4779 | }
|
---|
| 4780 | # elsif ($target eq 'foo') {
|
---|
[485] | 4781 | # __export_foo(@_);
|
---|
[103] | 4782 | #}
|
---|
| 4783 | # etc
|
---|
| 4784 |
|
---|
| 4785 | } # end export()
|
---|
| 4786 |
|
---|
| 4787 |
|
---|
| 4788 | ## DNSDB::__export_tiny
|
---|
| 4789 | # Internal sub to implement tinyDNS (compatible) export
|
---|
[485] | 4790 | # Takes filehandle to write export to, optional argument(s)
|
---|
[103] | 4791 | # to determine which data gets exported
|
---|
| 4792 | sub __export_tiny {
|
---|
[485] | 4793 | my $self = shift;
|
---|
| 4794 | my $dbh = $self->{dbh};
|
---|
[103] | 4795 | my $datafile = shift;
|
---|
| 4796 |
|
---|
| 4797 | ##fixme: slurp up further options to specify particular zone(s) to export
|
---|
| 4798 |
|
---|
| 4799 | ##fixme: fail if $datafile isn't an open, writable file
|
---|
| 4800 |
|
---|
| 4801 | # easy case - export all evarything
|
---|
| 4802 | # not-so-easy case - export item(s) specified
|
---|
| 4803 | # todo: figure out what kind of list we use to export items
|
---|
| 4804 |
|
---|
[329] | 4805 | # raw packet in unknown format: first byte indicates length
|
---|
| 4806 | # of remaining data, allows up to 255 raw bytes
|
---|
| 4807 |
|
---|
[372] | 4808 | # Locations/views - worth including in the caching setup?
|
---|
| 4809 | my $lochash = $dbh->selectall_hashref("SELECT location,iplist FROM locations", 'location');
|
---|
| 4810 | foreach my $location (keys %$lochash) {
|
---|
[375] | 4811 | foreach my $ipprefix (split /[,\s]+/, $lochash->{$location}{iplist}) {
|
---|
| 4812 | $ipprefix =~ s/\s+//g;
|
---|
[449] | 4813 | $ipprefix = new NetAddr::IP $ipprefix;
|
---|
| 4814 | ##fixme: how to handle IPv6?
|
---|
| 4815 | next if $ipprefix->{isv6};
|
---|
| 4816 | # have to account for /nn CIDR entries. tinydns only speaks octet-sliced prefix.
|
---|
| 4817 | if ($ipprefix->masklen <= 8) {
|
---|
| 4818 | foreach ($ipprefix->split(8)) {
|
---|
| 4819 | my $tmp = $_->addr;
|
---|
| 4820 | $tmp =~ s/\.\d+\.\d+\.\d+$//;
|
---|
| 4821 | print $datafile "%$location:$tmp\n";
|
---|
| 4822 | }
|
---|
| 4823 | } elsif ($ipprefix->masklen <= 16) {
|
---|
| 4824 | foreach ($ipprefix->split(16)) {
|
---|
| 4825 | my $tmp = $_->addr;
|
---|
| 4826 | $tmp =~ s/\.\d+\.\d+$//;
|
---|
| 4827 | print $datafile "%$location:$tmp\n";
|
---|
| 4828 | }
|
---|
| 4829 | } elsif ($ipprefix->masklen <= 24) {
|
---|
| 4830 | foreach ($ipprefix->split(24)) {
|
---|
| 4831 | my $tmp = $_->addr;
|
---|
| 4832 | $tmp =~ s/\.\d+$//;
|
---|
| 4833 | print $datafile "%$location:$tmp\n";
|
---|
| 4834 | }
|
---|
| 4835 | } else {
|
---|
| 4836 | foreach ($ipprefix->split(32)) {
|
---|
| 4837 | print $datafile "%$location:".$_->addr."\n";
|
---|
| 4838 | }
|
---|
| 4839 | }
|
---|
[372] | 4840 | }
|
---|
| 4841 | print $datafile "%$location\n" if !$lochash->{$location}{iplist};
|
---|
| 4842 | }
|
---|
| 4843 |
|
---|
[329] | 4844 | # tracking hash so we don't double-export A+PTR or AAAA+PTR records.
|
---|
| 4845 | my %recflags;
|
---|
| 4846 |
|
---|
[368] | 4847 | my $domsth = $dbh->prepare("SELECT domain_id,domain,status,changed FROM domains WHERE status=1");
|
---|
[372] | 4848 | my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
[368] | 4849 | "FROM records WHERE domain_id=? AND type < 65280"); # Just exclude all types relating to rDNS
|
---|
[372] | 4850 | my $zonesth = $dbh->prepare("UPDATE domains SET changed='n' WHERE domain_id=?");
|
---|
[103] | 4851 | $domsth->execute();
|
---|
[368] | 4852 | while (my ($domid,$dom,$domstat,$changed) = $domsth->fetchrow_array) {
|
---|
| 4853 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
| 4854 | # O_NOFOLLOW
|
---|
| 4855 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
| 4856 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
| 4857 | # still be followed.
|
---|
| 4858 | # but that doesn't help other platforms. :/
|
---|
| 4859 | sysopen(ZONECACHE, "$config{exportcache}/$dom", O_RDWR|O_CREAT);
|
---|
| 4860 | flock(ZONECACHE, LOCK_EX);
|
---|
| 4861 | if ($changed || -s "$config{exportcache}/$dom" == 0) {
|
---|
| 4862 | $recsth->execute($domid);
|
---|
[372] | 4863 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc) = $recsth->fetchrow_array) {
|
---|
[368] | 4864 | next if $recflags{$recid};
|
---|
[108] | 4865 |
|
---|
[372] | 4866 | $loc = '' if !$loc; # de-nullify - just in case
|
---|
| 4867 | ##fixme: handle case of record-with-location-that-doesn't-exist better.
|
---|
| 4868 | # note this currently fails safe (tested) - records with a location that
|
---|
| 4869 | # doesn't exist will not be sent to any client
|
---|
| 4870 | # $loc = '' if !$lochash->{$loc};
|
---|
| 4871 |
|
---|
[108] | 4872 | ##fixme: record validity timestamp. tinydns supports fiddling with timestamps.
|
---|
| 4873 | # note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
|
---|
| 4874 | # timestamps are TAI64
|
---|
| 4875 | # ~~ 2^62 + time()
|
---|
[368] | 4876 | my $stamp = '';
|
---|
[108] | 4877 |
|
---|
[368] | 4878 | # support tinydns' auto-TTL
|
---|
| 4879 | $ttl = '' if $ttl == '0';
|
---|
[367] | 4880 |
|
---|
[417] | 4881 | # Spaces are evil.
|
---|
[441] | 4882 | $host =~ s/^\s+//;
|
---|
| 4883 | $host =~ s/\s+$//;
|
---|
| 4884 | if ($typemap{$type} ne 'TXT') {
|
---|
[417] | 4885 | # Leading or trailng spaces could be legit in TXT records.
|
---|
[441] | 4886 | $val =~ s/^\s+//;
|
---|
| 4887 | $val =~ s/\s+$//;
|
---|
[417] | 4888 | }
|
---|
| 4889 |
|
---|
[368] | 4890 | _printrec_tiny(*ZONECACHE, 'n', \%recflags,
|
---|
| 4891 | $dom, $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp)
|
---|
| 4892 | if *ZONECACHE;
|
---|
[450] | 4893 |
|
---|
[368] | 4894 | # in case the zone shrunk, get rid of garbage at the end of the file.
|
---|
| 4895 | truncate(ZONECACHE, tell(ZONECACHE));
|
---|
| 4896 |
|
---|
| 4897 | $recflags{$recid} = 1;
|
---|
| 4898 | } # while ($recsth)
|
---|
| 4899 | }
|
---|
[450] | 4900 | # stream from cache, whether freshly created or existing
|
---|
| 4901 | print $datafile $_ while <ZONECACHE>;
|
---|
[368] | 4902 | close ZONECACHE;
|
---|
| 4903 | # mark domain as unmodified
|
---|
| 4904 | $zonesth->execute($domid);
|
---|
[329] | 4905 | } # while ($domsth)
|
---|
| 4906 |
|
---|
[368] | 4907 | my $revsth = $dbh->prepare("SELECT rdns_id,revnet,status,changed FROM revzones WHERE status=1 ".
|
---|
[337] | 4908 | "ORDER BY masklen(revnet) DESC");
|
---|
[372] | 4909 |
|
---|
[344] | 4910 | # For reasons unknown, we can't sanely UNION these statements. Feh.
|
---|
| 4911 | # Supposedly it should work though (note last 3 lines):
|
---|
| 4912 | ## PG manual
|
---|
| 4913 | #UNION Clause
|
---|
| 4914 | #
|
---|
| 4915 | #The UNION clause has this general form:
|
---|
| 4916 | #
|
---|
| 4917 | # select_statement UNION [ ALL ] select_statement
|
---|
| 4918 | #
|
---|
| 4919 | #select_statement is any SELECT statement without an ORDER BY, LIMIT, FOR UPDATE, or FOR SHARE clause. (ORDER BY
|
---|
| 4920 | #and LIMIT can be attached to a subexpression if it is enclosed in parentheses. Without parentheses, these
|
---|
| 4921 | #clauses will be taken to apply to the result of the UNION, not to its right-hand input expression.)
|
---|
[372] | 4922 | my $soasth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
[344] | 4923 | "FROM records WHERE rdns_id=? AND type=6");
|
---|
[372] | 4924 | $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
[337] | 4925 | "FROM records WHERE rdns_id=? AND not type=6 ".
|
---|
[344] | 4926 | "ORDER BY masklen(CAST(val AS inet)) DESC, CAST(val AS inet)");
|
---|
[372] | 4927 | $zonesth = $dbh->prepare("UPDATE revzones SET changed='n' WHERE rdns_id=?");
|
---|
[329] | 4928 | $revsth->execute();
|
---|
[368] | 4929 | while (my ($revid,$revzone,$revstat,$changed) = $revsth->fetchrow_array) {
|
---|
| 4930 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
| 4931 | # O_NOFOLLOW
|
---|
| 4932 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
| 4933 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
| 4934 | # still be followed.
|
---|
| 4935 | # but that doesn't help other platforms. :/
|
---|
| 4936 | my $tmpzone = NetAddr::IP->new($revzone);
|
---|
| 4937 | sysopen(ZONECACHE, "$config{exportcache}/".$tmpzone->network->addr, O_RDWR|O_CREAT);
|
---|
| 4938 | flock(ZONECACHE, LOCK_EX);
|
---|
| 4939 | if ($changed || -s "$config{exportcache}/".$tmpzone->network->addr == 0) {
|
---|
| 4940 | # need to fetch this separately since the rest of the records all (should) have real IPs in val
|
---|
| 4941 | $soasth->execute($revid);
|
---|
| 4942 | my (@zsoa) = $soasth->fetchrow_array();
|
---|
[445] | 4943 | _printrec_tiny(*ZONECACHE,'y',\%recflags,$revzone,
|
---|
| 4944 | $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],'');
|
---|
[344] | 4945 |
|
---|
[368] | 4946 | $recsth->execute($revid);
|
---|
[372] | 4947 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc) = $recsth->fetchrow_array) {
|
---|
[368] | 4948 | next if $recflags{$recid};
|
---|
[329] | 4949 |
|
---|
[372] | 4950 | $loc = '' if !$loc; # de-nullify - just in case
|
---|
| 4951 | ##fixme: handle case of record-with-location-that-doesn't-exist better.
|
---|
| 4952 | # note this currently fails safe (tested) - records with a location that
|
---|
| 4953 | # doesn't exist will not be sent to any client
|
---|
| 4954 | # $loc = '' if !$lochash->{$loc};
|
---|
| 4955 |
|
---|
[329] | 4956 | ##fixme: record validity timestamp. tinydns supports fiddling with timestamps.
|
---|
| 4957 | # note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
|
---|
| 4958 | # timestamps are TAI64
|
---|
| 4959 | # ~~ 2^62 + time()
|
---|
[368] | 4960 | my $stamp = '';
|
---|
[329] | 4961 |
|
---|
[368] | 4962 | # support tinydns' auto-TTL
|
---|
| 4963 | $ttl = '' if $ttl == '0';
|
---|
[367] | 4964 |
|
---|
[368] | 4965 | _printrec_tiny(*ZONECACHE, 'y', \%recflags, $revzone,
|
---|
| 4966 | $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp)
|
---|
| 4967 | if *ZONECACHE;
|
---|
[329] | 4968 |
|
---|
[450] | 4969 | # in case the zone shrunk, get rid of garbage at the end of the file.
|
---|
| 4970 | truncate(ZONECACHE, tell(ZONECACHE));
|
---|
| 4971 |
|
---|
[368] | 4972 | $recflags{$recid} = 1;
|
---|
| 4973 | } # while ($recsth)
|
---|
| 4974 | }
|
---|
[450] | 4975 | # stream from cache, whether freshly created or existing
|
---|
| 4976 | print $datafile $_ while <ZONECACHE>;
|
---|
[368] | 4977 | close ZONECACHE;
|
---|
[450] | 4978 | # mark zone as unmodified
|
---|
[368] | 4979 | $zonesth->execute($revid);
|
---|
[329] | 4980 | } # while ($domsth)
|
---|
| 4981 |
|
---|
| 4982 | } # end __export_tiny()
|
---|
| 4983 |
|
---|
| 4984 |
|
---|
| 4985 | # Utility sub for __export_tiny above
|
---|
| 4986 | sub _printrec_tiny {
|
---|
| 4987 | my ($datafile,$revrec,$recflags,$zone,$host,$type,$val,$dist,$weight,$port,$ttl,$loc,$stamp) = @_;
|
---|
| 4988 |
|
---|
| 4989 | ## Convert a bare number into an octal-coded pair of octets.
|
---|
| 4990 | # Take optional arg to indicate a decimal or hex input. Defaults to hex.
|
---|
| 4991 | sub octalize {
|
---|
| 4992 | my $tmp = shift;
|
---|
| 4993 | my $srctype = shift || 'h'; # default assumes hex string
|
---|
| 4994 | $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
|
---|
| 4995 | $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
|
---|
| 4996 | my @o = ($tmp =~ /^(..)(..)$/); # split into octets
|
---|
| 4997 | return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);;
|
---|
| 4998 | }
|
---|
| 4999 |
|
---|
[339] | 5000 | ## WARNING: This works to export even the whole Internet's worth of IP space...
|
---|
| 5001 | ## if you have the disk/RAM to handle the dataset, and you call this sub based on /16-sized chunks
|
---|
| 5002 | ## A /16 took ~3 seconds with a handful of separate records; adding a /8 pushed export time out to ~13m:40s
|
---|
| 5003 | ## 0/0 is estimated to take ~54 hours and ~256G of disk
|
---|
| 5004 | ## RAM usage depends on how many non-template entries you have in the set.
|
---|
| 5005 | ## This should probably be done on record addition rather than export; large blocks may need to be done in a
|
---|
| 5006 | ## forked process
|
---|
| 5007 | sub __publish_subnet {
|
---|
| 5008 | my $sub = shift;
|
---|
| 5009 | my $recflags = shift;
|
---|
| 5010 | my $hpat = shift;
|
---|
| 5011 | my $fh = shift;
|
---|
| 5012 | my $ttl = shift;
|
---|
| 5013 | my $stamp = shift;
|
---|
| 5014 | my $loc = shift;
|
---|
| 5015 | my $ptronly = shift || 0;
|
---|
| 5016 |
|
---|
| 5017 | my $iplist = $sub->splitref(32);
|
---|
| 5018 | foreach (@$iplist) {
|
---|
| 5019 | my $ip = $_->addr;
|
---|
| 5020 | # make as if we split the non-octet-aligned block into octet-aligned blocks as with SOA
|
---|
| 5021 | next if $ip =~ /\.(0|255)$/;
|
---|
| 5022 | next if $$recflags{$ip};
|
---|
| 5023 | $$recflags{$ip}++;
|
---|
[463] | 5024 | next if $hpat eq '%blank%'; # Allows blanking a subnet so no records are published.
|
---|
[339] | 5025 | my $rec = $hpat; # start fresh with the template for each IP
|
---|
| 5026 | _template4_expand(\$rec, $ip);
|
---|
| 5027 | print $fh ($ptronly ? "^"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$rec" : "=$rec:$ip").
|
---|
| 5028 | ":$ttl:$stamp:$loc\n";
|
---|
| 5029 | }
|
---|
| 5030 | }
|
---|
| 5031 |
|
---|
[103] | 5032 | ##fixme? append . to all host/val hostnames
|
---|
| 5033 | if ($typemap{$type} eq 'SOA') {
|
---|
| 5034 |
|
---|
| 5035 | # host contains pri-ns:responsible
|
---|
| 5036 | # val is abused to contain refresh:retry:expire:minttl
|
---|
| 5037 | ##fixme: "manual" serial vs tinydns-autoserial
|
---|
[202] | 5038 | # let's be explicit about abusing $host and $val
|
---|
| 5039 | my ($email, $primary) = (split /:/, $host)[0,1];
|
---|
| 5040 | my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
|
---|
[330] | 5041 | if ($revrec eq 'y') {
|
---|
[337] | 5042 | ##fixme: have to publish SOA records for each v4 /24 in sub-/16, and each /16 in sub-/8
|
---|
| 5043 | # what about v6?
|
---|
| 5044 | # -> only need SOA for local chunks offset from reverse delegation boundaries, so v6 is fine
|
---|
[330] | 5045 | $zone = NetAddr::IP->new($zone);
|
---|
[337] | 5046 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
| 5047 | if (!$zone->{isv6} && ($zone->masklen < 24) && ($zone->masklen % 8 != 0)) {
|
---|
| 5048 | foreach my $szone ($zone->split($zone->masklen + (8 - $zone->masklen % 8))) {
|
---|
| 5049 | $szone = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
| 5050 | print $datafile "Z$szone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
|
---|
| 5051 | }
|
---|
| 5052 | return; # skips "default" bits just below
|
---|
| 5053 | }
|
---|
[330] | 5054 | $zone = _ZONE($zone, 'ZONE', 'r', '.').($zone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 5055 | }
|
---|
[329] | 5056 | print $datafile "Z$zone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
|
---|
[103] | 5057 |
|
---|
| 5058 | } elsif ($typemap{$type} eq 'A') {
|
---|
| 5059 |
|
---|
[108] | 5060 | print $datafile "+$host:$val:$ttl:$stamp:$loc\n";
|
---|
[103] | 5061 |
|
---|
| 5062 | } elsif ($typemap{$type} eq 'NS') {
|
---|
| 5063 |
|
---|
[330] | 5064 | if ($revrec eq 'y') {
|
---|
| 5065 | $val = NetAddr::IP->new($val);
|
---|
[345] | 5066 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
| 5067 | if (!$val->{isv6} && ($val->masklen < 24) && ($val->masklen % 8 != 0)) {
|
---|
[346] | 5068 | foreach my $szone ($val->split($val->masklen + (8 - $val->masklen % 8))) {
|
---|
[345] | 5069 | my $szone2 = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
[346] | 5070 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
[345] | 5071 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n";
|
---|
[346] | 5072 | $$recflags{$szone2} = $val->masklen;
|
---|
[345] | 5073 | }
|
---|
[346] | 5074 | } elsif ($val->{isv6} && ($val->masklen < 64) && ($val->masklen % 4 !=0)) {
|
---|
| 5075 | foreach my $szone ($val->split($val->masklen + (4 - $val->masklen % 4))) {
|
---|
| 5076 | my $szone2 = _ZONE($szone, 'ZONE.ip6.arpa', 'r', '.');
|
---|
| 5077 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
| 5078 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n";
|
---|
| 5079 | $$recflags{$szone2} = $val->masklen;
|
---|
| 5080 | }
|
---|
| 5081 | } else {
|
---|
| 5082 | my $val2 = _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 5083 | print $datafile "\&$val2"."::$host:$ttl:$stamp:$loc\n";
|
---|
| 5084 | $$recflags{$val2} = $val->masklen;
|
---|
[345] | 5085 | }
|
---|
[330] | 5086 | } else {
|
---|
| 5087 | print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n";
|
---|
| 5088 | }
|
---|
[103] | 5089 |
|
---|
| 5090 | } elsif ($typemap{$type} eq 'AAAA') {
|
---|
| 5091 |
|
---|
| 5092 | print $datafile ":$host:28:";
|
---|
| 5093 | my $altgrp = 0;
|
---|
| 5094 | my @altconv;
|
---|
[108] | 5095 | # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
|
---|
[103] | 5096 | foreach (split /:/, $val) {
|
---|
| 5097 | if (/^$/) {
|
---|
| 5098 | # flag blank entry; this is a series of 0's of (currently) unknown length
|
---|
| 5099 | $altconv[$altgrp++] = 's';
|
---|
| 5100 | } else {
|
---|
| 5101 | # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
|
---|
| 5102 | $altconv[$altgrp++] = octalize($_)
|
---|
| 5103 | }
|
---|
| 5104 | }
|
---|
| 5105 | foreach my $octet (@altconv) {
|
---|
| 5106 | # if not 's', output
|
---|
| 5107 | print $datafile $octet unless $octet =~ /^s$/;
|
---|
| 5108 | # if 's', output (9-array length)x literal '\000\000'
|
---|
| 5109 | print $datafile '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
|
---|
| 5110 | }
|
---|
[108] | 5111 | print $datafile ":$ttl:$stamp:$loc\n";
|
---|
[103] | 5112 |
|
---|
| 5113 | } elsif ($typemap{$type} eq 'MX') {
|
---|
| 5114 |
|
---|
[108] | 5115 | print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n";
|
---|
[103] | 5116 |
|
---|
| 5117 | } elsif ($typemap{$type} eq 'TXT') {
|
---|
| 5118 |
|
---|
| 5119 | ##fixme: split v-e-r-y long TXT strings? will need to do so for BIND export, at least
|
---|
[350] | 5120 | if ($revrec eq 'n') {
|
---|
| 5121 | $val =~ s/:/\\072/g; # may need to replace other symbols
|
---|
| 5122 | print $datafile "'$host:$val:$ttl:$stamp:$loc\n";
|
---|
| 5123 | } else {
|
---|
| 5124 | $host =~ s/:/\\072/g; # may need to replace other symbols
|
---|
| 5125 | my $val2 = NetAddr::IP->new($val);
|
---|
| 5126 | print $datafile "'"._ZONE($val2, 'ZONE', 'r', '.').($val2->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
| 5127 | ":$host:$ttl:$stamp:$loc\n";
|
---|
| 5128 | }
|
---|
[103] | 5129 |
|
---|
| 5130 | # by-hand TXT
|
---|
| 5131 | #:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
|
---|
| 5132 | #@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
|
---|
| 5133 | #'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
|
---|
| 5134 |
|
---|
| 5135 | #txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
|
---|
| 5136 | #: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
|
---|
| 5137 |
|
---|
| 5138 | # very long TXT record as brought in by axfr-get
|
---|
| 5139 | # note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
|
---|
| 5140 | # also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
|
---|
| 5141 | #:longtxt.deepnet.cx:16:
|
---|
| 5142 | #\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
|
---|
| 5143 | #\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.
|
---|
| 5144 | #\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.
|
---|
| 5145 | #:3600
|
---|
| 5146 |
|
---|
| 5147 | } elsif ($typemap{$type} eq 'CNAME') {
|
---|
| 5148 |
|
---|
[372] | 5149 | if ($revrec eq 'n') {
|
---|
| 5150 | print $datafile "C$host:$val:$ttl:$stamp:$loc\n";
|
---|
| 5151 | } else {
|
---|
| 5152 | my $val2 = NetAddr::IP->new($val);
|
---|
| 5153 | print $datafile "C"._ZONE($val2, 'ZONE', 'r', '.').($val2->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
| 5154 | ":$host:$ttl:$stamp:$loc\n";
|
---|
| 5155 | }
|
---|
[103] | 5156 |
|
---|
| 5157 | } elsif ($typemap{$type} eq 'SRV') {
|
---|
| 5158 |
|
---|
| 5159 | # data is two-byte values for priority, weight, port, in that order,
|
---|
| 5160 | # followed by length/string data
|
---|
| 5161 |
|
---|
| 5162 | print $datafile ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
|
---|
| 5163 |
|
---|
| 5164 | $val .= '.' if $val !~ /\.$/;
|
---|
| 5165 | foreach (split /\./, $val) {
|
---|
| 5166 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
| 5167 | }
|
---|
[108] | 5168 | print $datafile "\\000:$ttl:$stamp:$loc\n";
|
---|
[103] | 5169 |
|
---|
| 5170 | } elsif ($typemap{$type} eq 'RP') {
|
---|
| 5171 |
|
---|
| 5172 | # RP consists of two mostly free-form strings.
|
---|
| 5173 | # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
|
---|
| 5174 | # The second is the "hostname" of a TXT record with more info.
|
---|
| 5175 | print $datafile ":$host:17:";
|
---|
| 5176 | my ($who,$what) = split /\s/, $val;
|
---|
| 5177 | foreach (split /\./, $who) {
|
---|
| 5178 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
| 5179 | }
|
---|
| 5180 | print $datafile '\000';
|
---|
| 5181 | foreach (split /\./, $what) {
|
---|
| 5182 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
| 5183 | }
|
---|
[108] | 5184 | print $datafile "\\000:$ttl:$stamp:$loc\n";
|
---|
[103] | 5185 |
|
---|
| 5186 | } elsif ($typemap{$type} eq 'PTR') {
|
---|
| 5187 |
|
---|
[332] | 5188 | $zone = NetAddr::IP->new($zone);
|
---|
[337] | 5189 | $$recflags{$val}++;
|
---|
[332] | 5190 | if (!$zone->{isv6} && $zone->masklen > 24) {
|
---|
| 5191 | ($val) = ($val =~ /\.(\d+)$/);
|
---|
| 5192 | print $datafile "^$val."._ZONE($zone, 'ZONE', 'r', '.').'.in-addr.arpa'.
|
---|
| 5193 | ":$host:ttl:$stamp:$loc\n";
|
---|
| 5194 | } else {
|
---|
| 5195 | $val = NetAddr::IP->new($val);
|
---|
| 5196 | print $datafile "^".
|
---|
| 5197 | _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
[334] | 5198 | ":$host:$ttl:$stamp:$loc\n";
|
---|
[332] | 5199 | }
|
---|
[103] | 5200 |
|
---|
[333] | 5201 | } elsif ($type == 65280) { # A+PTR
|
---|
[334] | 5202 |
|
---|
[337] | 5203 | $$recflags{$val}++;
|
---|
[334] | 5204 | print $datafile "=$host:$val:$ttl:$stamp:$loc\n";
|
---|
| 5205 |
|
---|
[333] | 5206 | } elsif ($type == 65281) { # AAAA+PTR
|
---|
| 5207 |
|
---|
[337] | 5208 | #$$recflags{$val}++;
|
---|
[333] | 5209 | # treat these as two separate records. since tinydns doesn't have
|
---|
| 5210 | # a native combined type, we have to create them separately anyway.
|
---|
| 5211 | if ($revrec eq 'n') {
|
---|
| 5212 | $type = 28;
|
---|
| 5213 | } else {
|
---|
| 5214 | $type = 12;
|
---|
| 5215 | }
|
---|
[334] | 5216 | _printrec_tiny($datafile,$revrec,$recflags,$zone,$host,$type,$val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
[335] | 5217 | ##fixme: add a config flag to indicate use of the patch from http://www.fefe.de/dns/
|
---|
| 5218 | # type 6 is for AAAA+PTR, type 3 is for AAAA
|
---|
[333] | 5219 |
|
---|
| 5220 | } elsif ($type == 65282) { # PTR template
|
---|
[335] | 5221 |
|
---|
| 5222 | # only useful for v4 with standard DNS software, since this expands all
|
---|
| 5223 | # IPs in $zone (or possibly $val?) with autogenerated records
|
---|
[337] | 5224 | $val = NetAddr::IP->new($val);
|
---|
| 5225 | return if $val->{isv6};
|
---|
[336] | 5226 |
|
---|
[339] | 5227 | if ($val->masklen <= 16) {
|
---|
| 5228 | foreach my $sub ($val->split(16)) {
|
---|
| 5229 | __publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, 1);
|
---|
| 5230 | }
|
---|
| 5231 | } else {
|
---|
| 5232 | __publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, 1);
|
---|
[337] | 5233 | }
|
---|
[335] | 5234 |
|
---|
[333] | 5235 | } elsif ($type == 65283) { # A+PTR template
|
---|
[335] | 5236 |
|
---|
[337] | 5237 | $val = NetAddr::IP->new($val);
|
---|
| 5238 | # Just In Case. An A+PTR should be impossible to add to a v6 revzone via API.
|
---|
| 5239 | return if $val->{isv6};
|
---|
[339] | 5240 |
|
---|
| 5241 | if ($val->masklen <= 16) {
|
---|
| 5242 | foreach my $sub ($val->split(16)) {
|
---|
| 5243 | __publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, 0);
|
---|
| 5244 | }
|
---|
| 5245 | } else {
|
---|
| 5246 | __publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, 0);
|
---|
[337] | 5247 | }
|
---|
[335] | 5248 |
|
---|
[333] | 5249 | } elsif ($type == 65284) { # AAAA+PTR template
|
---|
[335] | 5250 | # Stub for completeness. Could be exported to DNS software that supports
|
---|
| 5251 | # some degree of internal automagic in generic-record-creation
|
---|
| 5252 | # (eg http://search.cpan.org/dist/AllKnowingDNS/ )
|
---|
[333] | 5253 |
|
---|
[345] | 5254 | } elsif ($type == 65285) { # Delegation
|
---|
| 5255 | # This is intended for reverse zones, but may prove useful in forward zones.
|
---|
| 5256 |
|
---|
[346] | 5257 | # All delegations need to create one or more NS records. The NS record handler knows what to do.
|
---|
| 5258 | _printrec_tiny($datafile,$revrec,$recflags,$zone,$host,$reverse_typemap{'NS'},
|
---|
| 5259 | $val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
| 5260 | if ($revrec eq 'y') {
|
---|
| 5261 | # In the case of a sub-/24 v4 reverse delegation, we need to generate CNAMEs
|
---|
| 5262 | # to redirect all of the individual IP lookups as well.
|
---|
| 5263 | # Not sure how this would actually resolve if a /24 or larger was delegated
|
---|
| 5264 | # one way, and a sub-/24 in that >=/24 was delegated elsewhere...
|
---|
| 5265 | my $dblock = NetAddr::IP->new($val);
|
---|
| 5266 | if (!$dblock->{isv6} && $dblock->masklen > 24) {
|
---|
| 5267 | my @subs = $dblock->split;
|
---|
| 5268 | foreach (@subs) {
|
---|
| 5269 | next if $$recflags{"$_"};
|
---|
| 5270 | my ($oct) = ($_->addr =~ /(\d+)$/);
|
---|
| 5271 | print $datafile "C"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$oct.".
|
---|
| 5272 | _ZONE($dblock, 'ZONE.in-addr.arpa', 'r', '.').":$ttl:$stamp:$loc\n";
|
---|
| 5273 | $$recflags{"$_"}++;
|
---|
| 5274 | }
|
---|
| 5275 | }
|
---|
| 5276 | }
|
---|
[345] | 5277 |
|
---|
[364] | 5278 | ##
|
---|
| 5279 | ## Uncommon types. These will need better UI support Any Day Sometime Maybe(TM).
|
---|
| 5280 | ##
|
---|
| 5281 |
|
---|
| 5282 | } elsif ($type == 44) { # SSHFP
|
---|
| 5283 | my ($algo,$fpt,$fp) = split /\s+/, $val;
|
---|
| 5284 |
|
---|
| 5285 | my $rec = sprintf ":$host:44:\\%0.3o\\%0.3o", $algo, $fpt;
|
---|
| 5286 | while (my ($byte) = ($fp =~ /^(..)/) ) {
|
---|
| 5287 | $rec .= sprintf "\\%0.3o", hex($byte);
|
---|
| 5288 | $fp =~ s/^..//;
|
---|
| 5289 | }
|
---|
| 5290 | print $datafile "$rec:$ttl:$stamp:$loc\n";
|
---|
| 5291 |
|
---|
[345] | 5292 | } else {
|
---|
[108] | 5293 | # raw record. we don't know what's in here, so we ASS-U-ME the user has
|
---|
| 5294 | # put it in correctly, since either the user is messing directly with the
|
---|
| 5295 | # database, or the record was imported via AXFR
|
---|
| 5296 | # <split by char>
|
---|
| 5297 | # convert anything not a-zA-Z0-9.- to octal coding
|
---|
| 5298 |
|
---|
| 5299 | ##fixme: add flag to export "unknown" record types - note we'll probably end up
|
---|
| 5300 | # mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
|
---|
| 5301 | #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
|
---|
| 5302 |
|
---|
[103] | 5303 | } # record type if-else
|
---|
| 5304 |
|
---|
[329] | 5305 | } # end _printrec_tiny()
|
---|
[103] | 5306 |
|
---|
| 5307 |
|
---|
[197] | 5308 | ## DNSDB::mailNotify()
|
---|
[283] | 5309 | # Sends notification mail to recipients regarding a DNSDB operation
|
---|
[197] | 5310 | sub mailNotify {
|
---|
[483] | 5311 | my $self = shift;
|
---|
| 5312 | my $dbh = $self->{dbh};
|
---|
[197] | 5313 | my ($subj,$message) = @_;
|
---|
| 5314 |
|
---|
| 5315 | return if $config{mailhost} eq 'smtp.example.com'; # do nothing if still using default SMTP host.
|
---|
| 5316 |
|
---|
| 5317 | my $mailer = Net::SMTP->new($config{mailhost}, Hello => "dnsadmin.$config{domain}");
|
---|
| 5318 |
|
---|
| 5319 | my $mailsender = ($config{mailsender} ? $config{mailsender} : $config{mailnotify});
|
---|
| 5320 |
|
---|
| 5321 | $mailer->mail($mailsender);
|
---|
| 5322 | $mailer->to($config{mailnotify});
|
---|
[198] | 5323 | $mailer->data("From: \"$config{mailname}\" <$mailsender>\n",
|
---|
| 5324 | "To: <$config{mailnotify}>\n",
|
---|
[197] | 5325 | "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
|
---|
| 5326 | "Subject: $subj\n",
|
---|
| 5327 | "X-Mailer: DNSAdmin Notify v".sprintf("%.1d",$DNSDB::VERSION)."\n",
|
---|
| 5328 | "Organization: $config{orgname}\n",
|
---|
| 5329 | "\n$message\n");
|
---|
| 5330 | $mailer->quit;
|
---|
| 5331 | }
|
---|
| 5332 |
|
---|
[2] | 5333 | # shut Perl up
|
---|
| 5334 | 1;
|
---|