[2] | 1 | # dns/trunk/DNSDB.pm
|
---|
| 2 | # Abstraction functions for DNS administration
|
---|
[262] | 3 | ##
|
---|
| 4 | # $Id: DNSDB.pm 466 2013-03-12 16:06:28Z 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 database handle
|
---|
| 393 | # a hash containing at least the following keys:
|
---|
| 394 | # - defrec (default/live flag)
|
---|
| 395 | # - revrec (forward/reverse flag)
|
---|
| 396 | # - id (parent entity ID)
|
---|
| 397 | # - host (hostname)
|
---|
| 398 | # - rectype
|
---|
| 399 | # - val (IP, hostname [CNAME/MX/SRV] or text)
|
---|
| 400 | # - addr (NetAddr::IP object from val. May be undef.)
|
---|
| 401 | # MX and SRV record validation also expect distance, and SRV records expect weight and port as well.
|
---|
| 402 | # host, rectype, and addr should be references as these may be modified in validation
|
---|
| 403 |
|
---|
[228] | 404 | # A record
|
---|
| 405 | sub _validate_1 {
|
---|
[229] | 406 | my $dbh = shift;
|
---|
| 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.
|
---|
[230] | 414 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
|
---|
| 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 {
|
---|
[230] | 431 | my $dbh = shift;
|
---|
| 432 |
|
---|
| 433 | my %args = @_;
|
---|
| 434 |
|
---|
[328] | 435 | # Check that the target of the record is within the parent.
|
---|
| 436 | # Yes, host<->val are mixed up here; can't see a way to avoid it. :(
|
---|
| 437 | if ($args{defrec} eq 'n') {
|
---|
| 438 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
| 439 | if ($args{revrec} eq 'y') {
|
---|
| 440 | my $tmpip = NetAddr::IP->new(${$args{val}});
|
---|
| 441 | my $pname = revName($dbh,$args{id});
|
---|
| 442 | return ('FAIL',"${$args{val}} not within $pname")
|
---|
| 443 | unless _ipparent($dbh, $args{defrec}, $args{revrec}, $args{val}, $args{id}, \$tmpip);
|
---|
| 444 | # Sub the returned thing for ZONE? This could get stupid if you have typos...
|
---|
| 445 | ${$args{val}} =~ s/ZONE/$tmpip->address/;
|
---|
| 446 | } else {
|
---|
| 447 | my $pname = domainName($dbh,$args{id});
|
---|
| 448 | ${$args{host}} = $pname if ${$args{host}} !~ /\.$pname$/;
|
---|
| 449 | }
|
---|
[230] | 450 | } else {
|
---|
[328] | 451 | # Default reverse NS records should always refer to the implied parent
|
---|
| 452 | ${$args{host}} = 'DOMAIN' if $args{revrec} eq 'n';
|
---|
| 453 | ${$args{val}} = 'ZONE' if $args{revrec} eq 'y';
|
---|
[230] | 454 | }
|
---|
| 455 |
|
---|
| 456 | # Let this lie for now. Needs more magic.
|
---|
| 457 | # # Check IP is well-formed, and that it's a v4 address
|
---|
| 458 | # return ('FAIL',"A record must be a valid IPv4 address")
|
---|
| 459 | # unless $addr && !$addr->{isv6};
|
---|
| 460 | # # coerce IP/value to normalized form for storage
|
---|
| 461 | # $$val = $addr->addr;
|
---|
| 462 |
|
---|
[228] | 463 | return ('OK','OK');
|
---|
| 464 | } # done NS record
|
---|
| 465 |
|
---|
| 466 | # CNAME record
|
---|
| 467 | sub _validate_5 {
|
---|
[230] | 468 | my $dbh = shift;
|
---|
| 469 |
|
---|
| 470 | my %args = @_;
|
---|
| 471 |
|
---|
| 472 | # Not really true, but these are only useful for delegating smaller-than-/24 IP blocks.
|
---|
| 473 | # This is fundamentally a messy operation and should really just be taken care of by the
|
---|
| 474 | # export process, not manual maintenance of the necessary records.
|
---|
| 475 | return ('FAIL', 'Reverse zones cannot contain CNAME records') if $args{revrec} eq 'y';
|
---|
| 476 |
|
---|
| 477 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 478 | # or the intended parent domain for live records.
|
---|
| 479 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
|
---|
| 480 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 481 |
|
---|
[228] | 482 | return ('OK','OK');
|
---|
| 483 | } # done CNAME record
|
---|
| 484 |
|
---|
| 485 | # SOA record
|
---|
| 486 | sub _validate_6 {
|
---|
[230] | 487 | # Smart monkeys won't stick their fingers in here; we have
|
---|
| 488 | # separate dedicated routines to deal with SOA records.
|
---|
[228] | 489 | return ('OK','OK');
|
---|
| 490 | } # done SOA record
|
---|
| 491 |
|
---|
| 492 | # PTR record
|
---|
| 493 | sub _validate_12 {
|
---|
[232] | 494 | my $dbh = shift;
|
---|
| 495 |
|
---|
| 496 | my %args = @_;
|
---|
| 497 |
|
---|
| 498 | if ($args{revrec} eq 'y') {
|
---|
| 499 | if ($args{defrec} eq 'n') {
|
---|
| 500 | return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".revName($dbh, $args{id}))
|
---|
| 501 | unless _ipparent($dbh, $args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
| 502 | ${$args{val}} = $args{addr}->addr;
|
---|
| 503 | } else {
|
---|
[234] | 504 | if (${$args{val}} =~ /\./) {
|
---|
| 505 | # looks like a v4 or fragment
|
---|
| 506 | if (${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/) {
|
---|
| 507 | # woo! a complete IP! validate it and normalize, or fail.
|
---|
| 508 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
| 509 | or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
|
---|
| 510 | ${$args{val}} = $args{addr}->addr;
|
---|
| 511 | } else {
|
---|
[249] | 512 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
[234] | 513 | }
|
---|
| 514 | } elsif (${$args{val}} =~ /[a-f:]/) {
|
---|
| 515 | # looks like a v6 or fragment
|
---|
[251] | 516 | ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
|
---|
[234] | 517 | if ($args{addr}) {
|
---|
| 518 | if ($args{addr}->addr =~ /^0/) {
|
---|
[251] | 519 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
[234] | 520 | } else {
|
---|
| 521 | ${$args{val}} = $args{addr}->addr;
|
---|
| 522 | }
|
---|
| 523 | }
|
---|
| 524 | } else {
|
---|
| 525 | # bare number (probably). These could be v4 or v6, so we'll
|
---|
| 526 | # expand on these on creation of a reverse zone.
|
---|
[251] | 527 | ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
|
---|
[234] | 528 | }
|
---|
[249] | 529 | ${$args{host}} =~ s/\.*$/\.$config{domain}/ if ${$args{host}} !~ /(?:$config{domain}|ADMINDOMAIN)$/;
|
---|
[232] | 530 | }
|
---|
| 531 |
|
---|
| 532 | # Multiple PTR records do NOT generally do what most people believe they do,
|
---|
| 533 | # and tend to fail in the most awkward way possible. Check and warn.
|
---|
| 534 | # We use $val instead of $addr->addr since we may be in a defrec, and may have eg "ZONE::42" or "ZONE.12"
|
---|
[249] | 535 |
|
---|
| 536 | my @checkvals = (${$args{val}});
|
---|
| 537 | if (${$args{val}} =~ /,/) {
|
---|
| 538 | # push . and :: variants into checkvals if val has ,
|
---|
| 539 | my $tmp;
|
---|
| 540 | ($tmp = ${$args{val}}) =~ s/,/./;
|
---|
| 541 | push @checkvals, $tmp;
|
---|
| 542 | ($tmp = ${$args{val}}) =~ s/,/::/;
|
---|
| 543 | push @checkvals, $tmp;
|
---|
| 544 | }
|
---|
| 545 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ?");
|
---|
| 546 | foreach my $checkme (@checkvals) {
|
---|
[272] | 547 | if ($args{update}) {
|
---|
| 548 | # Record update. There should usually be an existing PTR (the record being updated)
|
---|
| 549 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 550 | " WHERE val = ?", undef, ($checkme)) };
|
---|
| 551 | return ('WARN', "PTR record for $checkme already exists; adding another will probably not do what you want")
|
---|
[273] | 552 | if @ptrs && (!grep /^$args{update}$/, @ptrs);
|
---|
[272] | 553 | } else {
|
---|
| 554 | # New record. Always warn if a PTR exists
|
---|
| 555 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 556 | " WHERE val = ?", undef, ($checkme));
|
---|
| 557 | return ('WARN', "PTR record for $checkme already exists; adding another will probably not do what you want")
|
---|
| 558 | if $ptrcount;
|
---|
| 559 | }
|
---|
[249] | 560 | }
|
---|
[272] | 561 |
|
---|
[232] | 562 | } else {
|
---|
| 563 | # Not absolutely true but only useful if you hack things up for sub-/24 v4 reverse delegations
|
---|
| 564 | # Simpler to just create the reverse zone and grant access for the customer to edit it, and create direct
|
---|
| 565 | # PTR records on export
|
---|
| 566 | return ('FAIL',"Forward zones cannot contain PTR records");
|
---|
| 567 | }
|
---|
| 568 |
|
---|
[228] | 569 | return ('OK','OK');
|
---|
| 570 | } # done PTR record
|
---|
| 571 |
|
---|
| 572 | # MX record
|
---|
| 573 | sub _validate_15 {
|
---|
[230] | 574 | my $dbh = shift;
|
---|
| 575 |
|
---|
| 576 | my %args = @_;
|
---|
| 577 |
|
---|
| 578 | # Not absolutely true but WTF use is an MX record for a reverse zone?
|
---|
| 579 | return ('FAIL', 'Reverse zones cannot contain MX records') if $args{revrec} eq 'y';
|
---|
| 580 |
|
---|
| 581 | return ('FAIL', "Distance is required for MX records") unless defined(${$args{dist}});
|
---|
| 582 | ${$args{dist}} =~ s/\s*//g;
|
---|
| 583 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
|
---|
| 584 |
|
---|
| 585 | ${$args{fields}} = "distance,";
|
---|
| 586 | push @{$args{vallist}}, ${$args{dist}};
|
---|
| 587 |
|
---|
| 588 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 589 | # or the intended parent domain for live records.
|
---|
| 590 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
|
---|
| 591 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 592 |
|
---|
[273] | 593 | # hmm.. this might work. except possibly for something pointing to "deadbeef.ca". <g>
|
---|
| 594 | # if ($type == $reverse_typemap{NS} || $type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
|
---|
| 595 | # if ($val =~ /^\s*[\da-f:.]+\s*$/) {
|
---|
| 596 | # return ('FAIL',"$val is not a valid IP address") if !$addr;
|
---|
| 597 | # }
|
---|
| 598 | # }
|
---|
| 599 |
|
---|
[228] | 600 | return ('OK','OK');
|
---|
| 601 | } # done MX record
|
---|
| 602 |
|
---|
| 603 | # TXT record
|
---|
| 604 | sub _validate_16 {
|
---|
[231] | 605 | # Could arguably put a WARN return here on very long (>512) records
|
---|
[228] | 606 | return ('OK','OK');
|
---|
| 607 | } # done TXT record
|
---|
| 608 |
|
---|
| 609 | # RP record
|
---|
| 610 | sub _validate_17 {
|
---|
[231] | 611 | # Probably have to validate these some day
|
---|
[228] | 612 | return ('OK','OK');
|
---|
| 613 | } # done RP record
|
---|
| 614 |
|
---|
| 615 | # AAAA record
|
---|
| 616 | sub _validate_28 {
|
---|
[229] | 617 | my $dbh = shift;
|
---|
| 618 |
|
---|
[230] | 619 | my %args = @_;
|
---|
[229] | 620 |
|
---|
[230] | 621 | return ('FAIL', 'Reverse zones cannot contain AAAA records') if $args{revrec} eq 'y';
|
---|
[229] | 622 |
|
---|
| 623 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 624 | # or the intended parent domain for live records.
|
---|
[230] | 625 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
|
---|
| 626 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
[229] | 627 |
|
---|
| 628 | # Check IP is well-formed, and that it's a v6 address
|
---|
[232] | 629 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
|
---|
[230] | 630 | unless $args{addr} && $args{addr}->{isv6};
|
---|
[229] | 631 | # coerce IP/value to normalized form for storage
|
---|
[230] | 632 | ${$args{val}} = $args{addr}->addr;
|
---|
[229] | 633 |
|
---|
[228] | 634 | return ('OK','OK');
|
---|
| 635 | } # done AAAA record
|
---|
| 636 |
|
---|
| 637 | # SRV record
|
---|
| 638 | sub _validate_33 {
|
---|
[231] | 639 | my $dbh = shift;
|
---|
| 640 |
|
---|
| 641 | my %args = @_;
|
---|
| 642 |
|
---|
| 643 | # Not absolutely true but WTF use is an SRV record for a reverse zone?
|
---|
| 644 | return ('FAIL', 'Reverse zones cannot contain SRV records') if $args{revrec} eq 'y';
|
---|
| 645 |
|
---|
| 646 | return ('FAIL', "Distance is required for SRV records") unless defined(${$args{dist}});
|
---|
| 647 | ${$args{dist}} =~ s/\s*//g;
|
---|
| 648 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
|
---|
| 649 |
|
---|
| 650 | return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]")
|
---|
| 651 | unless ${$args{host}} =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/;
|
---|
| 652 | return ('FAIL',"Port and weight are required for SRV records")
|
---|
| 653 | unless defined(${$args{weight}}) && defined(${$args{port}});
|
---|
| 654 | ${$args{weight}} =~ s/\s*//g;
|
---|
| 655 | ${$args{port}} =~ s/\s*//g;
|
---|
| 656 |
|
---|
| 657 | return ('FAIL',"Port and weight are required, and must be numeric")
|
---|
| 658 | unless ${$args{weight}} =~ /^\d+$/ && ${$args{port}} =~ /^\d+$/;
|
---|
| 659 |
|
---|
| 660 | ${$args{fields}} = "distance,weight,port,";
|
---|
| 661 | push @{$args{vallist}}, (${$args{dist}}, ${$args{weight}}, ${$args{port}});
|
---|
| 662 |
|
---|
| 663 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 664 | # or the intended parent domain for live records.
|
---|
| 665 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
|
---|
| 666 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 667 |
|
---|
[228] | 668 | return ('OK','OK');
|
---|
| 669 | } # done SRV record
|
---|
| 670 |
|
---|
| 671 | # Now the custom types
|
---|
| 672 |
|
---|
[232] | 673 | # A+PTR record. With a very little bit of magic we can also use this sub to validate AAAA+PTR. Whee!
|
---|
[228] | 674 | sub _validate_65280 {
|
---|
[232] | 675 | my $dbh = shift;
|
---|
| 676 |
|
---|
| 677 | my %args = @_;
|
---|
| 678 |
|
---|
| 679 | my $code = 'OK';
|
---|
| 680 | my $msg = 'OK';
|
---|
| 681 |
|
---|
| 682 | if ($args{defrec} eq 'n') {
|
---|
| 683 | # live record; revrec determines whether we validate the PTR or A component first.
|
---|
[233] | 684 |
|
---|
[232] | 685 | if ($args{revrec} eq 'y') {
|
---|
| 686 | ($code,$msg) = _validate_12($dbh, %args);
|
---|
| 687 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 688 |
|
---|
| 689 | # Check if the reqested domain exists. If not, coerce the type down to PTR and warn.
|
---|
| 690 | if (!(${$args{domid}} = _hostparent($dbh, ${$args{host}}))) {
|
---|
[272] | 691 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
| 692 | " as PTR instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
[232] | 693 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
| 694 | $msg = $addmsg if $code eq 'OK';
|
---|
| 695 | ${$args{rectype}} = $reverse_typemap{PTR};
|
---|
| 696 | return ('WARN', $msg);
|
---|
| 697 | }
|
---|
| 698 |
|
---|
[242] | 699 | # Add domain ID to field list and values
|
---|
| 700 | ${$args{fields}} .= "domain_id,";
|
---|
| 701 | push @{$args{vallist}}, ${$args{domid}};
|
---|
| 702 |
|
---|
[232] | 703 | } else {
|
---|
| 704 | ($code,$msg) = _validate_1($dbh, %args) if ${$args{rectype}} == 65280;
|
---|
| 705 | ($code,$msg) = _validate_28($dbh, %args) if ${$args{rectype}} == 65281;
|
---|
| 706 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 707 |
|
---|
| 708 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
| 709 | # work here since we don't *know* which parent to put it in.
|
---|
[233] | 710 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
[232] | 711 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
| 712 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
| 713 | if (!$revid) {
|
---|
[272] | 714 | $msg = "Record ".($args{update} ? 'updated' : 'added')." as ".(${$args{rectype}} == 65280 ? 'A' : 'AAAA').
|
---|
[232] | 715 | " instead of $typemap{${$args{rectype}}}; reverse zone not found for ${$args{val}}";
|
---|
| 716 | ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
| 717 | return ('WARN', $msg);
|
---|
| 718 | }
|
---|
| 719 |
|
---|
| 720 | # Check for duplicate PTRs. Note we don't have to play games with $code and $msg, because
|
---|
| 721 | # by definition there can't be duplicate PTRs if the reverse zone isn't managed here.
|
---|
[272] | 722 | if ($args{update}) {
|
---|
| 723 | # Record update. There should usually be an existing PTR (the record being updated)
|
---|
| 724 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 725 | " WHERE val = ?", undef, (${$args{val}})) };
|
---|
[273] | 726 | if (@ptrs && (!grep /^$args{update}$/, @ptrs)) {
|
---|
[272] | 727 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
|
---|
| 728 | $code = 'WARN';
|
---|
| 729 | }
|
---|
| 730 | } else {
|
---|
| 731 | # New record. Always warn if a PTR exists
|
---|
| 732 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 733 | " WHERE val = ?", undef, (${$args{val}}));
|
---|
| 734 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want"
|
---|
| 735 | if $ptrcount;
|
---|
| 736 | $code = 'WARN' if $ptrcount;
|
---|
[232] | 737 | }
|
---|
| 738 |
|
---|
[272] | 739 | # my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 740 | # " WHERE val = ?", undef, ${$args{val}});
|
---|
| 741 | # if ($ptrcount) {
|
---|
| 742 | # my $curid = $dbh->selectrow_array("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 743 | # " WHERE val = ?
|
---|
| 744 | # $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
|
---|
| 745 | # $code = 'WARN';
|
---|
| 746 | # }
|
---|
| 747 |
|
---|
[232] | 748 | ${$args{fields}} .= "rdns_id,";
|
---|
| 749 | push @{$args{vallist}}, $revid;
|
---|
| 750 | }
|
---|
| 751 |
|
---|
[233] | 752 | } else { # defrec eq 'y'
|
---|
| 753 | if ($args{revrec} eq 'y') {
|
---|
| 754 | ($code,$msg) = _validate_12($dbh, %args);
|
---|
| 755 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 756 | if (${$args{rectype}} == 65280) {
|
---|
| 757 | return ('FAIL',"A+PTR record must be a valid IPv4 address or fragment")
|
---|
| 758 | if ${$args{val}} =~ /:/;
|
---|
[234] | 759 | ${$args{val}} =~ s/^ZONE,/ZONE./; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
[233] | 760 | } elsif (${$args{rectype}} == 65281) {
|
---|
| 761 | return ('FAIL',"AAAA+PTR record must be a valid IPv6 address or fragment")
|
---|
| 762 | if ${$args{val}} =~ /\./;
|
---|
[234] | 763 | ${$args{val}} =~ s/^ZONE,/ZONE::/; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
[233] | 764 | }
|
---|
| 765 | } else {
|
---|
| 766 | # This is easy. I also can't see a real use-case for A/AAAA+PTR in *all* forward
|
---|
| 767 | # domains, since you wouldn't be able to substitute both domain and reverse zone
|
---|
| 768 | # sanely, and you'd end up with guaranteed over-replicated PTR records that would
|
---|
| 769 | # confuse the hell out of pretty much anything that uses them.
|
---|
[234] | 770 | ##fixme: make this a config flag?
|
---|
[233] | 771 | return ('FAIL', "$typemap{${$args{rectype}}} records not allowed in default domains");
|
---|
| 772 | }
|
---|
[232] | 773 | }
|
---|
| 774 |
|
---|
| 775 | return ($code, $msg);
|
---|
[228] | 776 | } # done A+PTR record
|
---|
| 777 |
|
---|
| 778 | # AAAA+PTR record
|
---|
[232] | 779 | # A+PTR above has been magicked to handle AAAA+PTR as well.
|
---|
[228] | 780 | sub _validate_65281 {
|
---|
[232] | 781 | return _validate_65280(@_);
|
---|
[228] | 782 | } # done AAAA+PTR record
|
---|
| 783 |
|
---|
| 784 | # PTR template record
|
---|
| 785 | sub _validate_65282 {
|
---|
[340] | 786 | my $dbh = shift;
|
---|
| 787 |
|
---|
| 788 | my %args = @_;
|
---|
| 789 |
|
---|
| 790 | # we're *this* >.< close to being able to just call _validate_12... unfortunately we can't, quite.
|
---|
| 791 | if ($args{revrec} eq 'y') {
|
---|
| 792 | if ($args{defrec} eq 'n') {
|
---|
| 793 | return ('FAIL', "Template block ${$args{val}} is not within ".revName($dbh, $args{id}))
|
---|
| 794 | unless _ipparent($dbh, $args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
| 795 | ##fixme: warn if $args{val} is not /31 or larger block?
|
---|
| 796 | ${$args{val}} = "$args{addr}";
|
---|
| 797 | } else {
|
---|
| 798 | if (${$args{val}} =~ /\./) {
|
---|
| 799 | # looks like a v4 or fragment
|
---|
| 800 | if (${$args{val}} =~ m|^\d+\.\d+\.\d+\.\d+(?:/\d+)?$|) {
|
---|
| 801 | # woo! a complete IP! validate it and normalize, or fail.
|
---|
| 802 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
| 803 | or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
|
---|
| 804 | ${$args{val}} = "$args{addr}";
|
---|
| 805 | } else {
|
---|
| 806 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
| 807 | }
|
---|
| 808 | } elsif (${$args{val}} =~ /[a-f:]/) {
|
---|
| 809 | # looks like a v6 or fragment
|
---|
| 810 | ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
|
---|
| 811 | if ($args{addr}) {
|
---|
| 812 | if ($args{addr}->addr =~ /^0/) {
|
---|
| 813 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
| 814 | } else {
|
---|
| 815 | ${$args{val}} = "$args{addr}";
|
---|
| 816 | }
|
---|
| 817 | }
|
---|
| 818 | } else {
|
---|
| 819 | # bare number (probably). These could be v4 or v6, so we'll
|
---|
| 820 | # expand on these on creation of a reverse zone.
|
---|
| 821 | ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
|
---|
| 822 | }
|
---|
| 823 | }
|
---|
| 824 | ##fixme: validate %-patterns?
|
---|
| 825 |
|
---|
| 826 | # Unlike single PTR records, there is absolutely no way to sanely support multiple
|
---|
| 827 | # PTR templates for the same block, since they expect to expand to all the individual
|
---|
| 828 | # IPs on export. Nested templates should be supported though.
|
---|
| 829 |
|
---|
| 830 | my @checkvals = (${$args{val}});
|
---|
| 831 | if (${$args{val}} =~ /,/) {
|
---|
| 832 | # push . and :: variants into checkvals if val has ,
|
---|
| 833 | my $tmp;
|
---|
| 834 | ($tmp = ${$args{val}}) =~ s/,/./;
|
---|
| 835 | push @checkvals, $tmp;
|
---|
| 836 | ($tmp = ${$args{val}}) =~ s/,/::/;
|
---|
| 837 | push @checkvals, $tmp;
|
---|
| 838 | }
|
---|
| 839 | ##fixme: this feels wrong still - need to restrict template pseudorecords to One Of Each
|
---|
| 840 | # Per Netblock such that they don't conflict on export
|
---|
| 841 | my $typeck;
|
---|
| 842 | # type 65282 -> ptr template -> look for any of 65282, 65283, 65284
|
---|
| 843 | $typeck = 'type=65283 OR type=65284' if ${$args{rectype}} == 65282;
|
---|
| 844 | # type 65283 -> a+ptr template -> v4 -> look for 65282 or 65283
|
---|
| 845 | $typeck = 'type=65283' if ${$args{rectype}} == 65282;
|
---|
| 846 | # type 65284 -> aaaa+ptr template -> v6 -> look for 65282 or 65284
|
---|
| 847 | $typeck = 'type=65284' if ${$args{rectype}} == 65282;
|
---|
| 848 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ? ".
|
---|
| 849 | "AND (type=65282 OR $typeck)");
|
---|
| 850 | foreach my $checkme (@checkvals) {
|
---|
| 851 | $pcsth->execute($checkme);
|
---|
| 852 | my ($rc) = $pcsth->fetchrow_array;
|
---|
[442] | 853 | return ('FAIL', "Only one template pseudorecord may exist for a given IP block") if $rc > 1;
|
---|
[340] | 854 | }
|
---|
| 855 |
|
---|
| 856 | } else {
|
---|
| 857 | return ('FAIL', "Forward zones cannot contain PTR records");
|
---|
| 858 | }
|
---|
| 859 |
|
---|
[228] | 860 | return ('OK','OK');
|
---|
| 861 | } # done PTR template record
|
---|
| 862 |
|
---|
| 863 | # A+PTR template record
|
---|
| 864 | sub _validate_65283 {
|
---|
[340] | 865 | my $dbh = shift;
|
---|
| 866 |
|
---|
| 867 | my %args = @_;
|
---|
| 868 |
|
---|
| 869 | my ($code,$msg) = ('OK','OK');
|
---|
| 870 |
|
---|
| 871 | ##fixme: need to fiddle things since A+PTR templates are acceptable in live
|
---|
| 872 | # forward zones but not default records
|
---|
| 873 | if ($args{defrec} eq 'n') {
|
---|
| 874 | if ($args{revrec} eq 'n') {
|
---|
| 875 | ($code,$msg) = _validate_1($dbh, %args) if ${$args{rectype}} == 65280;
|
---|
| 876 | ($code,$msg) = _validate_28($dbh, %args) if ${$args{rectype}} == 65281;
|
---|
| 877 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 878 |
|
---|
| 879 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
| 880 | # work here since we don't *know* which parent to put it in.
|
---|
| 881 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
| 882 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
| 883 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
| 884 | # Fail if no match; we can't coerce a PTR-template type down to not include the PTR bit currently.
|
---|
| 885 | if (!$revid) {
|
---|
| 886 | $msg = "Can't ".($args{update} ? 'update' : 'add')." ${$args{host}}/${$args{val}} as ".
|
---|
| 887 | "$typemap{${$args{rectype}}}: reverse zone not found for ${$args{val}}";
|
---|
| 888 | ##fixme: add A template, AAAA template types?
|
---|
| 889 | # ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
| 890 | return ('FAIL', $msg);
|
---|
| 891 | }
|
---|
| 892 |
|
---|
| 893 | # Add reverse zone ID to field list and values
|
---|
| 894 | ${$args{fields}} .= "rdns_id,";
|
---|
| 895 | push @{$args{vallist}}, $revid;
|
---|
| 896 |
|
---|
| 897 | } else {
|
---|
| 898 | return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".revName($dbh, $args{id}))
|
---|
| 899 | unless _ipparent($dbh, $args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
| 900 | ${$args{val}} = "$args{addr}";
|
---|
| 901 |
|
---|
| 902 | if (!(${$args{domid}} = _hostparent($dbh, ${$args{host}}))) {
|
---|
| 903 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
| 904 | " as PTR template instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
| 905 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
| 906 | $msg = $addmsg if $code eq 'OK';
|
---|
| 907 | ${$args{rectype}} = 65282;
|
---|
| 908 | return ('WARN', $msg);
|
---|
| 909 | }
|
---|
| 910 |
|
---|
| 911 | # Add domain ID to field list and values
|
---|
| 912 | ${$args{fields}} .= "domain_id,";
|
---|
| 913 | push @{$args{vallist}}, ${$args{domid}};
|
---|
| 914 | }
|
---|
| 915 |
|
---|
| 916 | } else {
|
---|
| 917 | my ($code,$msg) = _validate_65282($dbh, %args);
|
---|
| 918 | return ($code, $msg) if $code eq 'FAIL';
|
---|
| 919 | # get domain, check against ${$args{name}}
|
---|
| 920 | }
|
---|
| 921 |
|
---|
[228] | 922 | return ('OK','OK');
|
---|
| 923 | } # done AAAA+PTR template record
|
---|
| 924 |
|
---|
| 925 | # AAAA+PTR template record
|
---|
| 926 | sub _validate_65284 {
|
---|
| 927 | return ('OK','OK');
|
---|
| 928 | } # done AAAA+PTR template record
|
---|
| 929 |
|
---|
[342] | 930 | # Delegation record
|
---|
[345] | 931 | # This is essentially a specialized clone of the NS record, primarily useful
|
---|
| 932 | # for delegating IPv4 sub-/24 reverse blocks
|
---|
[342] | 933 | sub _validate_65285 {
|
---|
[345] | 934 | my $dbh = shift;
|
---|
| 935 |
|
---|
| 936 | my %args = @_;
|
---|
| 937 |
|
---|
| 938 | # Almost, but not quite, identical to NS record validation.
|
---|
| 939 |
|
---|
| 940 | # Check that the target of the record is within the parent.
|
---|
| 941 | # Yes, host<->val are mixed up here; can't see a way to avoid it. :(
|
---|
| 942 | if ($args{defrec} eq 'n') {
|
---|
| 943 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
| 944 | if ($args{revrec} eq 'y') {
|
---|
| 945 | my $tmpip = NetAddr::IP->new(${$args{val}});
|
---|
| 946 | my $pname = revName($dbh,$args{id});
|
---|
| 947 | return ('FAIL',"${$args{val}} not within $pname")
|
---|
| 948 | unless _ipparent($dbh, $args{defrec}, $args{revrec}, $args{val}, $args{id}, \$tmpip);
|
---|
| 949 | # Normalize
|
---|
| 950 | ${$args{val}} = "$tmpip";
|
---|
| 951 | } else {
|
---|
| 952 | my $pname = domainName($dbh,$args{id});
|
---|
| 953 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 954 | }
|
---|
| 955 | } else {
|
---|
| 956 | return ('FAIL',"Delegation records are not permitted in default record sets");
|
---|
| 957 | }
|
---|
[342] | 958 | return ('OK','OK');
|
---|
| 959 | }
|
---|
[228] | 960 |
|
---|
[342] | 961 |
|
---|
[265] | 962 | ##
|
---|
| 963 | ## Record data substitution subs
|
---|
| 964 | ##
|
---|
[228] | 965 |
|
---|
[298] | 966 | # Replace ZONE in hostname, or create (most of) the actual proper zone name
|
---|
[265] | 967 | sub _ZONE {
|
---|
| 968 | my $zone = shift;
|
---|
| 969 | my $string = shift;
|
---|
| 970 | my $fr = shift || 'f'; # flag for forward/reverse order? nb: ignored for IP
|
---|
[298] | 971 | my $sep = shift || '-'; # Separator character - unlikely we'll ever need more than . or -
|
---|
[265] | 972 |
|
---|
[298] | 973 | my $prefix;
|
---|
[265] | 974 |
|
---|
| 975 | $string =~ s/,/./ if !$zone->{isv6};
|
---|
| 976 | $string =~ s/,/::/ if $zone->{isv6};
|
---|
| 977 |
|
---|
[298] | 978 | # Subbing ZONE in the host. We need to properly ID the netblock range
|
---|
| 979 | # The subbed text should have "network IP with trailing zeros stripped" for
|
---|
| 980 | # blocks lined up on octet (for v4) or hex-quad (for v6) boundaries
|
---|
| 981 | # For blocks that do NOT line up on these boundaries, we take the most
|
---|
| 982 | # significant octet or 16-bit chunk of the "broadcast" IP and append it
|
---|
| 983 | # after a double-dash
|
---|
| 984 | # ie:
|
---|
| 985 | # 8.0.0.0/6 -> 8.0.0.0 -> 11.255.255.255; sub should be 8--11
|
---|
| 986 | # 10.0.0.0/12 -> 10.0.0.0 -> 10.0.0.0 -> 10.15.255.255; sub should be 10-0--15
|
---|
| 987 | # 192.168.4.0/22 -> 192.168.4.0 -> 192.168.7.255; sub should be 192-168-4--7
|
---|
| 988 | # 192.168.0.8/29 -> 192.168.0.8 -> 192.168.0.15; sub should be 192-168-0-8--15
|
---|
| 989 | # Similar for v6
|
---|
[265] | 990 |
|
---|
[298] | 991 | if (!$zone->{isv6}) { # IPv4
|
---|
| 992 |
|
---|
| 993 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
| 994 | # a funky subnet that had host bits set.
|
---|
| 995 | my $bc = $zone->broadcast->addr;
|
---|
| 996 |
|
---|
| 997 | if ($zone->masklen > 24) {
|
---|
| 998 | $bc =~ s/^\d+\.\d+\.\d+\.//;
|
---|
| 999 | } elsif ($zone->masklen > 16) {
|
---|
| 1000 | $prefix =~ s/\.0$//;
|
---|
| 1001 | $bc =~ s/^\d+\.\d+\.//;
|
---|
| 1002 | } elsif ($zone->masklen > 8) {
|
---|
| 1003 | $bc =~ s/^\d+\.//;
|
---|
| 1004 | $prefix =~ s/\.0\.0$//;
|
---|
| 1005 | } else {
|
---|
| 1006 | $prefix =~ s/\.0\.0\.0$//;
|
---|
| 1007 | }
|
---|
| 1008 | if ($zone->masklen % 8) {
|
---|
| 1009 | $bc =~ s/(\.255)+$//;
|
---|
| 1010 | $prefix .= "--$bc"; #"--".zone->masklen; # use range or mask length?
|
---|
| 1011 | }
|
---|
| 1012 | if ($fr eq 'f') {
|
---|
| 1013 | $prefix =~ s/\.+/$sep/g;
|
---|
| 1014 | } else {
|
---|
| 1015 | $prefix = join($sep, reverse(split(/\./, $prefix)));
|
---|
| 1016 | }
|
---|
| 1017 |
|
---|
| 1018 | } else { # IPv6
|
---|
| 1019 |
|
---|
| 1020 | if ($fr eq 'f') {
|
---|
| 1021 |
|
---|
| 1022 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
| 1023 | # a funky subnet that had host bits set.
|
---|
[265] | 1024 | my $bc = $zone->broadcast->addr;
|
---|
| 1025 | if (($zone->masklen % 16) != 0) {
|
---|
[298] | 1026 | # Strip trailing :0 off $prefix, and :ffff off the broadcast IP
|
---|
| 1027 | for (my $i=0; $i<(7-int($zone->masklen / 16)); $i++) {
|
---|
| 1028 | $prefix =~ s/:0$//;
|
---|
| 1029 | $bc =~ s/:ffff$//;
|
---|
| 1030 | }
|
---|
| 1031 | # Strip the leading 16-bit chunks off the front of the broadcast IP
|
---|
| 1032 | $bc =~ s/^([a-f0-9]+:)+//;
|
---|
| 1033 | # Append the remaining 16-bit chunk to the prefix after "--"
|
---|
| 1034 | $prefix .= "--$bc";
|
---|
[265] | 1035 | } else {
|
---|
[298] | 1036 | # Strip off :0 from the end until we reach the netblock length.
|
---|
| 1037 | for (my $i=0; $i<(8-$zone->masklen / 16); $i++) {
|
---|
[265] | 1038 | $prefix =~ s/:0$//;
|
---|
[298] | 1039 | }
|
---|
[265] | 1040 | }
|
---|
[298] | 1041 | # Actually deal with the separator
|
---|
| 1042 | $prefix =~ s/:/$sep/g;
|
---|
| 1043 |
|
---|
| 1044 | } else { # $fr eq 'f'
|
---|
| 1045 |
|
---|
| 1046 | $prefix = $zone->network->full; # Just In Case someone managed to slip in
|
---|
| 1047 | # a funky subnet that had host bits set.
|
---|
| 1048 | my $bc = $zone->broadcast->full;
|
---|
| 1049 | $prefix =~ s/://g; # clean these out since they're not spaced right for this case
|
---|
| 1050 | $bc =~ s/://g;
|
---|
| 1051 | # Strip trailing 0 off $prefix, and f off the broadcast IP, to match the mask length
|
---|
| 1052 | for (my $i=0; $i<(31-int($zone->masklen / 4)); $i++) {
|
---|
| 1053 | $prefix =~ s/0$//;
|
---|
| 1054 | $bc =~ s/f$//;
|
---|
| 1055 | }
|
---|
| 1056 | # Split and reverse the order of the nibbles in the network/broadcast IPs
|
---|
[332] | 1057 | # trim another 0 for nibble-aligned blocks first, but only if we really have a block, not an IP
|
---|
| 1058 | $prefix =~ s/0$// if $zone->masklen % 4 == 0 && $zone->masklen != 128;
|
---|
[298] | 1059 | my @nbits = reverse split //, $prefix;
|
---|
| 1060 | my @bbits = reverse split //, $bc;
|
---|
| 1061 | # Handle the sub-nibble case. Eww. I feel dirty supporting this...
|
---|
| 1062 | $nbits[0] = "$nbits[0]-$bbits[0]" if ($zone->masklen % 4) != 0;
|
---|
| 1063 | # Glue it back together
|
---|
| 1064 | $prefix = join($sep, @nbits);
|
---|
| 1065 |
|
---|
| 1066 | } # $fr ne 'f'
|
---|
| 1067 |
|
---|
| 1068 | } # $zone->{isv6}
|
---|
| 1069 |
|
---|
| 1070 | # Do the substitution, finally
|
---|
| 1071 | $string =~ s/ZONE/$prefix/;
|
---|
| 1072 | $string =~ s/--/-/ if $sep ne '-'; # - as separator needs extra help for sub-octet v4 netblocks
|
---|
| 1073 | return $string;
|
---|
| 1074 | } # done _ZONE()
|
---|
| 1075 |
|
---|
| 1076 | # Not quite a substitution sub, but placed here as it's basically the inverse of above;
|
---|
| 1077 | # given the .arpa zone name, return the CIDR netblock the zone is for.
|
---|
[304] | 1078 | # Supports v4 non-octet/non-classful netblocks as per the method outlined in the Grasshopper Book (2nd Ed p217-218)
|
---|
[298] | 1079 | # Does NOT support non-quad v6 netblocks via the same scheme; it shouldn't ever be necessary.
|
---|
| 1080 | # Takes a nominal .arpa zone name, returns a success code and NetAddr::IP, or a fail code and message
|
---|
| 1081 | sub _zone2cidr {
|
---|
| 1082 | my $zone = shift;
|
---|
| 1083 |
|
---|
| 1084 | my $cidr;
|
---|
[301] | 1085 | my $tmpcidr;
|
---|
| 1086 | my $warnmsg = '';
|
---|
[298] | 1087 |
|
---|
| 1088 | if ($zone =~ /\.in-addr\.arpa\.?$/) {
|
---|
| 1089 | # v4 revzone, formal zone name type
|
---|
| 1090 | my $tmpzone = $zone;
|
---|
| 1091 | $tmpzone =~ s/\.in-addr\.arpa\.?//;
|
---|
[301] | 1092 | return ('FAIL', "Non-numerics in apparent IPv4 reverse zone name") if $tmpzone !~ /^(?:\d+-)?[\d\.]+$/;
|
---|
[298] | 1093 |
|
---|
| 1094 | # Snag the octet pieces
|
---|
| 1095 | my @octs = split /\./, $tmpzone;
|
---|
| 1096 |
|
---|
| 1097 | # Map result of a range manipulation to a mask length change. Cheaper than finding the 2-root of $octets[0]+1.
|
---|
[304] | 1098 | # Note we will not support /31 blocks, mostly due to issues telling "24-31" -> .24/29 apart from
|
---|
| 1099 | # "24-31" -> .24/31", with a litte bit of "/31 is icky".
|
---|
| 1100 | my %maskmap = ( 3 => 2, 7 => 3, 15 => 4, 31 => 5, 63 => 6, 127 => 7,
|
---|
| 1101 | 30 => 2, 29 => 3, 28 => 4, 27 => 5, 26 => 6, 25 => 7
|
---|
| 1102 | );
|
---|
[298] | 1103 |
|
---|
| 1104 | # Handle "range" blocks, eg, 80-83.168.192.in-addr.arpa (192.168.80.0/22)
|
---|
| 1105 | # Need to take the size of the range to offset the basic octet-based mask length,
|
---|
| 1106 | # and make sure the first number in the range gets used as the network address for the block
|
---|
[304] | 1107 | # Alternate form: The second number is actually the real netmask, not the end of the range.
|
---|
[298] | 1108 | my $masklen = 0;
|
---|
[307] | 1109 | if ($octs[0] =~ /^((\d+)-(\d+))$/) { # take the range...
|
---|
| 1110 | if (24 < $3 && $3 < 31) {
|
---|
[304] | 1111 | # we have a real netmask
|
---|
[307] | 1112 | $masklen = -$maskmap{$3};
|
---|
[304] | 1113 | } else {
|
---|
| 1114 | # we have a range. NB: only real CIDR ranges are supported
|
---|
[307] | 1115 | $masklen -= $maskmap{-(eval $1)}; # find the mask base...
|
---|
[304] | 1116 | }
|
---|
[307] | 1117 | $octs[0] = $2; # set the base octet of the range...
|
---|
[265] | 1118 | }
|
---|
[298] | 1119 | @octs = reverse @octs; # We can reverse the octet pieces now that we've extracted and munged any ranges
|
---|
[265] | 1120 |
|
---|
[304] | 1121 | # arguably we should only allow sub-octet range/mask in-addr.arpa
|
---|
| 1122 | # specifications in the least significant octet, but the code is
|
---|
| 1123 | # simpler if we deal with sub-octet delegations at any level.
|
---|
| 1124 |
|
---|
[298] | 1125 | # Now we find the "true" mask with the aid of the "base" calculated above
|
---|
| 1126 | if ($#octs == 0) {
|
---|
| 1127 | $masklen += 8;
|
---|
| 1128 | $tmpcidr = "$octs[0].0.0.0/$masklen"; # really hope we don't see one of these very often.
|
---|
| 1129 | } elsif ($#octs == 1) {
|
---|
| 1130 | $masklen += 16;
|
---|
| 1131 | $tmpcidr = "$octs[0].$octs[1].0.0/$masklen";
|
---|
| 1132 | } elsif ($#octs == 2) {
|
---|
| 1133 | $masklen += 24;
|
---|
| 1134 | $tmpcidr = "$octs[0].$octs[1].$octs[2].0/$masklen";
|
---|
[265] | 1135 | } else {
|
---|
[298] | 1136 | $masklen += 32;
|
---|
| 1137 | $tmpcidr = "$octs[0].$octs[1].$octs[2].$octs[3]/$masklen";
|
---|
[265] | 1138 | }
|
---|
| 1139 |
|
---|
[298] | 1140 | } elsif ($zone =~ /\.ip6\.arpa$/) {
|
---|
| 1141 | # v6 revzone, formal zone name type
|
---|
| 1142 | my $tmpzone = $zone;
|
---|
| 1143 | $tmpzone =~ s/\.ip6\.arpa\.?//;
|
---|
[301] | 1144 | ##fixme: if-n-when we decide we can support sub-nibble v6 zone names, we'll need to change this segment
|
---|
| 1145 | return ('FAIL', "Non-hexadecimals in apparent IPv6 reverse zone name") if $tmpzone !~ /^[a-fA-F\d\.]+$/;
|
---|
[298] | 1146 | my @quads = reverse(split(/\./, $tmpzone));
|
---|
| 1147 | $warnmsg .= "Apparent sub-/64 IPv6 reverse zone\n" if $#quads > 15;
|
---|
| 1148 | my $nc;
|
---|
| 1149 | foreach (@quads) {
|
---|
[301] | 1150 | $tmpcidr .= $_;
|
---|
| 1151 | $tmpcidr .= ":" if ++$nc % 4 == 0;
|
---|
[298] | 1152 | }
|
---|
| 1153 | my $nq = 1 if $nc % 4 != 0;
|
---|
| 1154 | my $mask = $nc * 4; # need to do this here because we probably increment it below
|
---|
| 1155 | while ($nc++ % 4 != 0) {
|
---|
[301] | 1156 | $tmpcidr .= "0";
|
---|
[298] | 1157 | }
|
---|
[301] | 1158 | $tmpcidr .= ($nq ? '::' : ':')."/$mask";
|
---|
[298] | 1159 | }
|
---|
[301] | 1160 |
|
---|
| 1161 | # Just to be sure, use NetAddr::IP to validate. Saves a lot of nasty regex watching for valid octet values.
|
---|
| 1162 | return ('FAIL', "Invalid zone $zone (apparent netblock $tmpcidr)")
|
---|
| 1163 | unless $cidr = NetAddr::IP->new($tmpcidr);
|
---|
| 1164 |
|
---|
| 1165 | if ($warnmsg) {
|
---|
| 1166 | $errstr = $warnmsg;
|
---|
| 1167 | return ('WARN', $cidr);
|
---|
| 1168 | }
|
---|
| 1169 | return ('OK', $cidr);
|
---|
[298] | 1170 | } # done _zone2cidr()
|
---|
[265] | 1171 |
|
---|
[337] | 1172 | # Record template %-parameter expansion, IPv4. Note that IPv6 doesn't
|
---|
| 1173 | # really have a sane way to handle this type of expansion at the moment
|
---|
| 1174 | # due to the size of the address space.
|
---|
| 1175 | # Takes a reference to a template string to be expanded, and an IP to use in the replacement.
|
---|
| 1176 | sub _template4_expand {
|
---|
| 1177 | my $tmpl = shift;
|
---|
| 1178 | my $ip = shift;
|
---|
[298] | 1179 |
|
---|
[337] | 1180 | my @ipparts = split /\./, $ip;
|
---|
| 1181 | my @iphex;
|
---|
| 1182 | my @ippad;
|
---|
| 1183 | for (@ipparts) {
|
---|
| 1184 | push @iphex, sprintf("%x", $_);
|
---|
[443] | 1185 | push @ippad, sprintf("%0.3u", $_);
|
---|
[337] | 1186 | }
|
---|
| 1187 |
|
---|
| 1188 | # IP substitutions in template records:
|
---|
| 1189 | #major patterns:
|
---|
| 1190 | #dashed IP, forward and reverse
|
---|
| 1191 | #dotted IP, forward and reverse (even if forward is... dumb)
|
---|
| 1192 | # -> %r for reverse, %i for forward, leading - or . to indicate separator, defaults to -
|
---|
| 1193 | # %r or %-r => %4d-%3d-%2d-%1d
|
---|
| 1194 | # %.r => %4d.%3d.%2d.%1d
|
---|
| 1195 | # %i or %-i => %1d-%2d-%3d-%4d
|
---|
| 1196 | # %.i => %1d.%2d.%3d.%4d
|
---|
| 1197 | $$tmpl =~ s/\%r/\%4d-\%3d-\%2d-\%1d/g;
|
---|
| 1198 | $$tmpl =~ s/\%([-.])r/\%4d$1\%3d$1\%2d$1\%1d/g;
|
---|
| 1199 | $$tmpl =~ s/\%i/\%1d-\%2d-\%3d-\%4d/g;
|
---|
| 1200 | $$tmpl =~ s/\%([-.])i/\%1d$1\%2d$1\%3d$1\%4d/g;
|
---|
| 1201 |
|
---|
| 1202 | #hex-coded IP
|
---|
| 1203 | # %h
|
---|
| 1204 | $$tmpl =~ s/\%h/$iphex[0]$iphex[1]$iphex[2]$iphex[3]/g;
|
---|
| 1205 |
|
---|
| 1206 | #IP as decimal-coded 32-bit value
|
---|
| 1207 | # %d
|
---|
| 1208 | my $iptmp = $ipparts[0]*256*256*256 + $ipparts[1]*256*256 + $ipparts[2]*256 + $ipparts[3];
|
---|
| 1209 | $$tmpl =~ s/\%d/$iptmp/g;
|
---|
| 1210 |
|
---|
| 1211 | #minor patterns (per-octet)
|
---|
| 1212 | # %[1234][dh0]
|
---|
| 1213 | #octet
|
---|
| 1214 | #hex-coded octet
|
---|
| 1215 | #0-padded octet
|
---|
| 1216 | $$tmpl =~ s/\%([1234])d/$ipparts[$1-1]/g;
|
---|
| 1217 | $$tmpl =~ s/\%([1234])h/$iphex[$1-1]/g;
|
---|
[443] | 1218 | $$tmpl =~ s/\%([1234])0/$ippad[$1-1]/g;
|
---|
[337] | 1219 | } # _template4_expand()
|
---|
| 1220 |
|
---|
| 1221 |
|
---|
[228] | 1222 | ##
|
---|
[2] | 1223 | ## Initialization and cleanup subs
|
---|
| 1224 | ##
|
---|
| 1225 |
|
---|
[128] | 1226 | ## DNSDB::loadConfig()
|
---|
| 1227 | # Load the minimum required initial state (DB connect info) from a config file
|
---|
| 1228 | # Load misc other bits while we're at it.
|
---|
[400] | 1229 | # Takes an optional hash that may contain:
|
---|
| 1230 | # - basename and config path to look for
|
---|
[128] | 1231 | # Populates the %config and %def hashes
|
---|
| 1232 | sub loadConfig {
|
---|
[400] | 1233 | my %args = @_;
|
---|
[465] | 1234 | $args{configfile} = '' if !$args{configfile};
|
---|
[128] | 1235 |
|
---|
[465] | 1236 | ##fixme this is *intended* to load a system-default config template, and allow
|
---|
| 1237 | # overriding on a per-tool or per-web-UI-instance basis with a secondary config
|
---|
| 1238 | # file. The "default" config file can't be deleted in the current form.
|
---|
| 1239 |
|
---|
[128] | 1240 | my $deferr = ''; # place to put error from default config file in case we can't find either one
|
---|
| 1241 |
|
---|
[219] | 1242 | my $configroot = "/etc/dnsdb"; ##CFG_LEAF##
|
---|
[465] | 1243 | $configroot = '' if $args{configfile} =~ m|^/|; # allow passed siteconfig to specify an arbitrary absolute path
|
---|
| 1244 | $args{configfile} .= ".conf" if $args{configfile} !~ /\.conf$/;
|
---|
[128] | 1245 | my $defconfig = "$configroot/dnsdb.conf";
|
---|
[465] | 1246 | my $siteconfig = "$configroot/$args{configfile}";
|
---|
[128] | 1247 |
|
---|
| 1248 | # System defaults
|
---|
[465] | 1249 | __cfgload("$defconfig") or $deferr = $errstr;
|
---|
[128] | 1250 |
|
---|
[131] | 1251 | # Per-site-ish settings.
|
---|
[465] | 1252 | if ($args{configfile} ne '.conf') {
|
---|
| 1253 | unless (__cfgload("$siteconfig")) {
|
---|
[131] | 1254 | $errstr = ($deferr ? "Error opening default config file $defconfig: $deferr\n" : '').
|
---|
[128] | 1255 | "Error opening site config file $siteconfig";
|
---|
[131] | 1256 | return;
|
---|
| 1257 | }
|
---|
[128] | 1258 | }
|
---|
| 1259 |
|
---|
[195] | 1260 | # Munge log_failures.
|
---|
| 1261 | if ($config{log_failures} ne '1' && $config{log_failures} ne '0') {
|
---|
| 1262 | # true/false, on/off, yes/no all valid.
|
---|
| 1263 | if ($config{log_failures} =~ /^(?:true|false|on|off|yes|no)$/) {
|
---|
| 1264 | if ($config{log_failures} =~ /(?:true|on|yes)/) {
|
---|
| 1265 | $config{log_failures} = 1;
|
---|
| 1266 | } else {
|
---|
| 1267 | $config{log_failures} = 0;
|
---|
| 1268 | }
|
---|
| 1269 | } else {
|
---|
| 1270 | $errstr = "Bad log_failures setting $config{log_failures}";
|
---|
| 1271 | $config{log_failures} = 1;
|
---|
| 1272 | # Bad setting shouldn't be fatal.
|
---|
| 1273 | # return 2;
|
---|
| 1274 | }
|
---|
| 1275 | }
|
---|
| 1276 |
|
---|
[128] | 1277 | # All good, clear the error and go home.
|
---|
| 1278 | $errstr = '';
|
---|
| 1279 | return 1;
|
---|
| 1280 | } # end loadConfig()
|
---|
| 1281 |
|
---|
| 1282 |
|
---|
| 1283 | ## DNSDB::__cfgload()
|
---|
| 1284 | # Private sub to parse a config file and load it into %config
|
---|
[465] | 1285 | # Takes a filename
|
---|
[128] | 1286 | sub __cfgload {
|
---|
| 1287 | $errstr = '';
|
---|
| 1288 | my $cfgfile = shift;
|
---|
[131] | 1289 |
|
---|
[128] | 1290 | if (open CFG, "<$cfgfile") {
|
---|
| 1291 | while (<CFG>) {
|
---|
| 1292 | chomp;
|
---|
| 1293 | s/^\s*//;
|
---|
| 1294 | next if /^#/;
|
---|
| 1295 | next if /^$/;
|
---|
| 1296 | # hmm. more complex bits in this file might require [heading] headers, maybe?
|
---|
| 1297 | # $mode = $1 if /^\[(a-z)+]/;
|
---|
| 1298 | # DB connect info
|
---|
| 1299 | $config{dbname} = $1 if /^dbname\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1300 | $config{dbuser} = $1 if /^dbuser\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1301 | $config{dbpass} = $1 if /^dbpass\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1302 | $config{dbhost} = $1 if /^dbhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1303 | # SOA defaults
|
---|
| 1304 | $def{contact} = $1 if /^contact\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1305 | $def{prins} = $1 if /^prins\s*=\s*([a-z0-9_.-]+)/i;
|
---|
[201] | 1306 | $def{soattl} = $1 if /^soattl\s*=\s*(\d+)/i;
|
---|
| 1307 | $def{refresh} = $1 if /^refresh\s*=\s*(\d+)/i;
|
---|
| 1308 | $def{retry} = $1 if /^retry\s*=\s*(\d+)/i;
|
---|
| 1309 | $def{expire} = $1 if /^expire\s*=\s*(\d+)/i;
|
---|
| 1310 | $def{minttl} = $1 if /^minttl\s*=\s*(\d+)/i;
|
---|
| 1311 | $def{ttl} = $1 if /^ttl\s*=\s*(\d+)/i;
|
---|
[128] | 1312 | # Mail settings
|
---|
| 1313 | $config{mailhost} = $1 if /^mailhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
[198] | 1314 | $config{mailnotify} = $1 if /^mailnotify\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
| 1315 | $config{mailsender} = $1 if /^mailsender\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
[128] | 1316 | $config{mailname} = $1 if /^mailname\s*=\s*([a-z0-9\s_.-]+)/i;
|
---|
[195] | 1317 | $config{orgname} = $1 if /^orgname\s*=\s*([a-z0-9\s_.,'-]+)/i;
|
---|
| 1318 | $config{domain} = $1 if /^domain\s*=\s*([a-z0-9_.-]+)/i;
|
---|
[163] | 1319 | # session - note this is fed directly to CGI::Session
|
---|
[216] | 1320 | $config{timeout} = $1 if /^[tT][iI][mM][eE][oO][uU][tT]\s*=\s*(\d+[smhdwMy]?)/;
|
---|
| 1321 | $config{sessiondir} = $1 if m{^sessiondir\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
[201] | 1322 | # misc
|
---|
[195] | 1323 | $config{log_failures} = $1 if /^log_failures\s*=\s*([a-z01]+)/i;
|
---|
[201] | 1324 | $config{perpage} = $1 if /^perpage\s*=\s*(\d+)/i;
|
---|
[368] | 1325 | $config{exportcache} = $1 if m{^exportcache\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
[400] | 1326 | # RPC options
|
---|
[465] | 1327 | $config{rpcmode} = $1 if /^rpc_mode\s*=\s*(socket|HTTP|XMLRPC)\s*$/i;
|
---|
| 1328 | if (my ($tmp) = /^rpc_iplist\s*=\s*(.+)/i) {
|
---|
| 1329 | my @ips = split /[,\s]+/, $tmp;
|
---|
| 1330 | my $rpcsys = shift @ips;
|
---|
| 1331 | push @{$config{rpcacl}{$rpcsys}}, @ips;
|
---|
[400] | 1332 | }
|
---|
[128] | 1333 | }
|
---|
| 1334 | close CFG;
|
---|
| 1335 | } else {
|
---|
| 1336 | $errstr = $!;
|
---|
| 1337 | return;
|
---|
| 1338 | }
|
---|
| 1339 | return 1;
|
---|
| 1340 | } # end __cfgload()
|
---|
| 1341 |
|
---|
| 1342 |
|
---|
[2] | 1343 | ## DNSDB::connectDB()
|
---|
| 1344 | # Creates connection to DNS database.
|
---|
| 1345 | # Requires the database name, username, and password.
|
---|
[465] | 1346 | # Returns a handle to the db or undef on failure.
|
---|
[2] | 1347 | # Set up for a PostgreSQL db; could be any transactional DBMS with the
|
---|
| 1348 | # right changes.
|
---|
[465] | 1349 | # Called by new(); not intended to be called publicly.
|
---|
[2] | 1350 | sub connectDB {
|
---|
| 1351 | $errstr = '';
|
---|
[15] | 1352 | my $dbname = shift;
|
---|
| 1353 | my $user = shift;
|
---|
| 1354 | my $pass = shift;
|
---|
[2] | 1355 | my $dbh;
|
---|
| 1356 | my $DSN = "DBI:Pg:dbname=$dbname";
|
---|
| 1357 |
|
---|
| 1358 | my $host = shift;
|
---|
| 1359 | $DSN .= ";host=$host" if $host;
|
---|
| 1360 |
|
---|
| 1361 | # Note that we want to autocommit by default, and we will turn it off locally as necessary.
|
---|
| 1362 | # We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
|
---|
| 1363 | $dbh = DBI->connect($DSN, $user, $pass, {
|
---|
| 1364 | AutoCommit => 1,
|
---|
| 1365 | PrintError => 0
|
---|
[465] | 1366 | });
|
---|
| 1367 | if (!$dbh) {
|
---|
| 1368 | $errstr = $DBI::errstr;
|
---|
| 1369 | return;
|
---|
| 1370 | }
|
---|
| 1371 | #) if(!$dbh);
|
---|
[2] | 1372 |
|
---|
[465] | 1373 | local $dbh->{RaiseError} = 1;
|
---|
| 1374 |
|
---|
| 1375 | eval {
|
---|
[212] | 1376 | ##fixme: initialize the DB if we can't find the table (since, by definition, there's
|
---|
| 1377 | # nothing there if we can't select from it...)
|
---|
[465] | 1378 | my $tblsth = $dbh->prepare("SELECT count(*) FROM pg_catalog.pg_class WHERE relkind='r' AND relname=?");
|
---|
| 1379 | my ($tblcount) = $dbh->selectrow_array($tblsth, undef, ('misc'));
|
---|
| 1380 | # return (undef,$DBI::errstr) if $dbh->err;
|
---|
[212] | 1381 |
|
---|
| 1382 | #if ($tblcount == 0) {
|
---|
| 1383 | # # create tables one at a time, checking for each.
|
---|
| 1384 | # return (undef, "check table misc missing");
|
---|
| 1385 | #}
|
---|
| 1386 |
|
---|
| 1387 | # Return here if we can't select.
|
---|
| 1388 | # This should retrieve the dbversion key.
|
---|
[465] | 1389 | my $sth = $dbh->prepare("SELECT key,value FROM misc WHERE misc_id=1");
|
---|
| 1390 | $sth->execute();
|
---|
| 1391 | # return (undef,$DBI::errstr) if ($sth->err);
|
---|
[2] | 1392 |
|
---|
[212] | 1393 | ##fixme: do stuff to the DB on version mismatch
|
---|
| 1394 | # x.y series should upgrade on $DNSDB::VERSION > misc(key=>version)
|
---|
| 1395 | # DB should be downward-compatible; column defaults should give sane (if possibly
|
---|
| 1396 | # useless-and-needs-help) values in columns an older software stack doesn't know about.
|
---|
| 1397 |
|
---|
[2] | 1398 | # See if the select returned anything (or null data). This should
|
---|
| 1399 | # succeed if the select executed, but...
|
---|
[465] | 1400 | $sth->fetchrow();
|
---|
| 1401 | # return (undef,$DBI::errstr) if ($sth->err);
|
---|
[2] | 1402 |
|
---|
[465] | 1403 | $sth->finish;
|
---|
[2] | 1404 |
|
---|
[465] | 1405 | }; # wrapped DB checks
|
---|
| 1406 | if ($@) {
|
---|
| 1407 | $errstr = $@;
|
---|
| 1408 | return;
|
---|
| 1409 | }
|
---|
| 1410 |
|
---|
[2] | 1411 | # If we get here, we should be OK.
|
---|
[465] | 1412 | return $dbh;
|
---|
[2] | 1413 | } # end connectDB
|
---|
| 1414 |
|
---|
| 1415 |
|
---|
| 1416 | ## DNSDB::finish()
|
---|
| 1417 | # Cleans up after database handles and so on.
|
---|
| 1418 | # Requires a database handle
|
---|
| 1419 | sub finish {
|
---|
[465] | 1420 | my $self = shift;
|
---|
| 1421 | $self->{dbh}->disconnect;
|
---|
[2] | 1422 | } # end finish
|
---|
| 1423 |
|
---|
| 1424 |
|
---|
| 1425 | ## DNSDB::initGlobals()
|
---|
| 1426 | # Initialize global variables
|
---|
| 1427 | # NB: this does NOT include web-specific session variables!
|
---|
| 1428 | sub initGlobals {
|
---|
[465] | 1429 | my $self = shift;
|
---|
| 1430 | my $dbh = $self->{dbh};
|
---|
[2] | 1431 |
|
---|
[208] | 1432 | # load record types from database
|
---|
[228] | 1433 | my $sth = $dbh->prepare("SELECT val,name,stdflag FROM rectypes");
|
---|
[2] | 1434 | $sth->execute;
|
---|
[228] | 1435 | while (my ($recval,$recname,$stdflag) = $sth->fetchrow_array()) {
|
---|
[2] | 1436 | $typemap{$recval} = $recname;
|
---|
| 1437 | $reverse_typemap{$recname} = $recval;
|
---|
[228] | 1438 | # now we fill the record validation function hash
|
---|
| 1439 | if ($stdflag < 5) {
|
---|
| 1440 | my $fn = "_validate_$recval";
|
---|
| 1441 | $validators{$recval} = \&$fn;
|
---|
| 1442 | } else {
|
---|
| 1443 | my $fn = "sub { return ('FAIL','Type $recval ($recname) not supported'); }";
|
---|
| 1444 | $validators{$recval} = eval $fn;
|
---|
| 1445 | }
|
---|
[2] | 1446 | }
|
---|
| 1447 | } # end initGlobals
|
---|
| 1448 |
|
---|
| 1449 |
|
---|
[401] | 1450 | ## DNSDB::initRPC()
|
---|
| 1451 | # Takes a database handle, remote username, and remote fullname.
|
---|
| 1452 | # Sets up the RPC logging-pseudouser if needed.
|
---|
| 1453 | # Sets the %userdata hash for logging.
|
---|
| 1454 | # Returns undef on failure
|
---|
| 1455 | sub initRPC {
|
---|
| 1456 | my $dbh = shift;
|
---|
| 1457 | my %args = @_;
|
---|
| 1458 |
|
---|
| 1459 | return if !$args{username};
|
---|
| 1460 | return if !$args{fullname};
|
---|
| 1461 |
|
---|
[406] | 1462 | $args{username} = "$args{username}/$args{rpcsys}";
|
---|
| 1463 |
|
---|
| 1464 | my $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
|
---|
[404] | 1465 | " FROM users WHERE username=?", undef, ($args{username}) );
|
---|
[406] | 1466 | if (!$tmpuser) {
|
---|
[401] | 1467 | $dbh->do("INSERT INTO users (username,password,firstname,type) VALUES (?,'RPC',?,'R')", undef,
|
---|
| 1468 | ($args{username}, $args{fullname}) );
|
---|
[406] | 1469 | $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
|
---|
[404] | 1470 | " FROM users WHERE username=?", undef, ($args{username}) );
|
---|
[401] | 1471 | }
|
---|
[404] | 1472 | %userdata = %{$tmpuser};
|
---|
[410] | 1473 | $userdata{lastname} = '' if !$userdata{lastname};
|
---|
[404] | 1474 | $userdata{fullname} = "$userdata{firstname} $userdata{lastname} ($args{rpcsys})";
|
---|
[406] | 1475 | return 1 if $tmpuser;
|
---|
[401] | 1476 | } # end initRPC()
|
---|
| 1477 |
|
---|
| 1478 |
|
---|
[278] | 1479 | ## DNSDB::login()
|
---|
| 1480 | # Takes a database handle, username and password
|
---|
[316] | 1481 | # Returns a userdata hash (UID, GID, username, fullname parts) if username exists,
|
---|
| 1482 | # password matches the one on file, and account is not disabled
|
---|
[278] | 1483 | # Returns undef otherwise
|
---|
| 1484 | sub login {
|
---|
| 1485 | my $dbh = shift;
|
---|
| 1486 | my $user = shift;
|
---|
| 1487 | my $pass = shift;
|
---|
| 1488 |
|
---|
[316] | 1489 | my $userinfo = $dbh->selectrow_hashref("SELECT user_id,group_id,password,firstname,lastname,status".
|
---|
| 1490 | " FROM users WHERE username=?",
|
---|
[279] | 1491 | undef, ($user) );
|
---|
| 1492 | return if !$userinfo;
|
---|
[316] | 1493 | return if !$userinfo->{status};
|
---|
[278] | 1494 |
|
---|
[279] | 1495 | if ($userinfo->{password} =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
|
---|
[278] | 1496 | # native passwords (crypt-md5)
|
---|
[279] | 1497 | return if $userinfo->{password} ne unix_md5_crypt($pass,$1);
|
---|
| 1498 | } elsif ($userinfo->{password} =~ /^[0-9a-f]{32}$/) {
|
---|
[278] | 1499 | # VegaDNS import (hex-coded MD5)
|
---|
[279] | 1500 | return if $userinfo->{password} ne md5_hex($pass);
|
---|
[278] | 1501 | } else {
|
---|
| 1502 | # plaintext (convenient now and then)
|
---|
[279] | 1503 | return if $userinfo->{password} ne $pass;
|
---|
[278] | 1504 | }
|
---|
| 1505 |
|
---|
[279] | 1506 | return $userinfo;
|
---|
[278] | 1507 | } # end login()
|
---|
| 1508 |
|
---|
| 1509 |
|
---|
[279] | 1510 | ## DNSDB::initActionLog()
|
---|
| 1511 | # Set up action logging. Takes a database handle and user ID
|
---|
| 1512 | # Sets some internal globals and Does The Right Thing to set up a logging channel.
|
---|
| 1513 | # This sets up _log() to spew out log entries to the defined channel without worrying
|
---|
| 1514 | # about having to open a file or a syslog channel
|
---|
| 1515 | ##fixme Need to call _initActionLog_blah() for various logging channels, configured
|
---|
| 1516 | # via dnsdb.conf, in $config{log_channel} or something
|
---|
| 1517 | # See https://secure.deepnet.cx/trac/dnsadmin/ticket/21
|
---|
| 1518 | sub initActionLog {
|
---|
| 1519 | my $dbh = shift;
|
---|
| 1520 | my $uid = shift;
|
---|
| 1521 |
|
---|
| 1522 | return if !$uid;
|
---|
| 1523 |
|
---|
| 1524 | # snag user info for logging. there's got to be a way to not have to pass this back
|
---|
| 1525 | # and forth from a caller, but web usage means no persistence we can rely on from
|
---|
| 1526 | # the server side.
|
---|
| 1527 | my ($username,$fullname) = $dbh->selectrow_array("SELECT username, firstname || ' ' || lastname".
|
---|
| 1528 | " FROM users WHERE user_id=?", undef, ($uid));
|
---|
| 1529 | ##fixme: errors are unpossible!
|
---|
| 1530 |
|
---|
| 1531 | $userdata{username} = $username;
|
---|
| 1532 | $userdata{userid} = $uid;
|
---|
| 1533 | $userdata{fullname} = $fullname;
|
---|
| 1534 |
|
---|
| 1535 | # convert to real check once we have other logging channels
|
---|
| 1536 | # if ($config{log_channel} eq 'sql') {
|
---|
| 1537 | # Open Log, Sez Me!
|
---|
| 1538 | # }
|
---|
| 1539 |
|
---|
| 1540 | } # end initActionLog
|
---|
| 1541 |
|
---|
| 1542 |
|
---|
[65] | 1543 | ## DNSDB::initPermissions()
|
---|
| 1544 | # Set up permissions global
|
---|
| 1545 | # Takes database handle and UID
|
---|
| 1546 | sub initPermissions {
|
---|
| 1547 | my $dbh = shift;
|
---|
| 1548 | my $uid = shift;
|
---|
| 1549 |
|
---|
| 1550 | # %permissions = $(getPermissions($dbh,'user',$uid));
|
---|
| 1551 | getPermissions($dbh, 'user', $uid, \%permissions);
|
---|
| 1552 |
|
---|
| 1553 | } # end initPermissions()
|
---|
| 1554 |
|
---|
| 1555 |
|
---|
| 1556 | ## DNSDB::getPermissions()
|
---|
| 1557 | # Get permissions from DB
|
---|
| 1558 | # Requires DB handle, group or user flag, ID, and hashref.
|
---|
| 1559 | sub getPermissions {
|
---|
| 1560 | my $dbh = shift;
|
---|
| 1561 | my $type = shift;
|
---|
| 1562 | my $id = shift;
|
---|
| 1563 | my $hash = shift;
|
---|
| 1564 |
|
---|
| 1565 | my $sql = qq(
|
---|
| 1566 | SELECT
|
---|
| 1567 | p.admin,p.self_edit,
|
---|
| 1568 | p.group_create,p.group_edit,p.group_delete,
|
---|
| 1569 | p.user_create,p.user_edit,p.user_delete,
|
---|
| 1570 | p.domain_create,p.domain_edit,p.domain_delete,
|
---|
[387] | 1571 | p.record_create,p.record_edit,p.record_delete,p.record_locchg,
|
---|
[382] | 1572 | p.location_create,p.location_edit,p.location_delete,p.location_view
|
---|
[65] | 1573 | FROM permissions p
|
---|
| 1574 | );
|
---|
| 1575 | if ($type eq 'group') {
|
---|
| 1576 | $sql .= qq(
|
---|
| 1577 | JOIN groups g ON g.permission_id=p.permission_id
|
---|
| 1578 | WHERE g.group_id=?
|
---|
| 1579 | );
|
---|
| 1580 | } else {
|
---|
| 1581 | $sql .= qq(
|
---|
| 1582 | JOIN users u ON u.permission_id=p.permission_id
|
---|
| 1583 | WHERE u.user_id=?
|
---|
| 1584 | );
|
---|
| 1585 | }
|
---|
| 1586 |
|
---|
| 1587 | my $sth = $dbh->prepare($sql);
|
---|
| 1588 |
|
---|
| 1589 | $sth->execute($id) or die "argh: ".$sth->errstr;
|
---|
| 1590 |
|
---|
| 1591 | # my $permref = $sth->fetchrow_hashref;
|
---|
| 1592 | # return $permref;
|
---|
| 1593 | # $hash = $permref;
|
---|
| 1594 | # Eww. Need to learn how to forcibly drop a hashref onto an existing hash.
|
---|
| 1595 | ($hash->{admin},$hash->{self_edit},
|
---|
| 1596 | $hash->{group_create},$hash->{group_edit},$hash->{group_delete},
|
---|
| 1597 | $hash->{user_create},$hash->{user_edit},$hash->{user_delete},
|
---|
| 1598 | $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete},
|
---|
[387] | 1599 | $hash->{record_create},$hash->{record_edit},$hash->{record_delete},$hash->{record_locchg},
|
---|
[382] | 1600 | $hash->{location_create},$hash->{location_edit},$hash->{location_delete},$hash->{location_view}
|
---|
| 1601 | ) = $sth->fetchrow_array;
|
---|
[65] | 1602 |
|
---|
| 1603 | } # end getPermissions()
|
---|
| 1604 |
|
---|
| 1605 |
|
---|
| 1606 | ## DNSDB::changePermissions()
|
---|
| 1607 | # Update an ACL entry
|
---|
| 1608 | # Takes a db handle, type, owner-id, and hashref for the changed permissions.
|
---|
| 1609 | sub changePermissions {
|
---|
| 1610 | my $dbh = shift;
|
---|
| 1611 | my $type = shift;
|
---|
| 1612 | my $id = shift;
|
---|
| 1613 | my $newperms = shift;
|
---|
[87] | 1614 | my $inherit = shift || 0;
|
---|
[65] | 1615 |
|
---|
[294] | 1616 | my $resultmsg = '';
|
---|
[66] | 1617 |
|
---|
[87] | 1618 | # see if we're switching from inherited to custom. for bonus points,
|
---|
| 1619 | # snag the permid and parent permid anyway, since we'll need the permid
|
---|
| 1620 | # to set/alter custom perms, and both if we're switching from custom to
|
---|
| 1621 | # inherited.
|
---|
[294] | 1622 | my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id,".
|
---|
| 1623 | ($type eq 'user' ? 'u.group_id,u.username' : 'u.parent_group_id,u.group_name').
|
---|
[65] | 1624 | " FROM ".($type eq 'user' ? 'users' : 'groups')." u ".
|
---|
[66] | 1625 | " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ".
|
---|
[65] | 1626 | " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?");
|
---|
| 1627 | $sth->execute($id);
|
---|
| 1628 |
|
---|
[294] | 1629 | my ($wasinherited,$permid,$parpermid,$parid,$name) = $sth->fetchrow_array;
|
---|
[66] | 1630 |
|
---|
[78] | 1631 | # hack phtoui
|
---|
| 1632 | # group id 1 is "special" in that it's it's own parent (err... possibly.)
|
---|
| 1633 | # may make its parent id 0 which doesn't exist, and as a bonus is Perl-false.
|
---|
| 1634 | $wasinherited = 0 if ($type eq 'group' && $id == 1);
|
---|
| 1635 |
|
---|
[66] | 1636 | local $dbh->{AutoCommit} = 0;
|
---|
| 1637 | local $dbh->{RaiseError} = 1;
|
---|
| 1638 |
|
---|
| 1639 | # Wrap all the SQL in a transaction
|
---|
| 1640 | eval {
|
---|
[87] | 1641 | if ($inherit) {
|
---|
| 1642 |
|
---|
| 1643 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ".
|
---|
| 1644 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) );
|
---|
| 1645 | $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) );
|
---|
| 1646 |
|
---|
| 1647 | } else {
|
---|
| 1648 |
|
---|
| 1649 | if ($wasinherited) { # munge new permission entry in if we're switching from inherited perms
|
---|
[66] | 1650 | ##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users
|
---|
[87] | 1651 | # ... if'n'when we have groups with fully inherited permissions.
|
---|
| 1652 | # SQL is coo
|
---|
| 1653 | $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ".
|
---|
| 1654 | "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) );
|
---|
| 1655 | ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ".
|
---|
| 1656 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) );
|
---|
| 1657 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ".
|
---|
| 1658 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) );
|
---|
[66] | 1659 | }
|
---|
[78] | 1660 |
|
---|
[87] | 1661 | # and now set the permissions we were passed
|
---|
| 1662 | foreach (@permtypes) {
|
---|
| 1663 | if (defined ($newperms->{$_})) {
|
---|
| 1664 | $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) );
|
---|
| 1665 | }
|
---|
| 1666 | }
|
---|
| 1667 |
|
---|
| 1668 | } # (inherited->)? custom
|
---|
| 1669 |
|
---|
[294] | 1670 | if ($type eq 'user') {
|
---|
| 1671 | $resultmsg = "Updated permissions for user $name";
|
---|
| 1672 | } else {
|
---|
| 1673 | $resultmsg = "Updated default permissions for group $name";
|
---|
| 1674 | }
|
---|
| 1675 | _log($dbh, (group_id => ($type eq 'user' ? $parid : $id), entry => $resultmsg));
|
---|
[66] | 1676 | $dbh->commit;
|
---|
| 1677 | }; # end eval
|
---|
| 1678 | if ($@) {
|
---|
| 1679 | my $msg = $@;
|
---|
| 1680 | eval { $dbh->rollback; };
|
---|
[294] | 1681 | return ('FAIL',"Error changing permissions: $msg");
|
---|
[66] | 1682 | }
|
---|
| 1683 |
|
---|
[294] | 1684 | return ('OK',$resultmsg);
|
---|
[65] | 1685 | } # end changePermissions()
|
---|
| 1686 |
|
---|
| 1687 |
|
---|
[67] | 1688 | ## DNSDB::comparePermissions()
|
---|
| 1689 | # Compare two permission hashes
|
---|
| 1690 | # Returns '>', '<', '=', '!'
|
---|
| 1691 | sub comparePermissions {
|
---|
| 1692 | my $p1 = shift;
|
---|
| 1693 | my $p2 = shift;
|
---|
| 1694 |
|
---|
| 1695 | my $retval = '='; # assume equality until proven otherwise
|
---|
| 1696 |
|
---|
| 1697 | no warnings "uninitialized";
|
---|
| 1698 |
|
---|
| 1699 | foreach (@permtypes) {
|
---|
| 1700 | next if $p1->{$_} == $p2->{$_}; # equal is good
|
---|
| 1701 | if ($p1->{$_} && !$p2->{$_}) {
|
---|
| 1702 | if ($retval eq '<') { # if we've already found an unequal pair where
|
---|
| 1703 | $retval = '!'; # $p2 has more access, and we now find a pair
|
---|
| 1704 | last; # where $p1 has more access, the overall access
|
---|
| 1705 | } # is neither greater or lesser, it's unequal.
|
---|
| 1706 | $retval = '>';
|
---|
| 1707 | }
|
---|
| 1708 | if (!$p1->{$_} && $p2->{$_}) {
|
---|
| 1709 | if ($retval eq '>') { # if we've already found an unequal pair where
|
---|
| 1710 | $retval = '!'; # $p1 has more access, and we now find a pair
|
---|
| 1711 | last; # where $p2 has more access, the overall access
|
---|
| 1712 | } # is neither greater or lesser, it's unequal.
|
---|
| 1713 | $retval = '<';
|
---|
| 1714 | }
|
---|
| 1715 | }
|
---|
| 1716 | return $retval;
|
---|
| 1717 | } # end comparePermissions()
|
---|
| 1718 |
|
---|
| 1719 |
|
---|
[112] | 1720 | ## DNSDB::changeGroup()
|
---|
| 1721 | # Change group ID of an entity
|
---|
| 1722 | # Takes a database handle, entity type, entity ID, and new group ID
|
---|
| 1723 | sub changeGroup {
|
---|
| 1724 | my $dbh = shift;
|
---|
| 1725 | my $type = shift;
|
---|
| 1726 | my $id = shift;
|
---|
| 1727 | my $newgrp = shift;
|
---|
| 1728 |
|
---|
| 1729 | ##fixme: fail on not enough args
|
---|
| 1730 | #return ('FAIL', "Missing
|
---|
| 1731 |
|
---|
[295] | 1732 | return ('FAIL', "Can't change the group of a $type")
|
---|
| 1733 | unless grep /^$type$/, ('domain','revzone','user','group'); # could be extended for defrecs?
|
---|
| 1734 |
|
---|
| 1735 | # Collect some names for logging and messages
|
---|
| 1736 | my $entname;
|
---|
[112] | 1737 | if ($type eq 'domain') {
|
---|
[295] | 1738 | $entname = domainName($dbh, $id);
|
---|
| 1739 | } elsif ($type eq 'revzone') {
|
---|
| 1740 | $entname = revName($dbh, $id);
|
---|
[112] | 1741 | } elsif ($type eq 'user') {
|
---|
[295] | 1742 | $entname = userFullName($dbh, $id, '%u');
|
---|
[112] | 1743 | } elsif ($type eq 'group') {
|
---|
[295] | 1744 | $entname = groupName($dbh, $id);
|
---|
[112] | 1745 | }
|
---|
[295] | 1746 |
|
---|
| 1747 | my ($oldgid) = $dbh->selectrow_array("SELECT group_id FROM $par_tbl{$type} WHERE $id_col{$type}=?",
|
---|
| 1748 | undef, ($id));
|
---|
| 1749 | my $oldgname = groupName($dbh, $oldgid);
|
---|
| 1750 | my $newgname = groupName($dbh, $newgrp);
|
---|
| 1751 |
|
---|
| 1752 | return ('FAIL', "Can't move things into a group that doesn't exist") if !$newgname;
|
---|
| 1753 |
|
---|
| 1754 | return ('WARN', "Nothing to do, new group is the same as the old group") if $oldgid == $newgrp;
|
---|
| 1755 |
|
---|
| 1756 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 1757 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 1758 | local $dbh->{AutoCommit} = 0;
|
---|
| 1759 | local $dbh->{RaiseError} = 1;
|
---|
| 1760 |
|
---|
| 1761 | eval {
|
---|
| 1762 | $dbh->do("UPDATE $par_tbl{$type} SET group_id=? WHERE $id_col{$type}=?", undef, ($newgrp, $id));
|
---|
| 1763 | # Log the change in both the old and new groups
|
---|
| 1764 | _log($dbh, (group_id => $oldgid, entry => "Moved $type $entname from $oldgname to $newgname"));
|
---|
| 1765 | _log($dbh, (group_id => $newgrp, entry => "Moved $type $entname from $oldgname to $newgname"));
|
---|
| 1766 | $dbh->commit;
|
---|
| 1767 | };
|
---|
| 1768 | if ($@) {
|
---|
| 1769 | my $msg = $@;
|
---|
| 1770 | eval { $dbh->rollback; };
|
---|
| 1771 | if ($config{log_failures}) {
|
---|
| 1772 | _log($dbh, (group_id => $oldgid, entry => "Error moving $type $entname to $newgname: $msg"));
|
---|
| 1773 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 1774 | }
|
---|
| 1775 | return ('FAIL',"Error moving $type $entname to $newgname: $msg");
|
---|
| 1776 | }
|
---|
| 1777 |
|
---|
| 1778 | return ('OK',"Moved $type $entname from $oldgname to $newgname");
|
---|
[112] | 1779 | } # end changeGroup()
|
---|
| 1780 |
|
---|
| 1781 |
|
---|
[2] | 1782 | ##
|
---|
| 1783 | ## Processing subs
|
---|
| 1784 | ##
|
---|
| 1785 |
|
---|
| 1786 | ## DNSDB::addDomain()
|
---|
| 1787 | # Add a domain
|
---|
[190] | 1788 | # Takes a database handle, domain name, numeric group, boolean(ish) state (active/inactive),
|
---|
| 1789 | # and user info hash (for logging).
|
---|
[2] | 1790 | # Returns a status code and message
|
---|
| 1791 | sub addDomain {
|
---|
| 1792 | $errstr = '';
|
---|
| 1793 | my $dbh = shift;
|
---|
| 1794 | return ('FAIL',"Need database handle") if !$dbh;
|
---|
| 1795 | my $domain = shift;
|
---|
[91] | 1796 | return ('FAIL',"Domain must not be blank") if !$domain;
|
---|
[2] | 1797 | my $group = shift;
|
---|
| 1798 | return ('FAIL',"Need group") if !defined($group);
|
---|
| 1799 | my $state = shift;
|
---|
| 1800 | return ('FAIL',"Need domain status") if !defined($state);
|
---|
| 1801 |
|
---|
[116] | 1802 | $state = 1 if $state =~ /^active$/;
|
---|
| 1803 | $state = 1 if $state =~ /^on$/;
|
---|
| 1804 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 1805 | $state = 0 if $state =~ /^off$/;
|
---|
| 1806 |
|
---|
| 1807 | return ('FAIL',"Invalid domain status") if $state !~ /^\d+$/;
|
---|
| 1808 |
|
---|
[190] | 1809 | return ('FAIL', "Invalid characters in domain") if $domain !~ /^[a-zA-Z0-9_.-]+$/;
|
---|
| 1810 |
|
---|
[349] | 1811 | my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)");
|
---|
[3] | 1812 | my $dom_id;
|
---|
| 1813 |
|
---|
[38] | 1814 | # quick check to start to see if we've already got one
|
---|
| 1815 | $sth->execute($domain);
|
---|
| 1816 | ($dom_id) = $sth->fetchrow_array;
|
---|
| 1817 |
|
---|
| 1818 | return ('FAIL', "Domain already exists") if $dom_id;
|
---|
| 1819 |
|
---|
[2] | 1820 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 1821 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 1822 | local $dbh->{AutoCommit} = 0;
|
---|
| 1823 | local $dbh->{RaiseError} = 1;
|
---|
| 1824 |
|
---|
| 1825 | # Wrap all the SQL in a transaction
|
---|
| 1826 | eval {
|
---|
| 1827 | # insert the domain...
|
---|
[190] | 1828 | $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef, ($domain, $group, $state));
|
---|
[2] | 1829 |
|
---|
| 1830 | # get the ID...
|
---|
[349] | 1831 | ($dom_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
| 1832 | undef, ($domain));
|
---|
[2] | 1833 |
|
---|
[284] | 1834 | _log($dbh, (domain_id => $dom_id, group_id => $group,
|
---|
[259] | 1835 | entry => "Added ".($state ? 'active' : 'inactive')." domain $domain"));
|
---|
[190] | 1836 |
|
---|
[2] | 1837 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
[190] | 1838 | my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
| 1839 | my $sth_in = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,distance,weight,port,ttl)".
|
---|
| 1840 | " VALUES ($dom_id,?,?,?,?,?,?,?)");
|
---|
| 1841 | $sth->execute($group);
|
---|
[3] | 1842 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $sth->fetchrow_array()) {
|
---|
[2] | 1843 | $host =~ s/DOMAIN/$domain/g;
|
---|
[37] | 1844 | $val =~ s/DOMAIN/$domain/g;
|
---|
[3] | 1845 | $sth_in->execute($host,$type,$val,$dist,$weight,$port,$ttl);
|
---|
[190] | 1846 | if ($typemap{$type} eq 'SOA') {
|
---|
| 1847 | my @tmp1 = split /:/, $host;
|
---|
| 1848 | my @tmp2 = split /:/, $val;
|
---|
[284] | 1849 | _log($dbh, (domain_id => $dom_id, group_id => $group,
|
---|
| 1850 | entry => "[new $domain] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
[257] | 1851 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"));
|
---|
[190] | 1852 | } else {
|
---|
| 1853 | my $logentry = "[new $domain] Added record '$host $typemap{$type}";
|
---|
| 1854 | $logentry .= " [distance $dist]" if $typemap{$type} eq 'MX';
|
---|
| 1855 | $logentry .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$type} eq 'SRV';
|
---|
[284] | 1856 | _log($dbh, (domain_id => $dom_id, group_id => $group,
|
---|
| 1857 | entry => $logentry." $val', TTL $ttl"));
|
---|
[190] | 1858 | }
|
---|
[2] | 1859 | }
|
---|
| 1860 |
|
---|
| 1861 | # once we get here, we should have suceeded.
|
---|
| 1862 | $dbh->commit;
|
---|
| 1863 | }; # end eval
|
---|
| 1864 |
|
---|
| 1865 | if ($@) {
|
---|
| 1866 | my $msg = $@;
|
---|
| 1867 | eval { $dbh->rollback; };
|
---|
[286] | 1868 | _log($dbh, (group_id => $group, entry => "Failed adding domain $domain ($msg)"))
|
---|
[284] | 1869 | if $config{log_failures};
|
---|
| 1870 | $dbh->commit; # since we enabled transactions earlier
|
---|
[193] | 1871 | return ('FAIL',$msg);
|
---|
[2] | 1872 | } else {
|
---|
[3] | 1873 | return ('OK',$dom_id);
|
---|
[2] | 1874 | }
|
---|
| 1875 | } # end addDomain
|
---|
| 1876 |
|
---|
| 1877 |
|
---|
[274] | 1878 | ## DNSDB::delZone()
|
---|
| 1879 | # Delete a forward or reverse zone.
|
---|
| 1880 | # Takes a database handle, zone ID, and forward/reverse flag.
|
---|
[3] | 1881 | # for now, just delete the records, then the domain.
|
---|
| 1882 | # later we may want to archive it in some way instead (status code 2, for example?)
|
---|
[274] | 1883 | sub delZone {
|
---|
[3] | 1884 | my $dbh = shift;
|
---|
[274] | 1885 | my $zoneid = shift;
|
---|
| 1886 | my $revrec = shift;
|
---|
[3] | 1887 |
|
---|
| 1888 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 1889 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 1890 | local $dbh->{AutoCommit} = 0;
|
---|
| 1891 | local $dbh->{RaiseError} = 1;
|
---|
| 1892 |
|
---|
[285] | 1893 | my $msg = '';
|
---|
[23] | 1894 | my $failmsg = '';
|
---|
[285] | 1895 | my $zone = ($revrec eq 'n' ? domainName($dbh, $zoneid) : revName($dbh, $zoneid));
|
---|
[23] | 1896 |
|
---|
[343] | 1897 | return ('FAIL', ($revrec eq 'n' ? 'Domain' : 'Reverse zone')." ID $zoneid doesn't exist") if !$zone;
|
---|
| 1898 |
|
---|
[285] | 1899 | # Set this up here since we may use if if $config{log_failures} is enabled
|
---|
| 1900 | my %loghash;
|
---|
| 1901 | $loghash{domain_id} = $zoneid if $revrec eq 'n';
|
---|
| 1902 | $loghash{rdns_id} = $zoneid if $revrec eq 'y';
|
---|
| 1903 | $loghash{group_id} = parentID($dbh,
|
---|
| 1904 | (id => $zoneid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) );
|
---|
| 1905 |
|
---|
[3] | 1906 | # Wrap all the SQL in a transaction
|
---|
| 1907 | eval {
|
---|
[274] | 1908 | # Disentangle custom record types before removing the
|
---|
| 1909 | # ones that are only in the zone to be deleted
|
---|
| 1910 | if ($revrec eq 'n') {
|
---|
| 1911 | my $sth = $dbh->prepare("UPDATE records SET type=?,domain_id=0 WHERE domain_id=? AND type=?");
|
---|
| 1912 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
| 1913 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65280);
|
---|
| 1914 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65281);
|
---|
| 1915 | $sth->execute(65282, $zoneid, 65283);
|
---|
| 1916 | $sth->execute(65282, $zoneid, 65284);
|
---|
| 1917 | $failmsg = "Failure removing domain records";
|
---|
| 1918 | $dbh->do("DELETE FROM records WHERE domain_id=?", undef, ($zoneid));
|
---|
| 1919 | $failmsg = "Failure removing domain";
|
---|
| 1920 | $dbh->do("DELETE FROM domains WHERE domain_id=?", undef, ($zoneid));
|
---|
| 1921 | } else {
|
---|
| 1922 | my $sth = $dbh->prepare("UPDATE records SET type=?,rdns_id=0 WHERE rdns_id=? AND type=?");
|
---|
| 1923 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
| 1924 | $sth->execute($reverse_typemap{A}, $zoneid, 65280);
|
---|
| 1925 | $sth->execute($reverse_typemap{AAAA}, $zoneid, 65281);
|
---|
| 1926 | # We don't have an "A template" or "AAAA template" type, although it might be useful for symmetry.
|
---|
[345] | 1927 | # $sth->execute(65286?, $zoneid, 65283);
|
---|
| 1928 | # $sth->execute(65286?, $zoneid, 65284);
|
---|
[274] | 1929 | $failmsg = "Failure removing reverse records";
|
---|
| 1930 | $dbh->do("DELETE FROM records WHERE rdns_id=?", undef, ($zoneid));
|
---|
| 1931 | $failmsg = "Failure removing reverse zone";
|
---|
| 1932 | $dbh->do("DELETE FROM revzones WHERE rdns_id=?", undef, ($zoneid));
|
---|
| 1933 | }
|
---|
[3] | 1934 |
|
---|
[285] | 1935 | $msg = "Deleted ".($revrec eq 'n' ? 'domain' : 'reverse zone')." $zone";
|
---|
| 1936 | $loghash{entry} = $msg;
|
---|
| 1937 | _log($dbh, %loghash);
|
---|
| 1938 |
|
---|
[3] | 1939 | # once we get here, we should have suceeded.
|
---|
[23] | 1940 | $dbh->commit;
|
---|
[3] | 1941 | }; # end eval
|
---|
| 1942 |
|
---|
| 1943 | if ($@) {
|
---|
[285] | 1944 | $msg = $@;
|
---|
[3] | 1945 | eval { $dbh->rollback; };
|
---|
[295] | 1946 | $loghash{entry} = "Error deleting $zone: $msg ($failmsg)";
|
---|
| 1947 | if ($config{log_failures}) {
|
---|
| 1948 | _log($dbh, %loghash);
|
---|
| 1949 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 1950 | }
|
---|
| 1951 | return ('FAIL', $loghash{entry});
|
---|
[3] | 1952 | } else {
|
---|
[295] | 1953 | return ('OK', $msg);
|
---|
[3] | 1954 | }
|
---|
| 1955 |
|
---|
[274] | 1956 | } # end delZone()
|
---|
[3] | 1957 |
|
---|
| 1958 |
|
---|
[2] | 1959 | ## DNSDB::domainName()
|
---|
| 1960 | # Return the domain name based on a domain ID
|
---|
| 1961 | # Takes a database handle and the domain ID
|
---|
| 1962 | # Returns the domain name or undef on failure
|
---|
| 1963 | sub domainName {
|
---|
| 1964 | $errstr = '';
|
---|
| 1965 | my $dbh = shift;
|
---|
| 1966 | my $domid = shift;
|
---|
[91] | 1967 | my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
|
---|
[2] | 1968 | $errstr = $DBI::errstr if !$domname;
|
---|
| 1969 | return $domname if $domname;
|
---|
[91] | 1970 | } # end domainName()
|
---|
[2] | 1971 |
|
---|
| 1972 |
|
---|
[224] | 1973 | ## DNSDB::revName()
|
---|
| 1974 | # Return the reverse zone name based on an rDNS ID
|
---|
| 1975 | # Takes a database handle and the rDNS ID
|
---|
| 1976 | # Returns the reverse zone name or undef on failure
|
---|
| 1977 | sub revName {
|
---|
| 1978 | $errstr = '';
|
---|
| 1979 | my $dbh = shift;
|
---|
| 1980 | my $revid = shift;
|
---|
| 1981 | my ($revname) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id=?", undef, ($revid) );
|
---|
| 1982 | $errstr = $DBI::errstr if !$revname;
|
---|
| 1983 | return $revname if $revname;
|
---|
| 1984 | } # end revName()
|
---|
| 1985 |
|
---|
| 1986 |
|
---|
[91] | 1987 | ## DNSDB::domainID()
|
---|
| 1988 | # Takes a database handle and domain name
|
---|
| 1989 | # Returns the domain ID number
|
---|
| 1990 | sub domainID {
|
---|
| 1991 | $errstr = '';
|
---|
| 1992 | my $dbh = shift;
|
---|
| 1993 | my $domain = shift;
|
---|
[349] | 1994 | my ($domid) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
| 1995 | undef, ($domain) );
|
---|
[91] | 1996 | $errstr = $DBI::errstr if !$domid;
|
---|
| 1997 | return $domid if $domid;
|
---|
| 1998 | } # end domainID()
|
---|
| 1999 |
|
---|
| 2000 |
|
---|
[276] | 2001 | ## DNSDB::revID()
|
---|
| 2002 | # Takes a database handle and reverse zone name
|
---|
| 2003 | # Returns the rDNS ID number
|
---|
| 2004 | sub revID {
|
---|
| 2005 | $errstr = '';
|
---|
| 2006 | my $dbh = shift;
|
---|
| 2007 | my $revzone = shift;
|
---|
| 2008 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ($revzone) );
|
---|
| 2009 | $errstr = $DBI::errstr if !$revid;
|
---|
| 2010 | return $revid if $revid;
|
---|
| 2011 | } # end revID()
|
---|
| 2012 |
|
---|
| 2013 |
|
---|
[260] | 2014 | ## DNSDB::addRDNS
|
---|
| 2015 | # Adds a reverse DNS zone
|
---|
[286] | 2016 | # Takes a database handle, CIDR block, reverse DNS pattern, numeric group,
|
---|
| 2017 | # and boolean(ish) state (active/inactive)
|
---|
[260] | 2018 | # Returns a status code and message
|
---|
| 2019 | sub addRDNS {
|
---|
| 2020 | my $dbh = shift;
|
---|
| 2021 | my $zone = NetAddr::IP->new(shift);
|
---|
[446] | 2022 |
|
---|
[260] | 2023 | return ('FAIL',"Zone name must be a valid CIDR netblock") unless ($zone && $zone->addr !~ /^0/);
|
---|
[270] | 2024 | my $revpatt = shift; # construct a custom (A/AAAA+)? PTR template record
|
---|
[260] | 2025 | my $group = shift;
|
---|
| 2026 | my $state = shift;
|
---|
[446] | 2027 | my $defloc = shift || '';
|
---|
[260] | 2028 |
|
---|
| 2029 | $state = 1 if $state =~ /^active$/;
|
---|
| 2030 | $state = 1 if $state =~ /^on$/;
|
---|
| 2031 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 2032 | $state = 0 if $state =~ /^off$/;
|
---|
| 2033 |
|
---|
| 2034 | return ('FAIL',"Invalid zone status") if $state !~ /^\d+$/;
|
---|
| 2035 |
|
---|
| 2036 | # quick check to start to see if we've already got one
|
---|
[299] | 2037 | my ($rdns_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ("$zone"));
|
---|
[260] | 2038 |
|
---|
| 2039 | return ('FAIL', "Zone already exists") if $rdns_id;
|
---|
| 2040 |
|
---|
| 2041 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2042 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2043 | local $dbh->{AutoCommit} = 0;
|
---|
| 2044 | local $dbh->{RaiseError} = 1;
|
---|
| 2045 |
|
---|
[264] | 2046 | my $warnstr = '';
|
---|
[270] | 2047 | my $defttl = 3600; # 1 hour should be reasonable. And unless things have gone horribly
|
---|
| 2048 | # wrong, we should have a value to override this anyway.
|
---|
[264] | 2049 |
|
---|
[260] | 2050 | # Wrap all the SQL in a transaction
|
---|
| 2051 | eval {
|
---|
[446] | 2052 | # insert the zone...
|
---|
| 2053 | $dbh->do("INSERT INTO revzones (revnet,group_id,status,default_location) VALUES (?,?,?,?)", undef,
|
---|
| 2054 | ($zone, $group, $state, $defloc) );
|
---|
[260] | 2055 |
|
---|
| 2056 | # get the ID...
|
---|
| 2057 | ($rdns_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
| 2058 |
|
---|
[286] | 2059 | _log($dbh, (rdns_id => $rdns_id, group_id => $group,
|
---|
[260] | 2060 | entry => "Added ".($state ? 'active' : 'inactive')." reverse zone $zone"));
|
---|
| 2061 |
|
---|
| 2062 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
| 2063 | my $sth = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
[446] | 2064 | my $sth_in = $dbh->prepare("INSERT INTO records (rdns_id,domain_id,host,type,val,ttl,location)".
|
---|
| 2065 | " VALUES ($rdns_id,?,?,?,?,?,?)");
|
---|
[260] | 2066 | $sth->execute($group);
|
---|
| 2067 | while (my ($host,$type,$val,$ttl) = $sth->fetchrow_array()) {
|
---|
[264] | 2068 | # Silently skip v4/v6 mismatches. This is not an error, this is expected.
|
---|
| 2069 | if ($zone->{isv6}) {
|
---|
| 2070 | next if ($type == 65280 || $type == 65283);
|
---|
| 2071 | } else {
|
---|
| 2072 | next if ($type == 65281 || $type == 65284);
|
---|
| 2073 | }
|
---|
[269] | 2074 |
|
---|
[260] | 2075 | $host =~ s/ADMINDOMAIN/$config{domain}/g;
|
---|
[264] | 2076 |
|
---|
[265] | 2077 | # Check to make sure the IP stubs will fit in the zone. Under most usage failures here should be rare.
|
---|
| 2078 | # On failure, tack a note on to a warning string and continue without adding this record.
|
---|
| 2079 | # While we're at it, we substitute $zone for ZONE in the value.
|
---|
| 2080 | if ($val eq 'ZONE') {
|
---|
[444] | 2081 | # If we've got a pattern, we skip the default record version on (A+)PTR-template types
|
---|
| 2082 | next if $revpatt && ($type == 65282 || $type == 65283);
|
---|
[269] | 2083 | ##fixme? do we care if we have multiple whole-zone templates?
|
---|
[265] | 2084 | $val = $zone->network;
|
---|
| 2085 | } elsif ($val =~ /ZONE/) {
|
---|
| 2086 | my $tmpval = $val;
|
---|
| 2087 | $tmpval =~ s/ZONE//;
|
---|
[269] | 2088 | # Bend the rules and allow single-trailing-number PTR or PTR template records to be inserted
|
---|
| 2089 | # as either v4 or v6. May make this an off-by-default config flag
|
---|
| 2090 | # Note that the origin records that may trigger this **SHOULD** already have ZONE,\d
|
---|
| 2091 | if ($type == 12 || $type == 65282) {
|
---|
| 2092 | $tmpval =~ s/[,.]/::/ if ($tmpval =~ /^[,.]\d+$/ && $zone->{isv6});
|
---|
| 2093 | $tmpval =~ s/[,:]+/./ if ($tmpval =~ /^(?:,|::)\d+$/ && !$zone->{isv6});
|
---|
| 2094 | }
|
---|
[265] | 2095 | my $addr;
|
---|
| 2096 | if (_ipparent($dbh, 'n', 'y', \$tmpval, $rdns_id, \$addr)) {
|
---|
| 2097 | $val = $addr->addr;
|
---|
| 2098 | } else {
|
---|
[269] | 2099 | $warnstr .= "\nDefault record '$val $typemap{$type} $host' doesn't fit in $zone, skipping";
|
---|
[264] | 2100 | next;
|
---|
| 2101 | }
|
---|
| 2102 | }
|
---|
| 2103 |
|
---|
[328] | 2104 | # Substitute $zone for ZONE in the hostname, but only for non-NS records.
|
---|
| 2105 | # NS records get this substitution on the value instead.
|
---|
| 2106 | $host = _ZONE($zone, $host) if $type != 2;
|
---|
[265] | 2107 |
|
---|
[269] | 2108 | # Fill in the forward domain ID if we can find it, otherwise:
|
---|
| 2109 | # Coerce type down to PTR or PTR template if we can't
|
---|
| 2110 | my $domid = 0;
|
---|
| 2111 | if ($type >= 65280) {
|
---|
| 2112 | if (!($domid = _hostparent($dbh, $host))) {
|
---|
| 2113 | $warnstr .= "\nRecord added as PTR instead of $typemap{$type}; domain not found for $host";
|
---|
| 2114 | $type = $reverse_typemap{PTR};
|
---|
| 2115 | $domid = 0; # just to be explicit.
|
---|
| 2116 | }
|
---|
| 2117 | }
|
---|
| 2118 |
|
---|
[446] | 2119 | $sth_in->execute($domid,$host,$type,$val,$ttl,$defloc);
|
---|
[269] | 2120 |
|
---|
[260] | 2121 | if ($typemap{$type} eq 'SOA') {
|
---|
| 2122 | my @tmp1 = split /:/, $host;
|
---|
| 2123 | my @tmp2 = split /:/, $val;
|
---|
[286] | 2124 | _log($dbh, (rdns_id => $rdns_id, group_id => $group,
|
---|
| 2125 | entry => "[new $zone] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
[260] | 2126 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"));
|
---|
[270] | 2127 | $defttl = $tmp2[3];
|
---|
[260] | 2128 | } else {
|
---|
[446] | 2129 | my $logentry = "[new $zone] Added record '$host $typemap{$type} $val', TTL $ttl";
|
---|
| 2130 | $logentry .= ", default location ".getLoc($dbh, $defloc)->{description} if $defloc;
|
---|
| 2131 | _log($dbh, (rdns_id => $rdns_id, domain_id => $domid, group_id => $group, entry => $logentry) );
|
---|
[260] | 2132 | }
|
---|
| 2133 | }
|
---|
| 2134 |
|
---|
[270] | 2135 | # Generate record based on provided pattern.
|
---|
| 2136 | if ($revpatt) {
|
---|
| 2137 | my $host;
|
---|
| 2138 | my $type = ($zone->{isv6} ? 65284 : 65283);
|
---|
| 2139 | my $val = $zone->network;
|
---|
[269] | 2140 |
|
---|
[270] | 2141 | # Substitute $zone for ZONE in the hostname.
|
---|
| 2142 | $host = _ZONE($zone, $revpatt);
|
---|
| 2143 |
|
---|
| 2144 | my $domid = 0;
|
---|
| 2145 | if (!($domid = _hostparent($dbh, $host))) {
|
---|
| 2146 | $warnstr .= "\nDefault pattern added as PTR template instead of $typemap{$type}; domain not found for $host";
|
---|
| 2147 | $type = 65282;
|
---|
| 2148 | $domid = 0; # just to be explicit.
|
---|
| 2149 | }
|
---|
| 2150 |
|
---|
[446] | 2151 | $sth_in->execute($domid,$host,$type,$val,$defttl,$defloc);
|
---|
[286] | 2152 | my $logentry = "[new $zone] Added record '$host $typemap{$type}";
|
---|
| 2153 | _log($dbh, (rdns_id => $rdns_id, domain_id => $domid, group_id => $group,
|
---|
| 2154 | entry => $logentry." $val', TTL $defttl from pattern"));
|
---|
[270] | 2155 | }
|
---|
| 2156 |
|
---|
[264] | 2157 | # If there are warnings (presumably about default records skipped for cause) log them
|
---|
[286] | 2158 | _log($dbh, (rdns_id => $rdns_id, group_id => $group, entry => "Warning(s) adding $zone:$warnstr"))
|
---|
[264] | 2159 | if $warnstr;
|
---|
[269] | 2160 |
|
---|
[260] | 2161 | # once we get here, we should have suceeded.
|
---|
| 2162 | $dbh->commit;
|
---|
| 2163 | }; # end eval
|
---|
| 2164 |
|
---|
| 2165 | if ($@) {
|
---|
| 2166 | my $msg = $@;
|
---|
| 2167 | eval { $dbh->rollback; };
|
---|
[286] | 2168 | _log($dbh, (group_id => $group, entry => "Failed adding reverse zone $zone ($msg)"))
|
---|
| 2169 | if $config{log_failures};
|
---|
| 2170 | $dbh->commit; # since we enabled transactions earlier
|
---|
[260] | 2171 | return ('FAIL',$msg);
|
---|
| 2172 | } else {
|
---|
[286] | 2173 | my $retcode = 'OK';
|
---|
| 2174 | if ($warnstr) {
|
---|
| 2175 | $resultstr = $warnstr;
|
---|
| 2176 | $retcode = 'WARN';
|
---|
| 2177 | }
|
---|
| 2178 | return ($retcode, $rdns_id);
|
---|
[260] | 2179 | }
|
---|
| 2180 |
|
---|
| 2181 | } # end addRDNS()
|
---|
| 2182 |
|
---|
| 2183 |
|
---|
[237] | 2184 | ## DNSDB::getZoneCount
|
---|
| 2185 | # Get count of zones in group or groups
|
---|
| 2186 | # Takes a database handle and hash containing:
|
---|
| 2187 | # - the "current" group
|
---|
| 2188 | # - an array of "acceptable" groups
|
---|
| 2189 | # - a flag for forward/reverse zones
|
---|
| 2190 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
| 2191 | # Returns an integer count of the resulting zone list.
|
---|
| 2192 | sub getZoneCount {
|
---|
| 2193 | my $dbh = shift;
|
---|
| 2194 |
|
---|
| 2195 | my %args = @_;
|
---|
| 2196 |
|
---|
| 2197 | my @filterargs;
|
---|
[239] | 2198 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2199 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2200 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
[237] | 2201 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2202 |
|
---|
| 2203 | my $sql;
|
---|
| 2204 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
| 2205 | if ($args{revrec} eq 'n') {
|
---|
| 2206 | $sql = "SELECT count(*) FROM domains".
|
---|
| 2207 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2208 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
| 2209 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
| 2210 | } else {
|
---|
| 2211 | $sql = "SELECT count(*) FROM revzones".
|
---|
| 2212 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2213 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
|
---|
| 2214 | ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2215 | }
|
---|
| 2216 | my ($count) = $dbh->selectrow_array($sql, undef, @filterargs);
|
---|
| 2217 | return $count;
|
---|
| 2218 | } # end getZoneCount()
|
---|
| 2219 |
|
---|
| 2220 |
|
---|
| 2221 | ## DNSDB::getZoneList()
|
---|
| 2222 | # Get a list of zones in the specified group(s)
|
---|
| 2223 | # Takes the same arguments as getZoneCount() above
|
---|
| 2224 | # Returns a reference to an array of hashrefs suitable for feeding to HTML::Template
|
---|
| 2225 | sub getZoneList {
|
---|
| 2226 | my $dbh = shift;
|
---|
| 2227 |
|
---|
| 2228 | my %args = @_;
|
---|
| 2229 |
|
---|
| 2230 | my @zonelist;
|
---|
| 2231 |
|
---|
[309] | 2232 | $args{sortorder} = 'ASC' if !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
[239] | 2233 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[237] | 2234 |
|
---|
| 2235 | my @filterargs;
|
---|
[239] | 2236 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2237 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2238 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
[237] | 2239 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2240 |
|
---|
| 2241 | my $sql;
|
---|
| 2242 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
| 2243 | if ($args{revrec} eq 'n') {
|
---|
[309] | 2244 | $args{sortby} = 'domain' if !grep /^$args{sortby}$/, ('domain','group','status');
|
---|
[237] | 2245 | $sql = "SELECT domain_id,domain,status,groups.group_name AS group FROM domains".
|
---|
| 2246 | " INNER JOIN groups ON domains.group_id=groups.group_id".
|
---|
| 2247 | " WHERE domains.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2248 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
| 2249 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
| 2250 | } else {
|
---|
[239] | 2251 | ##fixme: arguably startwith here is irrelevant. depends on the UI though.
|
---|
[309] | 2252 | $args{sortby} = 'revnet' if !grep /^$args{sortby}$/, ('revnet','group','status');
|
---|
[237] | 2253 | $sql = "SELECT rdns_id,revnet,status,groups.group_name AS group FROM revzones".
|
---|
| 2254 | " INNER JOIN groups ON revzones.group_id=groups.group_id".
|
---|
| 2255 | " WHERE revzones.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2256 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
|
---|
| 2257 | ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2258 | }
|
---|
| 2259 | # A common tail.
|
---|
[239] | 2260 | $sql .= " ORDER BY ".($args{sortby} eq 'group' ? 'groups.group_name' : $args{sortby})." $args{sortorder} ".
|
---|
| 2261 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage}".
|
---|
[237] | 2262 | " OFFSET ".$args{offset}*$config{perpage});
|
---|
[402] | 2263 | my $sth = $dbh->prepare($sql);
|
---|
| 2264 | $sth->execute(@filterargs);
|
---|
| 2265 | my $rownum = 0;
|
---|
[237] | 2266 |
|
---|
[402] | 2267 | while (my @data = $sth->fetchrow_array) {
|
---|
| 2268 | my %row;
|
---|
| 2269 | $row{domain_id} = $data[0];
|
---|
| 2270 | $row{domain} = $data[1];
|
---|
| 2271 | $row{status} = $data[2];
|
---|
| 2272 | $row{group} = $data[3];
|
---|
| 2273 | push @zonelist, \%row;
|
---|
| 2274 | }
|
---|
| 2275 |
|
---|
| 2276 | return \@zonelist;
|
---|
[237] | 2277 | } # end getZoneList()
|
---|
| 2278 |
|
---|
| 2279 |
|
---|
[383] | 2280 | ## DNSDB::getZoneLocation()
|
---|
[387] | 2281 | # Retrieve the default location for a zone.
|
---|
[383] | 2282 | # Takes a database handle, forward/reverse flag, and zone ID
|
---|
| 2283 | sub getZoneLocation {
|
---|
| 2284 | my $dbh = shift;
|
---|
| 2285 | my $revrec = shift;
|
---|
| 2286 | my $zoneid = shift;
|
---|
| 2287 |
|
---|
| 2288 | my ($loc) = $dbh->selectrow_array("SELECT default_location FROM ".
|
---|
| 2289 | ($revrec eq 'n' ? 'domains WHERE domain_id = ?' : 'revzones WHERE rdns_id = ?'),
|
---|
| 2290 | undef, ($zoneid));
|
---|
| 2291 | return $loc;
|
---|
| 2292 | } # end getZoneLocation()
|
---|
| 2293 |
|
---|
| 2294 |
|
---|
[18] | 2295 | ## DNSDB::addGroup()
|
---|
| 2296 | # Add a group
|
---|
[66] | 2297 | # Takes a database handle, group name, parent group, hashref for permissions,
|
---|
[292] | 2298 | # and optional template-vs-cloneme flag for the default records
|
---|
[18] | 2299 | # Returns a status code and message
|
---|
| 2300 | sub addGroup {
|
---|
| 2301 | $errstr = '';
|
---|
| 2302 | my $dbh = shift;
|
---|
[20] | 2303 | my $groupname = shift;
|
---|
| 2304 | my $pargroup = shift;
|
---|
[66] | 2305 | my $permissions = shift;
|
---|
[18] | 2306 |
|
---|
[66] | 2307 | # 0 indicates "custom", hardcoded.
|
---|
[18] | 2308 | # Any other value clones that group's default records, if it exists.
|
---|
[66] | 2309 | my $inherit = shift || 0;
|
---|
| 2310 | ##fixme: need a flag to indicate clone records or <?> ?
|
---|
[18] | 2311 |
|
---|
| 2312 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2313 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2314 | local $dbh->{AutoCommit} = 0;
|
---|
| 2315 | local $dbh->{RaiseError} = 1;
|
---|
| 2316 |
|
---|
[292] | 2317 | my ($group_id) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($groupname));
|
---|
[38] | 2318 |
|
---|
| 2319 | return ('FAIL', "Group already exists") if $group_id;
|
---|
| 2320 |
|
---|
[18] | 2321 | # Wrap all the SQL in a transaction
|
---|
| 2322 | eval {
|
---|
[292] | 2323 | $dbh->do("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)", undef, ($pargroup, $groupname) );
|
---|
[18] | 2324 |
|
---|
[292] | 2325 | my ($groupid) = $dbh->selectrow_array("SELECT currval('groups_group_id_seq')");
|
---|
[18] | 2326 |
|
---|
[292] | 2327 | # We work through the whole set of permissions instead of specifying them so
|
---|
| 2328 | # that when we add a new permission, we don't have to change the code anywhere
|
---|
| 2329 | # that doesn't explicitly deal with that specific permission.
|
---|
| 2330 | my @permvals;
|
---|
| 2331 | foreach (@permtypes) {
|
---|
| 2332 | if (!defined ($permissions->{$_})) {
|
---|
| 2333 | push @permvals, 0;
|
---|
| 2334 | } else {
|
---|
| 2335 | push @permvals, $permissions->{$_};
|
---|
[66] | 2336 | }
|
---|
[292] | 2337 | }
|
---|
| 2338 | $dbh->do("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")",
|
---|
| 2339 | undef, ($groupid, @permvals) );
|
---|
| 2340 | my ($permid) = $dbh->selectrow_array("SELECT currval('permissions_permission_id_seq')");
|
---|
| 2341 | $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
|
---|
[66] | 2342 |
|
---|
[292] | 2343 | # Default records
|
---|
[255] | 2344 | my $sthf = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
|
---|
[20] | 2345 | "VALUES ($groupid,?,?,?,?,?,?,?)");
|
---|
[255] | 2346 | my $sthr = $dbh->prepare("INSERT INTO default_rev_records (group_id,host,type,val,ttl) ".
|
---|
| 2347 | "VALUES ($groupid,?,?,?,?)");
|
---|
[66] | 2348 | if ($inherit) {
|
---|
[87] | 2349 | # Duplicate records from parent. Actually relying on inherited records feels
|
---|
| 2350 | # very fragile, and it would be problematic to roll over at a later time.
|
---|
[18] | 2351 | my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
[87] | 2352 | $sth2->execute($pargroup);
|
---|
[18] | 2353 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
[255] | 2354 | $sthf->execute(@clonedata);
|
---|
[18] | 2355 | }
|
---|
[255] | 2356 | # And now the reverse records
|
---|
[292] | 2357 | $sth2 = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
[255] | 2358 | $sth2->execute($pargroup);
|
---|
| 2359 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
| 2360 | $sthr->execute(@clonedata);
|
---|
| 2361 | }
|
---|
[18] | 2362 | } else {
|
---|
[66] | 2363 | ##fixme: Hardcoding is Bad, mmmmkaaaay?
|
---|
[18] | 2364 | # reasonable basic defaults for SOA, MX, NS, and minimal hosting
|
---|
| 2365 | # could load from a config file, but somewhere along the line we need hardcoded bits.
|
---|
[255] | 2366 | $sthf->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
|
---|
| 2367 | $sthf->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
|
---|
| 2368 | $sthf->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
|
---|
| 2369 | $sthf->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
|
---|
| 2370 | $sthf->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
|
---|
| 2371 | $sthf->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
|
---|
| 2372 | # reasonable basic defaults for generic reverse zone. Same as initial SQL tabledef.
|
---|
| 2373 | $sthr->execute('hostmaster.ADMINDOMAIN:ns1.ADMINDOMAIN', 6, '10800:3600:604800:10800', 86400);
|
---|
| 2374 | $sthr->execute('unused-%r.ADMINDOMAIN', 65283, 'ZONE', 3600);
|
---|
[18] | 2375 | }
|
---|
| 2376 |
|
---|
[292] | 2377 | _log($dbh, (group_id => $pargroup, entry => "Added group $groupname") );
|
---|
| 2378 |
|
---|
[18] | 2379 | # once we get here, we should have suceeded.
|
---|
| 2380 | $dbh->commit;
|
---|
| 2381 | }; # end eval
|
---|
| 2382 |
|
---|
| 2383 | if ($@) {
|
---|
| 2384 | my $msg = $@;
|
---|
| 2385 | eval { $dbh->rollback; };
|
---|
[292] | 2386 | if ($config{log_failures}) {
|
---|
| 2387 | _log($dbh, (group_id => $pargroup, entry => "Failed to add group $groupname: $msg") );
|
---|
| 2388 | $dbh->commit;
|
---|
| 2389 | }
|
---|
[18] | 2390 | return ('FAIL',$msg);
|
---|
| 2391 | }
|
---|
| 2392 |
|
---|
[292] | 2393 | return ('OK','OK');
|
---|
[18] | 2394 | } # end addGroup()
|
---|
| 2395 |
|
---|
| 2396 |
|
---|
[22] | 2397 | ## DNSDB::delGroup()
|
---|
| 2398 | # Delete a group.
|
---|
| 2399 | # Takes a group ID
|
---|
| 2400 | # Returns a status code and message
|
---|
| 2401 | sub delGroup {
|
---|
| 2402 | my $dbh = shift;
|
---|
| 2403 | my $groupid = shift;
|
---|
| 2404 |
|
---|
| 2405 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2406 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2407 | local $dbh->{AutoCommit} = 0;
|
---|
| 2408 | local $dbh->{RaiseError} = 1;
|
---|
| 2409 |
|
---|
| 2410 | ##fixme: locate "knowable" error conditions and deal with them before the eval
|
---|
[23] | 2411 | # ... or inside, whatever.
|
---|
[22] | 2412 | # -> domains still exist in group
|
---|
| 2413 | # -> ...
|
---|
[23] | 2414 | my $failmsg = '';
|
---|
[293] | 2415 | my $resultmsg = '';
|
---|
[22] | 2416 |
|
---|
[293] | 2417 | # collect some pieces for logging and error messages
|
---|
| 2418 | my $groupname = groupName($dbh,$groupid);
|
---|
| 2419 | my $parid = parentID($dbh, (id => $groupid, type => 'group'));
|
---|
| 2420 |
|
---|
[22] | 2421 | # Wrap all the SQL in a transaction
|
---|
| 2422 | eval {
|
---|
[293] | 2423 | # Check for Things in the group
|
---|
| 2424 | $failmsg = "Can't remove group $groupname";
|
---|
| 2425 | my ($grpcnt) = $dbh->selectrow_array("SELECT count(*) FROM groups WHERE parent_group_id=?", undef, ($groupid));
|
---|
| 2426 | die "$grpcnt groups still in group\n" if $grpcnt;
|
---|
| 2427 | my ($domcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($groupid));
|
---|
[23] | 2428 | die "$domcnt domains still in group\n" if $domcnt;
|
---|
[293] | 2429 | my ($usercnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($groupid));
|
---|
| 2430 | die "$usercnt users still in group\n" if $usercnt;
|
---|
[23] | 2431 |
|
---|
[293] | 2432 | $failmsg = "Failed to delete default records for $groupname";
|
---|
| 2433 | $dbh->do("DELETE from default_records WHERE group_id=?", undef, ($groupid));
|
---|
| 2434 | $failmsg = "Failed to delete default reverse records for $groupname";
|
---|
| 2435 | $dbh->do("DELETE from default_rev_records WHERE group_id=?", undef, ($groupid));
|
---|
| 2436 | $failmsg = "Failed to remove group $groupname";
|
---|
| 2437 | $dbh->do("DELETE from groups WHERE group_id=?", undef, ($groupid));
|
---|
[22] | 2438 |
|
---|
[293] | 2439 | _log($dbh, (group_id => $parid, entry => "Deleted group $groupname"));
|
---|
| 2440 | $resultmsg = "Deleted group $groupname";
|
---|
| 2441 |
|
---|
[22] | 2442 | # once we get here, we should have suceeded.
|
---|
| 2443 | $dbh->commit;
|
---|
| 2444 | }; # end eval
|
---|
| 2445 |
|
---|
| 2446 | if ($@) {
|
---|
| 2447 | my $msg = $@;
|
---|
| 2448 | eval { $dbh->rollback; };
|
---|
[293] | 2449 | if ($config{log_failures}) {
|
---|
| 2450 | _log($dbh, (group_id => $parid, entry => "$failmsg: $msg"));
|
---|
| 2451 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2452 | }
|
---|
[23] | 2453 | return ('FAIL',"$failmsg: $msg");
|
---|
[22] | 2454 | }
|
---|
[293] | 2455 |
|
---|
| 2456 | return ('OK',$resultmsg);
|
---|
[22] | 2457 | } # end delGroup()
|
---|
| 2458 |
|
---|
| 2459 |
|
---|
[19] | 2460 | ## DNSDB::getChildren()
|
---|
| 2461 | # Get a list of all groups whose parent^n is group <n>
|
---|
[24] | 2462 | # Takes a database handle, group ID, reference to an array to put the group IDs in,
|
---|
| 2463 | # and an optional flag to return only immediate children or all children-of-children
|
---|
| 2464 | # default to returning all children
|
---|
[19] | 2465 | # Calls itself
|
---|
| 2466 | sub getChildren {
|
---|
| 2467 | $errstr = '';
|
---|
| 2468 | my $dbh = shift;
|
---|
[20] | 2469 | my $rootgroup = shift;
|
---|
| 2470 | my $groupdest = shift;
|
---|
[24] | 2471 | my $immed = shift || 'all';
|
---|
[19] | 2472 |
|
---|
| 2473 | # special break for default group; otherwise we get stuck.
|
---|
[20] | 2474 | if ($rootgroup == 1) {
|
---|
[19] | 2475 | # by definition, group 1 is the Root Of All Groups
|
---|
[24] | 2476 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
|
---|
[331] | 2477 | ($immed ne 'all' ? " AND parent_group_id=1" : '')." ORDER BY group_name");
|
---|
[19] | 2478 | $sth->execute;
|
---|
| 2479 | while (my @this = $sth->fetchrow_array) {
|
---|
[20] | 2480 | push @$groupdest, @this;
|
---|
[19] | 2481 | }
|
---|
| 2482 | } else {
|
---|
[331] | 2483 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=? ORDER BY group_name");
|
---|
[20] | 2484 | $sth->execute($rootgroup);
|
---|
[19] | 2485 | return if $sth->rows == 0;
|
---|
[20] | 2486 | my @grouplist;
|
---|
| 2487 | while (my ($group) = $sth->fetchrow_array) {
|
---|
| 2488 | push @$groupdest, $group;
|
---|
[24] | 2489 | getChildren($dbh,$group,$groupdest) if $immed eq 'all';
|
---|
[19] | 2490 | }
|
---|
| 2491 | }
|
---|
| 2492 | } # end getChildren()
|
---|
| 2493 |
|
---|
| 2494 |
|
---|
[20] | 2495 | ## DNSDB::groupName()
|
---|
[17] | 2496 | # Return the group name based on a group ID
|
---|
| 2497 | # Takes a database handle and the group ID
|
---|
| 2498 | # Returns the group name or undef on failure
|
---|
[20] | 2499 | sub groupName {
|
---|
[13] | 2500 | $errstr = '';
|
---|
| 2501 | my $dbh = shift;
|
---|
[20] | 2502 | my $groupid = shift;
|
---|
| 2503 | my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
|
---|
| 2504 | $sth->execute($groupid);
|
---|
| 2505 | my ($groupname) = $sth->fetchrow_array();
|
---|
| 2506 | $errstr = $DBI::errstr if !$groupname;
|
---|
| 2507 | return $groupname if $groupname;
|
---|
| 2508 | } # end groupName
|
---|
[13] | 2509 |
|
---|
| 2510 |
|
---|
[314] | 2511 | ## DNSDB::getGroupCount()
|
---|
| 2512 | # Get count of subgroups in group or groups
|
---|
| 2513 | # Takes a database handle and hash containing:
|
---|
| 2514 | # - the "current" group
|
---|
| 2515 | # - an array of "acceptable" groups
|
---|
| 2516 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
| 2517 | # Returns an integer count of the resulting group list.
|
---|
| 2518 | sub getGroupCount {
|
---|
| 2519 | my $dbh = shift;
|
---|
| 2520 |
|
---|
| 2521 | my %args = @_;
|
---|
| 2522 |
|
---|
| 2523 | my @filterargs;
|
---|
| 2524 |
|
---|
| 2525 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2526 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2527 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2528 |
|
---|
| 2529 | my $sql = "SELECT count(*) FROM groups ".
|
---|
| 2530 | "WHERE parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2531 | ($args{startwith} ? " AND group_name ~* ?" : '').
|
---|
| 2532 | ($args{filter} ? " AND group_name ~* ?" : '');
|
---|
| 2533 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 2534 | $errstr = $dbh->errstr if !$count;
|
---|
| 2535 | return $count;
|
---|
| 2536 | } # end getGroupCount
|
---|
| 2537 |
|
---|
| 2538 |
|
---|
| 2539 | ## DNSDB::getGroupList()
|
---|
| 2540 | # Get a list of sub^n-groups in the specified group(s)
|
---|
| 2541 | # Takes the same arguments as getGroupCount() above
|
---|
| 2542 | # Returns an arrayref containing hashrefs suitable for feeding straight to HTML::Template
|
---|
| 2543 | sub getGroupList {
|
---|
| 2544 | my $dbh = shift;
|
---|
| 2545 |
|
---|
| 2546 | my %args = @_;
|
---|
| 2547 |
|
---|
| 2548 | my @filterargs;
|
---|
| 2549 |
|
---|
| 2550 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2551 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2552 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2553 |
|
---|
| 2554 | # protection against bad or missing arguments
|
---|
| 2555 | $args{sortorder} = 'ASC' if !$args{sortorder};
|
---|
[397] | 2556 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[314] | 2557 |
|
---|
| 2558 | # munge sortby for columns in database
|
---|
| 2559 | $args{sortby} = 'g.group_name' if $args{sortby} eq 'group';
|
---|
| 2560 | $args{sortby} = 'g2.group_name' if $args{sortby} eq 'parent';
|
---|
| 2561 |
|
---|
[385] | 2562 | my $sql = q(SELECT g.group_id AS groupid, g.group_name AS groupname, g2.group_name AS pgroup
|
---|
[314] | 2563 | FROM groups g
|
---|
| 2564 | INNER JOIN groups g2 ON g2.group_id=g.parent_group_id
|
---|
| 2565 | ).
|
---|
[385] | 2566 | " WHERE g.parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
[314] | 2567 | ($args{startwith} ? " AND g.group_name ~* ?" : '').
|
---|
| 2568 | ($args{filter} ? " AND g.group_name ~* ?" : '').
|
---|
| 2569 | " GROUP BY g.group_id, g.group_name, g2.group_name ".
|
---|
| 2570 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
| 2571 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
| 2572 | my $glist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 2573 | $errstr = $dbh->errstr if !$glist;
|
---|
[385] | 2574 |
|
---|
| 2575 | # LEFT JOINs make the result set balloon beyond sanity just to include counts;
|
---|
| 2576 | # this means there's lots of crunching needed to trim the result set back down.
|
---|
| 2577 | # So instead we track the order of the groups, and push the counts into the
|
---|
| 2578 | # arrayref result separately.
|
---|
| 2579 | ##fixme: put this whole sub in a transaction? might be
|
---|
| 2580 | # needed for accurate results on very busy systems.
|
---|
[386] | 2581 | ##fixme: large group lists need prepared statements?
|
---|
| 2582 | #my $ucsth = $dbh->prepare("SELECT count(*) FROM users WHERE group_id=?");
|
---|
| 2583 | #my $dcsth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
|
---|
| 2584 | #my $rcsth = $dbh->prepare("SELECT count(*) FROM revzones WHERE group_id=?");
|
---|
[385] | 2585 | foreach (@{$glist}) {
|
---|
[386] | 2586 | my ($ucnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 2587 | $$_{nusers} = $ucnt;
|
---|
| 2588 | my ($dcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 2589 | $$_{ndomains} = $dcnt;
|
---|
| 2590 | my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 2591 | $$_{nrevzones} = $rcnt;
|
---|
[385] | 2592 | }
|
---|
| 2593 |
|
---|
[314] | 2594 | return $glist;
|
---|
| 2595 | } # end getGroupList
|
---|
| 2596 |
|
---|
| 2597 |
|
---|
[118] | 2598 | ## DNSDB::groupID()
|
---|
| 2599 | # Return the group ID based on the group name
|
---|
| 2600 | # Takes a database handle and the group name
|
---|
| 2601 | # Returns the group ID or undef on failure
|
---|
| 2602 | sub groupID {
|
---|
| 2603 | $errstr = '';
|
---|
| 2604 | my $dbh = shift;
|
---|
| 2605 | my $group = shift;
|
---|
[406] | 2606 | my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($group) );
|
---|
[118] | 2607 | $errstr = $DBI::errstr if !$grpid;
|
---|
| 2608 | return $grpid if $grpid;
|
---|
| 2609 | } # end groupID()
|
---|
| 2610 |
|
---|
| 2611 |
|
---|
[24] | 2612 | ## DNSDB::addUser()
|
---|
[87] | 2613 | # Add a user.
|
---|
| 2614 | # Takes a DB handle, username, group ID, password, state (active/inactive).
|
---|
| 2615 | # Optionally accepts:
|
---|
| 2616 | # user type (user/admin) - defaults to user
|
---|
| 2617 | # permissions string - defaults to inherit from group
|
---|
| 2618 | # three valid forms:
|
---|
| 2619 | # i - Inherit permissions
|
---|
| 2620 | # c:<user_id> - Clone permissions from <user_id>
|
---|
| 2621 | # C:<permission list> - Set these specific permissions
|
---|
| 2622 | # first name - defaults to username
|
---|
| 2623 | # last name - defaults to blank
|
---|
| 2624 | # phone - defaults to blank (could put other data within column def)
|
---|
[90] | 2625 | # Returns (OK,<uid>) on success, (FAIL,<message>) on failure
|
---|
[24] | 2626 | sub addUser {
|
---|
| 2627 | $errstr = '';
|
---|
| 2628 | my $dbh = shift;
|
---|
| 2629 | my $username = shift;
|
---|
| 2630 | my $group = shift;
|
---|
| 2631 | my $pass = shift;
|
---|
| 2632 | my $state = shift;
|
---|
[25] | 2633 |
|
---|
[90] | 2634 | return ('FAIL', "Missing one or more required entries") if !defined($state);
|
---|
| 2635 | return ('FAIL', "Username must not be blank") if !$username;
|
---|
[87] | 2636 |
|
---|
[408] | 2637 | # Munge in some alternate state values
|
---|
| 2638 | $state = 1 if $state =~ /^active$/;
|
---|
| 2639 | $state = 1 if $state =~ /^on$/;
|
---|
| 2640 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 2641 | $state = 0 if $state =~ /^off$/;
|
---|
| 2642 |
|
---|
[25] | 2643 | my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
|
---|
| 2644 |
|
---|
[67] | 2645 | my $permstring = shift || 'i'; # default is to inhert permissions from group
|
---|
| 2646 |
|
---|
[25] | 2647 | my $fname = shift || $username;
|
---|
[24] | 2648 | my $lname = shift || '';
|
---|
[25] | 2649 | my $phone = shift || ''; # not going format-check
|
---|
[24] | 2650 |
|
---|
[38] | 2651 | my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
|
---|
[24] | 2652 | my $user_id;
|
---|
| 2653 |
|
---|
[38] | 2654 | # quick check to start to see if we've already got one
|
---|
| 2655 | $sth->execute($username);
|
---|
| 2656 | ($user_id) = $sth->fetchrow_array;
|
---|
| 2657 |
|
---|
| 2658 | return ('FAIL', "User already exists") if $user_id;
|
---|
| 2659 |
|
---|
[24] | 2660 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2661 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2662 | local $dbh->{AutoCommit} = 0;
|
---|
| 2663 | local $dbh->{RaiseError} = 1;
|
---|
| 2664 |
|
---|
| 2665 | # Wrap all the SQL in a transaction
|
---|
| 2666 | eval {
|
---|
[87] | 2667 | # insert the user... note we set inherited perms by default since
|
---|
| 2668 | # it's simple and cleans up some other bits of state
|
---|
| 2669 | my $sth = $dbh->prepare("INSERT INTO users ".
|
---|
| 2670 | "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
|
---|
| 2671 | "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
|
---|
| 2672 | $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);
|
---|
[24] | 2673 |
|
---|
| 2674 | # get the ID...
|
---|
[94] | 2675 | ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");
|
---|
[24] | 2676 |
|
---|
[87] | 2677 | # Permissions! Gotta set'em all!
|
---|
[401] | 2678 | die "Invalid permission string $permstring\n"
|
---|
[87] | 2679 | if $permstring !~ /^(?:
|
---|
| 2680 | i # inherit
|
---|
| 2681 | |c:\d+ # clone
|
---|
| 2682 | # custom. no, the leading , is not a typo
|
---|
[391] | 2683 | |C:(?:,(?:group|user|domain|record|location|self)_(?:edit|create|delete|locchg|view))*
|
---|
[87] | 2684 | )$/x;
|
---|
| 2685 | # bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
|
---|
| 2686 | if ($permstring ne 'i') {
|
---|
| 2687 | # for cloned or custom permissions, we have to create a new permissions entry.
|
---|
| 2688 | my $clonesrc = $group;
|
---|
| 2689 | if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
|
---|
| 2690 | $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
|
---|
| 2691 | "SELECT $permlist,? FROM permissions WHERE permission_id=".
|
---|
| 2692 | "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
|
---|
| 2693 | undef, ($user_id,$clonesrc) );
|
---|
| 2694 | $dbh->do("UPDATE users SET permission_id=".
|
---|
| 2695 | "(SELECT permission_id FROM permissions WHERE user_id=?) ".
|
---|
| 2696 | "WHERE user_id=?", undef, ($user_id, $user_id) );
|
---|
| 2697 | }
|
---|
| 2698 | if ($permstring =~ /^C:/) {
|
---|
| 2699 | # finally for custom permissions, we set the passed-in permissions (and unset
|
---|
| 2700 | # any that might have been brought in by the clone operation above)
|
---|
| 2701 | my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
|
---|
| 2702 | undef, ($user_id) );
|
---|
| 2703 | foreach (@permtypes) {
|
---|
| 2704 | if ($permstring =~ /,$_/) {
|
---|
| 2705 | $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
|
---|
| 2706 | } else {
|
---|
| 2707 | $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
|
---|
| 2708 | }
|
---|
| 2709 | }
|
---|
| 2710 | }
|
---|
| 2711 |
|
---|
| 2712 | $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
|
---|
| 2713 |
|
---|
[25] | 2714 | ##fixme: add another table to hold name/email for log table?
|
---|
| 2715 |
|
---|
[294] | 2716 | _log($dbh, (group_id => $group, entry => "Added user $username ($fname $lname)"));
|
---|
[24] | 2717 | # once we get here, we should have suceeded.
|
---|
| 2718 | $dbh->commit;
|
---|
| 2719 | }; # end eval
|
---|
| 2720 |
|
---|
| 2721 | if ($@) {
|
---|
| 2722 | my $msg = $@;
|
---|
| 2723 | eval { $dbh->rollback; };
|
---|
[294] | 2724 | if ($config{log_failures}) {
|
---|
| 2725 | _log($dbh, (group_id => $group, entry => "Error adding user $username: $msg"));
|
---|
| 2726 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2727 | }
|
---|
| 2728 | return ('FAIL',"Error adding user $username: $msg");
|
---|
[24] | 2729 | }
|
---|
[294] | 2730 |
|
---|
| 2731 | return ('OK',"User $username ($fname $lname) added");
|
---|
[24] | 2732 | } # end addUser
|
---|
| 2733 |
|
---|
| 2734 |
|
---|
[325] | 2735 | ## DNSDB::getUserCount()
|
---|
| 2736 | # Get count of users in group
|
---|
| 2737 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
| 2738 | # - a reference list of secondary groups
|
---|
| 2739 | # - a filter string
|
---|
| 2740 | # - a "Starts with" string
|
---|
| 2741 | sub getUserCount {
|
---|
| 2742 | my $dbh = shift;
|
---|
| 2743 |
|
---|
| 2744 | my %args = @_;
|
---|
| 2745 |
|
---|
| 2746 | my @filterargs;
|
---|
| 2747 |
|
---|
| 2748 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2749 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2750 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2751 |
|
---|
| 2752 |
|
---|
| 2753 | my $sql = "SELECT count(*) FROM users ".
|
---|
| 2754 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2755 | ($args{startwith} ? " AND username ~* ?" : '').
|
---|
| 2756 | ($args{filter} ? " AND username ~* ?" : '');
|
---|
| 2757 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 2758 | $errstr = $dbh->errstr if !$count;
|
---|
| 2759 | return $count;
|
---|
| 2760 | } # end getUserCount()
|
---|
| 2761 |
|
---|
| 2762 |
|
---|
| 2763 | ## DNSDB::getUserList()
|
---|
| 2764 | # Get list of users
|
---|
| 2765 | # Takes the same arguments as getUserCount() above, plus optional:
|
---|
| 2766 | # - sort field
|
---|
| 2767 | # - sort order
|
---|
| 2768 | # - offset/return-all-everything flag (defaults to $perpage records)
|
---|
| 2769 | sub getUserList {
|
---|
| 2770 | my $dbh = shift;
|
---|
| 2771 |
|
---|
| 2772 | my %args = @_;
|
---|
| 2773 |
|
---|
| 2774 | my @filterargs;
|
---|
| 2775 |
|
---|
| 2776 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2777 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2778 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2779 |
|
---|
| 2780 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
| 2781 | my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
| 2782 | fname => 'fname');
|
---|
| 2783 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 2784 |
|
---|
| 2785 | # protection against bad or missing arguments
|
---|
| 2786 | $args{sortorder} = 'ASC' if !$args{sortorder};
|
---|
| 2787 | $args{sortby} = 'u.username' if !$args{sortby};
|
---|
[397] | 2788 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[325] | 2789 |
|
---|
| 2790 | my $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ".
|
---|
| 2791 | "FROM users u ".
|
---|
| 2792 | "INNER JOIN groups g ON u.group_id=g.group_id ".
|
---|
| 2793 | "WHERE u.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2794 | ($args{startwith} ? " AND u.username ~* ?" : '').
|
---|
| 2795 | ($args{filter} ? " AND u.username ~* ?" : '').
|
---|
[401] | 2796 | " AND NOT u.type = 'R' ".
|
---|
[325] | 2797 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
| 2798 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
| 2799 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 2800 | $errstr = $dbh->errstr if !$ulist;
|
---|
| 2801 | return $ulist;
|
---|
| 2802 | } # end getUserList()
|
---|
| 2803 |
|
---|
| 2804 |
|
---|
[326] | 2805 | ## DNSDB::getUserDropdown()
|
---|
| 2806 | # Get a list of usernames for use in a dropdown menu.
|
---|
| 2807 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
| 2808 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
| 2809 | sub getUserDropdown {
|
---|
| 2810 | my $dbh = shift;
|
---|
| 2811 | my $grp = shift;
|
---|
| 2812 | my $sel = shift || 0;
|
---|
| 2813 |
|
---|
| 2814 | my $sth = $dbh->prepare("SELECT username,user_id FROM users WHERE group_id=?");
|
---|
| 2815 | $sth->execute($grp);
|
---|
| 2816 |
|
---|
| 2817 | my @userlist;
|
---|
| 2818 | while (my ($username,$uid) = $sth->fetchrow_array) {
|
---|
| 2819 | my %row = (
|
---|
| 2820 | username => $username,
|
---|
| 2821 | uid => $uid,
|
---|
| 2822 | selected => ($sel == $uid ? 1 : 0)
|
---|
| 2823 | );
|
---|
| 2824 | push @userlist, \%row;
|
---|
| 2825 | }
|
---|
| 2826 | return \@userlist;
|
---|
| 2827 | } # end getUserDropdown()
|
---|
| 2828 |
|
---|
| 2829 |
|
---|
[55] | 2830 | ## DNSDB::checkUser()
|
---|
| 2831 | # Check user/pass combo on login
|
---|
| 2832 | sub checkUser {
|
---|
| 2833 | my $dbh = shift;
|
---|
| 2834 | my $user = shift;
|
---|
[56] | 2835 | my $inpass = shift;
|
---|
[55] | 2836 |
|
---|
| 2837 | my $sth = $dbh->prepare("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?");
|
---|
| 2838 | $sth->execute($user);
|
---|
| 2839 | my ($uid,$gid,$pass,$fname,$lname) = $sth->fetchrow_array;
|
---|
| 2840 | my $loginfailed = 1 if !defined($uid);
|
---|
| 2841 |
|
---|
| 2842 | if ($pass =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
|
---|
[56] | 2843 | $loginfailed = 1 if $pass ne unix_md5_crypt($inpass,$1);
|
---|
[55] | 2844 | } else {
|
---|
[56] | 2845 | $loginfailed = 1 if $pass ne $inpass;
|
---|
[55] | 2846 | }
|
---|
| 2847 |
|
---|
| 2848 | # nnnngggg
|
---|
| 2849 | return ($uid, $gid);
|
---|
| 2850 | } # end checkUser
|
---|
| 2851 |
|
---|
| 2852 |
|
---|
[83] | 2853 | ## DNSDB:: updateUser()
|
---|
[90] | 2854 | # Update general data about user
|
---|
[83] | 2855 | sub updateUser {
|
---|
| 2856 | my $dbh = shift;
|
---|
[118] | 2857 |
|
---|
| 2858 | ##fixme: tweak calling convention so that we can update any given bit of data
|
---|
[83] | 2859 | my $uid = shift;
|
---|
| 2860 | my $username = shift;
|
---|
| 2861 | my $group = shift;
|
---|
| 2862 | my $pass = shift;
|
---|
| 2863 | my $state = shift;
|
---|
[87] | 2864 | my $type = shift || 'u';
|
---|
[83] | 2865 | my $fname = shift || $username;
|
---|
| 2866 | my $lname = shift || '';
|
---|
| 2867 | my $phone = shift || ''; # not going format-check
|
---|
| 2868 |
|
---|
[294] | 2869 | my $resultmsg = '';
|
---|
[83] | 2870 |
|
---|
[411] | 2871 | # Munge in some alternate state values
|
---|
| 2872 | $state = 1 if $state =~ /^active$/;
|
---|
| 2873 | $state = 1 if $state =~ /^on$/;
|
---|
| 2874 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 2875 | $state = 0 if $state =~ /^off$/;
|
---|
| 2876 |
|
---|
[83] | 2877 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2878 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2879 | local $dbh->{AutoCommit} = 0;
|
---|
| 2880 | local $dbh->{RaiseError} = 1;
|
---|
| 2881 |
|
---|
| 2882 | my $sth;
|
---|
| 2883 |
|
---|
| 2884 | # Password can be left blank; if so we assume there's one on file.
|
---|
| 2885 | # Actual blank passwords are bad, mm'kay?
|
---|
| 2886 | if (!$pass) {
|
---|
[294] | 2887 | ($pass) = $dbh->selectrow_array("SELECT password FROM users WHERE user_id=?", undef, ($uid));
|
---|
[83] | 2888 | } else {
|
---|
| 2889 | $pass = unix_md5_crypt($pass);
|
---|
| 2890 | }
|
---|
| 2891 |
|
---|
| 2892 | eval {
|
---|
[294] | 2893 | $dbh->do("UPDATE users SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?".
|
---|
| 2894 | " WHERE user_id=?", undef, ($username, $pass, $fname, $lname, $phone, $type, $state, $uid));
|
---|
| 2895 | $resultmsg = "Updated user info for $username ($fname $lname)";
|
---|
| 2896 | _log($dbh, group_id => $group, entry => $resultmsg);
|
---|
[83] | 2897 | $dbh->commit;
|
---|
| 2898 | };
|
---|
| 2899 | if ($@) {
|
---|
| 2900 | my $msg = $@;
|
---|
| 2901 | eval { $dbh->rollback; };
|
---|
[294] | 2902 | if ($config{log_failures}) {
|
---|
| 2903 | _log($dbh, (group_id => $group, entry => "Error updating user $username: $msg"));
|
---|
| 2904 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2905 | }
|
---|
| 2906 | return ('FAIL',"Error updating user $username: $msg");
|
---|
[83] | 2907 | }
|
---|
[294] | 2908 |
|
---|
| 2909 | return ('OK',$resultmsg);
|
---|
[83] | 2910 | } # end updateUser()
|
---|
| 2911 |
|
---|
| 2912 |
|
---|
[24] | 2913 | ## DNSDB::delUser()
|
---|
[297] | 2914 | # Delete a user.
|
---|
| 2915 | # Takes a database handle and user ID
|
---|
| 2916 | # Returns a success/failure code and matching message
|
---|
[24] | 2917 | sub delUser {
|
---|
[25] | 2918 | my $dbh = shift;
|
---|
| 2919 | my $userid = shift;
|
---|
| 2920 |
|
---|
[297] | 2921 | return ('FAIL',"Bad userid") if !defined($userid);
|
---|
[25] | 2922 |
|
---|
[297] | 2923 | my $userdata = getUserData($dbh, $userid);
|
---|
[25] | 2924 |
|
---|
[297] | 2925 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2926 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2927 | local $dbh->{AutoCommit} = 0;
|
---|
| 2928 | local $dbh->{RaiseError} = 1;
|
---|
[25] | 2929 |
|
---|
[297] | 2930 | eval {
|
---|
| 2931 | $dbh->do("DELETE FROM users WHERE user_id=?", undef, ($userid));
|
---|
| 2932 | _log($dbh, (group_id => $userdata->{group_id},
|
---|
| 2933 | entry => "Deleted user ID $userid/".$userdata->{username}.
|
---|
| 2934 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")") );
|
---|
| 2935 | $dbh->commit;
|
---|
| 2936 | };
|
---|
| 2937 | if ($@) {
|
---|
| 2938 | my $msg = $@;
|
---|
| 2939 | eval { $dbh->rollback; };
|
---|
| 2940 | if ($config{log_failures}) {
|
---|
| 2941 | _log($dbh, (group_id => $userdata->{group_id}, entry => "Error deleting user ID ".
|
---|
| 2942 | "$userid/".$userdata->{username}.": $msg") );
|
---|
| 2943 | $dbh->commit;
|
---|
| 2944 | }
|
---|
| 2945 | return ('FAIL',"Error deleting user $userid/".$userdata->{username}.": $msg");
|
---|
| 2946 | }
|
---|
| 2947 |
|
---|
| 2948 | return ('OK',"Deleted user ".$userdata->{username}." (".$userdata->{firstname}." ".$userdata->{lastname}.")");
|
---|
[24] | 2949 | } # end delUser
|
---|
| 2950 |
|
---|
| 2951 |
|
---|
[25] | 2952 | ## DNSDB::userFullName()
|
---|
| 2953 | # Return a pretty string!
|
---|
| 2954 | # Takes a user_id and optional printf-ish string to indicate which pieces where:
|
---|
| 2955 | # %u for the username
|
---|
| 2956 | # %f for the first name
|
---|
| 2957 | # %l for the last name
|
---|
| 2958 | # All other text in the passed string will be left as-is.
|
---|
| 2959 | ##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
|
---|
| 2960 | sub userFullName {
|
---|
| 2961 | $errstr = '';
|
---|
| 2962 | my $dbh = shift;
|
---|
| 2963 | my $userid = shift;
|
---|
| 2964 | my $fullformat = shift || '%f %l (%u)';
|
---|
| 2965 | my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
|
---|
| 2966 | $sth->execute($userid);
|
---|
| 2967 | my ($uname,$fname,$lname) = $sth->fetchrow_array();
|
---|
| 2968 | $errstr = $DBI::errstr if !$uname;
|
---|
| 2969 |
|
---|
| 2970 | $fullformat =~ s/\%u/$uname/g;
|
---|
| 2971 | $fullformat =~ s/\%f/$fname/g;
|
---|
| 2972 | $fullformat =~ s/\%l/$lname/g;
|
---|
| 2973 |
|
---|
| 2974 | return $fullformat;
|
---|
| 2975 | } # end userFullName
|
---|
| 2976 |
|
---|
| 2977 |
|
---|
[51] | 2978 | ## DNSDB::userStatus()
|
---|
| 2979 | # Sets and/or returns a user's status
|
---|
| 2980 | # Takes a database handle, user ID and optionally a status argument
|
---|
| 2981 | # Returns undef on errors.
|
---|
| 2982 | sub userStatus {
|
---|
| 2983 | my $dbh = shift;
|
---|
| 2984 | my $id = shift;
|
---|
[296] | 2985 | my $newstatus = shift || 'mu';
|
---|
[51] | 2986 |
|
---|
| 2987 | return undef if $id !~ /^\d+$/;
|
---|
| 2988 |
|
---|
[296] | 2989 | my $userdata = getUserData($dbh, $id);
|
---|
[51] | 2990 |
|
---|
[296] | 2991 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2992 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2993 | local $dbh->{AutoCommit} = 0;
|
---|
| 2994 | local $dbh->{RaiseError} = 1;
|
---|
| 2995 |
|
---|
| 2996 | if ($newstatus ne 'mu') {
|
---|
| 2997 | # ooo, fun! let's see what we were passed for status
|
---|
| 2998 | eval {
|
---|
| 2999 | $newstatus = 0 if $newstatus eq 'useroff';
|
---|
| 3000 | $newstatus = 1 if $newstatus eq 'useron';
|
---|
| 3001 | $dbh->do("UPDATE users SET status=? WHERE user_id=?", undef, ($newstatus, $id));
|
---|
| 3002 |
|
---|
[297] | 3003 | $resultstr = ($newstatus ? 'Enabled' : 'Disabled')." user ".$userdata->{username}.
|
---|
| 3004 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")";
|
---|
[296] | 3005 |
|
---|
| 3006 | my %loghash;
|
---|
| 3007 | $loghash{group_id} = parentID($dbh, (id => $id, type => 'user'));
|
---|
| 3008 | $loghash{entry} = $resultstr;
|
---|
| 3009 | _log($dbh, %loghash);
|
---|
| 3010 |
|
---|
| 3011 | $dbh->commit;
|
---|
| 3012 | };
|
---|
| 3013 | if ($@) {
|
---|
| 3014 | my $msg = $@;
|
---|
| 3015 | eval { $dbh->rollback; };
|
---|
| 3016 | $resultstr = '';
|
---|
| 3017 | $errstr = $msg;
|
---|
| 3018 | ##fixme: failure logging?
|
---|
| 3019 | return;
|
---|
[51] | 3020 | }
|
---|
| 3021 | }
|
---|
| 3022 |
|
---|
[296] | 3023 | my ($status) = $dbh->selectrow_array("SELECT status FROM users WHERE user_id=?", undef, ($id));
|
---|
[51] | 3024 | return $status;
|
---|
| 3025 | } # end userStatus()
|
---|
| 3026 |
|
---|
| 3027 |
|
---|
[83] | 3028 | ## DNSDB::getUserData()
|
---|
| 3029 | # Get misc user data for display
|
---|
| 3030 | sub getUserData {
|
---|
| 3031 | my $dbh = shift;
|
---|
| 3032 | my $uid = shift;
|
---|
| 3033 |
|
---|
| 3034 | my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
|
---|
| 3035 | "FROM users WHERE user_id=?");
|
---|
| 3036 | $sth->execute($uid);
|
---|
| 3037 | return $sth->fetchrow_hashref();
|
---|
| 3038 | } # end getUserData()
|
---|
| 3039 |
|
---|
| 3040 |
|
---|
[370] | 3041 | ## DNSDB::addLoc()
|
---|
[375] | 3042 | # Add a new location.
|
---|
| 3043 | # Takes a database handle, group ID, short and long description, and a comma-separated
|
---|
| 3044 | # list of IP addresses.
|
---|
| 3045 | # Returns ('OK',<location>) on success, ('FAIL',<failmsg>) on failure
|
---|
| 3046 | sub addLoc {
|
---|
| 3047 | my $dbh = shift;
|
---|
| 3048 | my $grp = shift;
|
---|
| 3049 | my $shdesc = shift;
|
---|
| 3050 | my $comments = shift;
|
---|
| 3051 | my $iplist = shift;
|
---|
[370] | 3052 |
|
---|
[375] | 3053 | # $shdesc gets set to the generated location ID if possible, but these can be de-undefined here.
|
---|
| 3054 | $comments = '' if !$comments;
|
---|
| 3055 | $iplist = '' if !$iplist;
|
---|
| 3056 |
|
---|
| 3057 | my $loc;
|
---|
| 3058 |
|
---|
| 3059 | # Generate a location ID. This is, by spec, a two-character widget. We'll use [a-z][a-z]
|
---|
| 3060 | # for now; 676 locations should satisfy all but the largest of the huge networks.
|
---|
| 3061 | # Not sure whether these are case-sensitive, or what other rules might apply - in any case
|
---|
| 3062 | # the absolute maximum is 16K (256*256) since it's parsed by tinydns as a two-character field.
|
---|
| 3063 |
|
---|
| 3064 | # add just after "my $origloc = $loc;":
|
---|
| 3065 | # # These expand the possible space from 26^2 to 52^2 [* note in testing only 2052 were achieved],
|
---|
| 3066 | # # and wrap it around.
|
---|
| 3067 | # # Yes, they skip a couple of possibles. No, I don't care.
|
---|
| 3068 | # $loc = 'aA' if $loc eq 'zz';
|
---|
| 3069 | # $loc = 'Aa' if $loc eq 'zZ';
|
---|
| 3070 | # $loc = 'ZA' if $loc eq 'Zz';
|
---|
| 3071 | # $loc = 'aa' if $loc eq 'ZZ';
|
---|
| 3072 |
|
---|
| 3073 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3074 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3075 | local $dbh->{AutoCommit} = 0;
|
---|
| 3076 | local $dbh->{RaiseError} = 1;
|
---|
| 3077 |
|
---|
| 3078 | ##fixme: There is probably a far better way to do this. Sequential increments
|
---|
| 3079 | # are marginally less stupid that pure random generation though, and the existence
|
---|
| 3080 | # check makes sure we don't stomp on an imported one.
|
---|
| 3081 |
|
---|
| 3082 | eval {
|
---|
| 3083 | # Get the "last" location. Note this is the only use for loc_id, because selecting on location Does Funky Things
|
---|
| 3084 | ($loc) = $dbh->selectrow_array("SELECT location FROM locations ORDER BY loc_id DESC LIMIT 1");
|
---|
| 3085 | ($loc) = ($loc =~ /^(..)/);
|
---|
| 3086 | my $origloc = $loc;
|
---|
[446] | 3087 | $loc = 'aa' if !$loc;
|
---|
[375] | 3088 | # Make a change...
|
---|
| 3089 | $loc++;
|
---|
| 3090 | # ... and keep changing if it exists
|
---|
| 3091 | while ($dbh->selectrow_array("SELECT count(*) FROM locations WHERE location LIKE ?", undef, ($loc.'%'))) {
|
---|
| 3092 | $loc++;
|
---|
| 3093 | ($loc) = ($loc =~ /^(..)/);
|
---|
| 3094 | die "too many locations in use, can't add another one\n" if $loc eq $origloc;
|
---|
| 3095 | ##fixme: really need to handle this case faster somehow
|
---|
| 3096 | #if $loc eq $origloc die "<thwap> bad admin: all locations used, your network is too fragmented";
|
---|
| 3097 | }
|
---|
| 3098 | # And now we should have a unique location. tinydns fundamentally limits the
|
---|
| 3099 | # number of these but there's no doc on what characters are valid.
|
---|
| 3100 | $shdesc = $loc if !$shdesc;
|
---|
| 3101 | $dbh->do("INSERT INTO locations (location, group_id, iplist, description, comments) VALUES (?,?,?,?,?)",
|
---|
| 3102 | undef, ($loc, $grp, $iplist, $shdesc, $comments) );
|
---|
[377] | 3103 | _log($dbh, entry => "Added location ($shdesc, '$iplist')");
|
---|
| 3104 | $dbh->commit;
|
---|
[375] | 3105 | };
|
---|
| 3106 | if ($@) {
|
---|
| 3107 | my $msg = $@;
|
---|
| 3108 | eval { $dbh->rollback; };
|
---|
| 3109 | if ($config{log_failures}) {
|
---|
| 3110 | $shdesc = $loc if !$shdesc;
|
---|
| 3111 | _log($dbh, (entry => "Failed adding location ($shdesc, '$iplist'): $msg"));
|
---|
| 3112 | $dbh->commit;
|
---|
| 3113 | }
|
---|
| 3114 | return ('FAIL',$msg);
|
---|
| 3115 | }
|
---|
| 3116 |
|
---|
| 3117 | return ('OK',$loc);
|
---|
[377] | 3118 | } # end addLoc()
|
---|
[375] | 3119 |
|
---|
| 3120 |
|
---|
[370] | 3121 | ## DNSDB::updateLoc()
|
---|
[428] | 3122 | # Update details of a location.
|
---|
| 3123 | # Takes a database handle, location ID, group ID, short description,
|
---|
| 3124 | # long comments/notes, and comma/space-separated IP list
|
---|
| 3125 | # Returns a result code and message
|
---|
[377] | 3126 | sub updateLoc {
|
---|
| 3127 | my $dbh = shift;
|
---|
| 3128 | my $loc = shift;
|
---|
| 3129 | my $grp = shift;
|
---|
| 3130 | my $shdesc = shift;
|
---|
| 3131 | my $comments = shift;
|
---|
| 3132 | my $iplist = shift;
|
---|
[370] | 3133 |
|
---|
[377] | 3134 | $shdesc = '' if !$shdesc;
|
---|
| 3135 | $comments = '' if !$comments;
|
---|
| 3136 | $iplist = '' if !$iplist;
|
---|
| 3137 |
|
---|
| 3138 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3139 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3140 | local $dbh->{AutoCommit} = 0;
|
---|
| 3141 | local $dbh->{RaiseError} = 1;
|
---|
| 3142 |
|
---|
| 3143 | my $oldloc = getLoc($dbh, $loc);
|
---|
| 3144 | my $okmsg = "Updated location (".$oldloc->{description}.", '".$oldloc->{iplist}."') to ($shdesc, '$iplist')";
|
---|
| 3145 |
|
---|
| 3146 | eval {
|
---|
| 3147 | $dbh->do("UPDATE locations SET group_id=?,iplist=?,description=?,comments=? WHERE location=?",
|
---|
| 3148 | undef, ($grp, $iplist, $shdesc, $comments, $loc) );
|
---|
| 3149 | _log($dbh, entry => $okmsg);
|
---|
| 3150 | $dbh->commit;
|
---|
| 3151 | };
|
---|
| 3152 | if ($@) {
|
---|
| 3153 | my $msg = $@;
|
---|
| 3154 | eval { $dbh->rollback; };
|
---|
| 3155 | if ($config{log_failures}) {
|
---|
| 3156 | $shdesc = $loc if !$shdesc;
|
---|
| 3157 | _log($dbh, (entry => "Failed updating location ($shdesc, '$iplist'): $msg"));
|
---|
| 3158 | $dbh->commit;
|
---|
| 3159 | }
|
---|
| 3160 | return ('FAIL',$msg);
|
---|
| 3161 | }
|
---|
| 3162 |
|
---|
| 3163 | return ('OK',$okmsg);
|
---|
| 3164 | } # end updateLoc()
|
---|
| 3165 |
|
---|
| 3166 |
|
---|
[370] | 3167 | ## DNSDB::delLoc()
|
---|
[428] | 3168 | sub delLoc {
|
---|
| 3169 | my $dbh = shift;
|
---|
| 3170 | my $loc = shift;
|
---|
[370] | 3171 |
|
---|
[428] | 3172 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3173 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3174 | local $dbh->{AutoCommit} = 0;
|
---|
| 3175 | local $dbh->{RaiseError} = 1;
|
---|
[370] | 3176 |
|
---|
[428] | 3177 | my $oldloc = getLoc($dbh, $loc);
|
---|
| 3178 | my $olddesc = ($oldloc->{description} ? $oldloc->{description} : $loc);
|
---|
| 3179 | my $okmsg = "Deleted location ($olddesc, '".$oldloc->{iplist}."')";
|
---|
| 3180 |
|
---|
| 3181 | eval {
|
---|
| 3182 | # Check for records with this location first. Deleting a location without deleting records
|
---|
| 3183 | # tagged for that location will render them unpublished without other warning.
|
---|
| 3184 | my ($r) = $dbh->selectrow_array("SELECT record_id FROM records WHERE location=? LIMIT 1", undef, ($loc) );
|
---|
| 3185 | die "Records still exist in location $olddesc\n" if $r;
|
---|
| 3186 | $dbh->do("DELETE FROM locations WHERE location=?", undef, ($loc) );
|
---|
| 3187 | _log($dbh, entry => $okmsg);
|
---|
| 3188 | $dbh->commit;
|
---|
| 3189 | };
|
---|
| 3190 | if ($@) {
|
---|
| 3191 | my $msg = $@;
|
---|
| 3192 | eval { $dbh->rollback; };
|
---|
| 3193 | if ($config{log_failures}) {
|
---|
| 3194 | _log($dbh, (entry => "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg"));
|
---|
| 3195 | $dbh->commit;
|
---|
| 3196 | }
|
---|
| 3197 | return ('FAIL', "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
|
---|
| 3198 | }
|
---|
| 3199 |
|
---|
| 3200 | return ('OK',$okmsg);
|
---|
| 3201 | } # end delLoc()
|
---|
| 3202 |
|
---|
| 3203 |
|
---|
[375] | 3204 | ## DNSDB::getLoc()
|
---|
[428] | 3205 | # Get details about a location/view
|
---|
| 3206 | # Takes a database handle and location ID.
|
---|
| 3207 | # Returns a reference to a hash containing the group ID, IP list, description, and comments/notes
|
---|
[375] | 3208 | sub getLoc {
|
---|
| 3209 | my $dbh = shift;
|
---|
| 3210 | my $loc = shift;
|
---|
| 3211 |
|
---|
| 3212 | my $sth = $dbh->prepare("SELECT group_id,iplist,description,comments FROM locations WHERE location=?");
|
---|
| 3213 | $sth->execute($loc);
|
---|
| 3214 | return $sth->fetchrow_hashref();
|
---|
| 3215 | } # end getLoc()
|
---|
| 3216 |
|
---|
| 3217 |
|
---|
[370] | 3218 | ## DNSDB::getLocCount()
|
---|
| 3219 | # Get count of locations/views
|
---|
| 3220 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
| 3221 | # - a reference list of secondary groups
|
---|
| 3222 | # - a filter string
|
---|
| 3223 | # - a "Starts with" string
|
---|
| 3224 | sub getLocCount {
|
---|
| 3225 | my $dbh = shift;
|
---|
| 3226 |
|
---|
| 3227 | my %args = @_;
|
---|
| 3228 |
|
---|
| 3229 | my @filterargs;
|
---|
| 3230 |
|
---|
| 3231 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3232 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3233 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3234 |
|
---|
| 3235 |
|
---|
| 3236 | my $sql = "SELECT count(*) FROM locations ".
|
---|
| 3237 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3238 | ($args{startwith} ? " AND description ~* ?" : '').
|
---|
| 3239 | ($args{filter} ? " AND description ~* ?" : '');
|
---|
| 3240 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 3241 | $errstr = $dbh->errstr if !$count;
|
---|
| 3242 | return $count;
|
---|
| 3243 | } # end getLocCount()
|
---|
| 3244 |
|
---|
| 3245 |
|
---|
| 3246 | ## DNSDB::getLocList()
|
---|
| 3247 | sub getLocList {
|
---|
| 3248 | my $dbh = shift;
|
---|
| 3249 |
|
---|
| 3250 | my %args = @_;
|
---|
| 3251 |
|
---|
| 3252 | my @filterargs;
|
---|
| 3253 |
|
---|
| 3254 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3255 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3256 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3257 |
|
---|
| 3258 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
| 3259 | # my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
| 3260 | # fname => 'fname');
|
---|
| 3261 | # $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 3262 |
|
---|
| 3263 | # protection against bad or missing arguments
|
---|
| 3264 | $args{sortorder} = 'ASC' if !$args{sortorder};
|
---|
| 3265 | $args{sortby} = 'l.description' if !$args{sortby};
|
---|
[397] | 3266 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[370] | 3267 |
|
---|
| 3268 | my $sql = "SELECT l.location, l.description, l.iplist, g.group_name ".
|
---|
| 3269 | "FROM locations l ".
|
---|
| 3270 | "INNER JOIN groups g ON l.group_id=g.group_id ".
|
---|
| 3271 | "WHERE l.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3272 | ($args{startwith} ? " AND l.description ~* ?" : '').
|
---|
| 3273 | ($args{filter} ? " AND l.description ~* ?" : '').
|
---|
| 3274 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
| 3275 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
| 3276 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 3277 | $errstr = $dbh->errstr if !$ulist;
|
---|
| 3278 | return $ulist;
|
---|
| 3279 | } # end getLocList()
|
---|
| 3280 |
|
---|
| 3281 |
|
---|
| 3282 | ## DNSDB::getLocDropdown()
|
---|
[383] | 3283 | # Get a list of location names for use in a dropdown menu.
|
---|
| 3284 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
| 3285 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
| 3286 | sub getLocDropdown {
|
---|
| 3287 | my $dbh = shift;
|
---|
| 3288 | my $grp = shift;
|
---|
| 3289 | my $sel = shift || '';
|
---|
[370] | 3290 |
|
---|
[383] | 3291 | my $sth = $dbh->prepare(qq(
|
---|
| 3292 | SELECT description,location FROM locations
|
---|
| 3293 | WHERE group_id=?
|
---|
| 3294 | ORDER BY description
|
---|
| 3295 | ) );
|
---|
| 3296 | $sth->execute($grp);
|
---|
[370] | 3297 |
|
---|
[383] | 3298 | my @loclist;
|
---|
[446] | 3299 | push @loclist, { locname => "(Default/All)", loc => '', selected => ($sel ? 0 : ($sel eq '' ? 1 : 0)) };
|
---|
[383] | 3300 | while (my ($locname, $loc) = $sth->fetchrow_array) {
|
---|
| 3301 | my %row = (
|
---|
| 3302 | locname => $locname,
|
---|
| 3303 | loc => $loc,
|
---|
| 3304 | selected => ($sel eq $loc ? 1 : 0)
|
---|
| 3305 | );
|
---|
| 3306 | push @loclist, \%row;
|
---|
| 3307 | }
|
---|
| 3308 | return \@loclist;
|
---|
| 3309 | } # end getLocDropdown()
|
---|
| 3310 |
|
---|
| 3311 |
|
---|
[2] | 3312 | ## DNSDB::getSOA()
|
---|
| 3313 | # Return all suitable fields from an SOA record in separate elements of a hash
|
---|
[224] | 3314 | # Takes a database handle, default/live flag, domain/reverse flag, and parent ID
|
---|
[2] | 3315 | sub getSOA {
|
---|
| 3316 | $errstr = '';
|
---|
| 3317 | my $dbh = shift;
|
---|
| 3318 | my $def = shift;
|
---|
[224] | 3319 | my $rev = shift;
|
---|
[2] | 3320 | my $id = shift;
|
---|
| 3321 |
|
---|
[224] | 3322 | # (ab)use distance and weight columns to store SOA data? can't for default_rev_records...
|
---|
| 3323 | # - should really attach serial to the zone parent somewhere
|
---|
[101] | 3324 |
|
---|
[224] | 3325 | my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev).
|
---|
| 3326 | " WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}";
|
---|
[311] | 3327 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
| 3328 | return if !$ret;
|
---|
[246] | 3329 | ##fixme: stick a flag somewhere if the record doesn't exist. by the API, this is an impossible case, but...
|
---|
[2] | 3330 |
|
---|
[311] | 3331 | ($ret->{contact},$ret->{prins}) = split /:/, $ret->{host};
|
---|
| 3332 | delete $ret->{host};
|
---|
| 3333 | ($ret->{refresh},$ret->{retry},$ret->{expire},$ret->{minttl}) = split /:/, $ret->{val};
|
---|
| 3334 | delete $ret->{val};
|
---|
[2] | 3335 |
|
---|
[311] | 3336 | return $ret;
|
---|
[2] | 3337 | } # end getSOA()
|
---|
| 3338 |
|
---|
| 3339 |
|
---|
[246] | 3340 | ## DNSDB::updateSOA()
|
---|
| 3341 | # Update the specified SOA record
|
---|
| 3342 | # Takes a database handle, default/live flag, forward/reverse flag, and SOA data hash
|
---|
[277] | 3343 | # Returns a two-element list with a result code and message
|
---|
[246] | 3344 | sub updateSOA {
|
---|
| 3345 | my $dbh = shift;
|
---|
| 3346 | my $defrec = shift;
|
---|
[248] | 3347 | my $revrec = shift;
|
---|
[246] | 3348 |
|
---|
| 3349 | my %soa = @_;
|
---|
| 3350 |
|
---|
[311] | 3351 | my $oldsoa = getSOA($dbh, $defrec, $revrec, $soa{id});
|
---|
[277] | 3352 |
|
---|
[311] | 3353 | my $msg;
|
---|
| 3354 | my %logdata;
|
---|
| 3355 | if ($defrec eq 'n') {
|
---|
| 3356 | $logdata{domain_id} = $soa{id} if $revrec eq 'n';
|
---|
| 3357 | $logdata{rdns_id} = $soa{id} if $revrec eq 'y';
|
---|
| 3358 | $logdata{group_id} = parentID($dbh, (id => $soa{id}, revrec => $revrec,
|
---|
| 3359 | type => ($revrec eq 'n' ? 'domain' : 'revzone') ) );
|
---|
| 3360 | } else {
|
---|
| 3361 | $logdata{group_id} = $soa{id};
|
---|
| 3362 | }
|
---|
| 3363 | my $parname = ($defrec eq 'y' ? groupName($dbh, $soa{id}) :
|
---|
| 3364 | ($revrec eq 'n' ? domainName($dbh, $soa{id}) : revName($dbh, $soa{id})) );
|
---|
| 3365 |
|
---|
[277] | 3366 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3367 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3368 | local $dbh->{AutoCommit} = 0;
|
---|
| 3369 | local $dbh->{RaiseError} = 1;
|
---|
| 3370 |
|
---|
| 3371 | eval {
|
---|
| 3372 | my $sql = "UPDATE "._rectable($defrec, $revrec)." SET host=?, val=?, ttl=? WHERE record_id=? AND type=6";
|
---|
| 3373 | $dbh->do($sql, undef, ("$soa{contact}:$soa{prins}", "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}",
|
---|
[311] | 3374 | $soa{ttl}, $oldsoa->{record_id}) );
|
---|
| 3375 | $msg = "Updated ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse ' : 'default ') : '').
|
---|
| 3376 | "SOA for $parname: ".
|
---|
| 3377 | "(ns $oldsoa->{prins}, contact $oldsoa->{contact}, refresh $oldsoa->{refresh},".
|
---|
| 3378 | " retry $oldsoa->{retry}, expire $oldsoa->{expire}, minTTL $oldsoa->{minttl}, TTL $oldsoa->{ttl}) to ".
|
---|
[277] | 3379 | "(ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
|
---|
| 3380 | " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})";
|
---|
| 3381 |
|
---|
[311] | 3382 | $logdata{entry} = $msg;
|
---|
| 3383 | _log($dbh, %logdata);
|
---|
[277] | 3384 |
|
---|
| 3385 | $dbh->commit;
|
---|
| 3386 | };
|
---|
| 3387 | if ($@) {
|
---|
| 3388 | $msg = $@;
|
---|
| 3389 | eval { $dbh->rollback; };
|
---|
[311] | 3390 | $logdata{entry} = "Error updating ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse zone ' : 'default ') : '').
|
---|
| 3391 | "SOA record for $parname: $msg";
|
---|
| 3392 | if ($config{log_failures}) {
|
---|
| 3393 | _log($dbh, %logdata);
|
---|
| 3394 | $dbh->commit;
|
---|
| 3395 | }
|
---|
| 3396 | return ('FAIL', $logdata{entry});
|
---|
[277] | 3397 | } else {
|
---|
| 3398 | return ('OK', $msg);
|
---|
| 3399 | }
|
---|
[246] | 3400 | } # end updateSOA()
|
---|
| 3401 |
|
---|
| 3402 |
|
---|
[2] | 3403 | ## DNSDB::getRecLine()
|
---|
| 3404 | # Return all data fields for a zone record in separate elements of a hash
|
---|
[243] | 3405 | # Takes a database handle, default/live flag, forward/reverse flag, and record ID
|
---|
[2] | 3406 | sub getRecLine {
|
---|
| 3407 | $errstr = '';
|
---|
| 3408 | my $dbh = shift;
|
---|
[243] | 3409 | my $defrec = shift;
|
---|
| 3410 | my $revrec = shift;
|
---|
[2] | 3411 | my $id = shift;
|
---|
| 3412 |
|
---|
[429] | 3413 | my $sql = "SELECT record_id,host,type,val,ttl".
|
---|
| 3414 | ($defrec eq 'n' ? ',location' : '').
|
---|
| 3415 | ($revrec eq 'n' ? ',distance,weight,port' : '').
|
---|
[243] | 3416 | (($defrec eq 'y') ? ',group_id FROM ' : ',domain_id,rdns_id FROM ').
|
---|
| 3417 | _rectable($defrec,$revrec)." WHERE record_id=?";
|
---|
[123] | 3418 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
[2] | 3419 |
|
---|
[90] | 3420 | if ($dbh->err) {
|
---|
[2] | 3421 | $errstr = $DBI::errstr;
|
---|
| 3422 | return undef;
|
---|
| 3423 | }
|
---|
| 3424 |
|
---|
[123] | 3425 | if (!$ret) {
|
---|
| 3426 | $errstr = "No such record";
|
---|
| 3427 | return undef;
|
---|
| 3428 | }
|
---|
| 3429 |
|
---|
[243] | 3430 | # explicitly set a parent id
|
---|
| 3431 | if ($defrec eq 'y') {
|
---|
| 3432 | $ret->{parid} = $ret->{group_id};
|
---|
| 3433 | } else {
|
---|
| 3434 | $ret->{parid} = (($revrec eq 'n') ? $ret->{domain_id} : $ret->{rdns_id});
|
---|
| 3435 | # and a secondary if we have a custom type that lives in both a forward and reverse zone
|
---|
| 3436 | $ret->{secid} = (($revrec eq 'y') ? $ret->{domain_id} : $ret->{rdns_id}) if $ret->{type} > 65279;
|
---|
| 3437 | }
|
---|
[451] | 3438 | $ret->{address} = $ret->{val}; # because.
|
---|
[90] | 3439 |
|
---|
| 3440 | return $ret;
|
---|
[2] | 3441 | }
|
---|
| 3442 |
|
---|
| 3443 |
|
---|
| 3444 | ##fixme: should use above (getRecLine()) to get lines for below?
|
---|
| 3445 | ## DNSDB::getDomRecs()
|
---|
| 3446 | # Return records for a domain
|
---|
| 3447 | # Takes a database handle, default/live flag, group/domain ID, start,
|
---|
| 3448 | # number of records, sort field, and sort order
|
---|
| 3449 | # Returns a reference to an array of hashes
|
---|
| 3450 | sub getDomRecs {
|
---|
| 3451 | $errstr = '';
|
---|
| 3452 | my $dbh = shift;
|
---|
| 3453 |
|
---|
[397] | 3454 | my %args = @_;
|
---|
[4] | 3455 |
|
---|
[397] | 3456 | my @filterargs;
|
---|
[135] | 3457 |
|
---|
[397] | 3458 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3459 |
|
---|
| 3460 | # protection against bad or missing arguments
|
---|
| 3461 | $args{sortorder} = 'ASC' if !$args{sortorder};
|
---|
[399] | 3462 | $args{sortby} = 'host' if !$args{sortby} && $args{revrec} eq 'n'; # default sort by host on domain record list
|
---|
| 3463 | $args{sortby} = 'val' if !$args{sortby} && $args{revrec} eq 'y'; # default sort by IP on revzone record list
|
---|
[397] | 3464 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
| 3465 |
|
---|
[352] | 3466 | # sort reverse zones on IP, correctly
|
---|
[397] | 3467 | # do other fiddling with $args{sortby} while we're at it.
|
---|
[420] | 3468 | # whee! multisort means just passing comma-separated fields in sortby!
|
---|
| 3469 | my $newsort = '';
|
---|
| 3470 | foreach my $sf (split /,/, $args{sortby}) {
|
---|
| 3471 | $sf = "r.$sf";
|
---|
| 3472 | $sf =~ s/r\.val/CAST (r.val AS inet)/
|
---|
| 3473 | if $args{revrec} eq 'y' && $args{defrec} eq 'n';
|
---|
| 3474 | $sf =~ s/r\.type/t.alphaorder/;
|
---|
| 3475 | $newsort .= ",$sf";
|
---|
| 3476 | }
|
---|
| 3477 | $newsort =~ s/^,//;
|
---|
[352] | 3478 |
|
---|
[224] | 3479 | my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.ttl";
|
---|
[397] | 3480 | $sql .= ",l.description AS locname" if $args{defrec} eq 'n';
|
---|
| 3481 | $sql .= ",r.distance,r.weight,r.port" if $args{revrec} eq 'n';
|
---|
| 3482 | $sql .= " FROM "._rectable($args{defrec},$args{revrec})." r ";
|
---|
[104] | 3483 | $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
|
---|
[397] | 3484 | $sql .= "LEFT JOIN locations l ON r.location=l.location " if $args{defrec} eq 'n';
|
---|
| 3485 | $sql .= "WHERE "._recparent($args{defrec},$args{revrec})." = ?";
|
---|
[104] | 3486 | $sql .= " AND NOT r.type=$reverse_typemap{SOA}";
|
---|
[439] | 3487 | $sql .= " AND (r.host ~* ? OR r.val ~* ?)" if $args{filter};
|
---|
[420] | 3488 | $sql .= " ORDER BY $newsort $args{sortorder}";
|
---|
[324] | 3489 | # ensure consistent ordering by sorting on record_id too
|
---|
[397] | 3490 | $sql .= ", record_id $args{sortorder}";
|
---|
| 3491 | $sql .= ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
[4] | 3492 |
|
---|
[397] | 3493 | my @bindvars = ($args{id});
|
---|
[439] | 3494 | push @bindvars, ($args{filter},$args{filter}) if $args{filter};
|
---|
[224] | 3495 |
|
---|
[397] | 3496 | my $ret = $dbh->selectall_arrayref($sql, { Slice => {} }, (@bindvars) );
|
---|
[2] | 3497 | return $ret;
|
---|
| 3498 | } # end getDomRecs()
|
---|
| 3499 |
|
---|
| 3500 |
|
---|
[91] | 3501 | ## DNSDB::getRecCount()
|
---|
[224] | 3502 | # Return count of non-SOA records in zone (or default records in a group)
|
---|
| 3503 | # Takes a database handle, default/live flag, reverse/forward flag, group/domain ID,
|
---|
| 3504 | # and optional filtering modifier
|
---|
[91] | 3505 | # Returns the count
|
---|
| 3506 | sub getRecCount {
|
---|
| 3507 | my $dbh = shift;
|
---|
| 3508 | my $defrec = shift;
|
---|
[224] | 3509 | my $revrec = shift;
|
---|
[91] | 3510 | my $id = shift;
|
---|
[135] | 3511 | my $filter = shift || '';
|
---|
[91] | 3512 |
|
---|
[135] | 3513 | # keep the nasties down, since we can't ?-sub this bit. :/
|
---|
| 3514 | # note this is chars allowed in DNS hostnames
|
---|
| 3515 | $filter =~ s/[^a-zA-Z0-9_.:-]//g;
|
---|
| 3516 |
|
---|
[222] | 3517 | my @bindvars = ($id);
|
---|
| 3518 | push @bindvars, $filter if $filter;
|
---|
[224] | 3519 | my $sql = "SELECT count(*) FROM ".
|
---|
| 3520 | _rectable($defrec,$revrec).
|
---|
| 3521 | " WHERE "._recparent($defrec,$revrec)."=? ".
|
---|
| 3522 | "AND NOT type=$reverse_typemap{SOA}".
|
---|
| 3523 | ($filter ? " AND host ~* ?" : '');
|
---|
| 3524 | my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) );
|
---|
[91] | 3525 |
|
---|
| 3526 | return $count;
|
---|
| 3527 |
|
---|
| 3528 | } # end getRecCount()
|
---|
| 3529 |
|
---|
| 3530 |
|
---|
[3] | 3531 | ## DNSDB::addRec()
|
---|
[2] | 3532 | # Add a new record to a domain or a group's default records
|
---|
| 3533 | # Takes a database handle, default/live flag, group/domain ID,
|
---|
| 3534 | # host, type, value, and TTL
|
---|
| 3535 | # Some types require additional detail: "distance" for MX and SRV,
|
---|
| 3536 | # and weight/port for SRV
|
---|
| 3537 | # Returns a status code and detail message in case of error
|
---|
[234] | 3538 | ##fixme: pass a hash with the record data, not a series of separate values
|
---|
[2] | 3539 | sub addRec {
|
---|
| 3540 | $errstr = '';
|
---|
| 3541 | my $dbh = shift;
|
---|
| 3542 | my $defrec = shift;
|
---|
[226] | 3543 | my $revrec = shift;
|
---|
| 3544 | my $id = shift; # parent (group_id for defrecs, rdns_id for reverse records,
|
---|
| 3545 | # domain_id for domain records)
|
---|
[2] | 3546 |
|
---|
| 3547 | my $host = shift;
|
---|
[234] | 3548 | my $rectype = shift; # reference so we can coerce it if "+"-types can't find both zones
|
---|
[2] | 3549 | my $val = shift;
|
---|
| 3550 | my $ttl = shift;
|
---|
[389] | 3551 | my $location = shift;
|
---|
| 3552 | $location = '' if !$location;
|
---|
[2] | 3553 |
|
---|
[417] | 3554 | # Spaces are evil.
|
---|
| 3555 | $$host =~ s/^\s+//;
|
---|
| 3556 | $$host =~ s/\s+$//;
|
---|
[418] | 3557 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
[417] | 3558 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 3559 | $$val =~ s/^\s+//;
|
---|
| 3560 | $$val =~ s/\s+$//;
|
---|
| 3561 | }
|
---|
| 3562 |
|
---|
[226] | 3563 | # prep for validation
|
---|
[252] | 3564 | my $addr = NetAddr::IP->new($$val);
|
---|
| 3565 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
[226] | 3566 |
|
---|
| 3567 | my $domid = 0;
|
---|
| 3568 | my $revid = 0;
|
---|
| 3569 |
|
---|
| 3570 | my $retcode = 'OK'; # assume everything will go OK
|
---|
| 3571 | my $retmsg = '';
|
---|
| 3572 |
|
---|
| 3573 | # do simple validation first
|
---|
| 3574 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
|
---|
| 3575 |
|
---|
[234] | 3576 | # Quick check on hostname parts. Note the regex is more forgiving than the error message;
|
---|
| 3577 | # domain names technically are case-insensitive, and we use printf-like % codes for a couple
|
---|
| 3578 | # of types. Other things may also be added to validate default records of several flavours.
|
---|
| 3579 | return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z . _)")
|
---|
[350] | 3580 | if $defrec eq 'n' && ($revrec eq 'y' ? $$rectype != $reverse_typemap{TXT} : 1) &&
|
---|
| 3581 | $$host !~ /^[0-9a-z_%.-]+$/i;
|
---|
[226] | 3582 |
|
---|
[234] | 3583 | # Collect these even if we're only doing a simple A record so we can call *any* validation sub
|
---|
| 3584 | my $dist = shift;
|
---|
[281] | 3585 | my $weight = shift;
|
---|
[234] | 3586 | my $port = shift;
|
---|
[226] | 3587 |
|
---|
[234] | 3588 | my $fields;
|
---|
| 3589 | my @vallist;
|
---|
[226] | 3590 |
|
---|
[234] | 3591 | # Call the validation sub for the type requested.
|
---|
| 3592 | ($retcode,$retmsg) = $validators{$$rectype}($dbh, (defrec => $defrec, revrec => $revrec, id => $id,
|
---|
[249] | 3593 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
[234] | 3594 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
| 3595 | fields => \$fields, vallist => \@vallist) );
|
---|
[129] | 3596 |
|
---|
[234] | 3597 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
[209] | 3598 |
|
---|
[234] | 3599 | # Set up database fields and bind parameters
|
---|
[389] | 3600 | $fields .= "host,type,val,ttl,location,"._recparent($defrec,$revrec);
|
---|
| 3601 | push @vallist, ($$host,$$rectype,$$val,$ttl,$location,$id);
|
---|
[234] | 3602 | my $vallen = '?'.(',?'x$#vallist);
|
---|
[2] | 3603 |
|
---|
[287] | 3604 | # Put together the success log entry. We have to use this horrible kludge
|
---|
| 3605 | # because domain_id and rdns_id may or may not be present, and if they are,
|
---|
| 3606 | # they're not at a guaranteed consistent index in the array. wheee!
|
---|
| 3607 | my %logdata;
|
---|
| 3608 | my @ftmp = split /,/, $fields;
|
---|
| 3609 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
| 3610 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
| 3611 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
| 3612 | }
|
---|
| 3613 | $logdata{group_id} = $id if $defrec eq 'y';
|
---|
| 3614 | $logdata{group_id} = parentID($dbh,
|
---|
| 3615 | (id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) )
|
---|
| 3616 | if $defrec eq 'n';
|
---|
[328] | 3617 | $logdata{entry} = "Added ".($defrec eq 'y' ? 'default record' : 'record');
|
---|
| 3618 | # NS records for revzones get special treatment
|
---|
| 3619 | if ($revrec eq 'y' && $$rectype == 2) {
|
---|
| 3620 | $logdata{entry} .= " '$$val $typemap{$$rectype} $$host";
|
---|
| 3621 | } else {
|
---|
| 3622 | $logdata{entry} .= " '$$host $typemap{$$rectype} $$val";
|
---|
| 3623 | }
|
---|
| 3624 |
|
---|
[287] | 3625 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
| 3626 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]"
|
---|
| 3627 | if $typemap{$$rectype} eq 'SRV';
|
---|
[425] | 3628 | $logdata{entry} .= "', TTL $ttl";
|
---|
| 3629 | $logdata{entry} .= ", location ".getLoc($dbh, $location)->{description} if $location;
|
---|
[287] | 3630 |
|
---|
[90] | 3631 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3632 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3633 | local $dbh->{AutoCommit} = 0;
|
---|
| 3634 | local $dbh->{RaiseError} = 1;
|
---|
[2] | 3635 |
|
---|
[90] | 3636 | eval {
|
---|
[236] | 3637 | $dbh->do("INSERT INTO "._rectable($defrec, $revrec)." ($fields) VALUES ($vallen)",
|
---|
[90] | 3638 | undef, @vallist);
|
---|
[287] | 3639 | _log($dbh, %logdata);
|
---|
[90] | 3640 | $dbh->commit;
|
---|
| 3641 | };
|
---|
| 3642 | if ($@) {
|
---|
| 3643 | my $msg = $@;
|
---|
| 3644 | eval { $dbh->rollback; };
|
---|
[289] | 3645 | if ($config{log_failures}) {
|
---|
| 3646 | $logdata{entry} = "Failed adding ".($defrec eq 'y' ? 'default ' : '').
|
---|
| 3647 | "record '$$host $typemap{$$rectype} $$val', TTL $ttl ($msg)";
|
---|
| 3648 | _log($dbh, %logdata);
|
---|
| 3649 | $dbh->commit;
|
---|
| 3650 | }
|
---|
[90] | 3651 | return ('FAIL',$msg);
|
---|
| 3652 | }
|
---|
[2] | 3653 |
|
---|
[287] | 3654 | $resultstr = $logdata{entry};
|
---|
[226] | 3655 | return ($retcode, $retmsg);
|
---|
[90] | 3656 |
|
---|
[2] | 3657 | } # end addRec()
|
---|
| 3658 |
|
---|
| 3659 |
|
---|
[16] | 3660 | ## DNSDB::updateRec()
|
---|
| 3661 | # Update a record
|
---|
[273] | 3662 | # Takes a database handle, default and reverse flags, record ID, immediate parent ID, and new record data.
|
---|
| 3663 | # Returns a status code and message
|
---|
[16] | 3664 | sub updateRec {
|
---|
| 3665 | $errstr = '';
|
---|
[17] | 3666 |
|
---|
[16] | 3667 | my $dbh = shift;
|
---|
| 3668 | my $defrec = shift;
|
---|
[272] | 3669 | my $revrec = shift;
|
---|
[16] | 3670 | my $id = shift;
|
---|
[272] | 3671 | my $parid = shift; # immediate parent entity that we're descending from to update the record
|
---|
[16] | 3672 |
|
---|
[273] | 3673 | # all records have these
|
---|
[16] | 3674 | my $host = shift;
|
---|
[272] | 3675 | my $hostbk = $$host; # Keep a backup copy of the original, so we can WARN if the update mangles the domain
|
---|
| 3676 | my $rectype = shift;
|
---|
[16] | 3677 | my $val = shift;
|
---|
| 3678 | my $ttl = shift;
|
---|
[389] | 3679 | my $location = shift; # may be empty/null/undef depending on caller
|
---|
| 3680 | $location = '' if !$location;
|
---|
[16] | 3681 |
|
---|
[417] | 3682 | # Spaces are evil.
|
---|
| 3683 | $$host =~ s/^\s+//;
|
---|
| 3684 | $$host =~ s/\s+$//;
|
---|
[418] | 3685 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
[417] | 3686 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 3687 | $$val =~ s/^\s+//;
|
---|
| 3688 | $$val =~ s/\s+$//;
|
---|
| 3689 | }
|
---|
| 3690 |
|
---|
[272] | 3691 | # prep for validation
|
---|
| 3692 | my $addr = NetAddr::IP->new($$val);
|
---|
| 3693 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
[16] | 3694 |
|
---|
[272] | 3695 | my $domid = 0;
|
---|
| 3696 | my $revid = 0;
|
---|
| 3697 |
|
---|
| 3698 | my $retcode = 'OK'; # assume everything will go OK
|
---|
| 3699 | my $retmsg = '';
|
---|
| 3700 |
|
---|
[273] | 3701 | # do simple validation first
|
---|
[272] | 3702 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
|
---|
| 3703 |
|
---|
| 3704 | # Quick check on hostname parts. Note the regex is more forgiving than the error message;
|
---|
| 3705 | # domain names technically are case-insensitive, and we use printf-like % codes for a couple
|
---|
| 3706 | # of types. Other things may also be added to validate default records of several flavours.
|
---|
[273] | 3707 | return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z - . _)")
|
---|
[350] | 3708 | if $defrec eq 'n' && ($revrec eq 'y' ? $$rectype != $reverse_typemap{TXT} : 1) &&
|
---|
| 3709 | $$host !~ /^[0-9a-z_%.-]+$/i;
|
---|
[272] | 3710 |
|
---|
[273] | 3711 | # only MX and SRV will use these
|
---|
[288] | 3712 | my $dist = shift || 0;
|
---|
| 3713 | my $weight = shift || 0;
|
---|
| 3714 | my $port = shift || 0;
|
---|
[16] | 3715 |
|
---|
[272] | 3716 | my $fields;
|
---|
| 3717 | my @vallist;
|
---|
[16] | 3718 |
|
---|
[273] | 3719 | # get old record data so we have the right parent ID
|
---|
| 3720 | # and for logging (eventually)
|
---|
| 3721 | my $oldrec = getRecLine($dbh, $defrec, $revrec, $id);
|
---|
[223] | 3722 |
|
---|
[272] | 3723 | # Call the validation sub for the type requested.
|
---|
| 3724 | # Note the ID to pass here is the *parent*, not the record
|
---|
| 3725 | ($retcode,$retmsg) = $validators{$$rectype}($dbh, (defrec => $defrec, revrec => $revrec,
|
---|
| 3726 | id => ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})),
|
---|
| 3727 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
| 3728 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
| 3729 | fields => \$fields, vallist => \@vallist,
|
---|
| 3730 | update => $id) );
|
---|
| 3731 |
|
---|
| 3732 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
| 3733 |
|
---|
[273] | 3734 | # Set up database fields and bind parameters. Note only the optional fields
|
---|
| 3735 | # (distance, weight, port, secondary parent ID) are added in the validation call above
|
---|
[448] | 3736 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
| 3737 | push @vallist, ($$host,$$rectype,$$val,$ttl,
|
---|
[273] | 3738 | ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})) );
|
---|
[272] | 3739 |
|
---|
[448] | 3740 | # locations are not for default records, silly coder!
|
---|
| 3741 | if ($defrec eq 'n') {
|
---|
| 3742 | $fields .= ",location";
|
---|
| 3743 | push @vallist, $location;
|
---|
| 3744 | }
|
---|
| 3745 |
|
---|
[273] | 3746 | # hack hack PTHUI
|
---|
| 3747 | # need to forcibly make sure we disassociate a record with a parent it's no longer related to.
|
---|
| 3748 | # eg, PTR records may not have a domain parent, or A/AAAA records may not have a revzone parent.
|
---|
| 3749 | # mainly needed for crossover types that got coerced down to "standard" types
|
---|
| 3750 | if ($defrec eq 'n') {
|
---|
| 3751 | if ($$rectype == $reverse_typemap{PTR}) {
|
---|
| 3752 | $fields .= ",domain_id";
|
---|
| 3753 | push @vallist, 0;
|
---|
| 3754 | }
|
---|
| 3755 | if ($$rectype == $reverse_typemap{A} || $$rectype == $reverse_typemap{AAAA}) {
|
---|
| 3756 | $fields .= ",rdns_id";
|
---|
| 3757 | push @vallist, 0;
|
---|
| 3758 | }
|
---|
| 3759 | }
|
---|
[345] | 3760 | # fix fat-finger-originated record type changes
|
---|
| 3761 | if ($$rectype == 65285) {
|
---|
| 3762 | $fields .= ",rdns_id" if $revrec eq 'n';
|
---|
| 3763 | $fields .= ",domain_id" if $revrec eq 'y';
|
---|
| 3764 | push @vallist, 0;
|
---|
| 3765 | }
|
---|
[341] | 3766 | if ($defrec eq 'n') {
|
---|
| 3767 | $domid = $parid if $revrec eq 'n';
|
---|
| 3768 | $revid = $parid if $revrec eq 'y';
|
---|
| 3769 | }
|
---|
[272] | 3770 |
|
---|
[288] | 3771 | # Put together the success log entry. Horrible kludge from addRec() copied as-is since
|
---|
| 3772 | # we don't know whether the passed arguments or retrieved values for domain_id and rdns_id
|
---|
| 3773 | # will be maintained (due to "not-in-zone" validation changes)
|
---|
| 3774 | my %logdata;
|
---|
[341] | 3775 | $logdata{domain_id} = $domid;
|
---|
| 3776 | $logdata{rdns_id} = $revid;
|
---|
[288] | 3777 | my @ftmp = split /,/, $fields;
|
---|
| 3778 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
| 3779 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
| 3780 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
| 3781 | }
|
---|
| 3782 | $logdata{group_id} = $parid if $defrec eq 'y';
|
---|
| 3783 | $logdata{group_id} = parentID($dbh,
|
---|
| 3784 | (id => $parid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) )
|
---|
| 3785 | if $defrec eq 'n';
|
---|
[328] | 3786 | $logdata{entry} = "Updated ".($defrec eq 'y' ? 'default record' : 'record')." from\n";
|
---|
| 3787 | # NS records for revzones get special treatment
|
---|
| 3788 | if ($revrec eq 'y' && $$rectype == 2) {
|
---|
| 3789 | $logdata{entry} .= " '$oldrec->{val} $typemap{$oldrec->{type}} $oldrec->{host}";
|
---|
| 3790 | } else {
|
---|
| 3791 | $logdata{entry} .= " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
| 3792 | }
|
---|
[288] | 3793 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
| 3794 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
| 3795 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
[425] | 3796 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
| 3797 | $logdata{entry} .= ", location ".getLoc($dbh, $oldrec->{location})->{description} if $oldrec->{location};
|
---|
| 3798 | $logdata{entry} .= "\nto\n";
|
---|
[328] | 3799 | # More NS special
|
---|
| 3800 | if ($revrec eq 'y' && $$rectype == 2) {
|
---|
| 3801 | $logdata{entry} .= "'$$val $typemap{$$rectype} $$host";
|
---|
| 3802 | } else {
|
---|
| 3803 | $logdata{entry} .= "'$$host $typemap{$$rectype} $$val";
|
---|
| 3804 | }
|
---|
[288] | 3805 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
| 3806 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$$rectype} eq 'SRV';
|
---|
[425] | 3807 | $logdata{entry} .= "', TTL $ttl";
|
---|
| 3808 | $logdata{entry} .= ", location ".getLoc($dbh, $location)->{description} if $location;
|
---|
[288] | 3809 |
|
---|
[90] | 3810 | local $dbh->{AutoCommit} = 0;
|
---|
| 3811 | local $dbh->{RaiseError} = 1;
|
---|
| 3812 |
|
---|
[341] | 3813 | # Fiddle the field list into something suitable for updates
|
---|
| 3814 | $fields =~ s/,/=?,/g;
|
---|
| 3815 | $fields .= "=?";
|
---|
| 3816 |
|
---|
[90] | 3817 | eval {
|
---|
[273] | 3818 | $dbh->do("UPDATE "._rectable($defrec,$revrec)." SET $fields WHERE record_id=?", undef, (@vallist, $id) );
|
---|
[288] | 3819 | _log($dbh, %logdata);
|
---|
[130] | 3820 | $dbh->commit;
|
---|
[90] | 3821 | };
|
---|
| 3822 | if ($@) {
|
---|
| 3823 | my $msg = $@;
|
---|
[288] | 3824 | eval { $dbh->rollback; };
|
---|
[289] | 3825 | if ($config{log_failures}) {
|
---|
| 3826 | $logdata{entry} = "Failed updating ".($defrec eq 'y' ? 'default ' : '').
|
---|
| 3827 | "record '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
| 3828 | _log($dbh, %logdata);
|
---|
| 3829 | $dbh->commit;
|
---|
| 3830 | }
|
---|
[90] | 3831 | return ('FAIL', $msg);
|
---|
| 3832 | }
|
---|
| 3833 |
|
---|
[288] | 3834 | $resultstr = $logdata{entry};
|
---|
[272] | 3835 | return ($retcode, $retmsg);
|
---|
[16] | 3836 | } # end updateRec()
|
---|
| 3837 |
|
---|
| 3838 |
|
---|
[459] | 3839 | ## DNSDB::downconvert()
|
---|
| 3840 | # A mostly internal (not exported) semiutilty sub to downconvert from pseudotype <x>
|
---|
| 3841 | # to a compatible component type. Only a handful of operations are valid, anything
|
---|
| 3842 | # else is a null-op.
|
---|
| 3843 | # Takes the record ID and the new type. Returns boolean.
|
---|
| 3844 | sub downconvert {
|
---|
| 3845 | my $dbh = shift;
|
---|
| 3846 | my $recid = shift;
|
---|
| 3847 | my $newtype = shift;
|
---|
| 3848 |
|
---|
| 3849 | # also, only work on live records; little to no value trying to do this on default records.
|
---|
| 3850 | my $rec = getRecLine($dbh, 'n', 'y', $recid);
|
---|
| 3851 |
|
---|
| 3852 | # hm?
|
---|
| 3853 | #return 1 if !$rec;
|
---|
| 3854 |
|
---|
| 3855 | return 1 if $rec->{type} < 65000; # Only the reverse-record pseudotypes can be downconverted
|
---|
| 3856 | return 1 if $rec->{type} == 65282; # Nowhere to go
|
---|
| 3857 |
|
---|
| 3858 | my $delpar;
|
---|
| 3859 | my @sqlargs;
|
---|
| 3860 | if ($rec->{type} == 65280) {
|
---|
| 3861 | return 1 if $newtype != 1 && $newtype != 12;
|
---|
| 3862 | $delpar = ($newtype == 1 ? 'rdns_id' : 'domain_id');
|
---|
| 3863 | push @sqlargs, 0, $newtype, $recid;
|
---|
| 3864 | } elsif ($rec->{type} == 65281) {
|
---|
| 3865 | return 1 if $newtype != 28 && $newtype != 12;
|
---|
| 3866 | $delpar = ($newtype == 28 ? 'rdns_id' : 'domain_id');
|
---|
| 3867 | push @sqlargs, 0, $newtype, $recid;
|
---|
| 3868 | } elsif ($rec->{type} == 65283) {
|
---|
| 3869 | return 1 if $newtype != 65282;
|
---|
| 3870 | $delpar = 'rdns_id';
|
---|
| 3871 | } elsif ($rec->{type} == 65284) {
|
---|
| 3872 | return 1 if $newtype != 65282;
|
---|
| 3873 | $delpar = 'rdns_id';
|
---|
| 3874 | } else {
|
---|
| 3875 | # Your llama is on fire.
|
---|
| 3876 | }
|
---|
| 3877 |
|
---|
| 3878 | local $dbh->{AutoCommit} = 0;
|
---|
| 3879 | local $dbh->{RaiseError} = 1;
|
---|
| 3880 |
|
---|
| 3881 | eval {
|
---|
| 3882 | $dbh->do("UPDATE records SET $delpar = ?, type = ? WHERE record_id = ?", undef, @sqlargs);
|
---|
| 3883 | $dbh->commit;
|
---|
| 3884 | };
|
---|
| 3885 | if ($@) {
|
---|
| 3886 | $errstr = $@;
|
---|
| 3887 | eval { $dbh->rollback; };
|
---|
| 3888 | return 0;
|
---|
| 3889 | }
|
---|
| 3890 | return 1;
|
---|
| 3891 | } # end downconvert()
|
---|
| 3892 |
|
---|
| 3893 |
|
---|
[3] | 3894 | ## DNSDB::delRec()
|
---|
| 3895 | # Delete a record.
|
---|
| 3896 | sub delRec {
|
---|
| 3897 | $errstr = '';
|
---|
| 3898 | my $dbh = shift;
|
---|
| 3899 | my $defrec = shift;
|
---|
[243] | 3900 | my $revrec = shift;
|
---|
[3] | 3901 | my $id = shift;
|
---|
| 3902 |
|
---|
[290] | 3903 | my $oldrec = getRecLine($dbh, $defrec, $revrec, $id);
|
---|
[3] | 3904 |
|
---|
[290] | 3905 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3906 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3907 | local $dbh->{AutoCommit} = 0;
|
---|
| 3908 | local $dbh->{RaiseError} = 1;
|
---|
[3] | 3909 |
|
---|
[290] | 3910 | # Put together the log entry
|
---|
| 3911 | my %logdata;
|
---|
| 3912 | $logdata{domain_id} = $oldrec->{domain_id};
|
---|
| 3913 | $logdata{rdns_id} = $oldrec->{rdns_id};
|
---|
| 3914 | $logdata{group_id} = $oldrec->{group_id} if $defrec eq 'y';
|
---|
| 3915 | $logdata{group_id} = parentID($dbh,
|
---|
| 3916 | (id => $oldrec->{domain_id}, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) )
|
---|
| 3917 | if $defrec eq 'n';
|
---|
| 3918 | $logdata{entry} = "Deleted ".($defrec eq 'y' ? 'default record ' : 'record ').
|
---|
| 3919 | "'$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
| 3920 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
| 3921 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
| 3922 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
[425] | 3923 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
| 3924 | $logdata{entry} .= ", location ".getLoc($dbh, $oldrec->{location})->{description} if $oldrec->{location};
|
---|
[290] | 3925 |
|
---|
| 3926 | eval {
|
---|
| 3927 | my $sth = $dbh->do("DELETE FROM "._rectable($defrec,$revrec)." WHERE record_id=?", undef, ($id));
|
---|
| 3928 | _log($dbh, %logdata);
|
---|
| 3929 | $dbh->commit;
|
---|
| 3930 | };
|
---|
| 3931 | if ($@) {
|
---|
| 3932 | my $msg = $@;
|
---|
| 3933 | eval { $dbh->rollback; };
|
---|
| 3934 | if ($config{log_failures}) {
|
---|
| 3935 | $logdata{entry} = "Error deleting ".($defrec eq 'y' ? 'default record' : 'record').
|
---|
| 3936 | " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
| 3937 | _log($dbh, %logdata);
|
---|
| 3938 | $dbh->commit;
|
---|
| 3939 | }
|
---|
| 3940 | return ('FAIL', $msg);
|
---|
| 3941 | }
|
---|
| 3942 |
|
---|
| 3943 | return ('OK',$logdata{entry});
|
---|
[3] | 3944 | } # end delRec()
|
---|
| 3945 |
|
---|
| 3946 |
|
---|
[323] | 3947 | ## DNSDB::getLogCount()
|
---|
| 3948 | # Get a count of log entries
|
---|
| 3949 | # Takes a database handle and a hash containing at least:
|
---|
| 3950 | # - Entity ID and entity type as the primary log "slice"
|
---|
| 3951 | sub getLogCount {
|
---|
| 3952 | my $dbh = shift;
|
---|
| 3953 |
|
---|
| 3954 | my %args = @_;
|
---|
| 3955 |
|
---|
| 3956 | my @filterargs;
|
---|
| 3957 | ##fixme: which fields do we want to filter on?
|
---|
| 3958 | # push @filterargs,
|
---|
| 3959 |
|
---|
| 3960 | $errstr = 'Missing primary parent ID and/or type';
|
---|
| 3961 | # fail early if we don't have a "prime" ID to look for log entries for
|
---|
| 3962 | return if !$args{id};
|
---|
| 3963 |
|
---|
| 3964 | # or if the prime id type is missing or invalid
|
---|
| 3965 | return if !$args{logtype};
|
---|
| 3966 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
| 3967 | $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
|
---|
| 3968 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
|
---|
| 3969 |
|
---|
| 3970 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
| 3971 |
|
---|
| 3972 | my $sql = "SELECT count(*) FROM log ".
|
---|
| 3973 | "WHERE $id_col{$args{logtype}}=?".
|
---|
| 3974 | ($args{filter} ? " AND entry ~* ?" : '');
|
---|
| 3975 | my ($count) = $dbh->selectrow_array($sql, undef, ($args{id}, @filterargs) );
|
---|
| 3976 | $errstr = $dbh->errstr if !$count;
|
---|
| 3977 | return $count;
|
---|
| 3978 | } # end getLogCount()
|
---|
| 3979 |
|
---|
| 3980 |
|
---|
| 3981 | ## DNSDB::getLogEntries()
|
---|
| 3982 | # Get a list of log entries
|
---|
| 3983 | # Takes arguments as with getLogCount() above, plus optional:
|
---|
| 3984 | # - sort field
|
---|
| 3985 | # - sort order
|
---|
| 3986 | # - offset for pagination
|
---|
| 3987 | sub getLogEntries {
|
---|
| 3988 | my $dbh = shift;
|
---|
| 3989 |
|
---|
| 3990 | my %args = @_;
|
---|
| 3991 |
|
---|
| 3992 | my @filterargs;
|
---|
| 3993 |
|
---|
| 3994 | # fail early if we don't have a "prime" ID to look for log entries for
|
---|
| 3995 | return if !$args{id};
|
---|
| 3996 |
|
---|
| 3997 | # or if the prime id type is missing or invalid
|
---|
| 3998 | return if !$args{logtype};
|
---|
| 3999 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
| 4000 | $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
|
---|
| 4001 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
|
---|
| 4002 |
|
---|
| 4003 | # Sorting defaults
|
---|
| 4004 | $args{sortby} = 'stamp' if !$args{sortby};
|
---|
| 4005 | $args{sortorder} = 'DESC' if !$args{sortorder};
|
---|
[397] | 4006 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[323] | 4007 |
|
---|
[324] | 4008 | my %sortmap = (fname => 'name', username => 'email', entry => 'entry', stamp => 'stamp');
|
---|
[323] | 4009 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 4010 |
|
---|
| 4011 | my $sql = "SELECT user_id AS userid, email AS useremail, name AS userfname, entry AS logentry, ".
|
---|
| 4012 | "date_trunc('second',stamp) AS logtime ".
|
---|
| 4013 | "FROM log ".
|
---|
| 4014 | "WHERE $id_col{$args{logtype}}=?".
|
---|
| 4015 | ($args{filter} ? " AND entry ~* ?" : '').
|
---|
[324] | 4016 | " ORDER BY $args{sortby} $args{sortorder}, log_id $args{sortorder}".
|
---|
[323] | 4017 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
| 4018 | my $loglist = $dbh->selectall_arrayref($sql, { Slice => {} }, ($args{id}, @filterargs) );
|
---|
| 4019 | $errstr = $dbh->errstr if !$loglist;
|
---|
| 4020 | return $loglist;
|
---|
| 4021 | } # end getLogEntries()
|
---|
| 4022 |
|
---|
| 4023 |
|
---|
[452] | 4024 | ## IPDB::getRevPattern()
|
---|
| 4025 | # Get the narrowest template pattern applicable to a passed CIDR address (may be a netblock or an IP)
|
---|
| 4026 | sub getRevPattern {
|
---|
| 4027 | my $dbh = shift;
|
---|
| 4028 | my $cidr = shift;
|
---|
| 4029 | my $group = shift || 1; # just in case
|
---|
| 4030 |
|
---|
[462] | 4031 | # for speed! Casting and comparing even ~7K records takes ~2.5s, so narrow it down to one revzone first.
|
---|
| 4032 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >>= ? AND group_id = ?",
|
---|
| 4033 | undef, ($cidr, $group) );
|
---|
| 4034 |
|
---|
| 4035 | ##fixme? may need to narrow things down more by octet-chopping and doing text comparisons before casting.
|
---|
| 4036 | my ($revpatt) = $dbh->selectrow_array("SELECT host FROM records ".
|
---|
| 4037 | "WHERE (type in (12,65280,65281,65282,65283,65284)) AND rdns_id = ? AND CAST (val AS inet) >>= ? ".
|
---|
| 4038 | "ORDER BY CAST (val AS inet) DESC LIMIT 1", undef, ($revid, $cidr) );
|
---|
[452] | 4039 | return $revpatt;
|
---|
| 4040 | } # end getRevPattern()
|
---|
| 4041 |
|
---|
| 4042 |
|
---|
[225] | 4043 | ## DNSDB::getTypelist()
|
---|
| 4044 | # Get a list of record types for various UI dropdowns
|
---|
| 4045 | # Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A)
|
---|
| 4046 | # Returns an arrayref to list of hashrefs perfect for HTML::Template
|
---|
| 4047 | sub getTypelist {
|
---|
| 4048 | my $dbh = shift;
|
---|
| 4049 | my $recgroup = shift;
|
---|
| 4050 | my $type = shift || $reverse_typemap{A};
|
---|
| 4051 |
|
---|
| 4052 | # also accepting $webvar{revrec}!
|
---|
| 4053 | $recgroup = 'f' if $recgroup eq 'n';
|
---|
| 4054 | $recgroup = 'r' if $recgroup eq 'y';
|
---|
| 4055 |
|
---|
| 4056 | my $sql = "SELECT val,name FROM rectypes WHERE ";
|
---|
| 4057 | if ($recgroup eq 'r') {
|
---|
| 4058 | # reverse zone types
|
---|
| 4059 | $sql .= "stdflag=2 OR stdflag=3";
|
---|
| 4060 | } elsif ($recgroup eq 'l') {
|
---|
| 4061 | # DNS lookup types. Note we avoid our custom types >= 65280, since those are entirely internal.
|
---|
| 4062 | $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280";
|
---|
| 4063 | } else {
|
---|
| 4064 | # default; forward zone types. technically $type eq 'f' but not worth the error message.
|
---|
| 4065 | $sql .= "stdflag=1 OR stdflag=2";
|
---|
| 4066 | }
|
---|
| 4067 | $sql .= " ORDER BY listorder";
|
---|
| 4068 |
|
---|
| 4069 | my $sth = $dbh->prepare($sql);
|
---|
| 4070 | $sth->execute;
|
---|
| 4071 | my @typelist;
|
---|
| 4072 | while (my ($rval,$rname) = $sth->fetchrow_array()) {
|
---|
| 4073 | my %row = ( recval => $rval, recname => $rname );
|
---|
| 4074 | $row{tselect} = 1 if $rval == $type;
|
---|
| 4075 | push @typelist, \%row;
|
---|
| 4076 | }
|
---|
| 4077 |
|
---|
| 4078 | # Add SOA on lookups since it's not listed in other dropdowns.
|
---|
| 4079 | if ($recgroup eq 'l') {
|
---|
| 4080 | my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
|
---|
| 4081 | $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
|
---|
| 4082 | push @typelist, \%row;
|
---|
| 4083 | }
|
---|
| 4084 |
|
---|
| 4085 | return \@typelist;
|
---|
| 4086 | } # end getTypelist()
|
---|
| 4087 |
|
---|
| 4088 |
|
---|
[254] | 4089 | ## DNSDB::parentID()
|
---|
| 4090 | # Get ID of entity that is nearest parent to requested id
|
---|
| 4091 | # Takes a database handle and a hash of entity ID, entity type, optional parent type flag
|
---|
| 4092 | # (domain/reverse zone or group), and optional default/live and forward/reverse flags
|
---|
| 4093 | # Returns the ID or undef on failure
|
---|
| 4094 | sub parentID {
|
---|
[116] | 4095 | my $dbh = shift;
|
---|
| 4096 |
|
---|
[254] | 4097 | my %args = @_;
|
---|
[116] | 4098 |
|
---|
[254] | 4099 | # clean up the parent-type. Set it to group if not set; coerce revzone to domain for simpler logic
|
---|
| 4100 | $args{partype} = 'group' if !$args{partype};
|
---|
| 4101 | $args{partype} = 'domain' if $args{partype} eq 'revzone';
|
---|
[116] | 4102 |
|
---|
[254] | 4103 | # clean up defrec and revrec. default to live record, forward zone
|
---|
| 4104 | $args{defrec} = 'n' if !$args{defrec};
|
---|
| 4105 | $args{revrec} = 'n' if !$args{revrec};
|
---|
[116] | 4106 |
|
---|
[254] | 4107 | if ($par_type{$args{partype}} eq 'domain') {
|
---|
| 4108 | # only live records can have a domain/zone parent
|
---|
| 4109 | return unless ($args{type} eq 'record' && $args{defrec} eq 'n');
|
---|
| 4110 | my $result = $dbh->selectrow_hashref("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
| 4111 | " FROM records WHERE record_id = ?",
|
---|
| 4112 | undef, ($args{id}) ) or return;
|
---|
| 4113 | return $result;
|
---|
| 4114 | } else {
|
---|
| 4115 | # snag some arguments that will either fall through or be overwritten to save some code duplication
|
---|
| 4116 | my $tmpid = $args{id};
|
---|
| 4117 | my $type = $args{type};
|
---|
| 4118 | if ($type eq 'record' && $args{defrec} eq 'n') {
|
---|
| 4119 | # Live records go through the records table first.
|
---|
| 4120 | ($tmpid) = $dbh->selectrow_array("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
| 4121 | " FROM records WHERE record_id = ?",
|
---|
| 4122 | undef, ($args{id}) ) or return;
|
---|
| 4123 | $type = ($args{revrec} eq 'n' ? 'domain' : 'revzone');
|
---|
| 4124 | }
|
---|
| 4125 | my ($result) = $dbh->selectrow_array("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
|
---|
| 4126 | undef, ($tmpid) );
|
---|
| 4127 | return $result;
|
---|
| 4128 | }
|
---|
| 4129 | # should be impossible to get here with even remotely sane arguments
|
---|
| 4130 | return;
|
---|
| 4131 | } # end parentID()
|
---|
[116] | 4132 |
|
---|
| 4133 |
|
---|
[117] | 4134 | ## DNSDB::isParent()
|
---|
| 4135 | # Returns true if $id1 is a parent of $id2, false otherwise
|
---|
| 4136 | sub isParent {
|
---|
| 4137 | my $dbh = shift;
|
---|
| 4138 | my $id1 = shift;
|
---|
| 4139 | my $type1 = shift;
|
---|
| 4140 | my $id2 = shift;
|
---|
| 4141 | my $type2 = shift;
|
---|
| 4142 | ##todo: immediate, secondary, full (default)
|
---|
| 4143 |
|
---|
[157] | 4144 | # Return false on invalid types
|
---|
[244] | 4145 | return 0 if !grep /^$type1$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
| 4146 | return 0 if !grep /^$type2$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
[157] | 4147 |
|
---|
[117] | 4148 | # Return false on impossible relations
|
---|
| 4149 | return 0 if $type1 eq 'record'; # nothing may be a child of a record
|
---|
| 4150 | return 0 if $type1 eq 'defrec'; # nothing may be a child of a record
|
---|
[244] | 4151 | return 0 if $type1 eq 'defrevrec'; # nothing may be a child of a record
|
---|
[117] | 4152 | return 0 if $type1 eq 'user'; # nothing may be child of a user
|
---|
| 4153 | return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record
|
---|
[244] | 4154 | return 0 if $type1 eq 'revzone' && $type2 ne 'record';# reverse zone may not be a parent of anything other than a record
|
---|
[117] | 4155 |
|
---|
[186] | 4156 | # ennnhhhh.... if we're passed an id of 0, it will never be found. usual
|
---|
| 4157 | # case would be the UI creating a new <thing>, and so we don't have an ID for
|
---|
| 4158 | # <thing> to look up yet. in that case the UI should check the parent as well.
|
---|
| 4159 | return 0 if $id1 == 0; # nothing can have a parent id of 0
|
---|
| 4160 | return 1 if $id2 == 0; # anything could have a child id of 0 (or "unknown")
|
---|
| 4161 |
|
---|
[117] | 4162 | # group 1 is the ultimate root parent
|
---|
| 4163 | return 1 if $type1 eq 'group' && $id1 == 1;
|
---|
| 4164 |
|
---|
[155] | 4165 | # groups are always (a) parent of themselves
|
---|
| 4166 | return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2;
|
---|
| 4167 |
|
---|
[117] | 4168 | my $id = $id2;
|
---|
| 4169 | my $type = $type2;
|
---|
| 4170 | my $foundparent = 0;
|
---|
[155] | 4171 |
|
---|
[244] | 4172 | # Records are the only entity with two possible parents. We need to split the parent checks on
|
---|
| 4173 | # domain/rdns.
|
---|
| 4174 | if ($type eq 'record') {
|
---|
| 4175 | my ($dom,$rdns) = $dbh->selectrow_array("SELECT domain_id,rdns_id FROM records WHERE record_id=?",
|
---|
| 4176 | undef, ($id));
|
---|
| 4177 | # check immediate parent against request
|
---|
| 4178 | return 1 if $type1 eq 'domain' && $id1 == $dom;
|
---|
| 4179 | return 1 if $type1 eq 'revzone' && $id1 == $rdns;
|
---|
| 4180 | # if request is group, check *both* parents. Only check if the parent is nonzero though.
|
---|
| 4181 | return 1 if $dom && isParent($dbh, $id1, $type1, $dom, 'domain');
|
---|
| 4182 | return 1 if $rdns && isParent($dbh, $id1, $type1, $rdns, 'revzone');
|
---|
| 4183 | # exit here since we've executed the loop below by proxy in the above recursive calls.
|
---|
| 4184 | return 0;
|
---|
| 4185 | }
|
---|
| 4186 |
|
---|
| 4187 | # almost the same loop as getParents() above
|
---|
[186] | 4188 | my $limiter = 0;
|
---|
[117] | 4189 | while (1) {
|
---|
[155] | 4190 | my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
|
---|
[117] | 4191 | my $result = $dbh->selectrow_hashref($sql,
|
---|
[157] | 4192 | undef, ($id) );
|
---|
[186] | 4193 | if (!$result) {
|
---|
| 4194 | $limiter++;
|
---|
[244] | 4195 | ##fixme: how often will this happen on a live site? fail at max limiter <n>?
|
---|
[186] | 4196 | warn "no results looking for $sql with id $id (depth $limiter)\n";
|
---|
| 4197 | last;
|
---|
| 4198 | }
|
---|
[157] | 4199 | if ($result && $result->{$par_col{$type}} == $id1) {
|
---|
[117] | 4200 | $foundparent = 1;
|
---|
| 4201 | last;
|
---|
[157] | 4202 | } else {
|
---|
| 4203 | ##fixme: do we care about trying to return a "no such record/domain/user/group" error?
|
---|
[244] | 4204 | # should be impossible to create an inconsistent DB just with API calls.
|
---|
[157] | 4205 | warn $dbh->errstr." $sql, $id" if $dbh->errstr;
|
---|
[117] | 4206 | }
|
---|
| 4207 | # group 1 is its own parent. need this here more to break strange loops than for detecting a parent
|
---|
| 4208 | last if $result->{$par_col{$type}} == 1;
|
---|
[152] | 4209 | $id = $result->{$par_col{$type}};
|
---|
[117] | 4210 | $type = $par_type{$type};
|
---|
| 4211 | }
|
---|
| 4212 |
|
---|
| 4213 | return $foundparent;
|
---|
| 4214 | } # end isParent()
|
---|
| 4215 |
|
---|
| 4216 |
|
---|
[275] | 4217 | ## DNSDB::zoneStatus()
|
---|
| 4218 | # Returns and optionally sets a zone's status
|
---|
| 4219 | # Takes a database handle, domain/revzone ID, forward/reverse flag, and optionally a status argument
|
---|
| 4220 | # Returns status, or undef on errors.
|
---|
| 4221 | sub zoneStatus {
|
---|
[3] | 4222 | my $dbh = shift;
|
---|
| 4223 | my $id = shift;
|
---|
[275] | 4224 | my $revrec = shift;
|
---|
| 4225 | my $newstatus = shift || 'mu';
|
---|
[3] | 4226 |
|
---|
| 4227 | return undef if $id !~ /^\d+$/;
|
---|
| 4228 |
|
---|
[283] | 4229 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4230 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4231 | local $dbh->{AutoCommit} = 0;
|
---|
| 4232 | local $dbh->{RaiseError} = 1;
|
---|
| 4233 |
|
---|
[275] | 4234 | if ($newstatus ne 'mu') {
|
---|
[283] | 4235 | # ooo, fun! let's see what we were passed for status
|
---|
| 4236 | eval {
|
---|
| 4237 | $newstatus = 0 if $newstatus eq 'domoff';
|
---|
| 4238 | $newstatus = 1 if $newstatus eq 'domon';
|
---|
| 4239 | $dbh->do("UPDATE ".($revrec eq 'n' ? 'domains' : 'revzones')." SET status=? WHERE ".
|
---|
[275] | 4240 | ($revrec eq 'n' ? 'domain_id' : 'rdns_id')."=?", undef, ($newstatus,$id) );
|
---|
[283] | 4241 |
|
---|
| 4242 | ##fixme switch to more consise "Enabled <domain"/"Disabled <domain>" as with users?
|
---|
| 4243 | $resultstr = "Changed ".($revrec eq 'n' ? domainName($dbh, $id) : revName($dbh, $id)).
|
---|
| 4244 | " state to ".($newstatus ? 'active' : 'inactive');
|
---|
| 4245 |
|
---|
| 4246 | my %loghash;
|
---|
| 4247 | $loghash{domain_id} = $id if $revrec eq 'n';
|
---|
| 4248 | $loghash{rdns_id} = $id if $revrec eq 'y';
|
---|
| 4249 | $loghash{group_id} = parentID($dbh,
|
---|
| 4250 | (id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) );
|
---|
| 4251 | $loghash{entry} = $resultstr;
|
---|
| 4252 | _log($dbh, %loghash);
|
---|
| 4253 |
|
---|
| 4254 | $dbh->commit;
|
---|
| 4255 | };
|
---|
| 4256 | if ($@) {
|
---|
| 4257 | my $msg = $@;
|
---|
| 4258 | eval { $dbh->rollback; };
|
---|
| 4259 | $resultstr = '';
|
---|
| 4260 | $errstr = $msg;
|
---|
| 4261 | return;
|
---|
| 4262 | }
|
---|
[3] | 4263 | }
|
---|
| 4264 |
|
---|
[275] | 4265 | my ($status) = $dbh->selectrow_array("SELECT status FROM ".
|
---|
| 4266 | ($revrec eq 'n' ? "domains WHERE domain_id=?" : "revzones WHERE rdns_id=?"),
|
---|
| 4267 | undef, ($id) );
|
---|
[3] | 4268 | return $status;
|
---|
[275] | 4269 | } # end zoneStatus()
|
---|
[3] | 4270 |
|
---|
| 4271 |
|
---|
[452] | 4272 | ## DNSDB::getZonesByCIDR()
|
---|
| 4273 | # Get a list of zone names and IDs that records for a passed CIDR block are within.
|
---|
| 4274 | sub getZonesByCIDR {
|
---|
| 4275 | my $dbh = shift;
|
---|
| 4276 | my %args = @_;
|
---|
| 4277 |
|
---|
| 4278 | my $result = $dbh->selectall_arrayref("SELECT rdns_id,revnet FROM revzones WHERE revnet >>= ? OR revnet <<= ?",
|
---|
| 4279 | { Slice => {} }, ($args{cidr}, $args{cidr}) );
|
---|
| 4280 | return $result;
|
---|
| 4281 | } # end getZonesByCIDR()
|
---|
| 4282 |
|
---|
| 4283 |
|
---|
[33] | 4284 | ## DNSDB::importAXFR
|
---|
| 4285 | # Import a domain via AXFR
|
---|
[37] | 4286 | # Takes AXFR host, domain to transfer, group to put the domain in,
|
---|
| 4287 | # and optionally:
|
---|
| 4288 | # - active/inactive state flag (defaults to active)
|
---|
| 4289 | # - overwrite-SOA flag (defaults to off)
|
---|
| 4290 | # - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
|
---|
| 4291 | # Returns a status code (OK, WARN, or FAIL) and message - message should be blank
|
---|
| 4292 | # if status is OK, but WARN includes conditions that are not fatal but should
|
---|
| 4293 | # really be reported.
|
---|
[33] | 4294 | sub importAXFR {
|
---|
| 4295 | my $dbh = shift;
|
---|
[35] | 4296 | my $ifrom_in = shift;
|
---|
[301] | 4297 | my $zone = shift;
|
---|
[33] | 4298 | my $group = shift;
|
---|
[436] | 4299 | my $status = shift;
|
---|
| 4300 | $status = (defined($status) ? $status : 0); # force sane semantics, and allow passing "null" (inactive) status
|
---|
[33] | 4301 | my $rwsoa = shift || 0;
|
---|
| 4302 | my $rwns = shift || 0;
|
---|
[436] | 4303 | my $newttl = shift;
|
---|
[301] | 4304 | my $merge = shift || 0; # do we attempt to merge A/AAAA and PTR records whenever possible?
|
---|
| 4305 | # do we overload this with the fixme below?
|
---|
[33] | 4306 | ##fixme: add mode to delete&replace, merge+overwrite, merge new?
|
---|
| 4307 |
|
---|
[37] | 4308 | my $nrecs = 0;
|
---|
| 4309 | my $soaflag = 0;
|
---|
| 4310 | my $nsflag = 0;
|
---|
| 4311 | my $warnmsg = '';
|
---|
| 4312 | my $ifrom;
|
---|
[33] | 4313 |
|
---|
[301] | 4314 | my $rev = 'n';
|
---|
[302] | 4315 | my $code = 'OK';
|
---|
| 4316 | my $msg = 'foobar?';
|
---|
[301] | 4317 |
|
---|
[35] | 4318 | # choke on possible bad setting in ifrom
|
---|
[37] | 4319 | # IPv4 and v6, and valid hostnames!
|
---|
[35] | 4320 | ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
| 4321 | return ('FAIL', "Bad AXFR source host $ifrom")
|
---|
| 4322 | unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
| 4323 |
|
---|
[301] | 4324 | my $errmsg;
|
---|
| 4325 |
|
---|
| 4326 | my $zone_id;
|
---|
| 4327 | my $domain_id = 0;
|
---|
| 4328 | my $rdns_id = 0;
|
---|
| 4329 | my $cidr;
|
---|
| 4330 |
|
---|
| 4331 | # magic happens! detect if we're importing a domain or a reverse zone
|
---|
| 4332 | # while we're at it, figure out what the CIDR netblock is (if we got a .arpa)
|
---|
| 4333 | # or what the formal .arpa zone is (if we got a CIDR netblock)
|
---|
| 4334 | # Handles sub-octet v4 zones in the format specified in the Cricket Book, 2nd Ed, p217-218
|
---|
| 4335 |
|
---|
| 4336 | if ($zone =~ m{(?:\.arpa\.?|/\d+)$}) {
|
---|
| 4337 | # we seem to have a reverse zone
|
---|
| 4338 | $rev = 'y';
|
---|
| 4339 |
|
---|
| 4340 | if ($zone =~ /\.arpa\.?$/) {
|
---|
| 4341 | # we have a formal reverse zone. call _zone2cidr and get the CIDR block.
|
---|
| 4342 | ($code,$msg) = _zone2cidr($zone);
|
---|
| 4343 | return ($code, $msg) if $code eq 'FAIL';
|
---|
| 4344 | $cidr = $msg;
|
---|
| 4345 | } elsif ($zone =~ m|^[\d.]+/\d+$|) {
|
---|
| 4346 | # v4 revzone, CIDR netblock
|
---|
| 4347 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 4348 | $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
| 4349 | } elsif ($zone =~ m|^[a-fA-F\d:]+/\d+$|) {
|
---|
| 4350 | # v6 revzone, CIDR netblock
|
---|
| 4351 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 4352 | return ('FAIL', "$zone is not a nibble-aligned block") if $cidr->masklen % 4 != 0;
|
---|
| 4353 | $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.');
|
---|
| 4354 | } else {
|
---|
| 4355 | # there is. no. else!
|
---|
| 4356 | return ('FAIL', "Unknown zone name format");
|
---|
| 4357 | }
|
---|
| 4358 |
|
---|
| 4359 | # quick check to start to see if we've already got one
|
---|
| 4360 |
|
---|
| 4361 | ($zone_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?",
|
---|
| 4362 | undef, ("$cidr"));
|
---|
| 4363 | $rdns_id = $zone_id;
|
---|
| 4364 | } else {
|
---|
| 4365 | # default to domain
|
---|
[349] | 4366 | ($zone_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
[301] | 4367 | undef, ($zone));
|
---|
| 4368 | $domain_id = $zone_id;
|
---|
| 4369 | }
|
---|
| 4370 |
|
---|
| 4371 | return ('FAIL', ($rev eq 'n' ? 'Domain' : 'Reverse zone')." already exists") if $zone_id;
|
---|
| 4372 |
|
---|
[303] | 4373 | # little local utility sub to swap $val and $host for revzone records.
|
---|
| 4374 | sub _revswap {
|
---|
| 4375 | my $rechost = shift;
|
---|
| 4376 | my $recdata = shift;
|
---|
| 4377 |
|
---|
| 4378 | if ($rechost =~ /\.in-addr\.arpa\.?$/) {
|
---|
| 4379 | $rechost =~ s/\.in-addr\.arpa\.?$//;
|
---|
| 4380 | $rechost = join '.', reverse split /\./, $rechost;
|
---|
| 4381 | } else {
|
---|
| 4382 | $rechost =~ s/\.ip6\.arpa\.?$//;
|
---|
| 4383 | my @nibs = reverse split /\./, $rechost;
|
---|
| 4384 | $rechost = '';
|
---|
| 4385 | my $nc;
|
---|
| 4386 | foreach (@nibs) {
|
---|
| 4387 | $rechost.= $_;
|
---|
| 4388 | $rechost .= ":" if ++$nc % 4 == 0 && $nc < 32;
|
---|
| 4389 | }
|
---|
[307] | 4390 | $rechost .= ":" if $nc < 32 && $rechost !~ /\*$/; # close netblock records?
|
---|
| 4391 | ##fixme: there's a case that ends up with a partial entry here:
|
---|
| 4392 | # ip:add:re:ss::
|
---|
| 4393 | # can't reproduce after letting it sit overnight after discovery. :(
|
---|
| 4394 | #print "$rechost\n";
|
---|
[303] | 4395 | # canonicalize with NetAddr::IP
|
---|
| 4396 | $rechost = NetAddr::IP->new($rechost)->addr unless $rechost =~ /\*$/;
|
---|
| 4397 | }
|
---|
| 4398 | return ($recdata,$rechost)
|
---|
| 4399 | }
|
---|
| 4400 |
|
---|
| 4401 |
|
---|
[33] | 4402 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4403 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4404 | local $dbh->{AutoCommit} = 0;
|
---|
| 4405 | local $dbh->{RaiseError} = 1;
|
---|
| 4406 |
|
---|
[301] | 4407 | my $sth;
|
---|
| 4408 | eval {
|
---|
[34] | 4409 |
|
---|
[301] | 4410 | if ($rev eq 'n') {
|
---|
[33] | 4411 | ##fixme: serial
|
---|
[301] | 4412 | $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef, ($zone,$group,$status) );
|
---|
| 4413 | # get domain id so we can do the records
|
---|
| 4414 | ($zone_id) = $dbh->selectrow_array("SELECT currval('domains_domain_id_seq')");
|
---|
| 4415 | $domain_id = $zone_id;
|
---|
| 4416 | _log($dbh, (group_id => $group, domain_id => $domain_id,
|
---|
| 4417 | entry => "[Added ".($status ? 'active' : 'inactive')." domain $zone via AXFR]") );
|
---|
| 4418 | } else {
|
---|
| 4419 | ##fixme: serial
|
---|
| 4420 | $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef, ($cidr,$group,$status) );
|
---|
| 4421 | # get revzone id so we can do the records
|
---|
| 4422 | ($zone_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
| 4423 | $rdns_id = $zone_id;
|
---|
| 4424 | _log($dbh, (group_id => $group, rdns_id => $rdns_id,
|
---|
[303] | 4425 | entry => "[Added ".($status ? 'active' : 'inactive')." reverse zone $cidr via AXFR]") );
|
---|
[301] | 4426 | }
|
---|
[33] | 4427 |
|
---|
[35] | 4428 | ## bizarre DBI<->Net::DNS interaction bug:
|
---|
| 4429 | ## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
|
---|
[37] | 4430 | ## fixed, apparently I was doing *something* odd, but not certain what it was that
|
---|
| 4431 | ## caused a commit instead of barfing
|
---|
[35] | 4432 |
|
---|
[34] | 4433 | my $res = Net::DNS::Resolver->new;
|
---|
[35] | 4434 | $res->nameservers($ifrom);
|
---|
[301] | 4435 | $res->axfr_start($zone)
|
---|
[35] | 4436 | or die "Couldn't begin AXFR\n";
|
---|
[34] | 4437 |
|
---|
[301] | 4438 | $sth = $dbh->prepare("INSERT INTO records (domain_id,rdns_id,host,type,val,distance,weight,port,ttl)".
|
---|
| 4439 | " VALUES (?,?,?,?,?,?,?,?,?)");
|
---|
| 4440 |
|
---|
[307] | 4441 | # Stash info about sub-octet v4 revzones here so we don't have
|
---|
| 4442 | # to store the CNAMEs used to delegate a suboctet zone
|
---|
| 4443 | # $suboct{zone}{ns}[] -> array of nameservers
|
---|
| 4444 | # $suboct{zone}{cname}[] -> array of extant CNAMEs (Just In Case someone did something bizarre)
|
---|
| 4445 | ## commented pending actual use of this data. for now, we'll just
|
---|
| 4446 | ## auto-(re)create the CNAMEs in revzones on export
|
---|
| 4447 | # my %suboct;
|
---|
| 4448 |
|
---|
[35] | 4449 | while (my $rr = $res->axfr_next()) {
|
---|
[301] | 4450 |
|
---|
| 4451 | my $val;
|
---|
| 4452 | my $distance = 0;
|
---|
| 4453 | my $weight = 0;
|
---|
| 4454 | my $port = 0;
|
---|
[303] | 4455 | my $logfrag = '';
|
---|
[301] | 4456 |
|
---|
[33] | 4457 | my $type = $rr->type;
|
---|
[301] | 4458 | my $host = $rr->name;
|
---|
[436] | 4459 | my $ttl = ($newttl ? $newttl : $rr->ttl); # allow force-override TTLs
|
---|
[35] | 4460 |
|
---|
[37] | 4461 | $soaflag = 1 if $type eq 'SOA';
|
---|
| 4462 | $nsflag = 1 if $type eq 'NS';
|
---|
[35] | 4463 |
|
---|
[34] | 4464 | # "Primary" types:
|
---|
| 4465 | # A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
|
---|
| 4466 | # maybe KEY
|
---|
| 4467 |
|
---|
[302] | 4468 | # BIND supports:
|
---|
| 4469 | # [standard]
|
---|
| 4470 | # A AAAA CNAME MX NS PTR SOA TXT
|
---|
| 4471 | # [variously experimental, obsolete, or obscure]
|
---|
| 4472 | # 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
|
---|
| 4473 | # ... if one can ever find the right magic to format them correctly
|
---|
| 4474 |
|
---|
| 4475 | # Net::DNS supports:
|
---|
| 4476 | # RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
|
---|
| 4477 | # EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
|
---|
| 4478 | # DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
|
---|
| 4479 |
|
---|
[35] | 4480 | # nasty big ugly case-like thing here, since we have to do *some* different
|
---|
| 4481 | # processing depending on the record. le sigh.
|
---|
| 4482 |
|
---|
[105] | 4483 | ##fixme: what record types other than TXT can/will have >255-byte payloads?
|
---|
| 4484 |
|
---|
[34] | 4485 | if ($type eq 'A') {
|
---|
[301] | 4486 | $val = $rr->address;
|
---|
[34] | 4487 | } elsif ($type eq 'NS') {
|
---|
[37] | 4488 | # hmm. should we warn here if subdomain NS'es are left alone?
|
---|
[301] | 4489 | next if ($rwns && ($rr->name eq $zone));
|
---|
[302] | 4490 | if ($rev eq 'y') {
|
---|
| 4491 | # revzones have records more or less reversed from forward zones.
|
---|
| 4492 | my ($tmpcode,$tmpmsg) = _zone2cidr($host);
|
---|
[401] | 4493 | die "Error converting NS record: $tmpmsg\n" if $tmpcode eq 'FAIL'; # hmm. may not make sense...
|
---|
[302] | 4494 | $val = "$tmpmsg";
|
---|
| 4495 | $host = $rr->nsdname;
|
---|
[303] | 4496 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
[307] | 4497 | # Tag and preserve. For now this is commented for a no-op, but we have Ideas for
|
---|
| 4498 | # another custom storage type ("DELEGATE") that will use these subzone-delegation records
|
---|
| 4499 | #if ($val ne "$cidr") {
|
---|
| 4500 | # push @{$suboct{$val}{ns}}, $host;
|
---|
| 4501 | #}
|
---|
[302] | 4502 | } else {
|
---|
| 4503 | $val = $rr->nsdname;
|
---|
| 4504 | }
|
---|
[35] | 4505 | $nsflag = 1;
|
---|
[34] | 4506 | } elsif ($type eq 'CNAME') {
|
---|
[302] | 4507 | if ($rev eq 'y') {
|
---|
[303] | 4508 | # hmm. do we even want to bother with storing these at this level? Sub-octet delegation
|
---|
| 4509 | # by CNAME is essentially a record-publication hack, and we want to just represent the
|
---|
| 4510 | # "true" logical intentions as far down the stack as we can from the UI.
|
---|
| 4511 | ($host,$val) = _revswap($host,$rr->cname);
|
---|
| 4512 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
[307] | 4513 | # Tag and preserve in case we want to commit them as-is later, but mostly we don't care.
|
---|
| 4514 | # Commented pending actually doing something with possibly new type DELEGATE
|
---|
| 4515 | #my $tmprev = $host;
|
---|
| 4516 | #$tmprev =~ s/^\d+\.//;
|
---|
| 4517 | #($code,$tmprev) = _zone2cidr($tmprev);
|
---|
| 4518 | #push @{$suboct{"$tmprev"}{cname}}, $val;
|
---|
| 4519 | # Silently skip CNAMEs in revzones.
|
---|
| 4520 | next;
|
---|
[302] | 4521 | } else {
|
---|
| 4522 | $val = $rr->cname;
|
---|
| 4523 | }
|
---|
[34] | 4524 | } elsif ($type eq 'SOA') {
|
---|
[37] | 4525 | next if $rwsoa;
|
---|
[307] | 4526 | $host = $rr->rname.":".$rr->mname;
|
---|
[301] | 4527 | $val = $rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum;
|
---|
[35] | 4528 | $soaflag = 1;
|
---|
[34] | 4529 | } elsif ($type eq 'PTR') {
|
---|
[303] | 4530 | ($host,$val) = _revswap($host,$rr->ptrdname);
|
---|
| 4531 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
[34] | 4532 | # hmm. PTR records should not be in forward zones.
|
---|
| 4533 | } elsif ($type eq 'MX') {
|
---|
[301] | 4534 | $val = $rr->exchange;
|
---|
| 4535 | $distance = $rr->preference;
|
---|
[34] | 4536 | } elsif ($type eq 'TXT') {
|
---|
| 4537 | ##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
|
---|
| 4538 | ## but don't really seem enthusiastic about it.
|
---|
[303] | 4539 | #print "should use rdatastr:\n\t".$rr->rdatastr."\n or char_str_list:\n\t".join(' ',$rr->char_str_list())."\n";
|
---|
| 4540 | # rdatastr returns a BIND-targetted logical string, including opening and closing quotes
|
---|
| 4541 | # char_str_list returns a list of the individual string fragments in the record
|
---|
[307] | 4542 | # txtdata returns the more useful all-in-one form (since we want to push such protocol
|
---|
| 4543 | # details as far down the stack as we can)
|
---|
[303] | 4544 | # NB: this may turn out to be more troublesome if we ever have need of >512-byte TXT records.
|
---|
| 4545 | if ($rev eq 'y') {
|
---|
| 4546 | ($host,$val) = _revswap($host,$rr->txtdata);
|
---|
| 4547 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
| 4548 | } else {
|
---|
| 4549 | $val = $rr->txtdata;
|
---|
| 4550 | }
|
---|
[34] | 4551 | } elsif ($type eq 'SPF') {
|
---|
| 4552 | ##fixme: and the same caveat here, since it is apparently a clone of ::TXT
|
---|
[301] | 4553 | $val = $rr->txtdata;
|
---|
[34] | 4554 | } elsif ($type eq 'AAAA') {
|
---|
[301] | 4555 | $val = $rr->address;
|
---|
[34] | 4556 | } elsif ($type eq 'SRV') {
|
---|
[301] | 4557 | $val = $rr->target;
|
---|
| 4558 | $distance = $rr->priority;
|
---|
| 4559 | $weight = $rr->weight;
|
---|
| 4560 | $port = $rr->port;
|
---|
[34] | 4561 | } elsif ($type eq 'KEY') {
|
---|
[35] | 4562 | # we don't actually know what to do with these...
|
---|
[301] | 4563 | $val = $rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname;
|
---|
[35] | 4564 | } else {
|
---|
[301] | 4565 | $val = $rr->rdatastr;
|
---|
[35] | 4566 | # Finding a different record type is not fatal.... just problematic.
|
---|
[37] | 4567 | # We may not be able to export it correctly.
|
---|
[35] | 4568 | $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
|
---|
[33] | 4569 | }
|
---|
| 4570 |
|
---|
[303] | 4571 | my $logentry = "[AXFR ".($rev eq 'n' ? $zone : $cidr)."] ";
|
---|
[34] | 4572 |
|
---|
[307] | 4573 | if ($merge) {
|
---|
| 4574 | if ($rev eq 'n') {
|
---|
| 4575 | # importing a domain; we have A and AAAA records that could be merged with matching PTR records
|
---|
| 4576 | my $etype;
|
---|
| 4577 | my ($erdns,$erid,$ettl) = $dbh->selectrow_array("SELECT rdns_id,record_id,ttl FROM records ".
|
---|
| 4578 | "WHERE host=? AND val=? AND type=12",
|
---|
| 4579 | undef, ($host, $val) );
|
---|
| 4580 | if ($erid) {
|
---|
| 4581 | if ($type eq 'A') { # PTR -> A+PTR
|
---|
| 4582 | $etype = 65280;
|
---|
| 4583 | $logentry .= "Merged A record with existing PTR record '$host A+PTR $val', TTL $ettl";
|
---|
| 4584 | }
|
---|
| 4585 | if ($type eq 'AAAA') { # PTR -> AAAA+PTR
|
---|
| 4586 | $etype = 65281;
|
---|
| 4587 | $logentry .= "Merged AAAA record with existing PTR record '$host AAAA+PTR $val', TTL $ettl";
|
---|
| 4588 | }
|
---|
| 4589 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
| 4590 | $dbh->do("UPDATE records SET domain_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
| 4591 | ($domain_id, $ettl, $etype, $erid));
|
---|
| 4592 | $nrecs++;
|
---|
| 4593 | _log($dbh, (group_id => $group, domain_id => $domain_id, rdns_id => $erdns, entry => $logentry) );
|
---|
| 4594 | next; # while axfr_next
|
---|
| 4595 | }
|
---|
| 4596 | } # $rev eq 'n'
|
---|
| 4597 | else {
|
---|
| 4598 | # importing a revzone, we have PTR records that could be merged with matching A/AAAA records
|
---|
| 4599 | my ($domid,$erid,$ettl,$etype) = $dbh->selectrow_array("SELECT domain_id,record_id,ttl,type FROM records ".
|
---|
| 4600 | "WHERE host=? AND val=? AND (type=1 OR type=28)",
|
---|
| 4601 | undef, ($host, $val) );
|
---|
| 4602 | if ($erid) {
|
---|
| 4603 | if ($etype == 1) { # A -> A+PTR
|
---|
| 4604 | $etype = 65280;
|
---|
| 4605 | $logentry .= "Merged PTR record with existing matching A record '$host A+PTR $val', TTL $ettl";
|
---|
| 4606 | }
|
---|
| 4607 | if ($etype == 28) { # AAAA -> AAAA+PTR
|
---|
| 4608 | $etype = 65281;
|
---|
| 4609 | $logentry .= "Merged PTR record with existing matching AAAA record '$host AAAA+PTR $val', TTL $ettl";
|
---|
| 4610 | }
|
---|
| 4611 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
| 4612 | $dbh->do("UPDATE records SET rdns_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
| 4613 | ($rdns_id, $ettl, $etype, $erid));
|
---|
| 4614 | $nrecs++;
|
---|
| 4615 | _log($dbh, (group_id => $group, domain_id => $domid, rdns_id => $rdns_id, entry => $logentry) );
|
---|
| 4616 | next; # while axfr_next
|
---|
| 4617 | }
|
---|
| 4618 | } # $rev eq 'y'
|
---|
| 4619 | } # if $merge
|
---|
[34] | 4620 |
|
---|
[302] | 4621 | # Insert the new record
|
---|
[301] | 4622 | $sth->execute($domain_id, $rdns_id, $host, $reverse_typemap{$type}, $val,
|
---|
| 4623 | $distance, $weight, $port, $ttl);
|
---|
| 4624 |
|
---|
[37] | 4625 | $nrecs++;
|
---|
[34] | 4626 |
|
---|
[301] | 4627 | if ($type eq 'SOA') {
|
---|
| 4628 | # also !$rwsoa, but if that's set, it should be impossible to get here.
|
---|
| 4629 | my @tmp1 = split /:/, $host;
|
---|
| 4630 | my @tmp2 = split /:/, $val;
|
---|
| 4631 | $logentry .= "Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
| 4632 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl";
|
---|
[303] | 4633 | } elsif ($logfrag) {
|
---|
| 4634 | # special case for log entries we need to meddle with a little.
|
---|
| 4635 | $logentry .= $logfrag;
|
---|
[301] | 4636 | } else {
|
---|
| 4637 | $logentry .= "Added record '$host $type";
|
---|
| 4638 | $logentry .= " [distance $distance]" if $type eq 'MX';
|
---|
| 4639 | $logentry .= " [priority $distance] [weight $weight] [port $port]" if $type eq 'SRV';
|
---|
| 4640 | $logentry .= " $val', TTL $ttl";
|
---|
| 4641 | }
|
---|
| 4642 | _log($dbh, (group_id => $group, domain_id => $domain_id, rdns_id => $rdns_id, entry => $logentry) );
|
---|
| 4643 |
|
---|
[37] | 4644 | } # while axfr_next
|
---|
| 4645 |
|
---|
[307] | 4646 | # Detect and handle delegated subzones
|
---|
| 4647 | # Placeholder for when we decide what to actually do with this, see previous comments in NS and CNAME handling.
|
---|
| 4648 | #foreach (keys %suboct) {
|
---|
| 4649 | # print "found ".($suboct{$_}{ns} ? @{$suboct{$_}{ns}} : '0')." NS records and ".
|
---|
| 4650 | # ($suboct{$_}{cname} ? @{$suboct{$_}{cname}} : '0')." CNAMEs for $_\n";
|
---|
| 4651 | #}
|
---|
| 4652 |
|
---|
[37] | 4653 | # Overwrite SOA record
|
---|
| 4654 | if ($rwsoa) {
|
---|
| 4655 | $soaflag = 1;
|
---|
| 4656 | my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
|
---|
| 4657 | my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
| 4658 | $sthgetsoa->execute($group,$reverse_typemap{SOA});
|
---|
| 4659 | while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
|
---|
[301] | 4660 | $host =~ s/DOMAIN/$zone/g;
|
---|
| 4661 | $val =~ s/DOMAIN/$zone/g;
|
---|
| 4662 | $sthputsoa->execute($zone_id,$host,$reverse_typemap{SOA},$val,$ttl);
|
---|
[34] | 4663 | }
|
---|
[37] | 4664 | }
|
---|
[34] | 4665 |
|
---|
[37] | 4666 | # Overwrite NS records
|
---|
| 4667 | if ($rwns) {
|
---|
| 4668 | $nsflag = 1;
|
---|
| 4669 | my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
|
---|
| 4670 | my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
| 4671 | $sthgetns->execute($group,$reverse_typemap{NS});
|
---|
| 4672 | while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
|
---|
[301] | 4673 | $host =~ s/DOMAIN/$zone/g;
|
---|
| 4674 | $val =~ s/DOMAIN/$zone/g;
|
---|
| 4675 | $sthputns->execute($zone_id,$host,$reverse_typemap{NS},$val,$ttl);
|
---|
[37] | 4676 | }
|
---|
| 4677 | }
|
---|
[34] | 4678 |
|
---|
[35] | 4679 | die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
|
---|
| 4680 | die "Bad zone: No SOA record!\n" if !$soaflag;
|
---|
| 4681 | die "Bad zone: No NS records!\n" if !$nsflag;
|
---|
| 4682 |
|
---|
[37] | 4683 | $dbh->commit;
|
---|
[35] | 4684 |
|
---|
[33] | 4685 | };
|
---|
| 4686 |
|
---|
| 4687 | if ($@) {
|
---|
| 4688 | my $msg = $@;
|
---|
| 4689 | eval { $dbh->rollback; };
|
---|
[34] | 4690 | return ('FAIL',$msg." $warnmsg");
|
---|
[33] | 4691 | } else {
|
---|
[35] | 4692 | return ('WARN', $warnmsg) if $warnmsg;
|
---|
[91] | 4693 | return ('OK',"Imported OK");
|
---|
[33] | 4694 | }
|
---|
| 4695 |
|
---|
[37] | 4696 | # it should be impossible to get here.
|
---|
[34] | 4697 | return ('WARN',"OOOK!");
|
---|
[33] | 4698 | } # end importAXFR()
|
---|
| 4699 |
|
---|
| 4700 |
|
---|
[302] | 4701 | ## DNSDB::importBIND()
|
---|
| 4702 | sub importBIND {
|
---|
| 4703 | } # end importBIND()
|
---|
| 4704 |
|
---|
| 4705 |
|
---|
| 4706 | ## DNSDB::import_tinydns()
|
---|
| 4707 | sub import_tinydns {
|
---|
| 4708 | } # end import_tinydns()
|
---|
| 4709 |
|
---|
| 4710 |
|
---|
[103] | 4711 | ## DNSDB::export()
|
---|
| 4712 | # Export the DNS database, or a part of it
|
---|
| 4713 | # Takes database handle, export type, optional arguments depending on type
|
---|
| 4714 | # Writes zone data to targets as appropriate for type
|
---|
| 4715 | sub export {
|
---|
| 4716 | my $dbh = shift;
|
---|
| 4717 | my $target = shift;
|
---|
| 4718 |
|
---|
| 4719 | if ($target eq 'tiny') {
|
---|
| 4720 | __export_tiny($dbh,@_);
|
---|
| 4721 | }
|
---|
| 4722 | # elsif ($target eq 'foo') {
|
---|
| 4723 | # __export_foo($dbh,@_);
|
---|
| 4724 | #}
|
---|
| 4725 | # etc
|
---|
| 4726 |
|
---|
| 4727 | } # end export()
|
---|
| 4728 |
|
---|
| 4729 |
|
---|
| 4730 | ## DNSDB::__export_tiny
|
---|
| 4731 | # Internal sub to implement tinyDNS (compatible) export
|
---|
| 4732 | # Takes database handle, filehandle to write export to, optional argument(s)
|
---|
| 4733 | # to determine which data gets exported
|
---|
| 4734 | sub __export_tiny {
|
---|
| 4735 | my $dbh = shift;
|
---|
| 4736 | my $datafile = shift;
|
---|
| 4737 |
|
---|
| 4738 | ##fixme: slurp up further options to specify particular zone(s) to export
|
---|
| 4739 |
|
---|
| 4740 | ##fixme: fail if $datafile isn't an open, writable file
|
---|
| 4741 |
|
---|
| 4742 | # easy case - export all evarything
|
---|
| 4743 | # not-so-easy case - export item(s) specified
|
---|
| 4744 | # todo: figure out what kind of list we use to export items
|
---|
| 4745 |
|
---|
[329] | 4746 | # raw packet in unknown format: first byte indicates length
|
---|
| 4747 | # of remaining data, allows up to 255 raw bytes
|
---|
| 4748 |
|
---|
[372] | 4749 | # Locations/views - worth including in the caching setup?
|
---|
| 4750 | my $lochash = $dbh->selectall_hashref("SELECT location,iplist FROM locations", 'location');
|
---|
| 4751 | foreach my $location (keys %$lochash) {
|
---|
[375] | 4752 | foreach my $ipprefix (split /[,\s]+/, $lochash->{$location}{iplist}) {
|
---|
| 4753 | $ipprefix =~ s/\s+//g;
|
---|
[449] | 4754 | $ipprefix = new NetAddr::IP $ipprefix;
|
---|
| 4755 | ##fixme: how to handle IPv6?
|
---|
| 4756 | next if $ipprefix->{isv6};
|
---|
| 4757 | # have to account for /nn CIDR entries. tinydns only speaks octet-sliced prefix.
|
---|
| 4758 | if ($ipprefix->masklen <= 8) {
|
---|
| 4759 | foreach ($ipprefix->split(8)) {
|
---|
| 4760 | my $tmp = $_->addr;
|
---|
| 4761 | $tmp =~ s/\.\d+\.\d+\.\d+$//;
|
---|
| 4762 | print $datafile "%$location:$tmp\n";
|
---|
| 4763 | }
|
---|
| 4764 | } elsif ($ipprefix->masklen <= 16) {
|
---|
| 4765 | foreach ($ipprefix->split(16)) {
|
---|
| 4766 | my $tmp = $_->addr;
|
---|
| 4767 | $tmp =~ s/\.\d+\.\d+$//;
|
---|
| 4768 | print $datafile "%$location:$tmp\n";
|
---|
| 4769 | }
|
---|
| 4770 | } elsif ($ipprefix->masklen <= 24) {
|
---|
| 4771 | foreach ($ipprefix->split(24)) {
|
---|
| 4772 | my $tmp = $_->addr;
|
---|
| 4773 | $tmp =~ s/\.\d+$//;
|
---|
| 4774 | print $datafile "%$location:$tmp\n";
|
---|
| 4775 | }
|
---|
| 4776 | } else {
|
---|
| 4777 | foreach ($ipprefix->split(32)) {
|
---|
| 4778 | print $datafile "%$location:".$_->addr."\n";
|
---|
| 4779 | }
|
---|
| 4780 | }
|
---|
[372] | 4781 | }
|
---|
| 4782 | print $datafile "%$location\n" if !$lochash->{$location}{iplist};
|
---|
| 4783 | }
|
---|
| 4784 |
|
---|
[329] | 4785 | # tracking hash so we don't double-export A+PTR or AAAA+PTR records.
|
---|
| 4786 | my %recflags;
|
---|
| 4787 |
|
---|
[368] | 4788 | my $domsth = $dbh->prepare("SELECT domain_id,domain,status,changed FROM domains WHERE status=1");
|
---|
[372] | 4789 | my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
[368] | 4790 | "FROM records WHERE domain_id=? AND type < 65280"); # Just exclude all types relating to rDNS
|
---|
[372] | 4791 | my $zonesth = $dbh->prepare("UPDATE domains SET changed='n' WHERE domain_id=?");
|
---|
[103] | 4792 | $domsth->execute();
|
---|
[368] | 4793 | while (my ($domid,$dom,$domstat,$changed) = $domsth->fetchrow_array) {
|
---|
| 4794 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
| 4795 | # O_NOFOLLOW
|
---|
| 4796 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
| 4797 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
| 4798 | # still be followed.
|
---|
| 4799 | # but that doesn't help other platforms. :/
|
---|
| 4800 | sysopen(ZONECACHE, "$config{exportcache}/$dom", O_RDWR|O_CREAT);
|
---|
| 4801 | flock(ZONECACHE, LOCK_EX);
|
---|
| 4802 | if ($changed || -s "$config{exportcache}/$dom" == 0) {
|
---|
| 4803 | $recsth->execute($domid);
|
---|
[372] | 4804 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc) = $recsth->fetchrow_array) {
|
---|
[368] | 4805 | next if $recflags{$recid};
|
---|
[108] | 4806 |
|
---|
[372] | 4807 | $loc = '' if !$loc; # de-nullify - just in case
|
---|
| 4808 | ##fixme: handle case of record-with-location-that-doesn't-exist better.
|
---|
| 4809 | # note this currently fails safe (tested) - records with a location that
|
---|
| 4810 | # doesn't exist will not be sent to any client
|
---|
| 4811 | # $loc = '' if !$lochash->{$loc};
|
---|
| 4812 |
|
---|
[108] | 4813 | ##fixme: record validity timestamp. tinydns supports fiddling with timestamps.
|
---|
| 4814 | # note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
|
---|
| 4815 | # timestamps are TAI64
|
---|
| 4816 | # ~~ 2^62 + time()
|
---|
[368] | 4817 | my $stamp = '';
|
---|
[108] | 4818 |
|
---|
[368] | 4819 | # support tinydns' auto-TTL
|
---|
| 4820 | $ttl = '' if $ttl == '0';
|
---|
[367] | 4821 |
|
---|
[417] | 4822 | # Spaces are evil.
|
---|
[441] | 4823 | $host =~ s/^\s+//;
|
---|
| 4824 | $host =~ s/\s+$//;
|
---|
| 4825 | if ($typemap{$type} ne 'TXT') {
|
---|
[417] | 4826 | # Leading or trailng spaces could be legit in TXT records.
|
---|
[441] | 4827 | $val =~ s/^\s+//;
|
---|
| 4828 | $val =~ s/\s+$//;
|
---|
[417] | 4829 | }
|
---|
| 4830 |
|
---|
[368] | 4831 | _printrec_tiny(*ZONECACHE, 'n', \%recflags,
|
---|
| 4832 | $dom, $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp)
|
---|
| 4833 | if *ZONECACHE;
|
---|
[450] | 4834 |
|
---|
[368] | 4835 | # in case the zone shrunk, get rid of garbage at the end of the file.
|
---|
| 4836 | truncate(ZONECACHE, tell(ZONECACHE));
|
---|
| 4837 |
|
---|
| 4838 | $recflags{$recid} = 1;
|
---|
| 4839 | } # while ($recsth)
|
---|
| 4840 | }
|
---|
[450] | 4841 | # stream from cache, whether freshly created or existing
|
---|
| 4842 | print $datafile $_ while <ZONECACHE>;
|
---|
[368] | 4843 | close ZONECACHE;
|
---|
| 4844 | # mark domain as unmodified
|
---|
| 4845 | $zonesth->execute($domid);
|
---|
[329] | 4846 | } # while ($domsth)
|
---|
| 4847 |
|
---|
[368] | 4848 | my $revsth = $dbh->prepare("SELECT rdns_id,revnet,status,changed FROM revzones WHERE status=1 ".
|
---|
[337] | 4849 | "ORDER BY masklen(revnet) DESC");
|
---|
[372] | 4850 |
|
---|
[344] | 4851 | # For reasons unknown, we can't sanely UNION these statements. Feh.
|
---|
| 4852 | # Supposedly it should work though (note last 3 lines):
|
---|
| 4853 | ## PG manual
|
---|
| 4854 | #UNION Clause
|
---|
| 4855 | #
|
---|
| 4856 | #The UNION clause has this general form:
|
---|
| 4857 | #
|
---|
| 4858 | # select_statement UNION [ ALL ] select_statement
|
---|
| 4859 | #
|
---|
| 4860 | #select_statement is any SELECT statement without an ORDER BY, LIMIT, FOR UPDATE, or FOR SHARE clause. (ORDER BY
|
---|
| 4861 | #and LIMIT can be attached to a subexpression if it is enclosed in parentheses. Without parentheses, these
|
---|
| 4862 | #clauses will be taken to apply to the result of the UNION, not to its right-hand input expression.)
|
---|
[372] | 4863 | my $soasth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
[344] | 4864 | "FROM records WHERE rdns_id=? AND type=6");
|
---|
[372] | 4865 | $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
[337] | 4866 | "FROM records WHERE rdns_id=? AND not type=6 ".
|
---|
[344] | 4867 | "ORDER BY masklen(CAST(val AS inet)) DESC, CAST(val AS inet)");
|
---|
[372] | 4868 | $zonesth = $dbh->prepare("UPDATE revzones SET changed='n' WHERE rdns_id=?");
|
---|
[329] | 4869 | $revsth->execute();
|
---|
[368] | 4870 | while (my ($revid,$revzone,$revstat,$changed) = $revsth->fetchrow_array) {
|
---|
| 4871 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
| 4872 | # O_NOFOLLOW
|
---|
| 4873 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
| 4874 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
| 4875 | # still be followed.
|
---|
| 4876 | # but that doesn't help other platforms. :/
|
---|
| 4877 | my $tmpzone = NetAddr::IP->new($revzone);
|
---|
| 4878 | sysopen(ZONECACHE, "$config{exportcache}/".$tmpzone->network->addr, O_RDWR|O_CREAT);
|
---|
| 4879 | flock(ZONECACHE, LOCK_EX);
|
---|
| 4880 | if ($changed || -s "$config{exportcache}/".$tmpzone->network->addr == 0) {
|
---|
| 4881 | # need to fetch this separately since the rest of the records all (should) have real IPs in val
|
---|
| 4882 | $soasth->execute($revid);
|
---|
| 4883 | my (@zsoa) = $soasth->fetchrow_array();
|
---|
[445] | 4884 | _printrec_tiny(*ZONECACHE,'y',\%recflags,$revzone,
|
---|
| 4885 | $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],'');
|
---|
[344] | 4886 |
|
---|
[368] | 4887 | $recsth->execute($revid);
|
---|
[372] | 4888 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc) = $recsth->fetchrow_array) {
|
---|
[368] | 4889 | next if $recflags{$recid};
|
---|
[329] | 4890 |
|
---|
[372] | 4891 | $loc = '' if !$loc; # de-nullify - just in case
|
---|
| 4892 | ##fixme: handle case of record-with-location-that-doesn't-exist better.
|
---|
| 4893 | # note this currently fails safe (tested) - records with a location that
|
---|
| 4894 | # doesn't exist will not be sent to any client
|
---|
| 4895 | # $loc = '' if !$lochash->{$loc};
|
---|
| 4896 |
|
---|
[329] | 4897 | ##fixme: record validity timestamp. tinydns supports fiddling with timestamps.
|
---|
| 4898 | # note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
|
---|
| 4899 | # timestamps are TAI64
|
---|
| 4900 | # ~~ 2^62 + time()
|
---|
[368] | 4901 | my $stamp = '';
|
---|
[329] | 4902 |
|
---|
[368] | 4903 | # support tinydns' auto-TTL
|
---|
| 4904 | $ttl = '' if $ttl == '0';
|
---|
[367] | 4905 |
|
---|
[368] | 4906 | _printrec_tiny(*ZONECACHE, 'y', \%recflags, $revzone,
|
---|
| 4907 | $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp)
|
---|
| 4908 | if *ZONECACHE;
|
---|
[329] | 4909 |
|
---|
[450] | 4910 | # in case the zone shrunk, get rid of garbage at the end of the file.
|
---|
| 4911 | truncate(ZONECACHE, tell(ZONECACHE));
|
---|
| 4912 |
|
---|
[368] | 4913 | $recflags{$recid} = 1;
|
---|
| 4914 | } # while ($recsth)
|
---|
| 4915 | }
|
---|
[450] | 4916 | # stream from cache, whether freshly created or existing
|
---|
| 4917 | print $datafile $_ while <ZONECACHE>;
|
---|
[368] | 4918 | close ZONECACHE;
|
---|
[450] | 4919 | # mark zone as unmodified
|
---|
[368] | 4920 | $zonesth->execute($revid);
|
---|
[329] | 4921 | } # while ($domsth)
|
---|
| 4922 |
|
---|
| 4923 | } # end __export_tiny()
|
---|
| 4924 |
|
---|
| 4925 |
|
---|
| 4926 | # Utility sub for __export_tiny above
|
---|
| 4927 | sub _printrec_tiny {
|
---|
| 4928 | my ($datafile,$revrec,$recflags,$zone,$host,$type,$val,$dist,$weight,$port,$ttl,$loc,$stamp) = @_;
|
---|
| 4929 |
|
---|
| 4930 | ## Convert a bare number into an octal-coded pair of octets.
|
---|
| 4931 | # Take optional arg to indicate a decimal or hex input. Defaults to hex.
|
---|
| 4932 | sub octalize {
|
---|
| 4933 | my $tmp = shift;
|
---|
| 4934 | my $srctype = shift || 'h'; # default assumes hex string
|
---|
| 4935 | $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
|
---|
| 4936 | $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
|
---|
| 4937 | my @o = ($tmp =~ /^(..)(..)$/); # split into octets
|
---|
| 4938 | return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);;
|
---|
| 4939 | }
|
---|
| 4940 |
|
---|
[339] | 4941 | ## WARNING: This works to export even the whole Internet's worth of IP space...
|
---|
| 4942 | ## if you have the disk/RAM to handle the dataset, and you call this sub based on /16-sized chunks
|
---|
| 4943 | ## A /16 took ~3 seconds with a handful of separate records; adding a /8 pushed export time out to ~13m:40s
|
---|
| 4944 | ## 0/0 is estimated to take ~54 hours and ~256G of disk
|
---|
| 4945 | ## RAM usage depends on how many non-template entries you have in the set.
|
---|
| 4946 | ## This should probably be done on record addition rather than export; large blocks may need to be done in a
|
---|
| 4947 | ## forked process
|
---|
| 4948 | sub __publish_subnet {
|
---|
| 4949 | my $sub = shift;
|
---|
| 4950 | my $recflags = shift;
|
---|
| 4951 | my $hpat = shift;
|
---|
| 4952 | my $fh = shift;
|
---|
| 4953 | my $ttl = shift;
|
---|
| 4954 | my $stamp = shift;
|
---|
| 4955 | my $loc = shift;
|
---|
| 4956 | my $ptronly = shift || 0;
|
---|
| 4957 |
|
---|
| 4958 | my $iplist = $sub->splitref(32);
|
---|
| 4959 | foreach (@$iplist) {
|
---|
| 4960 | my $ip = $_->addr;
|
---|
| 4961 | # make as if we split the non-octet-aligned block into octet-aligned blocks as with SOA
|
---|
| 4962 | next if $ip =~ /\.(0|255)$/;
|
---|
| 4963 | next if $$recflags{$ip};
|
---|
| 4964 | $$recflags{$ip}++;
|
---|
[463] | 4965 | next if $hpat eq '%blank%'; # Allows blanking a subnet so no records are published.
|
---|
[339] | 4966 | my $rec = $hpat; # start fresh with the template for each IP
|
---|
| 4967 | _template4_expand(\$rec, $ip);
|
---|
| 4968 | print $fh ($ptronly ? "^"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$rec" : "=$rec:$ip").
|
---|
| 4969 | ":$ttl:$stamp:$loc\n";
|
---|
| 4970 | }
|
---|
| 4971 | }
|
---|
| 4972 |
|
---|
[103] | 4973 | ##fixme? append . to all host/val hostnames
|
---|
| 4974 | if ($typemap{$type} eq 'SOA') {
|
---|
| 4975 |
|
---|
| 4976 | # host contains pri-ns:responsible
|
---|
| 4977 | # val is abused to contain refresh:retry:expire:minttl
|
---|
| 4978 | ##fixme: "manual" serial vs tinydns-autoserial
|
---|
[202] | 4979 | # let's be explicit about abusing $host and $val
|
---|
| 4980 | my ($email, $primary) = (split /:/, $host)[0,1];
|
---|
| 4981 | my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
|
---|
[330] | 4982 | if ($revrec eq 'y') {
|
---|
[337] | 4983 | ##fixme: have to publish SOA records for each v4 /24 in sub-/16, and each /16 in sub-/8
|
---|
| 4984 | # what about v6?
|
---|
| 4985 | # -> only need SOA for local chunks offset from reverse delegation boundaries, so v6 is fine
|
---|
[330] | 4986 | $zone = NetAddr::IP->new($zone);
|
---|
[337] | 4987 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
| 4988 | if (!$zone->{isv6} && ($zone->masklen < 24) && ($zone->masklen % 8 != 0)) {
|
---|
| 4989 | foreach my $szone ($zone->split($zone->masklen + (8 - $zone->masklen % 8))) {
|
---|
| 4990 | $szone = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
| 4991 | print $datafile "Z$szone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
|
---|
| 4992 | }
|
---|
| 4993 | return; # skips "default" bits just below
|
---|
| 4994 | }
|
---|
[330] | 4995 | $zone = _ZONE($zone, 'ZONE', 'r', '.').($zone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 4996 | }
|
---|
[329] | 4997 | print $datafile "Z$zone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
|
---|
[103] | 4998 |
|
---|
| 4999 | } elsif ($typemap{$type} eq 'A') {
|
---|
| 5000 |
|
---|
[108] | 5001 | print $datafile "+$host:$val:$ttl:$stamp:$loc\n";
|
---|
[103] | 5002 |
|
---|
| 5003 | } elsif ($typemap{$type} eq 'NS') {
|
---|
| 5004 |
|
---|
[330] | 5005 | if ($revrec eq 'y') {
|
---|
| 5006 | $val = NetAddr::IP->new($val);
|
---|
[345] | 5007 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
| 5008 | if (!$val->{isv6} && ($val->masklen < 24) && ($val->masklen % 8 != 0)) {
|
---|
[346] | 5009 | foreach my $szone ($val->split($val->masklen + (8 - $val->masklen % 8))) {
|
---|
[345] | 5010 | my $szone2 = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
[346] | 5011 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
[345] | 5012 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n";
|
---|
[346] | 5013 | $$recflags{$szone2} = $val->masklen;
|
---|
[345] | 5014 | }
|
---|
[346] | 5015 | } elsif ($val->{isv6} && ($val->masklen < 64) && ($val->masklen % 4 !=0)) {
|
---|
| 5016 | foreach my $szone ($val->split($val->masklen + (4 - $val->masklen % 4))) {
|
---|
| 5017 | my $szone2 = _ZONE($szone, 'ZONE.ip6.arpa', 'r', '.');
|
---|
| 5018 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
| 5019 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n";
|
---|
| 5020 | $$recflags{$szone2} = $val->masklen;
|
---|
| 5021 | }
|
---|
| 5022 | } else {
|
---|
| 5023 | my $val2 = _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 5024 | print $datafile "\&$val2"."::$host:$ttl:$stamp:$loc\n";
|
---|
| 5025 | $$recflags{$val2} = $val->masklen;
|
---|
[345] | 5026 | }
|
---|
[330] | 5027 | } else {
|
---|
| 5028 | print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n";
|
---|
| 5029 | }
|
---|
[103] | 5030 |
|
---|
| 5031 | } elsif ($typemap{$type} eq 'AAAA') {
|
---|
| 5032 |
|
---|
| 5033 | print $datafile ":$host:28:";
|
---|
| 5034 | my $altgrp = 0;
|
---|
| 5035 | my @altconv;
|
---|
[108] | 5036 | # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
|
---|
[103] | 5037 | foreach (split /:/, $val) {
|
---|
| 5038 | if (/^$/) {
|
---|
| 5039 | # flag blank entry; this is a series of 0's of (currently) unknown length
|
---|
| 5040 | $altconv[$altgrp++] = 's';
|
---|
| 5041 | } else {
|
---|
| 5042 | # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
|
---|
| 5043 | $altconv[$altgrp++] = octalize($_)
|
---|
| 5044 | }
|
---|
| 5045 | }
|
---|
| 5046 | foreach my $octet (@altconv) {
|
---|
| 5047 | # if not 's', output
|
---|
| 5048 | print $datafile $octet unless $octet =~ /^s$/;
|
---|
| 5049 | # if 's', output (9-array length)x literal '\000\000'
|
---|
| 5050 | print $datafile '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
|
---|
| 5051 | }
|
---|
[108] | 5052 | print $datafile ":$ttl:$stamp:$loc\n";
|
---|
[103] | 5053 |
|
---|
| 5054 | } elsif ($typemap{$type} eq 'MX') {
|
---|
| 5055 |
|
---|
[108] | 5056 | print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n";
|
---|
[103] | 5057 |
|
---|
| 5058 | } elsif ($typemap{$type} eq 'TXT') {
|
---|
| 5059 |
|
---|
| 5060 | ##fixme: split v-e-r-y long TXT strings? will need to do so for BIND export, at least
|
---|
[350] | 5061 | if ($revrec eq 'n') {
|
---|
| 5062 | $val =~ s/:/\\072/g; # may need to replace other symbols
|
---|
| 5063 | print $datafile "'$host:$val:$ttl:$stamp:$loc\n";
|
---|
| 5064 | } else {
|
---|
| 5065 | $host =~ s/:/\\072/g; # may need to replace other symbols
|
---|
| 5066 | my $val2 = NetAddr::IP->new($val);
|
---|
| 5067 | print $datafile "'"._ZONE($val2, 'ZONE', 'r', '.').($val2->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
| 5068 | ":$host:$ttl:$stamp:$loc\n";
|
---|
| 5069 | }
|
---|
[103] | 5070 |
|
---|
| 5071 | # by-hand TXT
|
---|
| 5072 | #:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
|
---|
| 5073 | #@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
|
---|
| 5074 | #'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
|
---|
| 5075 |
|
---|
| 5076 | #txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
|
---|
| 5077 | #: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
|
---|
| 5078 |
|
---|
| 5079 | # very long TXT record as brought in by axfr-get
|
---|
| 5080 | # note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
|
---|
| 5081 | # also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
|
---|
| 5082 | #:longtxt.deepnet.cx:16:
|
---|
| 5083 | #\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
|
---|
| 5084 | #\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.
|
---|
| 5085 | #\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.
|
---|
| 5086 | #:3600
|
---|
| 5087 |
|
---|
| 5088 | } elsif ($typemap{$type} eq 'CNAME') {
|
---|
| 5089 |
|
---|
[372] | 5090 | if ($revrec eq 'n') {
|
---|
| 5091 | print $datafile "C$host:$val:$ttl:$stamp:$loc\n";
|
---|
| 5092 | } else {
|
---|
| 5093 | my $val2 = NetAddr::IP->new($val);
|
---|
| 5094 | print $datafile "C"._ZONE($val2, 'ZONE', 'r', '.').($val2->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
| 5095 | ":$host:$ttl:$stamp:$loc\n";
|
---|
| 5096 | }
|
---|
[103] | 5097 |
|
---|
| 5098 | } elsif ($typemap{$type} eq 'SRV') {
|
---|
| 5099 |
|
---|
| 5100 | # data is two-byte values for priority, weight, port, in that order,
|
---|
| 5101 | # followed by length/string data
|
---|
| 5102 |
|
---|
| 5103 | print $datafile ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
|
---|
| 5104 |
|
---|
| 5105 | $val .= '.' if $val !~ /\.$/;
|
---|
| 5106 | foreach (split /\./, $val) {
|
---|
| 5107 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
| 5108 | }
|
---|
[108] | 5109 | print $datafile "\\000:$ttl:$stamp:$loc\n";
|
---|
[103] | 5110 |
|
---|
| 5111 | } elsif ($typemap{$type} eq 'RP') {
|
---|
| 5112 |
|
---|
| 5113 | # RP consists of two mostly free-form strings.
|
---|
| 5114 | # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
|
---|
| 5115 | # The second is the "hostname" of a TXT record with more info.
|
---|
| 5116 | print $datafile ":$host:17:";
|
---|
| 5117 | my ($who,$what) = split /\s/, $val;
|
---|
| 5118 | foreach (split /\./, $who) {
|
---|
| 5119 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
| 5120 | }
|
---|
| 5121 | print $datafile '\000';
|
---|
| 5122 | foreach (split /\./, $what) {
|
---|
| 5123 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
| 5124 | }
|
---|
[108] | 5125 | print $datafile "\\000:$ttl:$stamp:$loc\n";
|
---|
[103] | 5126 |
|
---|
| 5127 | } elsif ($typemap{$type} eq 'PTR') {
|
---|
| 5128 |
|
---|
[332] | 5129 | $zone = NetAddr::IP->new($zone);
|
---|
[337] | 5130 | $$recflags{$val}++;
|
---|
[332] | 5131 | if (!$zone->{isv6} && $zone->masklen > 24) {
|
---|
| 5132 | ($val) = ($val =~ /\.(\d+)$/);
|
---|
| 5133 | print $datafile "^$val."._ZONE($zone, 'ZONE', 'r', '.').'.in-addr.arpa'.
|
---|
| 5134 | ":$host:ttl:$stamp:$loc\n";
|
---|
| 5135 | } else {
|
---|
| 5136 | $val = NetAddr::IP->new($val);
|
---|
| 5137 | print $datafile "^".
|
---|
| 5138 | _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
[334] | 5139 | ":$host:$ttl:$stamp:$loc\n";
|
---|
[332] | 5140 | }
|
---|
[103] | 5141 |
|
---|
[333] | 5142 | } elsif ($type == 65280) { # A+PTR
|
---|
[334] | 5143 |
|
---|
[337] | 5144 | $$recflags{$val}++;
|
---|
[334] | 5145 | print $datafile "=$host:$val:$ttl:$stamp:$loc\n";
|
---|
| 5146 |
|
---|
[333] | 5147 | } elsif ($type == 65281) { # AAAA+PTR
|
---|
| 5148 |
|
---|
[337] | 5149 | #$$recflags{$val}++;
|
---|
[333] | 5150 | # treat these as two separate records. since tinydns doesn't have
|
---|
| 5151 | # a native combined type, we have to create them separately anyway.
|
---|
| 5152 | if ($revrec eq 'n') {
|
---|
| 5153 | $type = 28;
|
---|
| 5154 | } else {
|
---|
| 5155 | $type = 12;
|
---|
| 5156 | }
|
---|
[334] | 5157 | _printrec_tiny($datafile,$revrec,$recflags,$zone,$host,$type,$val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
[335] | 5158 | ##fixme: add a config flag to indicate use of the patch from http://www.fefe.de/dns/
|
---|
| 5159 | # type 6 is for AAAA+PTR, type 3 is for AAAA
|
---|
[333] | 5160 |
|
---|
| 5161 | } elsif ($type == 65282) { # PTR template
|
---|
[335] | 5162 |
|
---|
| 5163 | # only useful for v4 with standard DNS software, since this expands all
|
---|
| 5164 | # IPs in $zone (or possibly $val?) with autogenerated records
|
---|
[337] | 5165 | $val = NetAddr::IP->new($val);
|
---|
| 5166 | return if $val->{isv6};
|
---|
[336] | 5167 |
|
---|
[339] | 5168 | if ($val->masklen <= 16) {
|
---|
| 5169 | foreach my $sub ($val->split(16)) {
|
---|
| 5170 | __publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, 1);
|
---|
| 5171 | }
|
---|
| 5172 | } else {
|
---|
| 5173 | __publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, 1);
|
---|
[337] | 5174 | }
|
---|
[335] | 5175 |
|
---|
[333] | 5176 | } elsif ($type == 65283) { # A+PTR template
|
---|
[335] | 5177 |
|
---|
[337] | 5178 | $val = NetAddr::IP->new($val);
|
---|
| 5179 | # Just In Case. An A+PTR should be impossible to add to a v6 revzone via API.
|
---|
| 5180 | return if $val->{isv6};
|
---|
[339] | 5181 |
|
---|
| 5182 | if ($val->masklen <= 16) {
|
---|
| 5183 | foreach my $sub ($val->split(16)) {
|
---|
| 5184 | __publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, 0);
|
---|
| 5185 | }
|
---|
| 5186 | } else {
|
---|
| 5187 | __publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, 0);
|
---|
[337] | 5188 | }
|
---|
[335] | 5189 |
|
---|
[333] | 5190 | } elsif ($type == 65284) { # AAAA+PTR template
|
---|
[335] | 5191 | # Stub for completeness. Could be exported to DNS software that supports
|
---|
| 5192 | # some degree of internal automagic in generic-record-creation
|
---|
| 5193 | # (eg http://search.cpan.org/dist/AllKnowingDNS/ )
|
---|
[333] | 5194 |
|
---|
[345] | 5195 | } elsif ($type == 65285) { # Delegation
|
---|
| 5196 | # This is intended for reverse zones, but may prove useful in forward zones.
|
---|
| 5197 |
|
---|
[346] | 5198 | # All delegations need to create one or more NS records. The NS record handler knows what to do.
|
---|
| 5199 | _printrec_tiny($datafile,$revrec,$recflags,$zone,$host,$reverse_typemap{'NS'},
|
---|
| 5200 | $val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
| 5201 | if ($revrec eq 'y') {
|
---|
| 5202 | # In the case of a sub-/24 v4 reverse delegation, we need to generate CNAMEs
|
---|
| 5203 | # to redirect all of the individual IP lookups as well.
|
---|
| 5204 | # Not sure how this would actually resolve if a /24 or larger was delegated
|
---|
| 5205 | # one way, and a sub-/24 in that >=/24 was delegated elsewhere...
|
---|
| 5206 | my $dblock = NetAddr::IP->new($val);
|
---|
| 5207 | if (!$dblock->{isv6} && $dblock->masklen > 24) {
|
---|
| 5208 | my @subs = $dblock->split;
|
---|
| 5209 | foreach (@subs) {
|
---|
| 5210 | next if $$recflags{"$_"};
|
---|
| 5211 | my ($oct) = ($_->addr =~ /(\d+)$/);
|
---|
| 5212 | print $datafile "C"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$oct.".
|
---|
| 5213 | _ZONE($dblock, 'ZONE.in-addr.arpa', 'r', '.').":$ttl:$stamp:$loc\n";
|
---|
| 5214 | $$recflags{"$_"}++;
|
---|
| 5215 | }
|
---|
| 5216 | }
|
---|
| 5217 | }
|
---|
[345] | 5218 |
|
---|
[364] | 5219 | ##
|
---|
| 5220 | ## Uncommon types. These will need better UI support Any Day Sometime Maybe(TM).
|
---|
| 5221 | ##
|
---|
| 5222 |
|
---|
| 5223 | } elsif ($type == 44) { # SSHFP
|
---|
| 5224 | my ($algo,$fpt,$fp) = split /\s+/, $val;
|
---|
| 5225 |
|
---|
| 5226 | my $rec = sprintf ":$host:44:\\%0.3o\\%0.3o", $algo, $fpt;
|
---|
| 5227 | while (my ($byte) = ($fp =~ /^(..)/) ) {
|
---|
| 5228 | $rec .= sprintf "\\%0.3o", hex($byte);
|
---|
| 5229 | $fp =~ s/^..//;
|
---|
| 5230 | }
|
---|
| 5231 | print $datafile "$rec:$ttl:$stamp:$loc\n";
|
---|
| 5232 |
|
---|
[345] | 5233 | } else {
|
---|
[108] | 5234 | # raw record. we don't know what's in here, so we ASS-U-ME the user has
|
---|
| 5235 | # put it in correctly, since either the user is messing directly with the
|
---|
| 5236 | # database, or the record was imported via AXFR
|
---|
| 5237 | # <split by char>
|
---|
| 5238 | # convert anything not a-zA-Z0-9.- to octal coding
|
---|
| 5239 |
|
---|
| 5240 | ##fixme: add flag to export "unknown" record types - note we'll probably end up
|
---|
| 5241 | # mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
|
---|
| 5242 | #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
|
---|
| 5243 |
|
---|
[103] | 5244 | } # record type if-else
|
---|
| 5245 |
|
---|
[329] | 5246 | } # end _printrec_tiny()
|
---|
[103] | 5247 |
|
---|
| 5248 |
|
---|
[197] | 5249 | ## DNSDB::mailNotify()
|
---|
[283] | 5250 | # Sends notification mail to recipients regarding a DNSDB operation
|
---|
[197] | 5251 | sub mailNotify {
|
---|
| 5252 | my $dbh = shift;
|
---|
| 5253 | my ($subj,$message) = @_;
|
---|
| 5254 |
|
---|
| 5255 | return if $config{mailhost} eq 'smtp.example.com'; # do nothing if still using default SMTP host.
|
---|
| 5256 |
|
---|
| 5257 | my $mailer = Net::SMTP->new($config{mailhost}, Hello => "dnsadmin.$config{domain}");
|
---|
| 5258 |
|
---|
| 5259 | my $mailsender = ($config{mailsender} ? $config{mailsender} : $config{mailnotify});
|
---|
| 5260 |
|
---|
| 5261 | $mailer->mail($mailsender);
|
---|
| 5262 | $mailer->to($config{mailnotify});
|
---|
[198] | 5263 | $mailer->data("From: \"$config{mailname}\" <$mailsender>\n",
|
---|
| 5264 | "To: <$config{mailnotify}>\n",
|
---|
[197] | 5265 | "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
|
---|
| 5266 | "Subject: $subj\n",
|
---|
| 5267 | "X-Mailer: DNSAdmin Notify v".sprintf("%.1d",$DNSDB::VERSION)."\n",
|
---|
| 5268 | "Organization: $config{orgname}\n",
|
---|
| 5269 | "\n$message\n");
|
---|
| 5270 | $mailer->quit;
|
---|
| 5271 | }
|
---|
| 5272 |
|
---|
[2] | 5273 | # shut Perl up
|
---|
| 5274 | 1;
|
---|