[2] | 1 | # dns/trunk/DNSDB.pm
|
---|
| 2 | # Abstraction functions for DNS administration
|
---|
[262] | 3 | ##
|
---|
| 4 | # $Id: DNSDB.pm 455 2013-01-16 23:01: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 $group = 1;
|
---|
| 95 | our $errstr = '';
|
---|
[283] | 96 | our $resultstr = '';
|
---|
[2] | 97 |
|
---|
| 98 | # Halfway sane defaults for SOA, TTL, etc.
|
---|
[101] | 99 | # serial defaults to 0 for convenience.
|
---|
| 100 | # value will be either YYYYMMDDNN for BIND/etc, or auto-internal for tinydns
|
---|
[2] | 101 | our %def = qw (
|
---|
| 102 | contact hostmaster.DOMAIN
|
---|
| 103 | prins ns1.myserver.com
|
---|
[101] | 104 | serial 0
|
---|
[2] | 105 | soattl 86400
|
---|
| 106 | refresh 10800
|
---|
| 107 | retry 3600
|
---|
| 108 | expire 604800
|
---|
| 109 | minttl 10800
|
---|
| 110 | ttl 10800
|
---|
| 111 | );
|
---|
| 112 |
|
---|
[66] | 113 | # Arguably defined wholly in the db, but little reason to change without supporting code changes
|
---|
[370] | 114 | # group_view, user_view permissions? separate rDNS permission(s)?
|
---|
[66] | 115 | our @permtypes = qw (
|
---|
| 116 | group_edit group_create group_delete
|
---|
| 117 | user_edit user_create user_delete
|
---|
| 118 | domain_edit domain_create domain_delete
|
---|
[387] | 119 | record_edit record_create record_delete record_locchg
|
---|
[370] | 120 | location_edit location_create location_delete location_view
|
---|
[66] | 121 | self_edit admin
|
---|
| 122 | );
|
---|
| 123 | our $permlist = join(',',@permtypes);
|
---|
| 124 |
|
---|
[390] | 125 | # Some permissions more or less require certain others.
|
---|
| 126 | our %permchains = (
|
---|
| 127 | user_edit => 'self_edit',
|
---|
| 128 | location_edit => 'location_view',
|
---|
| 129 | location_create => 'location_view',
|
---|
| 130 | location_delete => 'location_view',
|
---|
| 131 | record_locchg => 'location_view',
|
---|
| 132 | );
|
---|
| 133 |
|
---|
[2] | 134 | # DNS record type map and reverse map.
|
---|
| 135 | # loaded from the database, from http://www.iana.org/assignments/dns-parameters
|
---|
| 136 | our %typemap;
|
---|
| 137 | our %reverse_typemap;
|
---|
| 138 |
|
---|
[65] | 139 | our %permissions;
|
---|
[55] | 140 |
|
---|
[128] | 141 | # Prepopulate a basic config. Note some of these *will* cause errors if left unset.
|
---|
[195] | 142 | # note: add appropriate stanzas in loadConfig to parse these
|
---|
[128] | 143 | our %config = (
|
---|
| 144 | # Database connection info
|
---|
| 145 | dbname => 'dnsdb',
|
---|
| 146 | dbuser => 'dnsdb',
|
---|
| 147 | dbpass => 'secret',
|
---|
| 148 | dbhost => '',
|
---|
| 149 |
|
---|
| 150 | # Email notice settings
|
---|
| 151 | mailhost => 'smtp.example.com',
|
---|
[195] | 152 | mailnotify => 'dnsdb@example.com', # to
|
---|
| 153 | mailsender => 'dnsdb@example.com', # from
|
---|
[128] | 154 | mailname => 'DNS Administration',
|
---|
[195] | 155 | orgname => 'Example Corp',
|
---|
| 156 | domain => 'example.com',
|
---|
[128] | 157 |
|
---|
| 158 | # Template directory
|
---|
| 159 | templatedir => 'templates/',
|
---|
| 160 | # fmeh. this is a real web path, not a logical internal one. hm..
|
---|
[163] | 161 | # cssdir => 'templates/',
|
---|
[216] | 162 | sessiondir => 'session/',
|
---|
[368] | 163 | exportcache => 'cache/',
|
---|
[163] | 164 |
|
---|
| 165 | # Session params
|
---|
[195] | 166 | timeout => '3600', # 1 hour default
|
---|
| 167 |
|
---|
| 168 | # Other miscellanea
|
---|
| 169 | log_failures => 1, # log all evarthing by default
|
---|
[201] | 170 | perpage => 15,
|
---|
[128] | 171 | );
|
---|
| 172 |
|
---|
[228] | 173 | ## (Semi)private variables
|
---|
[278] | 174 |
|
---|
[228] | 175 | # Hash of functions for validating record types. Filled in initGlobals() since
|
---|
| 176 | # it relies on visibility flags from the rectypes table in the DB
|
---|
| 177 | my %validators;
|
---|
[128] | 178 |
|
---|
[278] | 179 | # Username, full name, ID - mainly for logging
|
---|
| 180 | my %userdata;
|
---|
[228] | 181 |
|
---|
[295] | 182 | # Entity-relationship reference hashes.
|
---|
| 183 | my %par_tbl = (
|
---|
| 184 | group => 'groups',
|
---|
| 185 | user => 'users',
|
---|
| 186 | defrec => 'default_records',
|
---|
| 187 | defrevrec => 'default_rev_records',
|
---|
| 188 | domain => 'domains',
|
---|
| 189 | revzone => 'revzones',
|
---|
| 190 | record => 'records'
|
---|
| 191 | );
|
---|
| 192 | my %id_col = (
|
---|
| 193 | group => 'group_id',
|
---|
| 194 | user => 'user_id',
|
---|
| 195 | defrec => 'record_id',
|
---|
| 196 | defrevrec => 'record_id',
|
---|
| 197 | domain => 'domain_id',
|
---|
| 198 | revzone => 'rdns_id',
|
---|
| 199 | record => 'record_id'
|
---|
| 200 | );
|
---|
| 201 | my %par_col = (
|
---|
| 202 | group => 'parent_group_id',
|
---|
| 203 | user => 'group_id',
|
---|
| 204 | defrec => 'group_id',
|
---|
| 205 | defrevrec => 'group_id',
|
---|
| 206 | domain => 'group_id',
|
---|
| 207 | revzone => 'group_id',
|
---|
| 208 | record => 'domain_id'
|
---|
| 209 | );
|
---|
| 210 | my %par_type = (
|
---|
| 211 | group => 'group',
|
---|
| 212 | user => 'group',
|
---|
| 213 | defrec => 'group',
|
---|
| 214 | defrevrec => 'group',
|
---|
| 215 | domain => 'group',
|
---|
| 216 | revzone => 'group',
|
---|
| 217 | record => 'domain'
|
---|
| 218 | );
|
---|
[278] | 219 |
|
---|
[2] | 220 | ##
|
---|
[225] | 221 | ## utility functions
|
---|
[281] | 222 | ##
|
---|
| 223 |
|
---|
| 224 | ## DNSDB::_rectable()
|
---|
[224] | 225 | # Takes default+rdns flags, returns appropriate table name
|
---|
| 226 | sub _rectable {
|
---|
| 227 | my $def = shift;
|
---|
| 228 | my $rev = shift;
|
---|
| 229 |
|
---|
| 230 | return 'records' if $def ne 'y';
|
---|
| 231 | return 'default_records' if $rev ne 'y';
|
---|
| 232 | return 'default_rev_records';
|
---|
| 233 | } # end _rectable()
|
---|
| 234 |
|
---|
[281] | 235 | ## DNSDB::_recparent()
|
---|
[224] | 236 | # Takes default+rdns flags, returns appropriate parent-id column name
|
---|
| 237 | sub _recparent {
|
---|
| 238 | my $def = shift;
|
---|
| 239 | my $rev = shift;
|
---|
| 240 |
|
---|
| 241 | return 'group_id' if $def eq 'y';
|
---|
| 242 | return 'rdns_id' if $rev eq 'y';
|
---|
| 243 | return 'domain_id';
|
---|
| 244 | } # end _recparent()
|
---|
| 245 |
|
---|
[281] | 246 | ## DNSDB::_ipparent()
|
---|
[226] | 247 | # Check an IP to be added in a reverse zone to see if it's really in the requested parent.
|
---|
| 248 | # Takes a database handle, default and reverse flags, IP (fragment) to check, parent zone ID,
|
---|
| 249 | # and a reference to a NetAddr::IP object (also used to pass back a fully-reconstructed IP for
|
---|
| 250 | # database insertion)
|
---|
| 251 | sub _ipparent {
|
---|
| 252 | my $dbh = shift;
|
---|
| 253 | my $defrec = shift;
|
---|
| 254 | my $revrec = shift;
|
---|
| 255 | my $val = shift;
|
---|
| 256 | my $id = shift;
|
---|
| 257 | my $addr = shift;
|
---|
[224] | 258 |
|
---|
[232] | 259 | return if $revrec ne 'y'; # this sub not useful in forward zones
|
---|
| 260 |
|
---|
| 261 | $$addr = NetAddr::IP->new($$val); #necessary?
|
---|
| 262 |
|
---|
[226] | 263 | # subsub to split, reverse, and overlay an IP fragment on a netblock
|
---|
| 264 | sub __rev_overlay {
|
---|
| 265 | my $splitme = shift; # ':' or '.', m'lud?
|
---|
| 266 | my $parnet = shift;
|
---|
| 267 | my $val = shift;
|
---|
| 268 | my $addr = shift;
|
---|
| 269 |
|
---|
| 270 | my $joinme = $splitme;
|
---|
| 271 | $splitme = '\.' if $splitme eq '.';
|
---|
[232] | 272 | my @working = reverse(split($splitme, $parnet->addr));
|
---|
| 273 | my @parts = reverse(split($splitme, $$val));
|
---|
[226] | 274 | for (my $i = 0; $i <= $#parts; $i++) {
|
---|
| 275 | $working[$i] = $parts[$i];
|
---|
| 276 | }
|
---|
[232] | 277 | my $checkme = NetAddr::IP->new(join($joinme, reverse(@working))) or return 0;
|
---|
| 278 | return 0 unless $checkme->within($parnet);
|
---|
[226] | 279 | $$addr = $checkme; # force "correct" IP to be recorded.
|
---|
| 280 | return 1;
|
---|
| 281 | }
|
---|
| 282 |
|
---|
| 283 | my ($parstr) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id = ?", undef, ($id));
|
---|
| 284 | my $parnet = NetAddr::IP->new($parstr);
|
---|
| 285 |
|
---|
| 286 | # Fail early on v6-in-v4 or v4-in-v6. We're not accepting these ATM.
|
---|
[232] | 287 | return 0 if $parnet->addr =~ /\./ && $$val =~ /:/;
|
---|
| 288 | return 0 if $parnet->addr =~ /:/ && $$val =~ /\./;
|
---|
[226] | 289 |
|
---|
[340] | 290 | if ($$addr && ($$val =~ /^[\da-fA-F][\da-fA-F:]+[\da-fA-F]$/ || $$val =~ m|/\d+$|)) {
|
---|
| 291 | # the only case where NetAddr::IP's acceptance of legitimate IPs is "correct" is for a proper IPv6 address,
|
---|
| 292 | # or a netblock (only expected on templates)
|
---|
[232] | 293 | # the rest we have to restructure before fiddling. *sigh*
|
---|
| 294 | return 1 if $$addr->within($parnet);
|
---|
| 295 | } else {
|
---|
[340] | 296 | # We don't have a complete IP in $$val (yet)... unless we have a netblock
|
---|
[232] | 297 | if ($parnet->addr =~ /:/) {
|
---|
| 298 | $$val =~ s/^:+//; # gotta strip'em all...
|
---|
[226] | 299 | return __rev_overlay(':', $parnet, $val, $addr);
|
---|
| 300 | }
|
---|
[232] | 301 | if ($parnet->addr =~ /\./) {
|
---|
| 302 | $$val =~ s/^\.+//;
|
---|
| 303 | return __rev_overlay('.', $parnet, $val, $addr);
|
---|
| 304 | }
|
---|
[226] | 305 | # should be impossible to get here...
|
---|
| 306 | }
|
---|
| 307 | # ... and here.
|
---|
| 308 | # can't do nuttin' in forward zones
|
---|
| 309 | } # end _ipparent()
|
---|
| 310 |
|
---|
[281] | 311 | ## DNSDB::_hostparent()
|
---|
[232] | 312 | # A little different than _ipparent above; this tries to *find* the parent zone of a hostname
|
---|
[281] | 313 | # Takes a database handle and hostname.
|
---|
| 314 | # Returns the domain ID of the parent domain if one was found.
|
---|
[232] | 315 | sub _hostparent {
|
---|
| 316 | my $dbh = shift;
|
---|
| 317 | my $hname = shift;
|
---|
[347] | 318 |
|
---|
| 319 | $hname =~ s/^\*\.//; # this should be impossible to find in the domains table.
|
---|
[232] | 320 | my @hostbits = split /\./, $hname;
|
---|
[349] | 321 | my $sth = $dbh->prepare("SELECT count(*),domain_id FROM domains WHERE lower(domain) = lower(?) GROUP BY domain_id");
|
---|
[232] | 322 | foreach (@hostbits) {
|
---|
| 323 | $sth->execute($hname);
|
---|
| 324 | my ($found, $parid) = $sth->fetchrow_array;
|
---|
| 325 | if ($found) {
|
---|
| 326 | return $parid;
|
---|
| 327 | }
|
---|
| 328 | $hname =~ s/^$_\.//;
|
---|
| 329 | }
|
---|
| 330 | } # end _hostparent()
|
---|
[228] | 331 |
|
---|
[281] | 332 | ## DNSDB::_log()
|
---|
| 333 | # Log an action
|
---|
| 334 | # Takes a database handle and log entry hash containing at least:
|
---|
[282] | 335 | # group_id, log entry
|
---|
[281] | 336 | # and optionally one or more of:
|
---|
| 337 | # domain_id, rdns_id
|
---|
[282] | 338 | # The %userdata hash provides the user ID, username, and fullname
|
---|
[281] | 339 | sub _log {
|
---|
| 340 | my $dbh = shift;
|
---|
| 341 |
|
---|
| 342 | my %args = @_;
|
---|
| 343 |
|
---|
| 344 | $args{rdns_id} = 0 if !$args{rdns_id};
|
---|
| 345 | $args{domain_id} = 0 if !$args{domain_id};
|
---|
| 346 |
|
---|
| 347 | ##fixme: farm out the actual logging to different subs for file, syslog, internal, etc based on config
|
---|
| 348 | # if ($config{log_channel} eq 'sql') {
|
---|
| 349 | $dbh->do("INSERT INTO log (domain_id,rdns_id,group_id,entry,user_id,email,name) VALUES (?,?,?,?,?,?,?)",
|
---|
| 350 | undef,
|
---|
| 351 | ($args{domain_id}, $args{rdns_id}, $args{group_id}, $args{entry},
|
---|
| 352 | $userdata{userid}, $userdata{username}, $userdata{fullname}) );
|
---|
| 353 | # } elsif ($config{log_channel} eq 'file') {
|
---|
| 354 | # } elsif ($config{log_channel} eq 'syslog') {
|
---|
| 355 | # }
|
---|
| 356 | } # end _log
|
---|
| 357 |
|
---|
| 358 |
|
---|
[224] | 359 | ##
|
---|
[228] | 360 | ## Record validation subs.
|
---|
| 361 | ##
|
---|
| 362 |
|
---|
[281] | 363 | ## All of these subs take substantially the same arguments:
|
---|
| 364 | # a database handle
|
---|
| 365 | # a hash containing at least the following keys:
|
---|
| 366 | # - defrec (default/live flag)
|
---|
| 367 | # - revrec (forward/reverse flag)
|
---|
| 368 | # - id (parent entity ID)
|
---|
| 369 | # - host (hostname)
|
---|
| 370 | # - rectype
|
---|
| 371 | # - val (IP, hostname [CNAME/MX/SRV] or text)
|
---|
| 372 | # - addr (NetAddr::IP object from val. May be undef.)
|
---|
| 373 | # MX and SRV record validation also expect distance, and SRV records expect weight and port as well.
|
---|
| 374 | # host, rectype, and addr should be references as these may be modified in validation
|
---|
| 375 |
|
---|
[228] | 376 | # A record
|
---|
| 377 | sub _validate_1 {
|
---|
[229] | 378 | my $dbh = shift;
|
---|
| 379 |
|
---|
[230] | 380 | my %args = @_;
|
---|
[229] | 381 |
|
---|
[230] | 382 | return ('FAIL', 'Reverse zones cannot contain A records') if $args{revrec} eq 'y';
|
---|
[229] | 383 |
|
---|
| 384 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 385 | # or the intended parent domain for live records.
|
---|
[230] | 386 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
|
---|
| 387 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
[229] | 388 |
|
---|
| 389 | # Check IP is well-formed, and that it's a v4 address
|
---|
[234] | 390 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
|
---|
[232] | 391 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
[234] | 392 | unless ${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/;
|
---|
| 393 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
[230] | 394 | unless $args{addr} && !$args{addr}->{isv6};
|
---|
[229] | 395 | # coerce IP/value to normalized form for storage
|
---|
[230] | 396 | ${$args{val}} = $args{addr}->addr;
|
---|
[229] | 397 |
|
---|
[228] | 398 | return ('OK','OK');
|
---|
| 399 | } # done A record
|
---|
| 400 |
|
---|
| 401 | # NS record
|
---|
| 402 | sub _validate_2 {
|
---|
[230] | 403 | my $dbh = shift;
|
---|
| 404 |
|
---|
| 405 | my %args = @_;
|
---|
| 406 |
|
---|
[328] | 407 | # Check that the target of the record is within the parent.
|
---|
| 408 | # Yes, host<->val are mixed up here; can't see a way to avoid it. :(
|
---|
| 409 | if ($args{defrec} eq 'n') {
|
---|
| 410 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
| 411 | if ($args{revrec} eq 'y') {
|
---|
| 412 | my $tmpip = NetAddr::IP->new(${$args{val}});
|
---|
| 413 | my $pname = revName($dbh,$args{id});
|
---|
| 414 | return ('FAIL',"${$args{val}} not within $pname")
|
---|
| 415 | unless _ipparent($dbh, $args{defrec}, $args{revrec}, $args{val}, $args{id}, \$tmpip);
|
---|
| 416 | # Sub the returned thing for ZONE? This could get stupid if you have typos...
|
---|
| 417 | ${$args{val}} =~ s/ZONE/$tmpip->address/;
|
---|
| 418 | } else {
|
---|
| 419 | my $pname = domainName($dbh,$args{id});
|
---|
| 420 | ${$args{host}} = $pname if ${$args{host}} !~ /\.$pname$/;
|
---|
| 421 | }
|
---|
[230] | 422 | } else {
|
---|
[328] | 423 | # Default reverse NS records should always refer to the implied parent
|
---|
| 424 | ${$args{host}} = 'DOMAIN' if $args{revrec} eq 'n';
|
---|
| 425 | ${$args{val}} = 'ZONE' if $args{revrec} eq 'y';
|
---|
[230] | 426 | }
|
---|
| 427 |
|
---|
| 428 | # Let this lie for now. Needs more magic.
|
---|
| 429 | # # Check IP is well-formed, and that it's a v4 address
|
---|
| 430 | # return ('FAIL',"A record must be a valid IPv4 address")
|
---|
| 431 | # unless $addr && !$addr->{isv6};
|
---|
| 432 | # # coerce IP/value to normalized form for storage
|
---|
| 433 | # $$val = $addr->addr;
|
---|
| 434 |
|
---|
[228] | 435 | return ('OK','OK');
|
---|
| 436 | } # done NS record
|
---|
| 437 |
|
---|
| 438 | # CNAME record
|
---|
| 439 | sub _validate_5 {
|
---|
[230] | 440 | my $dbh = shift;
|
---|
| 441 |
|
---|
| 442 | my %args = @_;
|
---|
| 443 |
|
---|
| 444 | # Not really true, but these are only useful for delegating smaller-than-/24 IP blocks.
|
---|
| 445 | # This is fundamentally a messy operation and should really just be taken care of by the
|
---|
| 446 | # export process, not manual maintenance of the necessary records.
|
---|
| 447 | return ('FAIL', 'Reverse zones cannot contain CNAME records') if $args{revrec} eq 'y';
|
---|
| 448 |
|
---|
| 449 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 450 | # or the intended parent domain for live records.
|
---|
| 451 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
|
---|
| 452 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 453 |
|
---|
[228] | 454 | return ('OK','OK');
|
---|
| 455 | } # done CNAME record
|
---|
| 456 |
|
---|
| 457 | # SOA record
|
---|
| 458 | sub _validate_6 {
|
---|
[230] | 459 | # Smart monkeys won't stick their fingers in here; we have
|
---|
| 460 | # separate dedicated routines to deal with SOA records.
|
---|
[228] | 461 | return ('OK','OK');
|
---|
| 462 | } # done SOA record
|
---|
| 463 |
|
---|
| 464 | # PTR record
|
---|
| 465 | sub _validate_12 {
|
---|
[232] | 466 | my $dbh = shift;
|
---|
| 467 |
|
---|
| 468 | my %args = @_;
|
---|
| 469 |
|
---|
| 470 | if ($args{revrec} eq 'y') {
|
---|
| 471 | if ($args{defrec} eq 'n') {
|
---|
| 472 | return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".revName($dbh, $args{id}))
|
---|
| 473 | unless _ipparent($dbh, $args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
| 474 | ${$args{val}} = $args{addr}->addr;
|
---|
| 475 | } else {
|
---|
[234] | 476 | if (${$args{val}} =~ /\./) {
|
---|
| 477 | # looks like a v4 or fragment
|
---|
| 478 | if (${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/) {
|
---|
| 479 | # woo! a complete IP! validate it and normalize, or fail.
|
---|
| 480 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
| 481 | or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
|
---|
| 482 | ${$args{val}} = $args{addr}->addr;
|
---|
| 483 | } else {
|
---|
[249] | 484 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
[234] | 485 | }
|
---|
| 486 | } elsif (${$args{val}} =~ /[a-f:]/) {
|
---|
| 487 | # looks like a v6 or fragment
|
---|
[251] | 488 | ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
|
---|
[234] | 489 | if ($args{addr}) {
|
---|
| 490 | if ($args{addr}->addr =~ /^0/) {
|
---|
[251] | 491 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
[234] | 492 | } else {
|
---|
| 493 | ${$args{val}} = $args{addr}->addr;
|
---|
| 494 | }
|
---|
| 495 | }
|
---|
| 496 | } else {
|
---|
| 497 | # bare number (probably). These could be v4 or v6, so we'll
|
---|
| 498 | # expand on these on creation of a reverse zone.
|
---|
[251] | 499 | ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
|
---|
[234] | 500 | }
|
---|
[249] | 501 | ${$args{host}} =~ s/\.*$/\.$config{domain}/ if ${$args{host}} !~ /(?:$config{domain}|ADMINDOMAIN)$/;
|
---|
[232] | 502 | }
|
---|
| 503 |
|
---|
| 504 | # Multiple PTR records do NOT generally do what most people believe they do,
|
---|
| 505 | # and tend to fail in the most awkward way possible. Check and warn.
|
---|
| 506 | # We use $val instead of $addr->addr since we may be in a defrec, and may have eg "ZONE::42" or "ZONE.12"
|
---|
[249] | 507 |
|
---|
| 508 | my @checkvals = (${$args{val}});
|
---|
| 509 | if (${$args{val}} =~ /,/) {
|
---|
| 510 | # push . and :: variants into checkvals if val has ,
|
---|
| 511 | my $tmp;
|
---|
| 512 | ($tmp = ${$args{val}}) =~ s/,/./;
|
---|
| 513 | push @checkvals, $tmp;
|
---|
| 514 | ($tmp = ${$args{val}}) =~ s/,/::/;
|
---|
| 515 | push @checkvals, $tmp;
|
---|
| 516 | }
|
---|
| 517 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ?");
|
---|
| 518 | foreach my $checkme (@checkvals) {
|
---|
[272] | 519 | if ($args{update}) {
|
---|
| 520 | # Record update. There should usually be an existing PTR (the record being updated)
|
---|
| 521 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 522 | " WHERE val = ?", undef, ($checkme)) };
|
---|
| 523 | return ('WARN', "PTR record for $checkme already exists; adding another will probably not do what you want")
|
---|
[273] | 524 | if @ptrs && (!grep /^$args{update}$/, @ptrs);
|
---|
[272] | 525 | } else {
|
---|
| 526 | # New record. Always warn if a PTR exists
|
---|
| 527 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 528 | " WHERE val = ?", undef, ($checkme));
|
---|
| 529 | return ('WARN', "PTR record for $checkme already exists; adding another will probably not do what you want")
|
---|
| 530 | if $ptrcount;
|
---|
| 531 | }
|
---|
[249] | 532 | }
|
---|
[272] | 533 |
|
---|
[232] | 534 | } else {
|
---|
| 535 | # Not absolutely true but only useful if you hack things up for sub-/24 v4 reverse delegations
|
---|
| 536 | # Simpler to just create the reverse zone and grant access for the customer to edit it, and create direct
|
---|
| 537 | # PTR records on export
|
---|
| 538 | return ('FAIL',"Forward zones cannot contain PTR records");
|
---|
| 539 | }
|
---|
| 540 |
|
---|
[228] | 541 | return ('OK','OK');
|
---|
| 542 | } # done PTR record
|
---|
| 543 |
|
---|
| 544 | # MX record
|
---|
| 545 | sub _validate_15 {
|
---|
[230] | 546 | my $dbh = shift;
|
---|
| 547 |
|
---|
| 548 | my %args = @_;
|
---|
| 549 |
|
---|
| 550 | # Not absolutely true but WTF use is an MX record for a reverse zone?
|
---|
| 551 | return ('FAIL', 'Reverse zones cannot contain MX records') if $args{revrec} eq 'y';
|
---|
| 552 |
|
---|
| 553 | return ('FAIL', "Distance is required for MX records") unless defined(${$args{dist}});
|
---|
| 554 | ${$args{dist}} =~ s/\s*//g;
|
---|
| 555 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
|
---|
| 556 |
|
---|
| 557 | ${$args{fields}} = "distance,";
|
---|
| 558 | push @{$args{vallist}}, ${$args{dist}};
|
---|
| 559 |
|
---|
| 560 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 561 | # or the intended parent domain for live records.
|
---|
| 562 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
|
---|
| 563 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 564 |
|
---|
[273] | 565 | # hmm.. this might work. except possibly for something pointing to "deadbeef.ca". <g>
|
---|
| 566 | # if ($type == $reverse_typemap{NS} || $type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
|
---|
| 567 | # if ($val =~ /^\s*[\da-f:.]+\s*$/) {
|
---|
| 568 | # return ('FAIL',"$val is not a valid IP address") if !$addr;
|
---|
| 569 | # }
|
---|
| 570 | # }
|
---|
| 571 |
|
---|
[228] | 572 | return ('OK','OK');
|
---|
| 573 | } # done MX record
|
---|
| 574 |
|
---|
| 575 | # TXT record
|
---|
| 576 | sub _validate_16 {
|
---|
[231] | 577 | # Could arguably put a WARN return here on very long (>512) records
|
---|
[228] | 578 | return ('OK','OK');
|
---|
| 579 | } # done TXT record
|
---|
| 580 |
|
---|
| 581 | # RP record
|
---|
| 582 | sub _validate_17 {
|
---|
[231] | 583 | # Probably have to validate these some day
|
---|
[228] | 584 | return ('OK','OK');
|
---|
| 585 | } # done RP record
|
---|
| 586 |
|
---|
| 587 | # AAAA record
|
---|
| 588 | sub _validate_28 {
|
---|
[229] | 589 | my $dbh = shift;
|
---|
| 590 |
|
---|
[230] | 591 | my %args = @_;
|
---|
[229] | 592 |
|
---|
[230] | 593 | return ('FAIL', 'Reverse zones cannot contain AAAA records') if $args{revrec} eq 'y';
|
---|
[229] | 594 |
|
---|
| 595 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 596 | # or the intended parent domain for live records.
|
---|
[230] | 597 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
|
---|
| 598 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
[229] | 599 |
|
---|
| 600 | # Check IP is well-formed, and that it's a v6 address
|
---|
[232] | 601 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
|
---|
[230] | 602 | unless $args{addr} && $args{addr}->{isv6};
|
---|
[229] | 603 | # coerce IP/value to normalized form for storage
|
---|
[230] | 604 | ${$args{val}} = $args{addr}->addr;
|
---|
[229] | 605 |
|
---|
[228] | 606 | return ('OK','OK');
|
---|
| 607 | } # done AAAA record
|
---|
| 608 |
|
---|
| 609 | # SRV record
|
---|
| 610 | sub _validate_33 {
|
---|
[231] | 611 | my $dbh = shift;
|
---|
| 612 |
|
---|
| 613 | my %args = @_;
|
---|
| 614 |
|
---|
| 615 | # Not absolutely true but WTF use is an SRV record for a reverse zone?
|
---|
| 616 | return ('FAIL', 'Reverse zones cannot contain SRV records') if $args{revrec} eq 'y';
|
---|
| 617 |
|
---|
| 618 | return ('FAIL', "Distance is required for SRV records") unless defined(${$args{dist}});
|
---|
| 619 | ${$args{dist}} =~ s/\s*//g;
|
---|
| 620 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
|
---|
| 621 |
|
---|
| 622 | return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]")
|
---|
| 623 | unless ${$args{host}} =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/;
|
---|
| 624 | return ('FAIL',"Port and weight are required for SRV records")
|
---|
| 625 | unless defined(${$args{weight}}) && defined(${$args{port}});
|
---|
| 626 | ${$args{weight}} =~ s/\s*//g;
|
---|
| 627 | ${$args{port}} =~ s/\s*//g;
|
---|
| 628 |
|
---|
| 629 | return ('FAIL',"Port and weight are required, and must be numeric")
|
---|
| 630 | unless ${$args{weight}} =~ /^\d+$/ && ${$args{port}} =~ /^\d+$/;
|
---|
| 631 |
|
---|
| 632 | ${$args{fields}} = "distance,weight,port,";
|
---|
| 633 | push @{$args{vallist}}, (${$args{dist}}, ${$args{weight}}, ${$args{port}});
|
---|
| 634 |
|
---|
| 635 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
| 636 | # or the intended parent domain for live records.
|
---|
| 637 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
|
---|
| 638 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 639 |
|
---|
[228] | 640 | return ('OK','OK');
|
---|
| 641 | } # done SRV record
|
---|
| 642 |
|
---|
| 643 | # Now the custom types
|
---|
| 644 |
|
---|
[232] | 645 | # A+PTR record. With a very little bit of magic we can also use this sub to validate AAAA+PTR. Whee!
|
---|
[228] | 646 | sub _validate_65280 {
|
---|
[232] | 647 | my $dbh = shift;
|
---|
| 648 |
|
---|
| 649 | my %args = @_;
|
---|
| 650 |
|
---|
| 651 | my $code = 'OK';
|
---|
| 652 | my $msg = 'OK';
|
---|
| 653 |
|
---|
| 654 | if ($args{defrec} eq 'n') {
|
---|
| 655 | # live record; revrec determines whether we validate the PTR or A component first.
|
---|
[233] | 656 |
|
---|
[232] | 657 | if ($args{revrec} eq 'y') {
|
---|
| 658 | ($code,$msg) = _validate_12($dbh, %args);
|
---|
| 659 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 660 |
|
---|
| 661 | # Check if the reqested domain exists. If not, coerce the type down to PTR and warn.
|
---|
| 662 | if (!(${$args{domid}} = _hostparent($dbh, ${$args{host}}))) {
|
---|
[272] | 663 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
| 664 | " as PTR instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
[232] | 665 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
| 666 | $msg = $addmsg if $code eq 'OK';
|
---|
| 667 | ${$args{rectype}} = $reverse_typemap{PTR};
|
---|
| 668 | return ('WARN', $msg);
|
---|
| 669 | }
|
---|
| 670 |
|
---|
[242] | 671 | # Add domain ID to field list and values
|
---|
| 672 | ${$args{fields}} .= "domain_id,";
|
---|
| 673 | push @{$args{vallist}}, ${$args{domid}};
|
---|
| 674 |
|
---|
[232] | 675 | } else {
|
---|
| 676 | ($code,$msg) = _validate_1($dbh, %args) if ${$args{rectype}} == 65280;
|
---|
| 677 | ($code,$msg) = _validate_28($dbh, %args) if ${$args{rectype}} == 65281;
|
---|
| 678 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 679 |
|
---|
| 680 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
| 681 | # work here since we don't *know* which parent to put it in.
|
---|
[233] | 682 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
[232] | 683 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
| 684 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
| 685 | if (!$revid) {
|
---|
[272] | 686 | $msg = "Record ".($args{update} ? 'updated' : 'added')." as ".(${$args{rectype}} == 65280 ? 'A' : 'AAAA').
|
---|
[232] | 687 | " instead of $typemap{${$args{rectype}}}; reverse zone not found for ${$args{val}}";
|
---|
| 688 | ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
| 689 | return ('WARN', $msg);
|
---|
| 690 | }
|
---|
| 691 |
|
---|
| 692 | # Check for duplicate PTRs. Note we don't have to play games with $code and $msg, because
|
---|
| 693 | # by definition there can't be duplicate PTRs if the reverse zone isn't managed here.
|
---|
[272] | 694 | if ($args{update}) {
|
---|
| 695 | # Record update. There should usually be an existing PTR (the record being updated)
|
---|
| 696 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 697 | " WHERE val = ?", undef, (${$args{val}})) };
|
---|
[273] | 698 | if (@ptrs && (!grep /^$args{update}$/, @ptrs)) {
|
---|
[272] | 699 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
|
---|
| 700 | $code = 'WARN';
|
---|
| 701 | }
|
---|
| 702 | } else {
|
---|
| 703 | # New record. Always warn if a PTR exists
|
---|
| 704 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 705 | " WHERE val = ?", undef, (${$args{val}}));
|
---|
| 706 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want"
|
---|
| 707 | if $ptrcount;
|
---|
| 708 | $code = 'WARN' if $ptrcount;
|
---|
[232] | 709 | }
|
---|
| 710 |
|
---|
[272] | 711 | # my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 712 | # " WHERE val = ?", undef, ${$args{val}});
|
---|
| 713 | # if ($ptrcount) {
|
---|
| 714 | # my $curid = $dbh->selectrow_array("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
| 715 | # " WHERE val = ?
|
---|
| 716 | # $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
|
---|
| 717 | # $code = 'WARN';
|
---|
| 718 | # }
|
---|
| 719 |
|
---|
[232] | 720 | ${$args{fields}} .= "rdns_id,";
|
---|
| 721 | push @{$args{vallist}}, $revid;
|
---|
| 722 | }
|
---|
| 723 |
|
---|
[233] | 724 | } else { # defrec eq 'y'
|
---|
| 725 | if ($args{revrec} eq 'y') {
|
---|
| 726 | ($code,$msg) = _validate_12($dbh, %args);
|
---|
| 727 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 728 | if (${$args{rectype}} == 65280) {
|
---|
| 729 | return ('FAIL',"A+PTR record must be a valid IPv4 address or fragment")
|
---|
| 730 | if ${$args{val}} =~ /:/;
|
---|
[234] | 731 | ${$args{val}} =~ s/^ZONE,/ZONE./; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
[233] | 732 | } elsif (${$args{rectype}} == 65281) {
|
---|
| 733 | return ('FAIL',"AAAA+PTR record must be a valid IPv6 address or fragment")
|
---|
| 734 | if ${$args{val}} =~ /\./;
|
---|
[234] | 735 | ${$args{val}} =~ s/^ZONE,/ZONE::/; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
[233] | 736 | }
|
---|
| 737 | } else {
|
---|
| 738 | # This is easy. I also can't see a real use-case for A/AAAA+PTR in *all* forward
|
---|
| 739 | # domains, since you wouldn't be able to substitute both domain and reverse zone
|
---|
| 740 | # sanely, and you'd end up with guaranteed over-replicated PTR records that would
|
---|
| 741 | # confuse the hell out of pretty much anything that uses them.
|
---|
[234] | 742 | ##fixme: make this a config flag?
|
---|
[233] | 743 | return ('FAIL', "$typemap{${$args{rectype}}} records not allowed in default domains");
|
---|
| 744 | }
|
---|
[232] | 745 | }
|
---|
| 746 |
|
---|
| 747 | return ($code, $msg);
|
---|
[228] | 748 | } # done A+PTR record
|
---|
| 749 |
|
---|
| 750 | # AAAA+PTR record
|
---|
[232] | 751 | # A+PTR above has been magicked to handle AAAA+PTR as well.
|
---|
[228] | 752 | sub _validate_65281 {
|
---|
[232] | 753 | return _validate_65280(@_);
|
---|
[228] | 754 | } # done AAAA+PTR record
|
---|
| 755 |
|
---|
| 756 | # PTR template record
|
---|
| 757 | sub _validate_65282 {
|
---|
[340] | 758 | my $dbh = shift;
|
---|
| 759 |
|
---|
| 760 | my %args = @_;
|
---|
| 761 |
|
---|
| 762 | # we're *this* >.< close to being able to just call _validate_12... unfortunately we can't, quite.
|
---|
| 763 | if ($args{revrec} eq 'y') {
|
---|
| 764 | if ($args{defrec} eq 'n') {
|
---|
| 765 | return ('FAIL', "Template block ${$args{val}} is not within ".revName($dbh, $args{id}))
|
---|
| 766 | unless _ipparent($dbh, $args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
| 767 | ##fixme: warn if $args{val} is not /31 or larger block?
|
---|
| 768 | ${$args{val}} = "$args{addr}";
|
---|
| 769 | } else {
|
---|
| 770 | if (${$args{val}} =~ /\./) {
|
---|
| 771 | # looks like a v4 or fragment
|
---|
| 772 | if (${$args{val}} =~ m|^\d+\.\d+\.\d+\.\d+(?:/\d+)?$|) {
|
---|
| 773 | # woo! a complete IP! validate it and normalize, or fail.
|
---|
| 774 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
| 775 | or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
|
---|
| 776 | ${$args{val}} = "$args{addr}";
|
---|
| 777 | } else {
|
---|
| 778 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
| 779 | }
|
---|
| 780 | } elsif (${$args{val}} =~ /[a-f:]/) {
|
---|
| 781 | # looks like a v6 or fragment
|
---|
| 782 | ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
|
---|
| 783 | if ($args{addr}) {
|
---|
| 784 | if ($args{addr}->addr =~ /^0/) {
|
---|
| 785 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
| 786 | } else {
|
---|
| 787 | ${$args{val}} = "$args{addr}";
|
---|
| 788 | }
|
---|
| 789 | }
|
---|
| 790 | } else {
|
---|
| 791 | # bare number (probably). These could be v4 or v6, so we'll
|
---|
| 792 | # expand on these on creation of a reverse zone.
|
---|
| 793 | ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
|
---|
| 794 | }
|
---|
| 795 | }
|
---|
| 796 | ##fixme: validate %-patterns?
|
---|
| 797 |
|
---|
| 798 | # Unlike single PTR records, there is absolutely no way to sanely support multiple
|
---|
| 799 | # PTR templates for the same block, since they expect to expand to all the individual
|
---|
| 800 | # IPs on export. Nested templates should be supported though.
|
---|
| 801 |
|
---|
| 802 | my @checkvals = (${$args{val}});
|
---|
| 803 | if (${$args{val}} =~ /,/) {
|
---|
| 804 | # push . and :: variants into checkvals if val has ,
|
---|
| 805 | my $tmp;
|
---|
| 806 | ($tmp = ${$args{val}}) =~ s/,/./;
|
---|
| 807 | push @checkvals, $tmp;
|
---|
| 808 | ($tmp = ${$args{val}}) =~ s/,/::/;
|
---|
| 809 | push @checkvals, $tmp;
|
---|
| 810 | }
|
---|
| 811 | ##fixme: this feels wrong still - need to restrict template pseudorecords to One Of Each
|
---|
| 812 | # Per Netblock such that they don't conflict on export
|
---|
| 813 | my $typeck;
|
---|
| 814 | # type 65282 -> ptr template -> look for any of 65282, 65283, 65284
|
---|
| 815 | $typeck = 'type=65283 OR type=65284' if ${$args{rectype}} == 65282;
|
---|
| 816 | # type 65283 -> a+ptr template -> v4 -> look for 65282 or 65283
|
---|
| 817 | $typeck = 'type=65283' if ${$args{rectype}} == 65282;
|
---|
| 818 | # type 65284 -> aaaa+ptr template -> v6 -> look for 65282 or 65284
|
---|
| 819 | $typeck = 'type=65284' if ${$args{rectype}} == 65282;
|
---|
| 820 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ? ".
|
---|
| 821 | "AND (type=65282 OR $typeck)");
|
---|
| 822 | foreach my $checkme (@checkvals) {
|
---|
| 823 | $pcsth->execute($checkme);
|
---|
| 824 | my ($rc) = $pcsth->fetchrow_array;
|
---|
[442] | 825 | return ('FAIL', "Only one template pseudorecord may exist for a given IP block") if $rc > 1;
|
---|
[340] | 826 | }
|
---|
| 827 |
|
---|
| 828 | } else {
|
---|
| 829 | return ('FAIL', "Forward zones cannot contain PTR records");
|
---|
| 830 | }
|
---|
| 831 |
|
---|
[228] | 832 | return ('OK','OK');
|
---|
| 833 | } # done PTR template record
|
---|
| 834 |
|
---|
| 835 | # A+PTR template record
|
---|
| 836 | sub _validate_65283 {
|
---|
[340] | 837 | my $dbh = shift;
|
---|
| 838 |
|
---|
| 839 | my %args = @_;
|
---|
| 840 |
|
---|
| 841 | my ($code,$msg) = ('OK','OK');
|
---|
| 842 |
|
---|
| 843 | ##fixme: need to fiddle things since A+PTR templates are acceptable in live
|
---|
| 844 | # forward zones but not default records
|
---|
| 845 | if ($args{defrec} eq 'n') {
|
---|
| 846 | if ($args{revrec} eq 'n') {
|
---|
| 847 | ($code,$msg) = _validate_1($dbh, %args) if ${$args{rectype}} == 65280;
|
---|
| 848 | ($code,$msg) = _validate_28($dbh, %args) if ${$args{rectype}} == 65281;
|
---|
| 849 | return ($code,$msg) if $code eq 'FAIL';
|
---|
| 850 |
|
---|
| 851 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
| 852 | # work here since we don't *know* which parent to put it in.
|
---|
| 853 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
| 854 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
| 855 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
| 856 | # Fail if no match; we can't coerce a PTR-template type down to not include the PTR bit currently.
|
---|
| 857 | if (!$revid) {
|
---|
| 858 | $msg = "Can't ".($args{update} ? 'update' : 'add')." ${$args{host}}/${$args{val}} as ".
|
---|
| 859 | "$typemap{${$args{rectype}}}: reverse zone not found for ${$args{val}}";
|
---|
| 860 | ##fixme: add A template, AAAA template types?
|
---|
| 861 | # ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
| 862 | return ('FAIL', $msg);
|
---|
| 863 | }
|
---|
| 864 |
|
---|
| 865 | # Add reverse zone ID to field list and values
|
---|
| 866 | ${$args{fields}} .= "rdns_id,";
|
---|
| 867 | push @{$args{vallist}}, $revid;
|
---|
| 868 |
|
---|
| 869 | } else {
|
---|
| 870 | return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".revName($dbh, $args{id}))
|
---|
| 871 | unless _ipparent($dbh, $args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
| 872 | ${$args{val}} = "$args{addr}";
|
---|
| 873 |
|
---|
| 874 | if (!(${$args{domid}} = _hostparent($dbh, ${$args{host}}))) {
|
---|
| 875 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
| 876 | " as PTR template instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
| 877 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
| 878 | $msg = $addmsg if $code eq 'OK';
|
---|
| 879 | ${$args{rectype}} = 65282;
|
---|
| 880 | return ('WARN', $msg);
|
---|
| 881 | }
|
---|
| 882 |
|
---|
| 883 | # Add domain ID to field list and values
|
---|
| 884 | ${$args{fields}} .= "domain_id,";
|
---|
| 885 | push @{$args{vallist}}, ${$args{domid}};
|
---|
| 886 | }
|
---|
| 887 |
|
---|
| 888 | } else {
|
---|
| 889 | my ($code,$msg) = _validate_65282($dbh, %args);
|
---|
| 890 | return ($code, $msg) if $code eq 'FAIL';
|
---|
| 891 | # get domain, check against ${$args{name}}
|
---|
| 892 | }
|
---|
| 893 |
|
---|
[228] | 894 | return ('OK','OK');
|
---|
| 895 | } # done AAAA+PTR template record
|
---|
| 896 |
|
---|
| 897 | # AAAA+PTR template record
|
---|
| 898 | sub _validate_65284 {
|
---|
| 899 | return ('OK','OK');
|
---|
| 900 | } # done AAAA+PTR template record
|
---|
| 901 |
|
---|
[342] | 902 | # Delegation record
|
---|
[345] | 903 | # This is essentially a specialized clone of the NS record, primarily useful
|
---|
| 904 | # for delegating IPv4 sub-/24 reverse blocks
|
---|
[342] | 905 | sub _validate_65285 {
|
---|
[345] | 906 | my $dbh = shift;
|
---|
| 907 |
|
---|
| 908 | my %args = @_;
|
---|
| 909 |
|
---|
| 910 | # Almost, but not quite, identical to NS record validation.
|
---|
| 911 |
|
---|
| 912 | # Check that the target of the record is within the parent.
|
---|
| 913 | # Yes, host<->val are mixed up here; can't see a way to avoid it. :(
|
---|
| 914 | if ($args{defrec} eq 'n') {
|
---|
| 915 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
| 916 | if ($args{revrec} eq 'y') {
|
---|
| 917 | my $tmpip = NetAddr::IP->new(${$args{val}});
|
---|
| 918 | my $pname = revName($dbh,$args{id});
|
---|
| 919 | return ('FAIL',"${$args{val}} not within $pname")
|
---|
| 920 | unless _ipparent($dbh, $args{defrec}, $args{revrec}, $args{val}, $args{id}, \$tmpip);
|
---|
| 921 | # Normalize
|
---|
| 922 | ${$args{val}} = "$tmpip";
|
---|
| 923 | } else {
|
---|
| 924 | my $pname = domainName($dbh,$args{id});
|
---|
| 925 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
| 926 | }
|
---|
| 927 | } else {
|
---|
| 928 | return ('FAIL',"Delegation records are not permitted in default record sets");
|
---|
| 929 | }
|
---|
[342] | 930 | return ('OK','OK');
|
---|
| 931 | }
|
---|
[228] | 932 |
|
---|
[342] | 933 |
|
---|
[265] | 934 | ##
|
---|
| 935 | ## Record data substitution subs
|
---|
| 936 | ##
|
---|
[228] | 937 |
|
---|
[298] | 938 | # Replace ZONE in hostname, or create (most of) the actual proper zone name
|
---|
[265] | 939 | sub _ZONE {
|
---|
| 940 | my $zone = shift;
|
---|
| 941 | my $string = shift;
|
---|
| 942 | my $fr = shift || 'f'; # flag for forward/reverse order? nb: ignored for IP
|
---|
[298] | 943 | my $sep = shift || '-'; # Separator character - unlikely we'll ever need more than . or -
|
---|
[265] | 944 |
|
---|
[298] | 945 | my $prefix;
|
---|
[265] | 946 |
|
---|
| 947 | $string =~ s/,/./ if !$zone->{isv6};
|
---|
| 948 | $string =~ s/,/::/ if $zone->{isv6};
|
---|
| 949 |
|
---|
[298] | 950 | # Subbing ZONE in the host. We need to properly ID the netblock range
|
---|
| 951 | # The subbed text should have "network IP with trailing zeros stripped" for
|
---|
| 952 | # blocks lined up on octet (for v4) or hex-quad (for v6) boundaries
|
---|
| 953 | # For blocks that do NOT line up on these boundaries, we take the most
|
---|
| 954 | # significant octet or 16-bit chunk of the "broadcast" IP and append it
|
---|
| 955 | # after a double-dash
|
---|
| 956 | # ie:
|
---|
| 957 | # 8.0.0.0/6 -> 8.0.0.0 -> 11.255.255.255; sub should be 8--11
|
---|
| 958 | # 10.0.0.0/12 -> 10.0.0.0 -> 10.0.0.0 -> 10.15.255.255; sub should be 10-0--15
|
---|
| 959 | # 192.168.4.0/22 -> 192.168.4.0 -> 192.168.7.255; sub should be 192-168-4--7
|
---|
| 960 | # 192.168.0.8/29 -> 192.168.0.8 -> 192.168.0.15; sub should be 192-168-0-8--15
|
---|
| 961 | # Similar for v6
|
---|
[265] | 962 |
|
---|
[298] | 963 | if (!$zone->{isv6}) { # IPv4
|
---|
| 964 |
|
---|
| 965 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
| 966 | # a funky subnet that had host bits set.
|
---|
| 967 | my $bc = $zone->broadcast->addr;
|
---|
| 968 |
|
---|
| 969 | if ($zone->masklen > 24) {
|
---|
| 970 | $bc =~ s/^\d+\.\d+\.\d+\.//;
|
---|
| 971 | } elsif ($zone->masklen > 16) {
|
---|
| 972 | $prefix =~ s/\.0$//;
|
---|
| 973 | $bc =~ s/^\d+\.\d+\.//;
|
---|
| 974 | } elsif ($zone->masklen > 8) {
|
---|
| 975 | $bc =~ s/^\d+\.//;
|
---|
| 976 | $prefix =~ s/\.0\.0$//;
|
---|
| 977 | } else {
|
---|
| 978 | $prefix =~ s/\.0\.0\.0$//;
|
---|
| 979 | }
|
---|
| 980 | if ($zone->masklen % 8) {
|
---|
| 981 | $bc =~ s/(\.255)+$//;
|
---|
| 982 | $prefix .= "--$bc"; #"--".zone->masklen; # use range or mask length?
|
---|
| 983 | }
|
---|
| 984 | if ($fr eq 'f') {
|
---|
| 985 | $prefix =~ s/\.+/$sep/g;
|
---|
| 986 | } else {
|
---|
| 987 | $prefix = join($sep, reverse(split(/\./, $prefix)));
|
---|
| 988 | }
|
---|
| 989 |
|
---|
| 990 | } else { # IPv6
|
---|
| 991 |
|
---|
| 992 | if ($fr eq 'f') {
|
---|
| 993 |
|
---|
| 994 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
| 995 | # a funky subnet that had host bits set.
|
---|
[265] | 996 | my $bc = $zone->broadcast->addr;
|
---|
| 997 | if (($zone->masklen % 16) != 0) {
|
---|
[298] | 998 | # Strip trailing :0 off $prefix, and :ffff off the broadcast IP
|
---|
| 999 | for (my $i=0; $i<(7-int($zone->masklen / 16)); $i++) {
|
---|
| 1000 | $prefix =~ s/:0$//;
|
---|
| 1001 | $bc =~ s/:ffff$//;
|
---|
| 1002 | }
|
---|
| 1003 | # Strip the leading 16-bit chunks off the front of the broadcast IP
|
---|
| 1004 | $bc =~ s/^([a-f0-9]+:)+//;
|
---|
| 1005 | # Append the remaining 16-bit chunk to the prefix after "--"
|
---|
| 1006 | $prefix .= "--$bc";
|
---|
[265] | 1007 | } else {
|
---|
[298] | 1008 | # Strip off :0 from the end until we reach the netblock length.
|
---|
| 1009 | for (my $i=0; $i<(8-$zone->masklen / 16); $i++) {
|
---|
[265] | 1010 | $prefix =~ s/:0$//;
|
---|
[298] | 1011 | }
|
---|
[265] | 1012 | }
|
---|
[298] | 1013 | # Actually deal with the separator
|
---|
| 1014 | $prefix =~ s/:/$sep/g;
|
---|
| 1015 |
|
---|
| 1016 | } else { # $fr eq 'f'
|
---|
| 1017 |
|
---|
| 1018 | $prefix = $zone->network->full; # Just In Case someone managed to slip in
|
---|
| 1019 | # a funky subnet that had host bits set.
|
---|
| 1020 | my $bc = $zone->broadcast->full;
|
---|
| 1021 | $prefix =~ s/://g; # clean these out since they're not spaced right for this case
|
---|
| 1022 | $bc =~ s/://g;
|
---|
| 1023 | # Strip trailing 0 off $prefix, and f off the broadcast IP, to match the mask length
|
---|
| 1024 | for (my $i=0; $i<(31-int($zone->masklen / 4)); $i++) {
|
---|
| 1025 | $prefix =~ s/0$//;
|
---|
| 1026 | $bc =~ s/f$//;
|
---|
| 1027 | }
|
---|
| 1028 | # Split and reverse the order of the nibbles in the network/broadcast IPs
|
---|
[332] | 1029 | # trim another 0 for nibble-aligned blocks first, but only if we really have a block, not an IP
|
---|
| 1030 | $prefix =~ s/0$// if $zone->masklen % 4 == 0 && $zone->masklen != 128;
|
---|
[298] | 1031 | my @nbits = reverse split //, $prefix;
|
---|
| 1032 | my @bbits = reverse split //, $bc;
|
---|
| 1033 | # Handle the sub-nibble case. Eww. I feel dirty supporting this...
|
---|
| 1034 | $nbits[0] = "$nbits[0]-$bbits[0]" if ($zone->masklen % 4) != 0;
|
---|
| 1035 | # Glue it back together
|
---|
| 1036 | $prefix = join($sep, @nbits);
|
---|
| 1037 |
|
---|
| 1038 | } # $fr ne 'f'
|
---|
| 1039 |
|
---|
| 1040 | } # $zone->{isv6}
|
---|
| 1041 |
|
---|
| 1042 | # Do the substitution, finally
|
---|
| 1043 | $string =~ s/ZONE/$prefix/;
|
---|
| 1044 | $string =~ s/--/-/ if $sep ne '-'; # - as separator needs extra help for sub-octet v4 netblocks
|
---|
| 1045 | return $string;
|
---|
| 1046 | } # done _ZONE()
|
---|
| 1047 |
|
---|
| 1048 | # Not quite a substitution sub, but placed here as it's basically the inverse of above;
|
---|
| 1049 | # given the .arpa zone name, return the CIDR netblock the zone is for.
|
---|
[304] | 1050 | # Supports v4 non-octet/non-classful netblocks as per the method outlined in the Grasshopper Book (2nd Ed p217-218)
|
---|
[298] | 1051 | # Does NOT support non-quad v6 netblocks via the same scheme; it shouldn't ever be necessary.
|
---|
| 1052 | # Takes a nominal .arpa zone name, returns a success code and NetAddr::IP, or a fail code and message
|
---|
| 1053 | sub _zone2cidr {
|
---|
| 1054 | my $zone = shift;
|
---|
| 1055 |
|
---|
| 1056 | my $cidr;
|
---|
[301] | 1057 | my $tmpcidr;
|
---|
| 1058 | my $warnmsg = '';
|
---|
[298] | 1059 |
|
---|
| 1060 | if ($zone =~ /\.in-addr\.arpa\.?$/) {
|
---|
| 1061 | # v4 revzone, formal zone name type
|
---|
| 1062 | my $tmpzone = $zone;
|
---|
| 1063 | $tmpzone =~ s/\.in-addr\.arpa\.?//;
|
---|
[301] | 1064 | return ('FAIL', "Non-numerics in apparent IPv4 reverse zone name") if $tmpzone !~ /^(?:\d+-)?[\d\.]+$/;
|
---|
[298] | 1065 |
|
---|
| 1066 | # Snag the octet pieces
|
---|
| 1067 | my @octs = split /\./, $tmpzone;
|
---|
| 1068 |
|
---|
| 1069 | # Map result of a range manipulation to a mask length change. Cheaper than finding the 2-root of $octets[0]+1.
|
---|
[304] | 1070 | # Note we will not support /31 blocks, mostly due to issues telling "24-31" -> .24/29 apart from
|
---|
| 1071 | # "24-31" -> .24/31", with a litte bit of "/31 is icky".
|
---|
| 1072 | my %maskmap = ( 3 => 2, 7 => 3, 15 => 4, 31 => 5, 63 => 6, 127 => 7,
|
---|
| 1073 | 30 => 2, 29 => 3, 28 => 4, 27 => 5, 26 => 6, 25 => 7
|
---|
| 1074 | );
|
---|
[298] | 1075 |
|
---|
| 1076 | # Handle "range" blocks, eg, 80-83.168.192.in-addr.arpa (192.168.80.0/22)
|
---|
| 1077 | # Need to take the size of the range to offset the basic octet-based mask length,
|
---|
| 1078 | # and make sure the first number in the range gets used as the network address for the block
|
---|
[304] | 1079 | # Alternate form: The second number is actually the real netmask, not the end of the range.
|
---|
[298] | 1080 | my $masklen = 0;
|
---|
[307] | 1081 | if ($octs[0] =~ /^((\d+)-(\d+))$/) { # take the range...
|
---|
| 1082 | if (24 < $3 && $3 < 31) {
|
---|
[304] | 1083 | # we have a real netmask
|
---|
[307] | 1084 | $masklen = -$maskmap{$3};
|
---|
[304] | 1085 | } else {
|
---|
| 1086 | # we have a range. NB: only real CIDR ranges are supported
|
---|
[307] | 1087 | $masklen -= $maskmap{-(eval $1)}; # find the mask base...
|
---|
[304] | 1088 | }
|
---|
[307] | 1089 | $octs[0] = $2; # set the base octet of the range...
|
---|
[265] | 1090 | }
|
---|
[298] | 1091 | @octs = reverse @octs; # We can reverse the octet pieces now that we've extracted and munged any ranges
|
---|
[265] | 1092 |
|
---|
[304] | 1093 | # arguably we should only allow sub-octet range/mask in-addr.arpa
|
---|
| 1094 | # specifications in the least significant octet, but the code is
|
---|
| 1095 | # simpler if we deal with sub-octet delegations at any level.
|
---|
| 1096 |
|
---|
[298] | 1097 | # Now we find the "true" mask with the aid of the "base" calculated above
|
---|
| 1098 | if ($#octs == 0) {
|
---|
| 1099 | $masklen += 8;
|
---|
| 1100 | $tmpcidr = "$octs[0].0.0.0/$masklen"; # really hope we don't see one of these very often.
|
---|
| 1101 | } elsif ($#octs == 1) {
|
---|
| 1102 | $masklen += 16;
|
---|
| 1103 | $tmpcidr = "$octs[0].$octs[1].0.0/$masklen";
|
---|
| 1104 | } elsif ($#octs == 2) {
|
---|
| 1105 | $masklen += 24;
|
---|
| 1106 | $tmpcidr = "$octs[0].$octs[1].$octs[2].0/$masklen";
|
---|
[265] | 1107 | } else {
|
---|
[298] | 1108 | $masklen += 32;
|
---|
| 1109 | $tmpcidr = "$octs[0].$octs[1].$octs[2].$octs[3]/$masklen";
|
---|
[265] | 1110 | }
|
---|
| 1111 |
|
---|
[298] | 1112 | } elsif ($zone =~ /\.ip6\.arpa$/) {
|
---|
| 1113 | # v6 revzone, formal zone name type
|
---|
| 1114 | my $tmpzone = $zone;
|
---|
| 1115 | $tmpzone =~ s/\.ip6\.arpa\.?//;
|
---|
[301] | 1116 | ##fixme: if-n-when we decide we can support sub-nibble v6 zone names, we'll need to change this segment
|
---|
| 1117 | return ('FAIL', "Non-hexadecimals in apparent IPv6 reverse zone name") if $tmpzone !~ /^[a-fA-F\d\.]+$/;
|
---|
[298] | 1118 | my @quads = reverse(split(/\./, $tmpzone));
|
---|
| 1119 | $warnmsg .= "Apparent sub-/64 IPv6 reverse zone\n" if $#quads > 15;
|
---|
| 1120 | my $nc;
|
---|
| 1121 | foreach (@quads) {
|
---|
[301] | 1122 | $tmpcidr .= $_;
|
---|
| 1123 | $tmpcidr .= ":" if ++$nc % 4 == 0;
|
---|
[298] | 1124 | }
|
---|
| 1125 | my $nq = 1 if $nc % 4 != 0;
|
---|
| 1126 | my $mask = $nc * 4; # need to do this here because we probably increment it below
|
---|
| 1127 | while ($nc++ % 4 != 0) {
|
---|
[301] | 1128 | $tmpcidr .= "0";
|
---|
[298] | 1129 | }
|
---|
[301] | 1130 | $tmpcidr .= ($nq ? '::' : ':')."/$mask";
|
---|
[298] | 1131 | }
|
---|
[301] | 1132 |
|
---|
| 1133 | # Just to be sure, use NetAddr::IP to validate. Saves a lot of nasty regex watching for valid octet values.
|
---|
| 1134 | return ('FAIL', "Invalid zone $zone (apparent netblock $tmpcidr)")
|
---|
| 1135 | unless $cidr = NetAddr::IP->new($tmpcidr);
|
---|
| 1136 |
|
---|
| 1137 | if ($warnmsg) {
|
---|
| 1138 | $errstr = $warnmsg;
|
---|
| 1139 | return ('WARN', $cidr);
|
---|
| 1140 | }
|
---|
| 1141 | return ('OK', $cidr);
|
---|
[298] | 1142 | } # done _zone2cidr()
|
---|
[265] | 1143 |
|
---|
[337] | 1144 | # Record template %-parameter expansion, IPv4. Note that IPv6 doesn't
|
---|
| 1145 | # really have a sane way to handle this type of expansion at the moment
|
---|
| 1146 | # due to the size of the address space.
|
---|
| 1147 | # Takes a reference to a template string to be expanded, and an IP to use in the replacement.
|
---|
| 1148 | sub _template4_expand {
|
---|
| 1149 | my $tmpl = shift;
|
---|
| 1150 | my $ip = shift;
|
---|
[298] | 1151 |
|
---|
[337] | 1152 | my @ipparts = split /\./, $ip;
|
---|
| 1153 | my @iphex;
|
---|
| 1154 | my @ippad;
|
---|
| 1155 | for (@ipparts) {
|
---|
| 1156 | push @iphex, sprintf("%x", $_);
|
---|
[443] | 1157 | push @ippad, sprintf("%0.3u", $_);
|
---|
[337] | 1158 | }
|
---|
| 1159 |
|
---|
| 1160 | # IP substitutions in template records:
|
---|
| 1161 | #major patterns:
|
---|
| 1162 | #dashed IP, forward and reverse
|
---|
| 1163 | #dotted IP, forward and reverse (even if forward is... dumb)
|
---|
| 1164 | # -> %r for reverse, %i for forward, leading - or . to indicate separator, defaults to -
|
---|
| 1165 | # %r or %-r => %4d-%3d-%2d-%1d
|
---|
| 1166 | # %.r => %4d.%3d.%2d.%1d
|
---|
| 1167 | # %i or %-i => %1d-%2d-%3d-%4d
|
---|
| 1168 | # %.i => %1d.%2d.%3d.%4d
|
---|
| 1169 | $$tmpl =~ s/\%r/\%4d-\%3d-\%2d-\%1d/g;
|
---|
| 1170 | $$tmpl =~ s/\%([-.])r/\%4d$1\%3d$1\%2d$1\%1d/g;
|
---|
| 1171 | $$tmpl =~ s/\%i/\%1d-\%2d-\%3d-\%4d/g;
|
---|
| 1172 | $$tmpl =~ s/\%([-.])i/\%1d$1\%2d$1\%3d$1\%4d/g;
|
---|
| 1173 |
|
---|
| 1174 | #hex-coded IP
|
---|
| 1175 | # %h
|
---|
| 1176 | $$tmpl =~ s/\%h/$iphex[0]$iphex[1]$iphex[2]$iphex[3]/g;
|
---|
| 1177 |
|
---|
| 1178 | #IP as decimal-coded 32-bit value
|
---|
| 1179 | # %d
|
---|
| 1180 | my $iptmp = $ipparts[0]*256*256*256 + $ipparts[1]*256*256 + $ipparts[2]*256 + $ipparts[3];
|
---|
| 1181 | $$tmpl =~ s/\%d/$iptmp/g;
|
---|
| 1182 |
|
---|
| 1183 | #minor patterns (per-octet)
|
---|
| 1184 | # %[1234][dh0]
|
---|
| 1185 | #octet
|
---|
| 1186 | #hex-coded octet
|
---|
| 1187 | #0-padded octet
|
---|
| 1188 | $$tmpl =~ s/\%([1234])d/$ipparts[$1-1]/g;
|
---|
| 1189 | $$tmpl =~ s/\%([1234])h/$iphex[$1-1]/g;
|
---|
[443] | 1190 | $$tmpl =~ s/\%([1234])0/$ippad[$1-1]/g;
|
---|
[337] | 1191 | } # _template4_expand()
|
---|
| 1192 |
|
---|
| 1193 |
|
---|
[228] | 1194 | ##
|
---|
[2] | 1195 | ## Initialization and cleanup subs
|
---|
| 1196 | ##
|
---|
| 1197 |
|
---|
[55] | 1198 |
|
---|
[128] | 1199 | ## DNSDB::loadConfig()
|
---|
| 1200 | # Load the minimum required initial state (DB connect info) from a config file
|
---|
| 1201 | # Load misc other bits while we're at it.
|
---|
[400] | 1202 | # Takes an optional hash that may contain:
|
---|
| 1203 | # - basename and config path to look for
|
---|
| 1204 | # - RPC flag (saves parsing the more complex RPC bits if not needed)
|
---|
[128] | 1205 | # Populates the %config and %def hashes
|
---|
| 1206 | sub loadConfig {
|
---|
[400] | 1207 | my %args = @_;
|
---|
| 1208 | $args{basename} = '' if !$args{basename};
|
---|
| 1209 | $args{rpcflag} = '' if !$args{rpcflag};
|
---|
| 1210 | ##fixme $args{basename} isn't doing what I think I thought I was trying to do.
|
---|
[128] | 1211 |
|
---|
| 1212 | my $deferr = ''; # place to put error from default config file in case we can't find either one
|
---|
| 1213 |
|
---|
[219] | 1214 | my $configroot = "/etc/dnsdb"; ##CFG_LEAF##
|
---|
[400] | 1215 | $configroot = '' if $args{basename} =~ m|^/|;
|
---|
| 1216 | $args{basename} .= ".conf" if $args{basename} !~ /\.conf$/;
|
---|
[128] | 1217 | my $defconfig = "$configroot/dnsdb.conf";
|
---|
[400] | 1218 | my $siteconfig = "$configroot/$args{basename}";
|
---|
[128] | 1219 |
|
---|
| 1220 | # System defaults
|
---|
[400] | 1221 | __cfgload("$defconfig", $args{rpcflag}) or $deferr = $errstr;
|
---|
[128] | 1222 |
|
---|
[131] | 1223 | # Per-site-ish settings.
|
---|
[400] | 1224 | if ($args{basename} ne '.conf') {
|
---|
| 1225 | unless (__cfgload("$siteconfig"), $args{rpcflag}) {
|
---|
[131] | 1226 | $errstr = ($deferr ? "Error opening default config file $defconfig: $deferr\n" : '').
|
---|
[128] | 1227 | "Error opening site config file $siteconfig";
|
---|
[131] | 1228 | return;
|
---|
| 1229 | }
|
---|
[128] | 1230 | }
|
---|
| 1231 |
|
---|
[195] | 1232 | # Munge log_failures.
|
---|
| 1233 | if ($config{log_failures} ne '1' && $config{log_failures} ne '0') {
|
---|
| 1234 | # true/false, on/off, yes/no all valid.
|
---|
| 1235 | if ($config{log_failures} =~ /^(?:true|false|on|off|yes|no)$/) {
|
---|
| 1236 | if ($config{log_failures} =~ /(?:true|on|yes)/) {
|
---|
| 1237 | $config{log_failures} = 1;
|
---|
| 1238 | } else {
|
---|
| 1239 | $config{log_failures} = 0;
|
---|
| 1240 | }
|
---|
| 1241 | } else {
|
---|
| 1242 | $errstr = "Bad log_failures setting $config{log_failures}";
|
---|
| 1243 | $config{log_failures} = 1;
|
---|
| 1244 | # Bad setting shouldn't be fatal.
|
---|
| 1245 | # return 2;
|
---|
| 1246 | }
|
---|
| 1247 | }
|
---|
| 1248 |
|
---|
[128] | 1249 | # All good, clear the error and go home.
|
---|
| 1250 | $errstr = '';
|
---|
| 1251 | return 1;
|
---|
| 1252 | } # end loadConfig()
|
---|
| 1253 |
|
---|
| 1254 |
|
---|
| 1255 | ## DNSDB::__cfgload()
|
---|
| 1256 | # Private sub to parse a config file and load it into %config
|
---|
| 1257 | # Takes a file handle on an open config file
|
---|
| 1258 | sub __cfgload {
|
---|
| 1259 | $errstr = '';
|
---|
| 1260 | my $cfgfile = shift;
|
---|
[400] | 1261 | my $rpcflag = shift;
|
---|
[131] | 1262 |
|
---|
[128] | 1263 | if (open CFG, "<$cfgfile") {
|
---|
| 1264 | while (<CFG>) {
|
---|
| 1265 | chomp;
|
---|
| 1266 | s/^\s*//;
|
---|
| 1267 | next if /^#/;
|
---|
| 1268 | next if /^$/;
|
---|
| 1269 | # hmm. more complex bits in this file might require [heading] headers, maybe?
|
---|
| 1270 | # $mode = $1 if /^\[(a-z)+]/;
|
---|
| 1271 | # DB connect info
|
---|
| 1272 | $config{dbname} = $1 if /^dbname\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1273 | $config{dbuser} = $1 if /^dbuser\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1274 | $config{dbpass} = $1 if /^dbpass\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1275 | $config{dbhost} = $1 if /^dbhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1276 | # SOA defaults
|
---|
| 1277 | $def{contact} = $1 if /^contact\s*=\s*([a-z0-9_.-]+)/i;
|
---|
| 1278 | $def{prins} = $1 if /^prins\s*=\s*([a-z0-9_.-]+)/i;
|
---|
[201] | 1279 | $def{soattl} = $1 if /^soattl\s*=\s*(\d+)/i;
|
---|
| 1280 | $def{refresh} = $1 if /^refresh\s*=\s*(\d+)/i;
|
---|
| 1281 | $def{retry} = $1 if /^retry\s*=\s*(\d+)/i;
|
---|
| 1282 | $def{expire} = $1 if /^expire\s*=\s*(\d+)/i;
|
---|
| 1283 | $def{minttl} = $1 if /^minttl\s*=\s*(\d+)/i;
|
---|
| 1284 | $def{ttl} = $1 if /^ttl\s*=\s*(\d+)/i;
|
---|
[128] | 1285 | # Mail settings
|
---|
| 1286 | $config{mailhost} = $1 if /^mailhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
[198] | 1287 | $config{mailnotify} = $1 if /^mailnotify\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
| 1288 | $config{mailsender} = $1 if /^mailsender\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
[128] | 1289 | $config{mailname} = $1 if /^mailname\s*=\s*([a-z0-9\s_.-]+)/i;
|
---|
[195] | 1290 | $config{orgname} = $1 if /^orgname\s*=\s*([a-z0-9\s_.,'-]+)/i;
|
---|
| 1291 | $config{domain} = $1 if /^domain\s*=\s*([a-z0-9_.-]+)/i;
|
---|
[163] | 1292 | # session - note this is fed directly to CGI::Session
|
---|
[216] | 1293 | $config{timeout} = $1 if /^[tT][iI][mM][eE][oO][uU][tT]\s*=\s*(\d+[smhdwMy]?)/;
|
---|
| 1294 | $config{sessiondir} = $1 if m{^sessiondir\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
[201] | 1295 | # misc
|
---|
[195] | 1296 | $config{log_failures} = $1 if /^log_failures\s*=\s*([a-z01]+)/i;
|
---|
[201] | 1297 | $config{perpage} = $1 if /^perpage\s*=\s*(\d+)/i;
|
---|
[368] | 1298 | $config{exportcache} = $1 if m{^exportcache\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
[400] | 1299 | # RPC options
|
---|
| 1300 | if ($rpcflag && /^rpc/) {
|
---|
| 1301 | if (my ($tmp) = /^rpc_iplist\s*=\s*(.+)/i) {
|
---|
| 1302 | my @ips = split /[,\s]+/, $tmp;
|
---|
| 1303 | my $rpcsys = shift @ips;
|
---|
| 1304 | push @{$config{rpcacl}{$rpcsys}}, @ips;
|
---|
| 1305 | }
|
---|
| 1306 | }
|
---|
[128] | 1307 | }
|
---|
| 1308 | close CFG;
|
---|
| 1309 | } else {
|
---|
| 1310 | $errstr = $!;
|
---|
| 1311 | return;
|
---|
| 1312 | }
|
---|
| 1313 | return 1;
|
---|
| 1314 | } # end __cfgload()
|
---|
| 1315 |
|
---|
| 1316 |
|
---|
[2] | 1317 | ## DNSDB::connectDB()
|
---|
| 1318 | # Creates connection to DNS database.
|
---|
| 1319 | # Requires the database name, username, and password.
|
---|
| 1320 | # Returns a handle to the db.
|
---|
| 1321 | # Set up for a PostgreSQL db; could be any transactional DBMS with the
|
---|
| 1322 | # right changes.
|
---|
| 1323 | sub connectDB {
|
---|
| 1324 | $errstr = '';
|
---|
[15] | 1325 | my $dbname = shift;
|
---|
| 1326 | my $user = shift;
|
---|
| 1327 | my $pass = shift;
|
---|
[2] | 1328 | my $dbh;
|
---|
| 1329 | my $DSN = "DBI:Pg:dbname=$dbname";
|
---|
| 1330 |
|
---|
| 1331 | my $host = shift;
|
---|
| 1332 | $DSN .= ";host=$host" if $host;
|
---|
| 1333 |
|
---|
| 1334 | # Note that we want to autocommit by default, and we will turn it off locally as necessary.
|
---|
| 1335 | # We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
|
---|
| 1336 | $dbh = DBI->connect($DSN, $user, $pass, {
|
---|
| 1337 | AutoCommit => 1,
|
---|
| 1338 | PrintError => 0
|
---|
| 1339 | })
|
---|
| 1340 | or return (undef, $DBI::errstr) if(!$dbh);
|
---|
| 1341 |
|
---|
[212] | 1342 | ##fixme: initialize the DB if we can't find the table (since, by definition, there's
|
---|
| 1343 | # nothing there if we can't select from it...)
|
---|
| 1344 | my $tblsth = $dbh->prepare("SELECT count(*) FROM pg_catalog.pg_class WHERE relkind='r' AND relname=?");
|
---|
| 1345 | my ($tblcount) = $dbh->selectrow_array($tblsth, undef, ('misc'));
|
---|
| 1346 | return (undef,$DBI::errstr) if $dbh->err;
|
---|
| 1347 |
|
---|
| 1348 | #if ($tblcount == 0) {
|
---|
| 1349 | # # create tables one at a time, checking for each.
|
---|
| 1350 | # return (undef, "check table misc missing");
|
---|
| 1351 | #}
|
---|
| 1352 |
|
---|
| 1353 |
|
---|
| 1354 | # Return here if we can't select.
|
---|
| 1355 | # This should retrieve the dbversion key.
|
---|
| 1356 | my $sth = $dbh->prepare("SELECT key,value FROM misc WHERE misc_id=1");
|
---|
[2] | 1357 | $sth->execute();
|
---|
| 1358 | return (undef,$DBI::errstr) if ($sth->err);
|
---|
| 1359 |
|
---|
[212] | 1360 | ##fixme: do stuff to the DB on version mismatch
|
---|
| 1361 | # x.y series should upgrade on $DNSDB::VERSION > misc(key=>version)
|
---|
| 1362 | # DB should be downward-compatible; column defaults should give sane (if possibly
|
---|
| 1363 | # useless-and-needs-help) values in columns an older software stack doesn't know about.
|
---|
| 1364 |
|
---|
[2] | 1365 | # See if the select returned anything (or null data). This should
|
---|
| 1366 | # succeed if the select executed, but...
|
---|
| 1367 | $sth->fetchrow();
|
---|
| 1368 | return (undef,$DBI::errstr) if ($sth->err);
|
---|
| 1369 |
|
---|
| 1370 | $sth->finish;
|
---|
| 1371 |
|
---|
| 1372 | # If we get here, we should be OK.
|
---|
| 1373 | return ($dbh,"DB connection OK");
|
---|
| 1374 | } # end connectDB
|
---|
| 1375 |
|
---|
| 1376 |
|
---|
| 1377 | ## DNSDB::finish()
|
---|
| 1378 | # Cleans up after database handles and so on.
|
---|
| 1379 | # Requires a database handle
|
---|
| 1380 | sub finish {
|
---|
| 1381 | my $dbh = $_[0];
|
---|
| 1382 | $dbh->disconnect;
|
---|
| 1383 | } # end finish
|
---|
| 1384 |
|
---|
| 1385 |
|
---|
| 1386 | ## DNSDB::initGlobals()
|
---|
| 1387 | # Initialize global variables
|
---|
| 1388 | # NB: this does NOT include web-specific session variables!
|
---|
| 1389 | # Requires a database handle
|
---|
| 1390 | sub initGlobals {
|
---|
| 1391 | my $dbh = shift;
|
---|
| 1392 |
|
---|
[208] | 1393 | # load record types from database
|
---|
[228] | 1394 | my $sth = $dbh->prepare("SELECT val,name,stdflag FROM rectypes");
|
---|
[2] | 1395 | $sth->execute;
|
---|
[228] | 1396 | while (my ($recval,$recname,$stdflag) = $sth->fetchrow_array()) {
|
---|
[2] | 1397 | $typemap{$recval} = $recname;
|
---|
| 1398 | $reverse_typemap{$recname} = $recval;
|
---|
[228] | 1399 | # now we fill the record validation function hash
|
---|
| 1400 | if ($stdflag < 5) {
|
---|
| 1401 | my $fn = "_validate_$recval";
|
---|
| 1402 | $validators{$recval} = \&$fn;
|
---|
| 1403 | } else {
|
---|
| 1404 | my $fn = "sub { return ('FAIL','Type $recval ($recname) not supported'); }";
|
---|
| 1405 | $validators{$recval} = eval $fn;
|
---|
| 1406 | }
|
---|
[2] | 1407 | }
|
---|
| 1408 | } # end initGlobals
|
---|
| 1409 |
|
---|
| 1410 |
|
---|
[401] | 1411 | ## DNSDB::initRPC()
|
---|
| 1412 | # Takes a database handle, remote username, and remote fullname.
|
---|
| 1413 | # Sets up the RPC logging-pseudouser if needed.
|
---|
| 1414 | # Sets the %userdata hash for logging.
|
---|
| 1415 | # Returns undef on failure
|
---|
| 1416 | sub initRPC {
|
---|
| 1417 | my $dbh = shift;
|
---|
| 1418 | my %args = @_;
|
---|
| 1419 |
|
---|
| 1420 | return if !$args{username};
|
---|
| 1421 | return if !$args{fullname};
|
---|
| 1422 |
|
---|
[406] | 1423 | $args{username} = "$args{username}/$args{rpcsys}";
|
---|
| 1424 |
|
---|
| 1425 | my $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
|
---|
[404] | 1426 | " FROM users WHERE username=?", undef, ($args{username}) );
|
---|
[406] | 1427 | if (!$tmpuser) {
|
---|
[401] | 1428 | $dbh->do("INSERT INTO users (username,password,firstname,type) VALUES (?,'RPC',?,'R')", undef,
|
---|
| 1429 | ($args{username}, $args{fullname}) );
|
---|
[406] | 1430 | $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
|
---|
[404] | 1431 | " FROM users WHERE username=?", undef, ($args{username}) );
|
---|
[401] | 1432 | }
|
---|
[404] | 1433 | %userdata = %{$tmpuser};
|
---|
[410] | 1434 | $userdata{lastname} = '' if !$userdata{lastname};
|
---|
[404] | 1435 | $userdata{fullname} = "$userdata{firstname} $userdata{lastname} ($args{rpcsys})";
|
---|
[406] | 1436 | return 1 if $tmpuser;
|
---|
[401] | 1437 | } # end initRPC()
|
---|
| 1438 |
|
---|
| 1439 |
|
---|
[278] | 1440 | ## DNSDB::login()
|
---|
| 1441 | # Takes a database handle, username and password
|
---|
[316] | 1442 | # Returns a userdata hash (UID, GID, username, fullname parts) if username exists,
|
---|
| 1443 | # password matches the one on file, and account is not disabled
|
---|
[278] | 1444 | # Returns undef otherwise
|
---|
| 1445 | sub login {
|
---|
| 1446 | my $dbh = shift;
|
---|
| 1447 | my $user = shift;
|
---|
| 1448 | my $pass = shift;
|
---|
| 1449 |
|
---|
[316] | 1450 | my $userinfo = $dbh->selectrow_hashref("SELECT user_id,group_id,password,firstname,lastname,status".
|
---|
| 1451 | " FROM users WHERE username=?",
|
---|
[279] | 1452 | undef, ($user) );
|
---|
| 1453 | return if !$userinfo;
|
---|
[316] | 1454 | return if !$userinfo->{status};
|
---|
[278] | 1455 |
|
---|
[279] | 1456 | if ($userinfo->{password} =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
|
---|
[278] | 1457 | # native passwords (crypt-md5)
|
---|
[279] | 1458 | return if $userinfo->{password} ne unix_md5_crypt($pass,$1);
|
---|
| 1459 | } elsif ($userinfo->{password} =~ /^[0-9a-f]{32}$/) {
|
---|
[278] | 1460 | # VegaDNS import (hex-coded MD5)
|
---|
[279] | 1461 | return if $userinfo->{password} ne md5_hex($pass);
|
---|
[278] | 1462 | } else {
|
---|
| 1463 | # plaintext (convenient now and then)
|
---|
[279] | 1464 | return if $userinfo->{password} ne $pass;
|
---|
[278] | 1465 | }
|
---|
| 1466 |
|
---|
[279] | 1467 | return $userinfo;
|
---|
[278] | 1468 | } # end login()
|
---|
| 1469 |
|
---|
| 1470 |
|
---|
[279] | 1471 | ## DNSDB::initActionLog()
|
---|
| 1472 | # Set up action logging. Takes a database handle and user ID
|
---|
| 1473 | # Sets some internal globals and Does The Right Thing to set up a logging channel.
|
---|
| 1474 | # This sets up _log() to spew out log entries to the defined channel without worrying
|
---|
| 1475 | # about having to open a file or a syslog channel
|
---|
| 1476 | ##fixme Need to call _initActionLog_blah() for various logging channels, configured
|
---|
| 1477 | # via dnsdb.conf, in $config{log_channel} or something
|
---|
| 1478 | # See https://secure.deepnet.cx/trac/dnsadmin/ticket/21
|
---|
| 1479 | sub initActionLog {
|
---|
| 1480 | my $dbh = shift;
|
---|
| 1481 | my $uid = shift;
|
---|
| 1482 |
|
---|
| 1483 | return if !$uid;
|
---|
| 1484 |
|
---|
| 1485 | # snag user info for logging. there's got to be a way to not have to pass this back
|
---|
| 1486 | # and forth from a caller, but web usage means no persistence we can rely on from
|
---|
| 1487 | # the server side.
|
---|
| 1488 | my ($username,$fullname) = $dbh->selectrow_array("SELECT username, firstname || ' ' || lastname".
|
---|
| 1489 | " FROM users WHERE user_id=?", undef, ($uid));
|
---|
| 1490 | ##fixme: errors are unpossible!
|
---|
| 1491 |
|
---|
| 1492 | $userdata{username} = $username;
|
---|
| 1493 | $userdata{userid} = $uid;
|
---|
| 1494 | $userdata{fullname} = $fullname;
|
---|
| 1495 |
|
---|
| 1496 | # convert to real check once we have other logging channels
|
---|
| 1497 | # if ($config{log_channel} eq 'sql') {
|
---|
| 1498 | # Open Log, Sez Me!
|
---|
| 1499 | # }
|
---|
| 1500 |
|
---|
| 1501 | } # end initActionLog
|
---|
| 1502 |
|
---|
| 1503 |
|
---|
[65] | 1504 | ## DNSDB::initPermissions()
|
---|
| 1505 | # Set up permissions global
|
---|
| 1506 | # Takes database handle and UID
|
---|
| 1507 | sub initPermissions {
|
---|
| 1508 | my $dbh = shift;
|
---|
| 1509 | my $uid = shift;
|
---|
| 1510 |
|
---|
| 1511 | # %permissions = $(getPermissions($dbh,'user',$uid));
|
---|
| 1512 | getPermissions($dbh, 'user', $uid, \%permissions);
|
---|
| 1513 |
|
---|
| 1514 | } # end initPermissions()
|
---|
| 1515 |
|
---|
| 1516 |
|
---|
| 1517 | ## DNSDB::getPermissions()
|
---|
| 1518 | # Get permissions from DB
|
---|
| 1519 | # Requires DB handle, group or user flag, ID, and hashref.
|
---|
| 1520 | sub getPermissions {
|
---|
| 1521 | my $dbh = shift;
|
---|
| 1522 | my $type = shift;
|
---|
| 1523 | my $id = shift;
|
---|
| 1524 | my $hash = shift;
|
---|
| 1525 |
|
---|
| 1526 | my $sql = qq(
|
---|
| 1527 | SELECT
|
---|
| 1528 | p.admin,p.self_edit,
|
---|
| 1529 | p.group_create,p.group_edit,p.group_delete,
|
---|
| 1530 | p.user_create,p.user_edit,p.user_delete,
|
---|
| 1531 | p.domain_create,p.domain_edit,p.domain_delete,
|
---|
[387] | 1532 | p.record_create,p.record_edit,p.record_delete,p.record_locchg,
|
---|
[382] | 1533 | p.location_create,p.location_edit,p.location_delete,p.location_view
|
---|
[65] | 1534 | FROM permissions p
|
---|
| 1535 | );
|
---|
| 1536 | if ($type eq 'group') {
|
---|
| 1537 | $sql .= qq(
|
---|
| 1538 | JOIN groups g ON g.permission_id=p.permission_id
|
---|
| 1539 | WHERE g.group_id=?
|
---|
| 1540 | );
|
---|
| 1541 | } else {
|
---|
| 1542 | $sql .= qq(
|
---|
| 1543 | JOIN users u ON u.permission_id=p.permission_id
|
---|
| 1544 | WHERE u.user_id=?
|
---|
| 1545 | );
|
---|
| 1546 | }
|
---|
| 1547 |
|
---|
| 1548 | my $sth = $dbh->prepare($sql);
|
---|
| 1549 |
|
---|
| 1550 | $sth->execute($id) or die "argh: ".$sth->errstr;
|
---|
| 1551 |
|
---|
| 1552 | # my $permref = $sth->fetchrow_hashref;
|
---|
| 1553 | # return $permref;
|
---|
| 1554 | # $hash = $permref;
|
---|
| 1555 | # Eww. Need to learn how to forcibly drop a hashref onto an existing hash.
|
---|
| 1556 | ($hash->{admin},$hash->{self_edit},
|
---|
| 1557 | $hash->{group_create},$hash->{group_edit},$hash->{group_delete},
|
---|
| 1558 | $hash->{user_create},$hash->{user_edit},$hash->{user_delete},
|
---|
| 1559 | $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete},
|
---|
[387] | 1560 | $hash->{record_create},$hash->{record_edit},$hash->{record_delete},$hash->{record_locchg},
|
---|
[382] | 1561 | $hash->{location_create},$hash->{location_edit},$hash->{location_delete},$hash->{location_view}
|
---|
| 1562 | ) = $sth->fetchrow_array;
|
---|
[65] | 1563 |
|
---|
| 1564 | } # end getPermissions()
|
---|
| 1565 |
|
---|
| 1566 |
|
---|
| 1567 | ## DNSDB::changePermissions()
|
---|
| 1568 | # Update an ACL entry
|
---|
| 1569 | # Takes a db handle, type, owner-id, and hashref for the changed permissions.
|
---|
| 1570 | sub changePermissions {
|
---|
| 1571 | my $dbh = shift;
|
---|
| 1572 | my $type = shift;
|
---|
| 1573 | my $id = shift;
|
---|
| 1574 | my $newperms = shift;
|
---|
[87] | 1575 | my $inherit = shift || 0;
|
---|
[65] | 1576 |
|
---|
[294] | 1577 | my $resultmsg = '';
|
---|
[66] | 1578 |
|
---|
[87] | 1579 | # see if we're switching from inherited to custom. for bonus points,
|
---|
| 1580 | # snag the permid and parent permid anyway, since we'll need the permid
|
---|
| 1581 | # to set/alter custom perms, and both if we're switching from custom to
|
---|
| 1582 | # inherited.
|
---|
[294] | 1583 | my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id,".
|
---|
| 1584 | ($type eq 'user' ? 'u.group_id,u.username' : 'u.parent_group_id,u.group_name').
|
---|
[65] | 1585 | " FROM ".($type eq 'user' ? 'users' : 'groups')." u ".
|
---|
[66] | 1586 | " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ".
|
---|
[65] | 1587 | " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?");
|
---|
| 1588 | $sth->execute($id);
|
---|
| 1589 |
|
---|
[294] | 1590 | my ($wasinherited,$permid,$parpermid,$parid,$name) = $sth->fetchrow_array;
|
---|
[66] | 1591 |
|
---|
[78] | 1592 | # hack phtoui
|
---|
| 1593 | # group id 1 is "special" in that it's it's own parent (err... possibly.)
|
---|
| 1594 | # may make its parent id 0 which doesn't exist, and as a bonus is Perl-false.
|
---|
| 1595 | $wasinherited = 0 if ($type eq 'group' && $id == 1);
|
---|
| 1596 |
|
---|
[66] | 1597 | local $dbh->{AutoCommit} = 0;
|
---|
| 1598 | local $dbh->{RaiseError} = 1;
|
---|
| 1599 |
|
---|
| 1600 | # Wrap all the SQL in a transaction
|
---|
| 1601 | eval {
|
---|
[87] | 1602 | if ($inherit) {
|
---|
| 1603 |
|
---|
| 1604 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ".
|
---|
| 1605 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) );
|
---|
| 1606 | $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) );
|
---|
| 1607 |
|
---|
| 1608 | } else {
|
---|
| 1609 |
|
---|
| 1610 | if ($wasinherited) { # munge new permission entry in if we're switching from inherited perms
|
---|
[66] | 1611 | ##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users
|
---|
[87] | 1612 | # ... if'n'when we have groups with fully inherited permissions.
|
---|
| 1613 | # SQL is coo
|
---|
| 1614 | $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ".
|
---|
| 1615 | "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) );
|
---|
| 1616 | ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ".
|
---|
| 1617 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) );
|
---|
| 1618 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ".
|
---|
| 1619 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) );
|
---|
[66] | 1620 | }
|
---|
[78] | 1621 |
|
---|
[87] | 1622 | # and now set the permissions we were passed
|
---|
| 1623 | foreach (@permtypes) {
|
---|
| 1624 | if (defined ($newperms->{$_})) {
|
---|
| 1625 | $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) );
|
---|
| 1626 | }
|
---|
| 1627 | }
|
---|
| 1628 |
|
---|
| 1629 | } # (inherited->)? custom
|
---|
| 1630 |
|
---|
[294] | 1631 | if ($type eq 'user') {
|
---|
| 1632 | $resultmsg = "Updated permissions for user $name";
|
---|
| 1633 | } else {
|
---|
| 1634 | $resultmsg = "Updated default permissions for group $name";
|
---|
| 1635 | }
|
---|
| 1636 | _log($dbh, (group_id => ($type eq 'user' ? $parid : $id), entry => $resultmsg));
|
---|
[66] | 1637 | $dbh->commit;
|
---|
| 1638 | }; # end eval
|
---|
| 1639 | if ($@) {
|
---|
| 1640 | my $msg = $@;
|
---|
| 1641 | eval { $dbh->rollback; };
|
---|
[294] | 1642 | return ('FAIL',"Error changing permissions: $msg");
|
---|
[66] | 1643 | }
|
---|
| 1644 |
|
---|
[294] | 1645 | return ('OK',$resultmsg);
|
---|
[65] | 1646 | } # end changePermissions()
|
---|
| 1647 |
|
---|
| 1648 |
|
---|
[67] | 1649 | ## DNSDB::comparePermissions()
|
---|
| 1650 | # Compare two permission hashes
|
---|
| 1651 | # Returns '>', '<', '=', '!'
|
---|
| 1652 | sub comparePermissions {
|
---|
| 1653 | my $p1 = shift;
|
---|
| 1654 | my $p2 = shift;
|
---|
| 1655 |
|
---|
| 1656 | my $retval = '='; # assume equality until proven otherwise
|
---|
| 1657 |
|
---|
| 1658 | no warnings "uninitialized";
|
---|
| 1659 |
|
---|
| 1660 | foreach (@permtypes) {
|
---|
| 1661 | next if $p1->{$_} == $p2->{$_}; # equal is good
|
---|
| 1662 | if ($p1->{$_} && !$p2->{$_}) {
|
---|
| 1663 | if ($retval eq '<') { # if we've already found an unequal pair where
|
---|
| 1664 | $retval = '!'; # $p2 has more access, and we now find a pair
|
---|
| 1665 | last; # where $p1 has more access, the overall access
|
---|
| 1666 | } # is neither greater or lesser, it's unequal.
|
---|
| 1667 | $retval = '>';
|
---|
| 1668 | }
|
---|
| 1669 | if (!$p1->{$_} && $p2->{$_}) {
|
---|
| 1670 | if ($retval eq '>') { # if we've already found an unequal pair where
|
---|
| 1671 | $retval = '!'; # $p1 has more access, and we now find a pair
|
---|
| 1672 | last; # where $p2 has more access, the overall access
|
---|
| 1673 | } # is neither greater or lesser, it's unequal.
|
---|
| 1674 | $retval = '<';
|
---|
| 1675 | }
|
---|
| 1676 | }
|
---|
| 1677 | return $retval;
|
---|
| 1678 | } # end comparePermissions()
|
---|
| 1679 |
|
---|
| 1680 |
|
---|
[112] | 1681 | ## DNSDB::changeGroup()
|
---|
| 1682 | # Change group ID of an entity
|
---|
| 1683 | # Takes a database handle, entity type, entity ID, and new group ID
|
---|
| 1684 | sub changeGroup {
|
---|
| 1685 | my $dbh = shift;
|
---|
| 1686 | my $type = shift;
|
---|
| 1687 | my $id = shift;
|
---|
| 1688 | my $newgrp = shift;
|
---|
| 1689 |
|
---|
| 1690 | ##fixme: fail on not enough args
|
---|
| 1691 | #return ('FAIL', "Missing
|
---|
| 1692 |
|
---|
[295] | 1693 | return ('FAIL', "Can't change the group of a $type")
|
---|
| 1694 | unless grep /^$type$/, ('domain','revzone','user','group'); # could be extended for defrecs?
|
---|
| 1695 |
|
---|
| 1696 | # Collect some names for logging and messages
|
---|
| 1697 | my $entname;
|
---|
[112] | 1698 | if ($type eq 'domain') {
|
---|
[295] | 1699 | $entname = domainName($dbh, $id);
|
---|
| 1700 | } elsif ($type eq 'revzone') {
|
---|
| 1701 | $entname = revName($dbh, $id);
|
---|
[112] | 1702 | } elsif ($type eq 'user') {
|
---|
[295] | 1703 | $entname = userFullName($dbh, $id, '%u');
|
---|
[112] | 1704 | } elsif ($type eq 'group') {
|
---|
[295] | 1705 | $entname = groupName($dbh, $id);
|
---|
[112] | 1706 | }
|
---|
[295] | 1707 |
|
---|
| 1708 | my ($oldgid) = $dbh->selectrow_array("SELECT group_id FROM $par_tbl{$type} WHERE $id_col{$type}=?",
|
---|
| 1709 | undef, ($id));
|
---|
| 1710 | my $oldgname = groupName($dbh, $oldgid);
|
---|
| 1711 | my $newgname = groupName($dbh, $newgrp);
|
---|
| 1712 |
|
---|
| 1713 | return ('FAIL', "Can't move things into a group that doesn't exist") if !$newgname;
|
---|
| 1714 |
|
---|
| 1715 | return ('WARN', "Nothing to do, new group is the same as the old group") if $oldgid == $newgrp;
|
---|
| 1716 |
|
---|
| 1717 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 1718 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 1719 | local $dbh->{AutoCommit} = 0;
|
---|
| 1720 | local $dbh->{RaiseError} = 1;
|
---|
| 1721 |
|
---|
| 1722 | eval {
|
---|
| 1723 | $dbh->do("UPDATE $par_tbl{$type} SET group_id=? WHERE $id_col{$type}=?", undef, ($newgrp, $id));
|
---|
| 1724 | # Log the change in both the old and new groups
|
---|
| 1725 | _log($dbh, (group_id => $oldgid, entry => "Moved $type $entname from $oldgname to $newgname"));
|
---|
| 1726 | _log($dbh, (group_id => $newgrp, entry => "Moved $type $entname from $oldgname to $newgname"));
|
---|
| 1727 | $dbh->commit;
|
---|
| 1728 | };
|
---|
| 1729 | if ($@) {
|
---|
| 1730 | my $msg = $@;
|
---|
| 1731 | eval { $dbh->rollback; };
|
---|
| 1732 | if ($config{log_failures}) {
|
---|
| 1733 | _log($dbh, (group_id => $oldgid, entry => "Error moving $type $entname to $newgname: $msg"));
|
---|
| 1734 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 1735 | }
|
---|
| 1736 | return ('FAIL',"Error moving $type $entname to $newgname: $msg");
|
---|
| 1737 | }
|
---|
| 1738 |
|
---|
| 1739 | return ('OK',"Moved $type $entname from $oldgname to $newgname");
|
---|
[112] | 1740 | } # end changeGroup()
|
---|
| 1741 |
|
---|
| 1742 |
|
---|
[2] | 1743 | ##
|
---|
| 1744 | ## Processing subs
|
---|
| 1745 | ##
|
---|
| 1746 |
|
---|
| 1747 | ## DNSDB::addDomain()
|
---|
| 1748 | # Add a domain
|
---|
[190] | 1749 | # Takes a database handle, domain name, numeric group, boolean(ish) state (active/inactive),
|
---|
| 1750 | # and user info hash (for logging).
|
---|
[2] | 1751 | # Returns a status code and message
|
---|
| 1752 | sub addDomain {
|
---|
| 1753 | $errstr = '';
|
---|
| 1754 | my $dbh = shift;
|
---|
| 1755 | return ('FAIL',"Need database handle") if !$dbh;
|
---|
| 1756 | my $domain = shift;
|
---|
[91] | 1757 | return ('FAIL',"Domain must not be blank") if !$domain;
|
---|
[2] | 1758 | my $group = shift;
|
---|
| 1759 | return ('FAIL',"Need group") if !defined($group);
|
---|
| 1760 | my $state = shift;
|
---|
| 1761 | return ('FAIL',"Need domain status") if !defined($state);
|
---|
| 1762 |
|
---|
[116] | 1763 | $state = 1 if $state =~ /^active$/;
|
---|
| 1764 | $state = 1 if $state =~ /^on$/;
|
---|
| 1765 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 1766 | $state = 0 if $state =~ /^off$/;
|
---|
| 1767 |
|
---|
| 1768 | return ('FAIL',"Invalid domain status") if $state !~ /^\d+$/;
|
---|
| 1769 |
|
---|
[190] | 1770 | return ('FAIL', "Invalid characters in domain") if $domain !~ /^[a-zA-Z0-9_.-]+$/;
|
---|
| 1771 |
|
---|
[349] | 1772 | my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)");
|
---|
[3] | 1773 | my $dom_id;
|
---|
| 1774 |
|
---|
[38] | 1775 | # quick check to start to see if we've already got one
|
---|
| 1776 | $sth->execute($domain);
|
---|
| 1777 | ($dom_id) = $sth->fetchrow_array;
|
---|
| 1778 |
|
---|
| 1779 | return ('FAIL', "Domain already exists") if $dom_id;
|
---|
| 1780 |
|
---|
[2] | 1781 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 1782 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 1783 | local $dbh->{AutoCommit} = 0;
|
---|
| 1784 | local $dbh->{RaiseError} = 1;
|
---|
| 1785 |
|
---|
| 1786 | # Wrap all the SQL in a transaction
|
---|
| 1787 | eval {
|
---|
| 1788 | # insert the domain...
|
---|
[190] | 1789 | $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef, ($domain, $group, $state));
|
---|
[2] | 1790 |
|
---|
| 1791 | # get the ID...
|
---|
[349] | 1792 | ($dom_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
| 1793 | undef, ($domain));
|
---|
[2] | 1794 |
|
---|
[284] | 1795 | _log($dbh, (domain_id => $dom_id, group_id => $group,
|
---|
[259] | 1796 | entry => "Added ".($state ? 'active' : 'inactive')." domain $domain"));
|
---|
[190] | 1797 |
|
---|
[2] | 1798 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
[190] | 1799 | my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
| 1800 | my $sth_in = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,distance,weight,port,ttl)".
|
---|
| 1801 | " VALUES ($dom_id,?,?,?,?,?,?,?)");
|
---|
| 1802 | $sth->execute($group);
|
---|
[3] | 1803 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $sth->fetchrow_array()) {
|
---|
[2] | 1804 | $host =~ s/DOMAIN/$domain/g;
|
---|
[37] | 1805 | $val =~ s/DOMAIN/$domain/g;
|
---|
[3] | 1806 | $sth_in->execute($host,$type,$val,$dist,$weight,$port,$ttl);
|
---|
[190] | 1807 | if ($typemap{$type} eq 'SOA') {
|
---|
| 1808 | my @tmp1 = split /:/, $host;
|
---|
| 1809 | my @tmp2 = split /:/, $val;
|
---|
[284] | 1810 | _log($dbh, (domain_id => $dom_id, group_id => $group,
|
---|
| 1811 | entry => "[new $domain] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
[257] | 1812 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"));
|
---|
[190] | 1813 | } else {
|
---|
| 1814 | my $logentry = "[new $domain] Added record '$host $typemap{$type}";
|
---|
| 1815 | $logentry .= " [distance $dist]" if $typemap{$type} eq 'MX';
|
---|
| 1816 | $logentry .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$type} eq 'SRV';
|
---|
[284] | 1817 | _log($dbh, (domain_id => $dom_id, group_id => $group,
|
---|
| 1818 | entry => $logentry." $val', TTL $ttl"));
|
---|
[190] | 1819 | }
|
---|
[2] | 1820 | }
|
---|
| 1821 |
|
---|
| 1822 | # once we get here, we should have suceeded.
|
---|
| 1823 | $dbh->commit;
|
---|
| 1824 | }; # end eval
|
---|
| 1825 |
|
---|
| 1826 | if ($@) {
|
---|
| 1827 | my $msg = $@;
|
---|
| 1828 | eval { $dbh->rollback; };
|
---|
[286] | 1829 | _log($dbh, (group_id => $group, entry => "Failed adding domain $domain ($msg)"))
|
---|
[284] | 1830 | if $config{log_failures};
|
---|
| 1831 | $dbh->commit; # since we enabled transactions earlier
|
---|
[193] | 1832 | return ('FAIL',$msg);
|
---|
[2] | 1833 | } else {
|
---|
[3] | 1834 | return ('OK',$dom_id);
|
---|
[2] | 1835 | }
|
---|
| 1836 | } # end addDomain
|
---|
| 1837 |
|
---|
| 1838 |
|
---|
[274] | 1839 | ## DNSDB::delZone()
|
---|
| 1840 | # Delete a forward or reverse zone.
|
---|
| 1841 | # Takes a database handle, zone ID, and forward/reverse flag.
|
---|
[3] | 1842 | # for now, just delete the records, then the domain.
|
---|
| 1843 | # later we may want to archive it in some way instead (status code 2, for example?)
|
---|
[274] | 1844 | sub delZone {
|
---|
[3] | 1845 | my $dbh = shift;
|
---|
[274] | 1846 | my $zoneid = shift;
|
---|
| 1847 | my $revrec = shift;
|
---|
[3] | 1848 |
|
---|
| 1849 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 1850 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 1851 | local $dbh->{AutoCommit} = 0;
|
---|
| 1852 | local $dbh->{RaiseError} = 1;
|
---|
| 1853 |
|
---|
[285] | 1854 | my $msg = '';
|
---|
[23] | 1855 | my $failmsg = '';
|
---|
[285] | 1856 | my $zone = ($revrec eq 'n' ? domainName($dbh, $zoneid) : revName($dbh, $zoneid));
|
---|
[23] | 1857 |
|
---|
[343] | 1858 | return ('FAIL', ($revrec eq 'n' ? 'Domain' : 'Reverse zone')." ID $zoneid doesn't exist") if !$zone;
|
---|
| 1859 |
|
---|
[285] | 1860 | # Set this up here since we may use if if $config{log_failures} is enabled
|
---|
| 1861 | my %loghash;
|
---|
| 1862 | $loghash{domain_id} = $zoneid if $revrec eq 'n';
|
---|
| 1863 | $loghash{rdns_id} = $zoneid if $revrec eq 'y';
|
---|
| 1864 | $loghash{group_id} = parentID($dbh,
|
---|
| 1865 | (id => $zoneid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) );
|
---|
| 1866 |
|
---|
[3] | 1867 | # Wrap all the SQL in a transaction
|
---|
| 1868 | eval {
|
---|
[274] | 1869 | # Disentangle custom record types before removing the
|
---|
| 1870 | # ones that are only in the zone to be deleted
|
---|
| 1871 | if ($revrec eq 'n') {
|
---|
| 1872 | my $sth = $dbh->prepare("UPDATE records SET type=?,domain_id=0 WHERE domain_id=? AND type=?");
|
---|
| 1873 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
| 1874 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65280);
|
---|
| 1875 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65281);
|
---|
| 1876 | $sth->execute(65282, $zoneid, 65283);
|
---|
| 1877 | $sth->execute(65282, $zoneid, 65284);
|
---|
| 1878 | $failmsg = "Failure removing domain records";
|
---|
| 1879 | $dbh->do("DELETE FROM records WHERE domain_id=?", undef, ($zoneid));
|
---|
| 1880 | $failmsg = "Failure removing domain";
|
---|
| 1881 | $dbh->do("DELETE FROM domains WHERE domain_id=?", undef, ($zoneid));
|
---|
| 1882 | } else {
|
---|
| 1883 | my $sth = $dbh->prepare("UPDATE records SET type=?,rdns_id=0 WHERE rdns_id=? AND type=?");
|
---|
| 1884 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
| 1885 | $sth->execute($reverse_typemap{A}, $zoneid, 65280);
|
---|
| 1886 | $sth->execute($reverse_typemap{AAAA}, $zoneid, 65281);
|
---|
| 1887 | # We don't have an "A template" or "AAAA template" type, although it might be useful for symmetry.
|
---|
[345] | 1888 | # $sth->execute(65286?, $zoneid, 65283);
|
---|
| 1889 | # $sth->execute(65286?, $zoneid, 65284);
|
---|
[274] | 1890 | $failmsg = "Failure removing reverse records";
|
---|
| 1891 | $dbh->do("DELETE FROM records WHERE rdns_id=?", undef, ($zoneid));
|
---|
| 1892 | $failmsg = "Failure removing reverse zone";
|
---|
| 1893 | $dbh->do("DELETE FROM revzones WHERE rdns_id=?", undef, ($zoneid));
|
---|
| 1894 | }
|
---|
[3] | 1895 |
|
---|
[285] | 1896 | $msg = "Deleted ".($revrec eq 'n' ? 'domain' : 'reverse zone')." $zone";
|
---|
| 1897 | $loghash{entry} = $msg;
|
---|
| 1898 | _log($dbh, %loghash);
|
---|
| 1899 |
|
---|
[3] | 1900 | # once we get here, we should have suceeded.
|
---|
[23] | 1901 | $dbh->commit;
|
---|
[3] | 1902 | }; # end eval
|
---|
| 1903 |
|
---|
| 1904 | if ($@) {
|
---|
[285] | 1905 | $msg = $@;
|
---|
[3] | 1906 | eval { $dbh->rollback; };
|
---|
[295] | 1907 | $loghash{entry} = "Error deleting $zone: $msg ($failmsg)";
|
---|
| 1908 | if ($config{log_failures}) {
|
---|
| 1909 | _log($dbh, %loghash);
|
---|
| 1910 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 1911 | }
|
---|
| 1912 | return ('FAIL', $loghash{entry});
|
---|
[3] | 1913 | } else {
|
---|
[295] | 1914 | return ('OK', $msg);
|
---|
[3] | 1915 | }
|
---|
| 1916 |
|
---|
[274] | 1917 | } # end delZone()
|
---|
[3] | 1918 |
|
---|
| 1919 |
|
---|
[2] | 1920 | ## DNSDB::domainName()
|
---|
| 1921 | # Return the domain name based on a domain ID
|
---|
| 1922 | # Takes a database handle and the domain ID
|
---|
| 1923 | # Returns the domain name or undef on failure
|
---|
| 1924 | sub domainName {
|
---|
| 1925 | $errstr = '';
|
---|
| 1926 | my $dbh = shift;
|
---|
| 1927 | my $domid = shift;
|
---|
[91] | 1928 | my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
|
---|
[2] | 1929 | $errstr = $DBI::errstr if !$domname;
|
---|
| 1930 | return $domname if $domname;
|
---|
[91] | 1931 | } # end domainName()
|
---|
[2] | 1932 |
|
---|
| 1933 |
|
---|
[224] | 1934 | ## DNSDB::revName()
|
---|
| 1935 | # Return the reverse zone name based on an rDNS ID
|
---|
| 1936 | # Takes a database handle and the rDNS ID
|
---|
| 1937 | # Returns the reverse zone name or undef on failure
|
---|
| 1938 | sub revName {
|
---|
| 1939 | $errstr = '';
|
---|
| 1940 | my $dbh = shift;
|
---|
| 1941 | my $revid = shift;
|
---|
| 1942 | my ($revname) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id=?", undef, ($revid) );
|
---|
| 1943 | $errstr = $DBI::errstr if !$revname;
|
---|
| 1944 | return $revname if $revname;
|
---|
| 1945 | } # end revName()
|
---|
| 1946 |
|
---|
| 1947 |
|
---|
[91] | 1948 | ## DNSDB::domainID()
|
---|
| 1949 | # Takes a database handle and domain name
|
---|
| 1950 | # Returns the domain ID number
|
---|
| 1951 | sub domainID {
|
---|
| 1952 | $errstr = '';
|
---|
| 1953 | my $dbh = shift;
|
---|
| 1954 | my $domain = shift;
|
---|
[349] | 1955 | my ($domid) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
| 1956 | undef, ($domain) );
|
---|
[91] | 1957 | $errstr = $DBI::errstr if !$domid;
|
---|
| 1958 | return $domid if $domid;
|
---|
| 1959 | } # end domainID()
|
---|
| 1960 |
|
---|
| 1961 |
|
---|
[276] | 1962 | ## DNSDB::revID()
|
---|
| 1963 | # Takes a database handle and reverse zone name
|
---|
| 1964 | # Returns the rDNS ID number
|
---|
| 1965 | sub revID {
|
---|
| 1966 | $errstr = '';
|
---|
| 1967 | my $dbh = shift;
|
---|
| 1968 | my $revzone = shift;
|
---|
| 1969 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ($revzone) );
|
---|
| 1970 | $errstr = $DBI::errstr if !$revid;
|
---|
| 1971 | return $revid if $revid;
|
---|
| 1972 | } # end revID()
|
---|
| 1973 |
|
---|
| 1974 |
|
---|
[260] | 1975 | ## DNSDB::addRDNS
|
---|
| 1976 | # Adds a reverse DNS zone
|
---|
[286] | 1977 | # Takes a database handle, CIDR block, reverse DNS pattern, numeric group,
|
---|
| 1978 | # and boolean(ish) state (active/inactive)
|
---|
[260] | 1979 | # Returns a status code and message
|
---|
| 1980 | sub addRDNS {
|
---|
| 1981 | my $dbh = shift;
|
---|
| 1982 | my $zone = NetAddr::IP->new(shift);
|
---|
[446] | 1983 |
|
---|
[260] | 1984 | return ('FAIL',"Zone name must be a valid CIDR netblock") unless ($zone && $zone->addr !~ /^0/);
|
---|
[270] | 1985 | my $revpatt = shift; # construct a custom (A/AAAA+)? PTR template record
|
---|
[260] | 1986 | my $group = shift;
|
---|
| 1987 | my $state = shift;
|
---|
[446] | 1988 | my $defloc = shift || '';
|
---|
[260] | 1989 |
|
---|
| 1990 | $state = 1 if $state =~ /^active$/;
|
---|
| 1991 | $state = 1 if $state =~ /^on$/;
|
---|
| 1992 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 1993 | $state = 0 if $state =~ /^off$/;
|
---|
| 1994 |
|
---|
| 1995 | return ('FAIL',"Invalid zone status") if $state !~ /^\d+$/;
|
---|
| 1996 |
|
---|
| 1997 | # quick check to start to see if we've already got one
|
---|
[299] | 1998 | my ($rdns_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ("$zone"));
|
---|
[260] | 1999 |
|
---|
| 2000 | return ('FAIL', "Zone already exists") if $rdns_id;
|
---|
| 2001 |
|
---|
| 2002 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2003 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2004 | local $dbh->{AutoCommit} = 0;
|
---|
| 2005 | local $dbh->{RaiseError} = 1;
|
---|
| 2006 |
|
---|
[264] | 2007 | my $warnstr = '';
|
---|
[270] | 2008 | my $defttl = 3600; # 1 hour should be reasonable. And unless things have gone horribly
|
---|
| 2009 | # wrong, we should have a value to override this anyway.
|
---|
[264] | 2010 |
|
---|
[260] | 2011 | # Wrap all the SQL in a transaction
|
---|
| 2012 | eval {
|
---|
[446] | 2013 | # insert the zone...
|
---|
| 2014 | $dbh->do("INSERT INTO revzones (revnet,group_id,status,default_location) VALUES (?,?,?,?)", undef,
|
---|
| 2015 | ($zone, $group, $state, $defloc) );
|
---|
[260] | 2016 |
|
---|
| 2017 | # get the ID...
|
---|
| 2018 | ($rdns_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
| 2019 |
|
---|
[286] | 2020 | _log($dbh, (rdns_id => $rdns_id, group_id => $group,
|
---|
[260] | 2021 | entry => "Added ".($state ? 'active' : 'inactive')." reverse zone $zone"));
|
---|
| 2022 |
|
---|
| 2023 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
| 2024 | my $sth = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
[446] | 2025 | my $sth_in = $dbh->prepare("INSERT INTO records (rdns_id,domain_id,host,type,val,ttl,location)".
|
---|
| 2026 | " VALUES ($rdns_id,?,?,?,?,?,?)");
|
---|
[260] | 2027 | $sth->execute($group);
|
---|
| 2028 | while (my ($host,$type,$val,$ttl) = $sth->fetchrow_array()) {
|
---|
[264] | 2029 | # Silently skip v4/v6 mismatches. This is not an error, this is expected.
|
---|
| 2030 | if ($zone->{isv6}) {
|
---|
| 2031 | next if ($type == 65280 || $type == 65283);
|
---|
| 2032 | } else {
|
---|
| 2033 | next if ($type == 65281 || $type == 65284);
|
---|
| 2034 | }
|
---|
[269] | 2035 |
|
---|
[260] | 2036 | $host =~ s/ADMINDOMAIN/$config{domain}/g;
|
---|
[264] | 2037 |
|
---|
[265] | 2038 | # Check to make sure the IP stubs will fit in the zone. Under most usage failures here should be rare.
|
---|
| 2039 | # On failure, tack a note on to a warning string and continue without adding this record.
|
---|
| 2040 | # While we're at it, we substitute $zone for ZONE in the value.
|
---|
| 2041 | if ($val eq 'ZONE') {
|
---|
[444] | 2042 | # If we've got a pattern, we skip the default record version on (A+)PTR-template types
|
---|
| 2043 | next if $revpatt && ($type == 65282 || $type == 65283);
|
---|
[269] | 2044 | ##fixme? do we care if we have multiple whole-zone templates?
|
---|
[265] | 2045 | $val = $zone->network;
|
---|
| 2046 | } elsif ($val =~ /ZONE/) {
|
---|
| 2047 | my $tmpval = $val;
|
---|
| 2048 | $tmpval =~ s/ZONE//;
|
---|
[269] | 2049 | # Bend the rules and allow single-trailing-number PTR or PTR template records to be inserted
|
---|
| 2050 | # as either v4 or v6. May make this an off-by-default config flag
|
---|
| 2051 | # Note that the origin records that may trigger this **SHOULD** already have ZONE,\d
|
---|
| 2052 | if ($type == 12 || $type == 65282) {
|
---|
| 2053 | $tmpval =~ s/[,.]/::/ if ($tmpval =~ /^[,.]\d+$/ && $zone->{isv6});
|
---|
| 2054 | $tmpval =~ s/[,:]+/./ if ($tmpval =~ /^(?:,|::)\d+$/ && !$zone->{isv6});
|
---|
| 2055 | }
|
---|
[265] | 2056 | my $addr;
|
---|
| 2057 | if (_ipparent($dbh, 'n', 'y', \$tmpval, $rdns_id, \$addr)) {
|
---|
| 2058 | $val = $addr->addr;
|
---|
| 2059 | } else {
|
---|
[269] | 2060 | $warnstr .= "\nDefault record '$val $typemap{$type} $host' doesn't fit in $zone, skipping";
|
---|
[264] | 2061 | next;
|
---|
| 2062 | }
|
---|
| 2063 | }
|
---|
| 2064 |
|
---|
[328] | 2065 | # Substitute $zone for ZONE in the hostname, but only for non-NS records.
|
---|
| 2066 | # NS records get this substitution on the value instead.
|
---|
| 2067 | $host = _ZONE($zone, $host) if $type != 2;
|
---|
[265] | 2068 |
|
---|
[269] | 2069 | # Fill in the forward domain ID if we can find it, otherwise:
|
---|
| 2070 | # Coerce type down to PTR or PTR template if we can't
|
---|
| 2071 | my $domid = 0;
|
---|
| 2072 | if ($type >= 65280) {
|
---|
| 2073 | if (!($domid = _hostparent($dbh, $host))) {
|
---|
| 2074 | $warnstr .= "\nRecord added as PTR instead of $typemap{$type}; domain not found for $host";
|
---|
| 2075 | $type = $reverse_typemap{PTR};
|
---|
| 2076 | $domid = 0; # just to be explicit.
|
---|
| 2077 | }
|
---|
| 2078 | }
|
---|
| 2079 |
|
---|
[446] | 2080 | $sth_in->execute($domid,$host,$type,$val,$ttl,$defloc);
|
---|
[269] | 2081 |
|
---|
[260] | 2082 | if ($typemap{$type} eq 'SOA') {
|
---|
| 2083 | my @tmp1 = split /:/, $host;
|
---|
| 2084 | my @tmp2 = split /:/, $val;
|
---|
[286] | 2085 | _log($dbh, (rdns_id => $rdns_id, group_id => $group,
|
---|
| 2086 | entry => "[new $zone] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
[260] | 2087 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"));
|
---|
[270] | 2088 | $defttl = $tmp2[3];
|
---|
[260] | 2089 | } else {
|
---|
[446] | 2090 | my $logentry = "[new $zone] Added record '$host $typemap{$type} $val', TTL $ttl";
|
---|
| 2091 | $logentry .= ", default location ".getLoc($dbh, $defloc)->{description} if $defloc;
|
---|
| 2092 | _log($dbh, (rdns_id => $rdns_id, domain_id => $domid, group_id => $group, entry => $logentry) );
|
---|
[260] | 2093 | }
|
---|
| 2094 | }
|
---|
| 2095 |
|
---|
[270] | 2096 | # Generate record based on provided pattern.
|
---|
| 2097 | if ($revpatt) {
|
---|
| 2098 | my $host;
|
---|
| 2099 | my $type = ($zone->{isv6} ? 65284 : 65283);
|
---|
| 2100 | my $val = $zone->network;
|
---|
[269] | 2101 |
|
---|
[270] | 2102 | # Substitute $zone for ZONE in the hostname.
|
---|
| 2103 | $host = _ZONE($zone, $revpatt);
|
---|
| 2104 |
|
---|
| 2105 | my $domid = 0;
|
---|
| 2106 | if (!($domid = _hostparent($dbh, $host))) {
|
---|
| 2107 | $warnstr .= "\nDefault pattern added as PTR template instead of $typemap{$type}; domain not found for $host";
|
---|
| 2108 | $type = 65282;
|
---|
| 2109 | $domid = 0; # just to be explicit.
|
---|
| 2110 | }
|
---|
| 2111 |
|
---|
[446] | 2112 | $sth_in->execute($domid,$host,$type,$val,$defttl,$defloc);
|
---|
[286] | 2113 | my $logentry = "[new $zone] Added record '$host $typemap{$type}";
|
---|
| 2114 | _log($dbh, (rdns_id => $rdns_id, domain_id => $domid, group_id => $group,
|
---|
| 2115 | entry => $logentry." $val', TTL $defttl from pattern"));
|
---|
[270] | 2116 | }
|
---|
| 2117 |
|
---|
[264] | 2118 | # If there are warnings (presumably about default records skipped for cause) log them
|
---|
[286] | 2119 | _log($dbh, (rdns_id => $rdns_id, group_id => $group, entry => "Warning(s) adding $zone:$warnstr"))
|
---|
[264] | 2120 | if $warnstr;
|
---|
[269] | 2121 |
|
---|
[260] | 2122 | # once we get here, we should have suceeded.
|
---|
| 2123 | $dbh->commit;
|
---|
| 2124 | }; # end eval
|
---|
| 2125 |
|
---|
| 2126 | if ($@) {
|
---|
| 2127 | my $msg = $@;
|
---|
| 2128 | eval { $dbh->rollback; };
|
---|
[286] | 2129 | _log($dbh, (group_id => $group, entry => "Failed adding reverse zone $zone ($msg)"))
|
---|
| 2130 | if $config{log_failures};
|
---|
| 2131 | $dbh->commit; # since we enabled transactions earlier
|
---|
[260] | 2132 | return ('FAIL',$msg);
|
---|
| 2133 | } else {
|
---|
[286] | 2134 | my $retcode = 'OK';
|
---|
| 2135 | if ($warnstr) {
|
---|
| 2136 | $resultstr = $warnstr;
|
---|
| 2137 | $retcode = 'WARN';
|
---|
| 2138 | }
|
---|
| 2139 | return ($retcode, $rdns_id);
|
---|
[260] | 2140 | }
|
---|
| 2141 |
|
---|
| 2142 | } # end addRDNS()
|
---|
| 2143 |
|
---|
| 2144 |
|
---|
[237] | 2145 | ## DNSDB::getZoneCount
|
---|
| 2146 | # Get count of zones in group or groups
|
---|
| 2147 | # Takes a database handle and hash containing:
|
---|
| 2148 | # - the "current" group
|
---|
| 2149 | # - an array of "acceptable" groups
|
---|
| 2150 | # - a flag for forward/reverse zones
|
---|
| 2151 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
| 2152 | # Returns an integer count of the resulting zone list.
|
---|
| 2153 | sub getZoneCount {
|
---|
| 2154 | my $dbh = shift;
|
---|
| 2155 |
|
---|
| 2156 | my %args = @_;
|
---|
| 2157 |
|
---|
| 2158 | my @filterargs;
|
---|
[239] | 2159 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2160 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2161 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
[237] | 2162 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2163 |
|
---|
| 2164 | my $sql;
|
---|
| 2165 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
| 2166 | if ($args{revrec} eq 'n') {
|
---|
| 2167 | $sql = "SELECT count(*) FROM domains".
|
---|
| 2168 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2169 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
| 2170 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
| 2171 | } else {
|
---|
| 2172 | $sql = "SELECT count(*) FROM revzones".
|
---|
| 2173 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2174 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
|
---|
| 2175 | ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2176 | }
|
---|
| 2177 | my ($count) = $dbh->selectrow_array($sql, undef, @filterargs);
|
---|
| 2178 | return $count;
|
---|
| 2179 | } # end getZoneCount()
|
---|
| 2180 |
|
---|
| 2181 |
|
---|
| 2182 | ## DNSDB::getZoneList()
|
---|
| 2183 | # Get a list of zones in the specified group(s)
|
---|
| 2184 | # Takes the same arguments as getZoneCount() above
|
---|
| 2185 | # Returns a reference to an array of hashrefs suitable for feeding to HTML::Template
|
---|
| 2186 | sub getZoneList {
|
---|
| 2187 | my $dbh = shift;
|
---|
| 2188 |
|
---|
| 2189 | my %args = @_;
|
---|
| 2190 |
|
---|
| 2191 | my @zonelist;
|
---|
| 2192 |
|
---|
[309] | 2193 | $args{sortorder} = 'ASC' if !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
[239] | 2194 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[237] | 2195 |
|
---|
| 2196 | my @filterargs;
|
---|
[239] | 2197 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2198 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2199 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
[237] | 2200 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2201 |
|
---|
| 2202 | my $sql;
|
---|
| 2203 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
| 2204 | if ($args{revrec} eq 'n') {
|
---|
[309] | 2205 | $args{sortby} = 'domain' if !grep /^$args{sortby}$/, ('domain','group','status');
|
---|
[237] | 2206 | $sql = "SELECT domain_id,domain,status,groups.group_name AS group FROM domains".
|
---|
| 2207 | " INNER JOIN groups ON domains.group_id=groups.group_id".
|
---|
| 2208 | " WHERE domains.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2209 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
| 2210 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
| 2211 | } else {
|
---|
[239] | 2212 | ##fixme: arguably startwith here is irrelevant. depends on the UI though.
|
---|
[309] | 2213 | $args{sortby} = 'revnet' if !grep /^$args{sortby}$/, ('revnet','group','status');
|
---|
[237] | 2214 | $sql = "SELECT rdns_id,revnet,status,groups.group_name AS group FROM revzones".
|
---|
| 2215 | " INNER JOIN groups ON revzones.group_id=groups.group_id".
|
---|
| 2216 | " WHERE revzones.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2217 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
|
---|
| 2218 | ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
| 2219 | }
|
---|
| 2220 | # A common tail.
|
---|
[239] | 2221 | $sql .= " ORDER BY ".($args{sortby} eq 'group' ? 'groups.group_name' : $args{sortby})." $args{sortorder} ".
|
---|
| 2222 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage}".
|
---|
[237] | 2223 | " OFFSET ".$args{offset}*$config{perpage});
|
---|
[402] | 2224 | my $sth = $dbh->prepare($sql);
|
---|
| 2225 | $sth->execute(@filterargs);
|
---|
| 2226 | my $rownum = 0;
|
---|
[237] | 2227 |
|
---|
[402] | 2228 | while (my @data = $sth->fetchrow_array) {
|
---|
| 2229 | my %row;
|
---|
| 2230 | $row{domain_id} = $data[0];
|
---|
| 2231 | $row{domain} = $data[1];
|
---|
| 2232 | $row{status} = $data[2];
|
---|
| 2233 | $row{group} = $data[3];
|
---|
| 2234 | push @zonelist, \%row;
|
---|
| 2235 | }
|
---|
| 2236 |
|
---|
| 2237 | return \@zonelist;
|
---|
[237] | 2238 | } # end getZoneList()
|
---|
| 2239 |
|
---|
| 2240 |
|
---|
[383] | 2241 | ## DNSDB::getZoneLocation()
|
---|
[387] | 2242 | # Retrieve the default location for a zone.
|
---|
[383] | 2243 | # Takes a database handle, forward/reverse flag, and zone ID
|
---|
| 2244 | sub getZoneLocation {
|
---|
| 2245 | my $dbh = shift;
|
---|
| 2246 | my $revrec = shift;
|
---|
| 2247 | my $zoneid = shift;
|
---|
| 2248 |
|
---|
| 2249 | my ($loc) = $dbh->selectrow_array("SELECT default_location FROM ".
|
---|
| 2250 | ($revrec eq 'n' ? 'domains WHERE domain_id = ?' : 'revzones WHERE rdns_id = ?'),
|
---|
| 2251 | undef, ($zoneid));
|
---|
| 2252 | return $loc;
|
---|
| 2253 | } # end getZoneLocation()
|
---|
| 2254 |
|
---|
| 2255 |
|
---|
[18] | 2256 | ## DNSDB::addGroup()
|
---|
| 2257 | # Add a group
|
---|
[66] | 2258 | # Takes a database handle, group name, parent group, hashref for permissions,
|
---|
[292] | 2259 | # and optional template-vs-cloneme flag for the default records
|
---|
[18] | 2260 | # Returns a status code and message
|
---|
| 2261 | sub addGroup {
|
---|
| 2262 | $errstr = '';
|
---|
| 2263 | my $dbh = shift;
|
---|
[20] | 2264 | my $groupname = shift;
|
---|
| 2265 | my $pargroup = shift;
|
---|
[66] | 2266 | my $permissions = shift;
|
---|
[18] | 2267 |
|
---|
[66] | 2268 | # 0 indicates "custom", hardcoded.
|
---|
[18] | 2269 | # Any other value clones that group's default records, if it exists.
|
---|
[66] | 2270 | my $inherit = shift || 0;
|
---|
| 2271 | ##fixme: need a flag to indicate clone records or <?> ?
|
---|
[18] | 2272 |
|
---|
| 2273 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2274 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2275 | local $dbh->{AutoCommit} = 0;
|
---|
| 2276 | local $dbh->{RaiseError} = 1;
|
---|
| 2277 |
|
---|
[292] | 2278 | my ($group_id) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($groupname));
|
---|
[38] | 2279 |
|
---|
| 2280 | return ('FAIL', "Group already exists") if $group_id;
|
---|
| 2281 |
|
---|
[18] | 2282 | # Wrap all the SQL in a transaction
|
---|
| 2283 | eval {
|
---|
[292] | 2284 | $dbh->do("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)", undef, ($pargroup, $groupname) );
|
---|
[18] | 2285 |
|
---|
[292] | 2286 | my ($groupid) = $dbh->selectrow_array("SELECT currval('groups_group_id_seq')");
|
---|
[18] | 2287 |
|
---|
[292] | 2288 | # We work through the whole set of permissions instead of specifying them so
|
---|
| 2289 | # that when we add a new permission, we don't have to change the code anywhere
|
---|
| 2290 | # that doesn't explicitly deal with that specific permission.
|
---|
| 2291 | my @permvals;
|
---|
| 2292 | foreach (@permtypes) {
|
---|
| 2293 | if (!defined ($permissions->{$_})) {
|
---|
| 2294 | push @permvals, 0;
|
---|
| 2295 | } else {
|
---|
| 2296 | push @permvals, $permissions->{$_};
|
---|
[66] | 2297 | }
|
---|
[292] | 2298 | }
|
---|
| 2299 | $dbh->do("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")",
|
---|
| 2300 | undef, ($groupid, @permvals) );
|
---|
| 2301 | my ($permid) = $dbh->selectrow_array("SELECT currval('permissions_permission_id_seq')");
|
---|
| 2302 | $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
|
---|
[66] | 2303 |
|
---|
[292] | 2304 | # Default records
|
---|
[255] | 2305 | my $sthf = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
|
---|
[20] | 2306 | "VALUES ($groupid,?,?,?,?,?,?,?)");
|
---|
[255] | 2307 | my $sthr = $dbh->prepare("INSERT INTO default_rev_records (group_id,host,type,val,ttl) ".
|
---|
| 2308 | "VALUES ($groupid,?,?,?,?)");
|
---|
[66] | 2309 | if ($inherit) {
|
---|
[87] | 2310 | # Duplicate records from parent. Actually relying on inherited records feels
|
---|
| 2311 | # very fragile, and it would be problematic to roll over at a later time.
|
---|
[18] | 2312 | my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
[87] | 2313 | $sth2->execute($pargroup);
|
---|
[18] | 2314 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
[255] | 2315 | $sthf->execute(@clonedata);
|
---|
[18] | 2316 | }
|
---|
[255] | 2317 | # And now the reverse records
|
---|
[292] | 2318 | $sth2 = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
[255] | 2319 | $sth2->execute($pargroup);
|
---|
| 2320 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
| 2321 | $sthr->execute(@clonedata);
|
---|
| 2322 | }
|
---|
[18] | 2323 | } else {
|
---|
[66] | 2324 | ##fixme: Hardcoding is Bad, mmmmkaaaay?
|
---|
[18] | 2325 | # reasonable basic defaults for SOA, MX, NS, and minimal hosting
|
---|
| 2326 | # could load from a config file, but somewhere along the line we need hardcoded bits.
|
---|
[255] | 2327 | $sthf->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
|
---|
| 2328 | $sthf->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
|
---|
| 2329 | $sthf->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
|
---|
| 2330 | $sthf->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
|
---|
| 2331 | $sthf->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
|
---|
| 2332 | $sthf->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
|
---|
| 2333 | # reasonable basic defaults for generic reverse zone. Same as initial SQL tabledef.
|
---|
| 2334 | $sthr->execute('hostmaster.ADMINDOMAIN:ns1.ADMINDOMAIN', 6, '10800:3600:604800:10800', 86400);
|
---|
| 2335 | $sthr->execute('unused-%r.ADMINDOMAIN', 65283, 'ZONE', 3600);
|
---|
[18] | 2336 | }
|
---|
| 2337 |
|
---|
[292] | 2338 | _log($dbh, (group_id => $pargroup, entry => "Added group $groupname") );
|
---|
| 2339 |
|
---|
[18] | 2340 | # once we get here, we should have suceeded.
|
---|
| 2341 | $dbh->commit;
|
---|
| 2342 | }; # end eval
|
---|
| 2343 |
|
---|
| 2344 | if ($@) {
|
---|
| 2345 | my $msg = $@;
|
---|
| 2346 | eval { $dbh->rollback; };
|
---|
[292] | 2347 | if ($config{log_failures}) {
|
---|
| 2348 | _log($dbh, (group_id => $pargroup, entry => "Failed to add group $groupname: $msg") );
|
---|
| 2349 | $dbh->commit;
|
---|
| 2350 | }
|
---|
[18] | 2351 | return ('FAIL',$msg);
|
---|
| 2352 | }
|
---|
| 2353 |
|
---|
[292] | 2354 | return ('OK','OK');
|
---|
[18] | 2355 | } # end addGroup()
|
---|
| 2356 |
|
---|
| 2357 |
|
---|
[22] | 2358 | ## DNSDB::delGroup()
|
---|
| 2359 | # Delete a group.
|
---|
| 2360 | # Takes a group ID
|
---|
| 2361 | # Returns a status code and message
|
---|
| 2362 | sub delGroup {
|
---|
| 2363 | my $dbh = shift;
|
---|
| 2364 | my $groupid = shift;
|
---|
| 2365 |
|
---|
| 2366 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2367 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2368 | local $dbh->{AutoCommit} = 0;
|
---|
| 2369 | local $dbh->{RaiseError} = 1;
|
---|
| 2370 |
|
---|
| 2371 | ##fixme: locate "knowable" error conditions and deal with them before the eval
|
---|
[23] | 2372 | # ... or inside, whatever.
|
---|
[22] | 2373 | # -> domains still exist in group
|
---|
| 2374 | # -> ...
|
---|
[23] | 2375 | my $failmsg = '';
|
---|
[293] | 2376 | my $resultmsg = '';
|
---|
[22] | 2377 |
|
---|
[293] | 2378 | # collect some pieces for logging and error messages
|
---|
| 2379 | my $groupname = groupName($dbh,$groupid);
|
---|
| 2380 | my $parid = parentID($dbh, (id => $groupid, type => 'group'));
|
---|
| 2381 |
|
---|
[22] | 2382 | # Wrap all the SQL in a transaction
|
---|
| 2383 | eval {
|
---|
[293] | 2384 | # Check for Things in the group
|
---|
| 2385 | $failmsg = "Can't remove group $groupname";
|
---|
| 2386 | my ($grpcnt) = $dbh->selectrow_array("SELECT count(*) FROM groups WHERE parent_group_id=?", undef, ($groupid));
|
---|
| 2387 | die "$grpcnt groups still in group\n" if $grpcnt;
|
---|
| 2388 | my ($domcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($groupid));
|
---|
[23] | 2389 | die "$domcnt domains still in group\n" if $domcnt;
|
---|
[293] | 2390 | my ($usercnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($groupid));
|
---|
| 2391 | die "$usercnt users still in group\n" if $usercnt;
|
---|
[23] | 2392 |
|
---|
[293] | 2393 | $failmsg = "Failed to delete default records for $groupname";
|
---|
| 2394 | $dbh->do("DELETE from default_records WHERE group_id=?", undef, ($groupid));
|
---|
| 2395 | $failmsg = "Failed to delete default reverse records for $groupname";
|
---|
| 2396 | $dbh->do("DELETE from default_rev_records WHERE group_id=?", undef, ($groupid));
|
---|
| 2397 | $failmsg = "Failed to remove group $groupname";
|
---|
| 2398 | $dbh->do("DELETE from groups WHERE group_id=?", undef, ($groupid));
|
---|
[22] | 2399 |
|
---|
[293] | 2400 | _log($dbh, (group_id => $parid, entry => "Deleted group $groupname"));
|
---|
| 2401 | $resultmsg = "Deleted group $groupname";
|
---|
| 2402 |
|
---|
[22] | 2403 | # once we get here, we should have suceeded.
|
---|
| 2404 | $dbh->commit;
|
---|
| 2405 | }; # end eval
|
---|
| 2406 |
|
---|
| 2407 | if ($@) {
|
---|
| 2408 | my $msg = $@;
|
---|
| 2409 | eval { $dbh->rollback; };
|
---|
[293] | 2410 | if ($config{log_failures}) {
|
---|
| 2411 | _log($dbh, (group_id => $parid, entry => "$failmsg: $msg"));
|
---|
| 2412 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2413 | }
|
---|
[23] | 2414 | return ('FAIL',"$failmsg: $msg");
|
---|
[22] | 2415 | }
|
---|
[293] | 2416 |
|
---|
| 2417 | return ('OK',$resultmsg);
|
---|
[22] | 2418 | } # end delGroup()
|
---|
| 2419 |
|
---|
| 2420 |
|
---|
[19] | 2421 | ## DNSDB::getChildren()
|
---|
| 2422 | # Get a list of all groups whose parent^n is group <n>
|
---|
[24] | 2423 | # Takes a database handle, group ID, reference to an array to put the group IDs in,
|
---|
| 2424 | # and an optional flag to return only immediate children or all children-of-children
|
---|
| 2425 | # default to returning all children
|
---|
[19] | 2426 | # Calls itself
|
---|
| 2427 | sub getChildren {
|
---|
| 2428 | $errstr = '';
|
---|
| 2429 | my $dbh = shift;
|
---|
[20] | 2430 | my $rootgroup = shift;
|
---|
| 2431 | my $groupdest = shift;
|
---|
[24] | 2432 | my $immed = shift || 'all';
|
---|
[19] | 2433 |
|
---|
| 2434 | # special break for default group; otherwise we get stuck.
|
---|
[20] | 2435 | if ($rootgroup == 1) {
|
---|
[19] | 2436 | # by definition, group 1 is the Root Of All Groups
|
---|
[24] | 2437 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
|
---|
[331] | 2438 | ($immed ne 'all' ? " AND parent_group_id=1" : '')." ORDER BY group_name");
|
---|
[19] | 2439 | $sth->execute;
|
---|
| 2440 | while (my @this = $sth->fetchrow_array) {
|
---|
[20] | 2441 | push @$groupdest, @this;
|
---|
[19] | 2442 | }
|
---|
| 2443 | } else {
|
---|
[331] | 2444 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=? ORDER BY group_name");
|
---|
[20] | 2445 | $sth->execute($rootgroup);
|
---|
[19] | 2446 | return if $sth->rows == 0;
|
---|
[20] | 2447 | my @grouplist;
|
---|
| 2448 | while (my ($group) = $sth->fetchrow_array) {
|
---|
| 2449 | push @$groupdest, $group;
|
---|
[24] | 2450 | getChildren($dbh,$group,$groupdest) if $immed eq 'all';
|
---|
[19] | 2451 | }
|
---|
| 2452 | }
|
---|
| 2453 | } # end getChildren()
|
---|
| 2454 |
|
---|
| 2455 |
|
---|
[20] | 2456 | ## DNSDB::groupName()
|
---|
[17] | 2457 | # Return the group name based on a group ID
|
---|
| 2458 | # Takes a database handle and the group ID
|
---|
| 2459 | # Returns the group name or undef on failure
|
---|
[20] | 2460 | sub groupName {
|
---|
[13] | 2461 | $errstr = '';
|
---|
| 2462 | my $dbh = shift;
|
---|
[20] | 2463 | my $groupid = shift;
|
---|
| 2464 | my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
|
---|
| 2465 | $sth->execute($groupid);
|
---|
| 2466 | my ($groupname) = $sth->fetchrow_array();
|
---|
| 2467 | $errstr = $DBI::errstr if !$groupname;
|
---|
| 2468 | return $groupname if $groupname;
|
---|
| 2469 | } # end groupName
|
---|
[13] | 2470 |
|
---|
| 2471 |
|
---|
[314] | 2472 | ## DNSDB::getGroupCount()
|
---|
| 2473 | # Get count of subgroups in group or groups
|
---|
| 2474 | # Takes a database handle and hash containing:
|
---|
| 2475 | # - the "current" group
|
---|
| 2476 | # - an array of "acceptable" groups
|
---|
| 2477 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
| 2478 | # Returns an integer count of the resulting group list.
|
---|
| 2479 | sub getGroupCount {
|
---|
| 2480 | my $dbh = shift;
|
---|
| 2481 |
|
---|
| 2482 | my %args = @_;
|
---|
| 2483 |
|
---|
| 2484 | my @filterargs;
|
---|
| 2485 |
|
---|
| 2486 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2487 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2488 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2489 |
|
---|
| 2490 | my $sql = "SELECT count(*) FROM groups ".
|
---|
| 2491 | "WHERE parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2492 | ($args{startwith} ? " AND group_name ~* ?" : '').
|
---|
| 2493 | ($args{filter} ? " AND group_name ~* ?" : '');
|
---|
| 2494 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 2495 | $errstr = $dbh->errstr if !$count;
|
---|
| 2496 | return $count;
|
---|
| 2497 | } # end getGroupCount
|
---|
| 2498 |
|
---|
| 2499 |
|
---|
| 2500 | ## DNSDB::getGroupList()
|
---|
| 2501 | # Get a list of sub^n-groups in the specified group(s)
|
---|
| 2502 | # Takes the same arguments as getGroupCount() above
|
---|
| 2503 | # Returns an arrayref containing hashrefs suitable for feeding straight to HTML::Template
|
---|
| 2504 | sub getGroupList {
|
---|
| 2505 | my $dbh = shift;
|
---|
| 2506 |
|
---|
| 2507 | my %args = @_;
|
---|
| 2508 |
|
---|
| 2509 | my @filterargs;
|
---|
| 2510 |
|
---|
| 2511 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2512 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2513 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2514 |
|
---|
| 2515 | # protection against bad or missing arguments
|
---|
| 2516 | $args{sortorder} = 'ASC' if !$args{sortorder};
|
---|
[397] | 2517 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[314] | 2518 |
|
---|
| 2519 | # munge sortby for columns in database
|
---|
| 2520 | $args{sortby} = 'g.group_name' if $args{sortby} eq 'group';
|
---|
| 2521 | $args{sortby} = 'g2.group_name' if $args{sortby} eq 'parent';
|
---|
| 2522 |
|
---|
[385] | 2523 | my $sql = q(SELECT g.group_id AS groupid, g.group_name AS groupname, g2.group_name AS pgroup
|
---|
[314] | 2524 | FROM groups g
|
---|
| 2525 | INNER JOIN groups g2 ON g2.group_id=g.parent_group_id
|
---|
| 2526 | ).
|
---|
[385] | 2527 | " WHERE g.parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
[314] | 2528 | ($args{startwith} ? " AND g.group_name ~* ?" : '').
|
---|
| 2529 | ($args{filter} ? " AND g.group_name ~* ?" : '').
|
---|
| 2530 | " GROUP BY g.group_id, g.group_name, g2.group_name ".
|
---|
| 2531 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
| 2532 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
| 2533 | my $glist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 2534 | $errstr = $dbh->errstr if !$glist;
|
---|
[385] | 2535 |
|
---|
| 2536 | # LEFT JOINs make the result set balloon beyond sanity just to include counts;
|
---|
| 2537 | # this means there's lots of crunching needed to trim the result set back down.
|
---|
| 2538 | # So instead we track the order of the groups, and push the counts into the
|
---|
| 2539 | # arrayref result separately.
|
---|
| 2540 | ##fixme: put this whole sub in a transaction? might be
|
---|
| 2541 | # needed for accurate results on very busy systems.
|
---|
[386] | 2542 | ##fixme: large group lists need prepared statements?
|
---|
| 2543 | #my $ucsth = $dbh->prepare("SELECT count(*) FROM users WHERE group_id=?");
|
---|
| 2544 | #my $dcsth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
|
---|
| 2545 | #my $rcsth = $dbh->prepare("SELECT count(*) FROM revzones WHERE group_id=?");
|
---|
[385] | 2546 | foreach (@{$glist}) {
|
---|
[386] | 2547 | my ($ucnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 2548 | $$_{nusers} = $ucnt;
|
---|
| 2549 | my ($dcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 2550 | $$_{ndomains} = $dcnt;
|
---|
| 2551 | my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($$_{groupid}));
|
---|
| 2552 | $$_{nrevzones} = $rcnt;
|
---|
[385] | 2553 | }
|
---|
| 2554 |
|
---|
[314] | 2555 | return $glist;
|
---|
| 2556 | } # end getGroupList
|
---|
| 2557 |
|
---|
| 2558 |
|
---|
[118] | 2559 | ## DNSDB::groupID()
|
---|
| 2560 | # Return the group ID based on the group name
|
---|
| 2561 | # Takes a database handle and the group name
|
---|
| 2562 | # Returns the group ID or undef on failure
|
---|
| 2563 | sub groupID {
|
---|
| 2564 | $errstr = '';
|
---|
| 2565 | my $dbh = shift;
|
---|
| 2566 | my $group = shift;
|
---|
[406] | 2567 | my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($group) );
|
---|
[118] | 2568 | $errstr = $DBI::errstr if !$grpid;
|
---|
| 2569 | return $grpid if $grpid;
|
---|
| 2570 | } # end groupID()
|
---|
| 2571 |
|
---|
| 2572 |
|
---|
[24] | 2573 | ## DNSDB::addUser()
|
---|
[87] | 2574 | # Add a user.
|
---|
| 2575 | # Takes a DB handle, username, group ID, password, state (active/inactive).
|
---|
| 2576 | # Optionally accepts:
|
---|
| 2577 | # user type (user/admin) - defaults to user
|
---|
| 2578 | # permissions string - defaults to inherit from group
|
---|
| 2579 | # three valid forms:
|
---|
| 2580 | # i - Inherit permissions
|
---|
| 2581 | # c:<user_id> - Clone permissions from <user_id>
|
---|
| 2582 | # C:<permission list> - Set these specific permissions
|
---|
| 2583 | # first name - defaults to username
|
---|
| 2584 | # last name - defaults to blank
|
---|
| 2585 | # phone - defaults to blank (could put other data within column def)
|
---|
[90] | 2586 | # Returns (OK,<uid>) on success, (FAIL,<message>) on failure
|
---|
[24] | 2587 | sub addUser {
|
---|
| 2588 | $errstr = '';
|
---|
| 2589 | my $dbh = shift;
|
---|
| 2590 | my $username = shift;
|
---|
| 2591 | my $group = shift;
|
---|
| 2592 | my $pass = shift;
|
---|
| 2593 | my $state = shift;
|
---|
[25] | 2594 |
|
---|
[90] | 2595 | return ('FAIL', "Missing one or more required entries") if !defined($state);
|
---|
| 2596 | return ('FAIL', "Username must not be blank") if !$username;
|
---|
[87] | 2597 |
|
---|
[408] | 2598 | # Munge in some alternate state values
|
---|
| 2599 | $state = 1 if $state =~ /^active$/;
|
---|
| 2600 | $state = 1 if $state =~ /^on$/;
|
---|
| 2601 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 2602 | $state = 0 if $state =~ /^off$/;
|
---|
| 2603 |
|
---|
[25] | 2604 | my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
|
---|
| 2605 |
|
---|
[67] | 2606 | my $permstring = shift || 'i'; # default is to inhert permissions from group
|
---|
| 2607 |
|
---|
[25] | 2608 | my $fname = shift || $username;
|
---|
[24] | 2609 | my $lname = shift || '';
|
---|
[25] | 2610 | my $phone = shift || ''; # not going format-check
|
---|
[24] | 2611 |
|
---|
[38] | 2612 | my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
|
---|
[24] | 2613 | my $user_id;
|
---|
| 2614 |
|
---|
[38] | 2615 | # quick check to start to see if we've already got one
|
---|
| 2616 | $sth->execute($username);
|
---|
| 2617 | ($user_id) = $sth->fetchrow_array;
|
---|
| 2618 |
|
---|
| 2619 | return ('FAIL', "User already exists") if $user_id;
|
---|
| 2620 |
|
---|
[24] | 2621 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2622 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2623 | local $dbh->{AutoCommit} = 0;
|
---|
| 2624 | local $dbh->{RaiseError} = 1;
|
---|
| 2625 |
|
---|
| 2626 | # Wrap all the SQL in a transaction
|
---|
| 2627 | eval {
|
---|
[87] | 2628 | # insert the user... note we set inherited perms by default since
|
---|
| 2629 | # it's simple and cleans up some other bits of state
|
---|
| 2630 | my $sth = $dbh->prepare("INSERT INTO users ".
|
---|
| 2631 | "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
|
---|
| 2632 | "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
|
---|
| 2633 | $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);
|
---|
[24] | 2634 |
|
---|
| 2635 | # get the ID...
|
---|
[94] | 2636 | ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");
|
---|
[24] | 2637 |
|
---|
[87] | 2638 | # Permissions! Gotta set'em all!
|
---|
[401] | 2639 | die "Invalid permission string $permstring\n"
|
---|
[87] | 2640 | if $permstring !~ /^(?:
|
---|
| 2641 | i # inherit
|
---|
| 2642 | |c:\d+ # clone
|
---|
| 2643 | # custom. no, the leading , is not a typo
|
---|
[391] | 2644 | |C:(?:,(?:group|user|domain|record|location|self)_(?:edit|create|delete|locchg|view))*
|
---|
[87] | 2645 | )$/x;
|
---|
| 2646 | # bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
|
---|
| 2647 | if ($permstring ne 'i') {
|
---|
| 2648 | # for cloned or custom permissions, we have to create a new permissions entry.
|
---|
| 2649 | my $clonesrc = $group;
|
---|
| 2650 | if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
|
---|
| 2651 | $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
|
---|
| 2652 | "SELECT $permlist,? FROM permissions WHERE permission_id=".
|
---|
| 2653 | "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
|
---|
| 2654 | undef, ($user_id,$clonesrc) );
|
---|
| 2655 | $dbh->do("UPDATE users SET permission_id=".
|
---|
| 2656 | "(SELECT permission_id FROM permissions WHERE user_id=?) ".
|
---|
| 2657 | "WHERE user_id=?", undef, ($user_id, $user_id) );
|
---|
| 2658 | }
|
---|
| 2659 | if ($permstring =~ /^C:/) {
|
---|
| 2660 | # finally for custom permissions, we set the passed-in permissions (and unset
|
---|
| 2661 | # any that might have been brought in by the clone operation above)
|
---|
| 2662 | my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
|
---|
| 2663 | undef, ($user_id) );
|
---|
| 2664 | foreach (@permtypes) {
|
---|
| 2665 | if ($permstring =~ /,$_/) {
|
---|
| 2666 | $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
|
---|
| 2667 | } else {
|
---|
| 2668 | $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
|
---|
| 2669 | }
|
---|
| 2670 | }
|
---|
| 2671 | }
|
---|
| 2672 |
|
---|
| 2673 | $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
|
---|
| 2674 |
|
---|
[25] | 2675 | ##fixme: add another table to hold name/email for log table?
|
---|
| 2676 |
|
---|
[294] | 2677 | _log($dbh, (group_id => $group, entry => "Added user $username ($fname $lname)"));
|
---|
[24] | 2678 | # once we get here, we should have suceeded.
|
---|
| 2679 | $dbh->commit;
|
---|
| 2680 | }; # end eval
|
---|
| 2681 |
|
---|
| 2682 | if ($@) {
|
---|
| 2683 | my $msg = $@;
|
---|
| 2684 | eval { $dbh->rollback; };
|
---|
[294] | 2685 | if ($config{log_failures}) {
|
---|
| 2686 | _log($dbh, (group_id => $group, entry => "Error adding user $username: $msg"));
|
---|
| 2687 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2688 | }
|
---|
| 2689 | return ('FAIL',"Error adding user $username: $msg");
|
---|
[24] | 2690 | }
|
---|
[294] | 2691 |
|
---|
| 2692 | return ('OK',"User $username ($fname $lname) added");
|
---|
[24] | 2693 | } # end addUser
|
---|
| 2694 |
|
---|
| 2695 |
|
---|
[325] | 2696 | ## DNSDB::getUserCount()
|
---|
| 2697 | # Get count of users in group
|
---|
| 2698 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
| 2699 | # - a reference list of secondary groups
|
---|
| 2700 | # - a filter string
|
---|
| 2701 | # - a "Starts with" string
|
---|
| 2702 | sub getUserCount {
|
---|
| 2703 | my $dbh = shift;
|
---|
| 2704 |
|
---|
| 2705 | my %args = @_;
|
---|
| 2706 |
|
---|
| 2707 | my @filterargs;
|
---|
| 2708 |
|
---|
| 2709 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2710 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2711 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2712 |
|
---|
| 2713 |
|
---|
| 2714 | my $sql = "SELECT count(*) FROM users ".
|
---|
| 2715 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2716 | ($args{startwith} ? " AND username ~* ?" : '').
|
---|
| 2717 | ($args{filter} ? " AND username ~* ?" : '');
|
---|
| 2718 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 2719 | $errstr = $dbh->errstr if !$count;
|
---|
| 2720 | return $count;
|
---|
| 2721 | } # end getUserCount()
|
---|
| 2722 |
|
---|
| 2723 |
|
---|
| 2724 | ## DNSDB::getUserList()
|
---|
| 2725 | # Get list of users
|
---|
| 2726 | # Takes the same arguments as getUserCount() above, plus optional:
|
---|
| 2727 | # - sort field
|
---|
| 2728 | # - sort order
|
---|
| 2729 | # - offset/return-all-everything flag (defaults to $perpage records)
|
---|
| 2730 | sub getUserList {
|
---|
| 2731 | my $dbh = shift;
|
---|
| 2732 |
|
---|
| 2733 | my %args = @_;
|
---|
| 2734 |
|
---|
| 2735 | my @filterargs;
|
---|
| 2736 |
|
---|
| 2737 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 2738 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 2739 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 2740 |
|
---|
| 2741 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
| 2742 | my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
| 2743 | fname => 'fname');
|
---|
| 2744 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 2745 |
|
---|
| 2746 | # protection against bad or missing arguments
|
---|
| 2747 | $args{sortorder} = 'ASC' if !$args{sortorder};
|
---|
| 2748 | $args{sortby} = 'u.username' if !$args{sortby};
|
---|
[397] | 2749 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[325] | 2750 |
|
---|
| 2751 | my $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ".
|
---|
| 2752 | "FROM users u ".
|
---|
| 2753 | "INNER JOIN groups g ON u.group_id=g.group_id ".
|
---|
| 2754 | "WHERE u.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 2755 | ($args{startwith} ? " AND u.username ~* ?" : '').
|
---|
| 2756 | ($args{filter} ? " AND u.username ~* ?" : '').
|
---|
[401] | 2757 | " AND NOT u.type = 'R' ".
|
---|
[325] | 2758 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
| 2759 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
| 2760 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 2761 | $errstr = $dbh->errstr if !$ulist;
|
---|
| 2762 | return $ulist;
|
---|
| 2763 | } # end getUserList()
|
---|
| 2764 |
|
---|
| 2765 |
|
---|
[326] | 2766 | ## DNSDB::getUserDropdown()
|
---|
| 2767 | # Get a list of usernames for use in a dropdown menu.
|
---|
| 2768 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
| 2769 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
| 2770 | sub getUserDropdown {
|
---|
| 2771 | my $dbh = shift;
|
---|
| 2772 | my $grp = shift;
|
---|
| 2773 | my $sel = shift || 0;
|
---|
| 2774 |
|
---|
| 2775 | my $sth = $dbh->prepare("SELECT username,user_id FROM users WHERE group_id=?");
|
---|
| 2776 | $sth->execute($grp);
|
---|
| 2777 |
|
---|
| 2778 | my @userlist;
|
---|
| 2779 | while (my ($username,$uid) = $sth->fetchrow_array) {
|
---|
| 2780 | my %row = (
|
---|
| 2781 | username => $username,
|
---|
| 2782 | uid => $uid,
|
---|
| 2783 | selected => ($sel == $uid ? 1 : 0)
|
---|
| 2784 | );
|
---|
| 2785 | push @userlist, \%row;
|
---|
| 2786 | }
|
---|
| 2787 | return \@userlist;
|
---|
| 2788 | } # end getUserDropdown()
|
---|
| 2789 |
|
---|
| 2790 |
|
---|
[55] | 2791 | ## DNSDB::checkUser()
|
---|
| 2792 | # Check user/pass combo on login
|
---|
| 2793 | sub checkUser {
|
---|
| 2794 | my $dbh = shift;
|
---|
| 2795 | my $user = shift;
|
---|
[56] | 2796 | my $inpass = shift;
|
---|
[55] | 2797 |
|
---|
| 2798 | my $sth = $dbh->prepare("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?");
|
---|
| 2799 | $sth->execute($user);
|
---|
| 2800 | my ($uid,$gid,$pass,$fname,$lname) = $sth->fetchrow_array;
|
---|
| 2801 | my $loginfailed = 1 if !defined($uid);
|
---|
| 2802 |
|
---|
| 2803 | if ($pass =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
|
---|
[56] | 2804 | $loginfailed = 1 if $pass ne unix_md5_crypt($inpass,$1);
|
---|
[55] | 2805 | } else {
|
---|
[56] | 2806 | $loginfailed = 1 if $pass ne $inpass;
|
---|
[55] | 2807 | }
|
---|
| 2808 |
|
---|
| 2809 | # nnnngggg
|
---|
| 2810 | return ($uid, $gid);
|
---|
| 2811 | } # end checkUser
|
---|
| 2812 |
|
---|
| 2813 |
|
---|
[83] | 2814 | ## DNSDB:: updateUser()
|
---|
[90] | 2815 | # Update general data about user
|
---|
[83] | 2816 | sub updateUser {
|
---|
| 2817 | my $dbh = shift;
|
---|
[118] | 2818 |
|
---|
| 2819 | ##fixme: tweak calling convention so that we can update any given bit of data
|
---|
[83] | 2820 | my $uid = shift;
|
---|
| 2821 | my $username = shift;
|
---|
| 2822 | my $group = shift;
|
---|
| 2823 | my $pass = shift;
|
---|
| 2824 | my $state = shift;
|
---|
[87] | 2825 | my $type = shift || 'u';
|
---|
[83] | 2826 | my $fname = shift || $username;
|
---|
| 2827 | my $lname = shift || '';
|
---|
| 2828 | my $phone = shift || ''; # not going format-check
|
---|
| 2829 |
|
---|
[294] | 2830 | my $resultmsg = '';
|
---|
[83] | 2831 |
|
---|
[411] | 2832 | # Munge in some alternate state values
|
---|
| 2833 | $state = 1 if $state =~ /^active$/;
|
---|
| 2834 | $state = 1 if $state =~ /^on$/;
|
---|
| 2835 | $state = 0 if $state =~ /^inactive$/;
|
---|
| 2836 | $state = 0 if $state =~ /^off$/;
|
---|
| 2837 |
|
---|
[83] | 2838 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2839 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2840 | local $dbh->{AutoCommit} = 0;
|
---|
| 2841 | local $dbh->{RaiseError} = 1;
|
---|
| 2842 |
|
---|
| 2843 | my $sth;
|
---|
| 2844 |
|
---|
| 2845 | # Password can be left blank; if so we assume there's one on file.
|
---|
| 2846 | # Actual blank passwords are bad, mm'kay?
|
---|
| 2847 | if (!$pass) {
|
---|
[294] | 2848 | ($pass) = $dbh->selectrow_array("SELECT password FROM users WHERE user_id=?", undef, ($uid));
|
---|
[83] | 2849 | } else {
|
---|
| 2850 | $pass = unix_md5_crypt($pass);
|
---|
| 2851 | }
|
---|
| 2852 |
|
---|
| 2853 | eval {
|
---|
[294] | 2854 | $dbh->do("UPDATE users SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?".
|
---|
| 2855 | " WHERE user_id=?", undef, ($username, $pass, $fname, $lname, $phone, $type, $state, $uid));
|
---|
| 2856 | $resultmsg = "Updated user info for $username ($fname $lname)";
|
---|
| 2857 | _log($dbh, group_id => $group, entry => $resultmsg);
|
---|
[83] | 2858 | $dbh->commit;
|
---|
| 2859 | };
|
---|
| 2860 | if ($@) {
|
---|
| 2861 | my $msg = $@;
|
---|
| 2862 | eval { $dbh->rollback; };
|
---|
[294] | 2863 | if ($config{log_failures}) {
|
---|
| 2864 | _log($dbh, (group_id => $group, entry => "Error updating user $username: $msg"));
|
---|
| 2865 | $dbh->commit; # since we enabled transactions earlier
|
---|
| 2866 | }
|
---|
| 2867 | return ('FAIL',"Error updating user $username: $msg");
|
---|
[83] | 2868 | }
|
---|
[294] | 2869 |
|
---|
| 2870 | return ('OK',$resultmsg);
|
---|
[83] | 2871 | } # end updateUser()
|
---|
| 2872 |
|
---|
| 2873 |
|
---|
[24] | 2874 | ## DNSDB::delUser()
|
---|
[297] | 2875 | # Delete a user.
|
---|
| 2876 | # Takes a database handle and user ID
|
---|
| 2877 | # Returns a success/failure code and matching message
|
---|
[24] | 2878 | sub delUser {
|
---|
[25] | 2879 | my $dbh = shift;
|
---|
| 2880 | my $userid = shift;
|
---|
| 2881 |
|
---|
[297] | 2882 | return ('FAIL',"Bad userid") if !defined($userid);
|
---|
[25] | 2883 |
|
---|
[297] | 2884 | my $userdata = getUserData($dbh, $userid);
|
---|
[25] | 2885 |
|
---|
[297] | 2886 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2887 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2888 | local $dbh->{AutoCommit} = 0;
|
---|
| 2889 | local $dbh->{RaiseError} = 1;
|
---|
[25] | 2890 |
|
---|
[297] | 2891 | eval {
|
---|
| 2892 | $dbh->do("DELETE FROM users WHERE user_id=?", undef, ($userid));
|
---|
| 2893 | _log($dbh, (group_id => $userdata->{group_id},
|
---|
| 2894 | entry => "Deleted user ID $userid/".$userdata->{username}.
|
---|
| 2895 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")") );
|
---|
| 2896 | $dbh->commit;
|
---|
| 2897 | };
|
---|
| 2898 | if ($@) {
|
---|
| 2899 | my $msg = $@;
|
---|
| 2900 | eval { $dbh->rollback; };
|
---|
| 2901 | if ($config{log_failures}) {
|
---|
| 2902 | _log($dbh, (group_id => $userdata->{group_id}, entry => "Error deleting user ID ".
|
---|
| 2903 | "$userid/".$userdata->{username}.": $msg") );
|
---|
| 2904 | $dbh->commit;
|
---|
| 2905 | }
|
---|
| 2906 | return ('FAIL',"Error deleting user $userid/".$userdata->{username}.": $msg");
|
---|
| 2907 | }
|
---|
| 2908 |
|
---|
| 2909 | return ('OK',"Deleted user ".$userdata->{username}." (".$userdata->{firstname}." ".$userdata->{lastname}.")");
|
---|
[24] | 2910 | } # end delUser
|
---|
| 2911 |
|
---|
| 2912 |
|
---|
[25] | 2913 | ## DNSDB::userFullName()
|
---|
| 2914 | # Return a pretty string!
|
---|
| 2915 | # Takes a user_id and optional printf-ish string to indicate which pieces where:
|
---|
| 2916 | # %u for the username
|
---|
| 2917 | # %f for the first name
|
---|
| 2918 | # %l for the last name
|
---|
| 2919 | # All other text in the passed string will be left as-is.
|
---|
| 2920 | ##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
|
---|
| 2921 | sub userFullName {
|
---|
| 2922 | $errstr = '';
|
---|
| 2923 | my $dbh = shift;
|
---|
| 2924 | my $userid = shift;
|
---|
| 2925 | my $fullformat = shift || '%f %l (%u)';
|
---|
| 2926 | my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
|
---|
| 2927 | $sth->execute($userid);
|
---|
| 2928 | my ($uname,$fname,$lname) = $sth->fetchrow_array();
|
---|
| 2929 | $errstr = $DBI::errstr if !$uname;
|
---|
| 2930 |
|
---|
| 2931 | $fullformat =~ s/\%u/$uname/g;
|
---|
| 2932 | $fullformat =~ s/\%f/$fname/g;
|
---|
| 2933 | $fullformat =~ s/\%l/$lname/g;
|
---|
| 2934 |
|
---|
| 2935 | return $fullformat;
|
---|
| 2936 | } # end userFullName
|
---|
| 2937 |
|
---|
| 2938 |
|
---|
[51] | 2939 | ## DNSDB::userStatus()
|
---|
| 2940 | # Sets and/or returns a user's status
|
---|
| 2941 | # Takes a database handle, user ID and optionally a status argument
|
---|
| 2942 | # Returns undef on errors.
|
---|
| 2943 | sub userStatus {
|
---|
| 2944 | my $dbh = shift;
|
---|
| 2945 | my $id = shift;
|
---|
[296] | 2946 | my $newstatus = shift || 'mu';
|
---|
[51] | 2947 |
|
---|
| 2948 | return undef if $id !~ /^\d+$/;
|
---|
| 2949 |
|
---|
[296] | 2950 | my $userdata = getUserData($dbh, $id);
|
---|
[51] | 2951 |
|
---|
[296] | 2952 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 2953 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 2954 | local $dbh->{AutoCommit} = 0;
|
---|
| 2955 | local $dbh->{RaiseError} = 1;
|
---|
| 2956 |
|
---|
| 2957 | if ($newstatus ne 'mu') {
|
---|
| 2958 | # ooo, fun! let's see what we were passed for status
|
---|
| 2959 | eval {
|
---|
| 2960 | $newstatus = 0 if $newstatus eq 'useroff';
|
---|
| 2961 | $newstatus = 1 if $newstatus eq 'useron';
|
---|
| 2962 | $dbh->do("UPDATE users SET status=? WHERE user_id=?", undef, ($newstatus, $id));
|
---|
| 2963 |
|
---|
[297] | 2964 | $resultstr = ($newstatus ? 'Enabled' : 'Disabled')." user ".$userdata->{username}.
|
---|
| 2965 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")";
|
---|
[296] | 2966 |
|
---|
| 2967 | my %loghash;
|
---|
| 2968 | $loghash{group_id} = parentID($dbh, (id => $id, type => 'user'));
|
---|
| 2969 | $loghash{entry} = $resultstr;
|
---|
| 2970 | _log($dbh, %loghash);
|
---|
| 2971 |
|
---|
| 2972 | $dbh->commit;
|
---|
| 2973 | };
|
---|
| 2974 | if ($@) {
|
---|
| 2975 | my $msg = $@;
|
---|
| 2976 | eval { $dbh->rollback; };
|
---|
| 2977 | $resultstr = '';
|
---|
| 2978 | $errstr = $msg;
|
---|
| 2979 | ##fixme: failure logging?
|
---|
| 2980 | return;
|
---|
[51] | 2981 | }
|
---|
| 2982 | }
|
---|
| 2983 |
|
---|
[296] | 2984 | my ($status) = $dbh->selectrow_array("SELECT status FROM users WHERE user_id=?", undef, ($id));
|
---|
[51] | 2985 | return $status;
|
---|
| 2986 | } # end userStatus()
|
---|
| 2987 |
|
---|
| 2988 |
|
---|
[83] | 2989 | ## DNSDB::getUserData()
|
---|
| 2990 | # Get misc user data for display
|
---|
| 2991 | sub getUserData {
|
---|
| 2992 | my $dbh = shift;
|
---|
| 2993 | my $uid = shift;
|
---|
| 2994 |
|
---|
| 2995 | my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
|
---|
| 2996 | "FROM users WHERE user_id=?");
|
---|
| 2997 | $sth->execute($uid);
|
---|
| 2998 | return $sth->fetchrow_hashref();
|
---|
| 2999 | } # end getUserData()
|
---|
| 3000 |
|
---|
| 3001 |
|
---|
[370] | 3002 | ## DNSDB::addLoc()
|
---|
[375] | 3003 | # Add a new location.
|
---|
| 3004 | # Takes a database handle, group ID, short and long description, and a comma-separated
|
---|
| 3005 | # list of IP addresses.
|
---|
| 3006 | # Returns ('OK',<location>) on success, ('FAIL',<failmsg>) on failure
|
---|
| 3007 | sub addLoc {
|
---|
| 3008 | my $dbh = shift;
|
---|
| 3009 | my $grp = shift;
|
---|
| 3010 | my $shdesc = shift;
|
---|
| 3011 | my $comments = shift;
|
---|
| 3012 | my $iplist = shift;
|
---|
[370] | 3013 |
|
---|
[375] | 3014 | # $shdesc gets set to the generated location ID if possible, but these can be de-undefined here.
|
---|
| 3015 | $comments = '' if !$comments;
|
---|
| 3016 | $iplist = '' if !$iplist;
|
---|
| 3017 |
|
---|
| 3018 | my $loc;
|
---|
| 3019 |
|
---|
| 3020 | # Generate a location ID. This is, by spec, a two-character widget. We'll use [a-z][a-z]
|
---|
| 3021 | # for now; 676 locations should satisfy all but the largest of the huge networks.
|
---|
| 3022 | # Not sure whether these are case-sensitive, or what other rules might apply - in any case
|
---|
| 3023 | # the absolute maximum is 16K (256*256) since it's parsed by tinydns as a two-character field.
|
---|
| 3024 |
|
---|
| 3025 | # add just after "my $origloc = $loc;":
|
---|
| 3026 | # # These expand the possible space from 26^2 to 52^2 [* note in testing only 2052 were achieved],
|
---|
| 3027 | # # and wrap it around.
|
---|
| 3028 | # # Yes, they skip a couple of possibles. No, I don't care.
|
---|
| 3029 | # $loc = 'aA' if $loc eq 'zz';
|
---|
| 3030 | # $loc = 'Aa' if $loc eq 'zZ';
|
---|
| 3031 | # $loc = 'ZA' if $loc eq 'Zz';
|
---|
| 3032 | # $loc = 'aa' if $loc eq 'ZZ';
|
---|
| 3033 |
|
---|
| 3034 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3035 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3036 | local $dbh->{AutoCommit} = 0;
|
---|
| 3037 | local $dbh->{RaiseError} = 1;
|
---|
| 3038 |
|
---|
| 3039 | ##fixme: There is probably a far better way to do this. Sequential increments
|
---|
| 3040 | # are marginally less stupid that pure random generation though, and the existence
|
---|
| 3041 | # check makes sure we don't stomp on an imported one.
|
---|
| 3042 |
|
---|
| 3043 | eval {
|
---|
| 3044 | # Get the "last" location. Note this is the only use for loc_id, because selecting on location Does Funky Things
|
---|
| 3045 | ($loc) = $dbh->selectrow_array("SELECT location FROM locations ORDER BY loc_id DESC LIMIT 1");
|
---|
| 3046 | ($loc) = ($loc =~ /^(..)/);
|
---|
| 3047 | my $origloc = $loc;
|
---|
[446] | 3048 | $loc = 'aa' if !$loc;
|
---|
[375] | 3049 | # Make a change...
|
---|
| 3050 | $loc++;
|
---|
| 3051 | # ... and keep changing if it exists
|
---|
| 3052 | while ($dbh->selectrow_array("SELECT count(*) FROM locations WHERE location LIKE ?", undef, ($loc.'%'))) {
|
---|
| 3053 | $loc++;
|
---|
| 3054 | ($loc) = ($loc =~ /^(..)/);
|
---|
| 3055 | die "too many locations in use, can't add another one\n" if $loc eq $origloc;
|
---|
| 3056 | ##fixme: really need to handle this case faster somehow
|
---|
| 3057 | #if $loc eq $origloc die "<thwap> bad admin: all locations used, your network is too fragmented";
|
---|
| 3058 | }
|
---|
| 3059 | # And now we should have a unique location. tinydns fundamentally limits the
|
---|
| 3060 | # number of these but there's no doc on what characters are valid.
|
---|
| 3061 | $shdesc = $loc if !$shdesc;
|
---|
| 3062 | $dbh->do("INSERT INTO locations (location, group_id, iplist, description, comments) VALUES (?,?,?,?,?)",
|
---|
| 3063 | undef, ($loc, $grp, $iplist, $shdesc, $comments) );
|
---|
[377] | 3064 | _log($dbh, entry => "Added location ($shdesc, '$iplist')");
|
---|
| 3065 | $dbh->commit;
|
---|
[375] | 3066 | };
|
---|
| 3067 | if ($@) {
|
---|
| 3068 | my $msg = $@;
|
---|
| 3069 | eval { $dbh->rollback; };
|
---|
| 3070 | if ($config{log_failures}) {
|
---|
| 3071 | $shdesc = $loc if !$shdesc;
|
---|
| 3072 | _log($dbh, (entry => "Failed adding location ($shdesc, '$iplist'): $msg"));
|
---|
| 3073 | $dbh->commit;
|
---|
| 3074 | }
|
---|
| 3075 | return ('FAIL',$msg);
|
---|
| 3076 | }
|
---|
| 3077 |
|
---|
| 3078 | return ('OK',$loc);
|
---|
[377] | 3079 | } # end addLoc()
|
---|
[375] | 3080 |
|
---|
| 3081 |
|
---|
[370] | 3082 | ## DNSDB::updateLoc()
|
---|
[428] | 3083 | # Update details of a location.
|
---|
| 3084 | # Takes a database handle, location ID, group ID, short description,
|
---|
| 3085 | # long comments/notes, and comma/space-separated IP list
|
---|
| 3086 | # Returns a result code and message
|
---|
[377] | 3087 | sub updateLoc {
|
---|
| 3088 | my $dbh = shift;
|
---|
| 3089 | my $loc = shift;
|
---|
| 3090 | my $grp = shift;
|
---|
| 3091 | my $shdesc = shift;
|
---|
| 3092 | my $comments = shift;
|
---|
| 3093 | my $iplist = shift;
|
---|
[370] | 3094 |
|
---|
[377] | 3095 | $shdesc = '' if !$shdesc;
|
---|
| 3096 | $comments = '' if !$comments;
|
---|
| 3097 | $iplist = '' if !$iplist;
|
---|
| 3098 |
|
---|
| 3099 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3100 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3101 | local $dbh->{AutoCommit} = 0;
|
---|
| 3102 | local $dbh->{RaiseError} = 1;
|
---|
| 3103 |
|
---|
| 3104 | my $oldloc = getLoc($dbh, $loc);
|
---|
| 3105 | my $okmsg = "Updated location (".$oldloc->{description}.", '".$oldloc->{iplist}."') to ($shdesc, '$iplist')";
|
---|
| 3106 |
|
---|
| 3107 | eval {
|
---|
| 3108 | $dbh->do("UPDATE locations SET group_id=?,iplist=?,description=?,comments=? WHERE location=?",
|
---|
| 3109 | undef, ($grp, $iplist, $shdesc, $comments, $loc) );
|
---|
| 3110 | _log($dbh, entry => $okmsg);
|
---|
| 3111 | $dbh->commit;
|
---|
| 3112 | };
|
---|
| 3113 | if ($@) {
|
---|
| 3114 | my $msg = $@;
|
---|
| 3115 | eval { $dbh->rollback; };
|
---|
| 3116 | if ($config{log_failures}) {
|
---|
| 3117 | $shdesc = $loc if !$shdesc;
|
---|
| 3118 | _log($dbh, (entry => "Failed updating location ($shdesc, '$iplist'): $msg"));
|
---|
| 3119 | $dbh->commit;
|
---|
| 3120 | }
|
---|
| 3121 | return ('FAIL',$msg);
|
---|
| 3122 | }
|
---|
| 3123 |
|
---|
| 3124 | return ('OK',$okmsg);
|
---|
| 3125 | } # end updateLoc()
|
---|
| 3126 |
|
---|
| 3127 |
|
---|
[370] | 3128 | ## DNSDB::delLoc()
|
---|
[428] | 3129 | sub delLoc {
|
---|
| 3130 | my $dbh = shift;
|
---|
| 3131 | my $loc = shift;
|
---|
[370] | 3132 |
|
---|
[428] | 3133 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3134 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3135 | local $dbh->{AutoCommit} = 0;
|
---|
| 3136 | local $dbh->{RaiseError} = 1;
|
---|
[370] | 3137 |
|
---|
[428] | 3138 | my $oldloc = getLoc($dbh, $loc);
|
---|
| 3139 | my $olddesc = ($oldloc->{description} ? $oldloc->{description} : $loc);
|
---|
| 3140 | my $okmsg = "Deleted location ($olddesc, '".$oldloc->{iplist}."')";
|
---|
| 3141 |
|
---|
| 3142 | eval {
|
---|
| 3143 | # Check for records with this location first. Deleting a location without deleting records
|
---|
| 3144 | # tagged for that location will render them unpublished without other warning.
|
---|
| 3145 | my ($r) = $dbh->selectrow_array("SELECT record_id FROM records WHERE location=? LIMIT 1", undef, ($loc) );
|
---|
| 3146 | die "Records still exist in location $olddesc\n" if $r;
|
---|
| 3147 | $dbh->do("DELETE FROM locations WHERE location=?", undef, ($loc) );
|
---|
| 3148 | _log($dbh, entry => $okmsg);
|
---|
| 3149 | $dbh->commit;
|
---|
| 3150 | };
|
---|
| 3151 | if ($@) {
|
---|
| 3152 | my $msg = $@;
|
---|
| 3153 | eval { $dbh->rollback; };
|
---|
| 3154 | if ($config{log_failures}) {
|
---|
| 3155 | _log($dbh, (entry => "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg"));
|
---|
| 3156 | $dbh->commit;
|
---|
| 3157 | }
|
---|
| 3158 | return ('FAIL', "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
|
---|
| 3159 | }
|
---|
| 3160 |
|
---|
| 3161 | return ('OK',$okmsg);
|
---|
| 3162 | } # end delLoc()
|
---|
| 3163 |
|
---|
| 3164 |
|
---|
[375] | 3165 | ## DNSDB::getLoc()
|
---|
[428] | 3166 | # Get details about a location/view
|
---|
| 3167 | # Takes a database handle and location ID.
|
---|
| 3168 | # Returns a reference to a hash containing the group ID, IP list, description, and comments/notes
|
---|
[375] | 3169 | sub getLoc {
|
---|
| 3170 | my $dbh = shift;
|
---|
| 3171 | my $loc = shift;
|
---|
| 3172 |
|
---|
| 3173 | my $sth = $dbh->prepare("SELECT group_id,iplist,description,comments FROM locations WHERE location=?");
|
---|
| 3174 | $sth->execute($loc);
|
---|
| 3175 | return $sth->fetchrow_hashref();
|
---|
| 3176 | } # end getLoc()
|
---|
| 3177 |
|
---|
| 3178 |
|
---|
[370] | 3179 | ## DNSDB::getLocCount()
|
---|
| 3180 | # Get count of locations/views
|
---|
| 3181 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
| 3182 | # - a reference list of secondary groups
|
---|
| 3183 | # - a filter string
|
---|
| 3184 | # - a "Starts with" string
|
---|
| 3185 | sub getLocCount {
|
---|
| 3186 | my $dbh = shift;
|
---|
| 3187 |
|
---|
| 3188 | my %args = @_;
|
---|
| 3189 |
|
---|
| 3190 | my @filterargs;
|
---|
| 3191 |
|
---|
| 3192 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3193 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3194 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3195 |
|
---|
| 3196 |
|
---|
| 3197 | my $sql = "SELECT count(*) FROM locations ".
|
---|
| 3198 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3199 | ($args{startwith} ? " AND description ~* ?" : '').
|
---|
| 3200 | ($args{filter} ? " AND description ~* ?" : '');
|
---|
| 3201 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
| 3202 | $errstr = $dbh->errstr if !$count;
|
---|
| 3203 | return $count;
|
---|
| 3204 | } # end getLocCount()
|
---|
| 3205 |
|
---|
| 3206 |
|
---|
| 3207 | ## DNSDB::getLocList()
|
---|
| 3208 | sub getLocList {
|
---|
| 3209 | my $dbh = shift;
|
---|
| 3210 |
|
---|
| 3211 | my %args = @_;
|
---|
| 3212 |
|
---|
| 3213 | my @filterargs;
|
---|
| 3214 |
|
---|
| 3215 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
| 3216 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
| 3217 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3218 |
|
---|
| 3219 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
| 3220 | # my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
| 3221 | # fname => 'fname');
|
---|
| 3222 | # $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 3223 |
|
---|
| 3224 | # protection against bad or missing arguments
|
---|
| 3225 | $args{sortorder} = 'ASC' if !$args{sortorder};
|
---|
| 3226 | $args{sortby} = 'l.description' if !$args{sortby};
|
---|
[397] | 3227 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[370] | 3228 |
|
---|
| 3229 | my $sql = "SELECT l.location, l.description, l.iplist, g.group_name ".
|
---|
| 3230 | "FROM locations l ".
|
---|
| 3231 | "INNER JOIN groups g ON l.group_id=g.group_id ".
|
---|
| 3232 | "WHERE l.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
| 3233 | ($args{startwith} ? " AND l.description ~* ?" : '').
|
---|
| 3234 | ($args{filter} ? " AND l.description ~* ?" : '').
|
---|
| 3235 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
| 3236 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
| 3237 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
| 3238 | $errstr = $dbh->errstr if !$ulist;
|
---|
| 3239 | return $ulist;
|
---|
| 3240 | } # end getLocList()
|
---|
| 3241 |
|
---|
| 3242 |
|
---|
| 3243 | ## DNSDB::getLocDropdown()
|
---|
[383] | 3244 | # Get a list of location names for use in a dropdown menu.
|
---|
| 3245 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
| 3246 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
| 3247 | sub getLocDropdown {
|
---|
| 3248 | my $dbh = shift;
|
---|
| 3249 | my $grp = shift;
|
---|
| 3250 | my $sel = shift || '';
|
---|
[370] | 3251 |
|
---|
[383] | 3252 | my $sth = $dbh->prepare(qq(
|
---|
| 3253 | SELECT description,location FROM locations
|
---|
| 3254 | WHERE group_id=?
|
---|
| 3255 | ORDER BY description
|
---|
| 3256 | ) );
|
---|
| 3257 | $sth->execute($grp);
|
---|
[370] | 3258 |
|
---|
[383] | 3259 | my @loclist;
|
---|
[446] | 3260 | push @loclist, { locname => "(Default/All)", loc => '', selected => ($sel ? 0 : ($sel eq '' ? 1 : 0)) };
|
---|
[383] | 3261 | while (my ($locname, $loc) = $sth->fetchrow_array) {
|
---|
| 3262 | my %row = (
|
---|
| 3263 | locname => $locname,
|
---|
| 3264 | loc => $loc,
|
---|
| 3265 | selected => ($sel eq $loc ? 1 : 0)
|
---|
| 3266 | );
|
---|
| 3267 | push @loclist, \%row;
|
---|
| 3268 | }
|
---|
| 3269 | return \@loclist;
|
---|
| 3270 | } # end getLocDropdown()
|
---|
| 3271 |
|
---|
| 3272 |
|
---|
[2] | 3273 | ## DNSDB::getSOA()
|
---|
| 3274 | # Return all suitable fields from an SOA record in separate elements of a hash
|
---|
[224] | 3275 | # Takes a database handle, default/live flag, domain/reverse flag, and parent ID
|
---|
[2] | 3276 | sub getSOA {
|
---|
| 3277 | $errstr = '';
|
---|
| 3278 | my $dbh = shift;
|
---|
| 3279 | my $def = shift;
|
---|
[224] | 3280 | my $rev = shift;
|
---|
[2] | 3281 | my $id = shift;
|
---|
| 3282 |
|
---|
[224] | 3283 | # (ab)use distance and weight columns to store SOA data? can't for default_rev_records...
|
---|
| 3284 | # - should really attach serial to the zone parent somewhere
|
---|
[101] | 3285 |
|
---|
[224] | 3286 | my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev).
|
---|
| 3287 | " WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}";
|
---|
[311] | 3288 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
| 3289 | return if !$ret;
|
---|
[246] | 3290 | ##fixme: stick a flag somewhere if the record doesn't exist. by the API, this is an impossible case, but...
|
---|
[2] | 3291 |
|
---|
[311] | 3292 | ($ret->{contact},$ret->{prins}) = split /:/, $ret->{host};
|
---|
| 3293 | delete $ret->{host};
|
---|
| 3294 | ($ret->{refresh},$ret->{retry},$ret->{expire},$ret->{minttl}) = split /:/, $ret->{val};
|
---|
| 3295 | delete $ret->{val};
|
---|
[2] | 3296 |
|
---|
[311] | 3297 | return $ret;
|
---|
[2] | 3298 | } # end getSOA()
|
---|
| 3299 |
|
---|
| 3300 |
|
---|
[246] | 3301 | ## DNSDB::updateSOA()
|
---|
| 3302 | # Update the specified SOA record
|
---|
| 3303 | # Takes a database handle, default/live flag, forward/reverse flag, and SOA data hash
|
---|
[277] | 3304 | # Returns a two-element list with a result code and message
|
---|
[246] | 3305 | sub updateSOA {
|
---|
| 3306 | my $dbh = shift;
|
---|
| 3307 | my $defrec = shift;
|
---|
[248] | 3308 | my $revrec = shift;
|
---|
[246] | 3309 |
|
---|
| 3310 | my %soa = @_;
|
---|
| 3311 |
|
---|
[311] | 3312 | my $oldsoa = getSOA($dbh, $defrec, $revrec, $soa{id});
|
---|
[277] | 3313 |
|
---|
[311] | 3314 | my $msg;
|
---|
| 3315 | my %logdata;
|
---|
| 3316 | if ($defrec eq 'n') {
|
---|
| 3317 | $logdata{domain_id} = $soa{id} if $revrec eq 'n';
|
---|
| 3318 | $logdata{rdns_id} = $soa{id} if $revrec eq 'y';
|
---|
| 3319 | $logdata{group_id} = parentID($dbh, (id => $soa{id}, revrec => $revrec,
|
---|
| 3320 | type => ($revrec eq 'n' ? 'domain' : 'revzone') ) );
|
---|
| 3321 | } else {
|
---|
| 3322 | $logdata{group_id} = $soa{id};
|
---|
| 3323 | }
|
---|
| 3324 | my $parname = ($defrec eq 'y' ? groupName($dbh, $soa{id}) :
|
---|
| 3325 | ($revrec eq 'n' ? domainName($dbh, $soa{id}) : revName($dbh, $soa{id})) );
|
---|
| 3326 |
|
---|
[277] | 3327 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3328 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3329 | local $dbh->{AutoCommit} = 0;
|
---|
| 3330 | local $dbh->{RaiseError} = 1;
|
---|
| 3331 |
|
---|
| 3332 | eval {
|
---|
| 3333 | my $sql = "UPDATE "._rectable($defrec, $revrec)." SET host=?, val=?, ttl=? WHERE record_id=? AND type=6";
|
---|
| 3334 | $dbh->do($sql, undef, ("$soa{contact}:$soa{prins}", "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}",
|
---|
[311] | 3335 | $soa{ttl}, $oldsoa->{record_id}) );
|
---|
| 3336 | $msg = "Updated ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse ' : 'default ') : '').
|
---|
| 3337 | "SOA for $parname: ".
|
---|
| 3338 | "(ns $oldsoa->{prins}, contact $oldsoa->{contact}, refresh $oldsoa->{refresh},".
|
---|
| 3339 | " retry $oldsoa->{retry}, expire $oldsoa->{expire}, minTTL $oldsoa->{minttl}, TTL $oldsoa->{ttl}) to ".
|
---|
[277] | 3340 | "(ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
|
---|
| 3341 | " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})";
|
---|
| 3342 |
|
---|
[311] | 3343 | $logdata{entry} = $msg;
|
---|
| 3344 | _log($dbh, %logdata);
|
---|
[277] | 3345 |
|
---|
| 3346 | $dbh->commit;
|
---|
| 3347 | };
|
---|
| 3348 | if ($@) {
|
---|
| 3349 | $msg = $@;
|
---|
| 3350 | eval { $dbh->rollback; };
|
---|
[311] | 3351 | $logdata{entry} = "Error updating ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse zone ' : 'default ') : '').
|
---|
| 3352 | "SOA record for $parname: $msg";
|
---|
| 3353 | if ($config{log_failures}) {
|
---|
| 3354 | _log($dbh, %logdata);
|
---|
| 3355 | $dbh->commit;
|
---|
| 3356 | }
|
---|
| 3357 | return ('FAIL', $logdata{entry});
|
---|
[277] | 3358 | } else {
|
---|
| 3359 | return ('OK', $msg);
|
---|
| 3360 | }
|
---|
[246] | 3361 | } # end updateSOA()
|
---|
| 3362 |
|
---|
| 3363 |
|
---|
[2] | 3364 | ## DNSDB::getRecLine()
|
---|
| 3365 | # Return all data fields for a zone record in separate elements of a hash
|
---|
[243] | 3366 | # Takes a database handle, default/live flag, forward/reverse flag, and record ID
|
---|
[2] | 3367 | sub getRecLine {
|
---|
| 3368 | $errstr = '';
|
---|
| 3369 | my $dbh = shift;
|
---|
[243] | 3370 | my $defrec = shift;
|
---|
| 3371 | my $revrec = shift;
|
---|
[2] | 3372 | my $id = shift;
|
---|
| 3373 |
|
---|
[429] | 3374 | my $sql = "SELECT record_id,host,type,val,ttl".
|
---|
| 3375 | ($defrec eq 'n' ? ',location' : '').
|
---|
| 3376 | ($revrec eq 'n' ? ',distance,weight,port' : '').
|
---|
[243] | 3377 | (($defrec eq 'y') ? ',group_id FROM ' : ',domain_id,rdns_id FROM ').
|
---|
| 3378 | _rectable($defrec,$revrec)." WHERE record_id=?";
|
---|
[123] | 3379 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
[2] | 3380 |
|
---|
[90] | 3381 | if ($dbh->err) {
|
---|
[2] | 3382 | $errstr = $DBI::errstr;
|
---|
| 3383 | return undef;
|
---|
| 3384 | }
|
---|
| 3385 |
|
---|
[123] | 3386 | if (!$ret) {
|
---|
| 3387 | $errstr = "No such record";
|
---|
| 3388 | return undef;
|
---|
| 3389 | }
|
---|
| 3390 |
|
---|
[243] | 3391 | # explicitly set a parent id
|
---|
| 3392 | if ($defrec eq 'y') {
|
---|
| 3393 | $ret->{parid} = $ret->{group_id};
|
---|
| 3394 | } else {
|
---|
| 3395 | $ret->{parid} = (($revrec eq 'n') ? $ret->{domain_id} : $ret->{rdns_id});
|
---|
| 3396 | # and a secondary if we have a custom type that lives in both a forward and reverse zone
|
---|
| 3397 | $ret->{secid} = (($revrec eq 'y') ? $ret->{domain_id} : $ret->{rdns_id}) if $ret->{type} > 65279;
|
---|
| 3398 | }
|
---|
[451] | 3399 | $ret->{address} = $ret->{val}; # because.
|
---|
[90] | 3400 |
|
---|
| 3401 | return $ret;
|
---|
[2] | 3402 | }
|
---|
| 3403 |
|
---|
| 3404 |
|
---|
| 3405 | ##fixme: should use above (getRecLine()) to get lines for below?
|
---|
| 3406 | ## DNSDB::getDomRecs()
|
---|
| 3407 | # Return records for a domain
|
---|
| 3408 | # Takes a database handle, default/live flag, group/domain ID, start,
|
---|
| 3409 | # number of records, sort field, and sort order
|
---|
| 3410 | # Returns a reference to an array of hashes
|
---|
| 3411 | sub getDomRecs {
|
---|
| 3412 | $errstr = '';
|
---|
| 3413 | my $dbh = shift;
|
---|
| 3414 |
|
---|
[397] | 3415 | my %args = @_;
|
---|
[4] | 3416 |
|
---|
[397] | 3417 | my @filterargs;
|
---|
[135] | 3418 |
|
---|
[397] | 3419 | push @filterargs, $args{filter} if $args{filter};
|
---|
| 3420 |
|
---|
| 3421 | # protection against bad or missing arguments
|
---|
| 3422 | $args{sortorder} = 'ASC' if !$args{sortorder};
|
---|
[399] | 3423 | $args{sortby} = 'host' if !$args{sortby} && $args{revrec} eq 'n'; # default sort by host on domain record list
|
---|
| 3424 | $args{sortby} = 'val' if !$args{sortby} && $args{revrec} eq 'y'; # default sort by IP on revzone record list
|
---|
[397] | 3425 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
| 3426 |
|
---|
[352] | 3427 | # sort reverse zones on IP, correctly
|
---|
[397] | 3428 | # do other fiddling with $args{sortby} while we're at it.
|
---|
[420] | 3429 | # whee! multisort means just passing comma-separated fields in sortby!
|
---|
| 3430 | my $newsort = '';
|
---|
| 3431 | foreach my $sf (split /,/, $args{sortby}) {
|
---|
| 3432 | $sf = "r.$sf";
|
---|
| 3433 | $sf =~ s/r\.val/CAST (r.val AS inet)/
|
---|
| 3434 | if $args{revrec} eq 'y' && $args{defrec} eq 'n';
|
---|
| 3435 | $sf =~ s/r\.type/t.alphaorder/;
|
---|
| 3436 | $newsort .= ",$sf";
|
---|
| 3437 | }
|
---|
| 3438 | $newsort =~ s/^,//;
|
---|
[352] | 3439 |
|
---|
[224] | 3440 | my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.ttl";
|
---|
[397] | 3441 | $sql .= ",l.description AS locname" if $args{defrec} eq 'n';
|
---|
| 3442 | $sql .= ",r.distance,r.weight,r.port" if $args{revrec} eq 'n';
|
---|
| 3443 | $sql .= " FROM "._rectable($args{defrec},$args{revrec})." r ";
|
---|
[104] | 3444 | $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
|
---|
[397] | 3445 | $sql .= "LEFT JOIN locations l ON r.location=l.location " if $args{defrec} eq 'n';
|
---|
| 3446 | $sql .= "WHERE "._recparent($args{defrec},$args{revrec})." = ?";
|
---|
[104] | 3447 | $sql .= " AND NOT r.type=$reverse_typemap{SOA}";
|
---|
[439] | 3448 | $sql .= " AND (r.host ~* ? OR r.val ~* ?)" if $args{filter};
|
---|
[420] | 3449 | $sql .= " ORDER BY $newsort $args{sortorder}";
|
---|
[324] | 3450 | # ensure consistent ordering by sorting on record_id too
|
---|
[397] | 3451 | $sql .= ", record_id $args{sortorder}";
|
---|
| 3452 | $sql .= ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
[4] | 3453 |
|
---|
[397] | 3454 | my @bindvars = ($args{id});
|
---|
[439] | 3455 | push @bindvars, ($args{filter},$args{filter}) if $args{filter};
|
---|
[224] | 3456 |
|
---|
[397] | 3457 | my $ret = $dbh->selectall_arrayref($sql, { Slice => {} }, (@bindvars) );
|
---|
[2] | 3458 | return $ret;
|
---|
| 3459 | } # end getDomRecs()
|
---|
| 3460 |
|
---|
| 3461 |
|
---|
[91] | 3462 | ## DNSDB::getRecCount()
|
---|
[224] | 3463 | # Return count of non-SOA records in zone (or default records in a group)
|
---|
| 3464 | # Takes a database handle, default/live flag, reverse/forward flag, group/domain ID,
|
---|
| 3465 | # and optional filtering modifier
|
---|
[91] | 3466 | # Returns the count
|
---|
| 3467 | sub getRecCount {
|
---|
| 3468 | my $dbh = shift;
|
---|
| 3469 | my $defrec = shift;
|
---|
[224] | 3470 | my $revrec = shift;
|
---|
[91] | 3471 | my $id = shift;
|
---|
[135] | 3472 | my $filter = shift || '';
|
---|
[91] | 3473 |
|
---|
[135] | 3474 | # keep the nasties down, since we can't ?-sub this bit. :/
|
---|
| 3475 | # note this is chars allowed in DNS hostnames
|
---|
| 3476 | $filter =~ s/[^a-zA-Z0-9_.:-]//g;
|
---|
| 3477 |
|
---|
[222] | 3478 | my @bindvars = ($id);
|
---|
| 3479 | push @bindvars, $filter if $filter;
|
---|
[224] | 3480 | my $sql = "SELECT count(*) FROM ".
|
---|
| 3481 | _rectable($defrec,$revrec).
|
---|
| 3482 | " WHERE "._recparent($defrec,$revrec)."=? ".
|
---|
| 3483 | "AND NOT type=$reverse_typemap{SOA}".
|
---|
| 3484 | ($filter ? " AND host ~* ?" : '');
|
---|
| 3485 | my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) );
|
---|
[91] | 3486 |
|
---|
| 3487 | return $count;
|
---|
| 3488 |
|
---|
| 3489 | } # end getRecCount()
|
---|
| 3490 |
|
---|
| 3491 |
|
---|
[3] | 3492 | ## DNSDB::addRec()
|
---|
[2] | 3493 | # Add a new record to a domain or a group's default records
|
---|
| 3494 | # Takes a database handle, default/live flag, group/domain ID,
|
---|
| 3495 | # host, type, value, and TTL
|
---|
| 3496 | # Some types require additional detail: "distance" for MX and SRV,
|
---|
| 3497 | # and weight/port for SRV
|
---|
| 3498 | # Returns a status code and detail message in case of error
|
---|
[234] | 3499 | ##fixme: pass a hash with the record data, not a series of separate values
|
---|
[2] | 3500 | sub addRec {
|
---|
| 3501 | $errstr = '';
|
---|
| 3502 | my $dbh = shift;
|
---|
| 3503 | my $defrec = shift;
|
---|
[226] | 3504 | my $revrec = shift;
|
---|
| 3505 | my $id = shift; # parent (group_id for defrecs, rdns_id for reverse records,
|
---|
| 3506 | # domain_id for domain records)
|
---|
[2] | 3507 |
|
---|
| 3508 | my $host = shift;
|
---|
[234] | 3509 | my $rectype = shift; # reference so we can coerce it if "+"-types can't find both zones
|
---|
[2] | 3510 | my $val = shift;
|
---|
| 3511 | my $ttl = shift;
|
---|
[389] | 3512 | my $location = shift;
|
---|
| 3513 | $location = '' if !$location;
|
---|
[2] | 3514 |
|
---|
[417] | 3515 | # Spaces are evil.
|
---|
| 3516 | $$host =~ s/^\s+//;
|
---|
| 3517 | $$host =~ s/\s+$//;
|
---|
[418] | 3518 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
[417] | 3519 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 3520 | $$val =~ s/^\s+//;
|
---|
| 3521 | $$val =~ s/\s+$//;
|
---|
| 3522 | }
|
---|
| 3523 |
|
---|
[226] | 3524 | # prep for validation
|
---|
[252] | 3525 | my $addr = NetAddr::IP->new($$val);
|
---|
| 3526 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
[226] | 3527 |
|
---|
| 3528 | my $domid = 0;
|
---|
| 3529 | my $revid = 0;
|
---|
| 3530 |
|
---|
| 3531 | my $retcode = 'OK'; # assume everything will go OK
|
---|
| 3532 | my $retmsg = '';
|
---|
| 3533 |
|
---|
| 3534 | # do simple validation first
|
---|
| 3535 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
|
---|
| 3536 |
|
---|
[234] | 3537 | # Quick check on hostname parts. Note the regex is more forgiving than the error message;
|
---|
| 3538 | # domain names technically are case-insensitive, and we use printf-like % codes for a couple
|
---|
| 3539 | # of types. Other things may also be added to validate default records of several flavours.
|
---|
| 3540 | return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z . _)")
|
---|
[350] | 3541 | if $defrec eq 'n' && ($revrec eq 'y' ? $$rectype != $reverse_typemap{TXT} : 1) &&
|
---|
| 3542 | $$host !~ /^[0-9a-z_%.-]+$/i;
|
---|
[226] | 3543 |
|
---|
[234] | 3544 | # Collect these even if we're only doing a simple A record so we can call *any* validation sub
|
---|
| 3545 | my $dist = shift;
|
---|
[281] | 3546 | my $weight = shift;
|
---|
[234] | 3547 | my $port = shift;
|
---|
[226] | 3548 |
|
---|
[234] | 3549 | my $fields;
|
---|
| 3550 | my @vallist;
|
---|
[226] | 3551 |
|
---|
[234] | 3552 | # Call the validation sub for the type requested.
|
---|
| 3553 | ($retcode,$retmsg) = $validators{$$rectype}($dbh, (defrec => $defrec, revrec => $revrec, id => $id,
|
---|
[249] | 3554 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
[234] | 3555 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
| 3556 | fields => \$fields, vallist => \@vallist) );
|
---|
[129] | 3557 |
|
---|
[234] | 3558 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
[209] | 3559 |
|
---|
[234] | 3560 | # Set up database fields and bind parameters
|
---|
[389] | 3561 | $fields .= "host,type,val,ttl,location,"._recparent($defrec,$revrec);
|
---|
| 3562 | push @vallist, ($$host,$$rectype,$$val,$ttl,$location,$id);
|
---|
[234] | 3563 | my $vallen = '?'.(',?'x$#vallist);
|
---|
[2] | 3564 |
|
---|
[287] | 3565 | # Put together the success log entry. We have to use this horrible kludge
|
---|
| 3566 | # because domain_id and rdns_id may or may not be present, and if they are,
|
---|
| 3567 | # they're not at a guaranteed consistent index in the array. wheee!
|
---|
| 3568 | my %logdata;
|
---|
| 3569 | my @ftmp = split /,/, $fields;
|
---|
| 3570 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
| 3571 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
| 3572 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
| 3573 | }
|
---|
| 3574 | $logdata{group_id} = $id if $defrec eq 'y';
|
---|
| 3575 | $logdata{group_id} = parentID($dbh,
|
---|
| 3576 | (id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) )
|
---|
| 3577 | if $defrec eq 'n';
|
---|
[328] | 3578 | $logdata{entry} = "Added ".($defrec eq 'y' ? 'default record' : 'record');
|
---|
| 3579 | # NS records for revzones get special treatment
|
---|
| 3580 | if ($revrec eq 'y' && $$rectype == 2) {
|
---|
| 3581 | $logdata{entry} .= " '$$val $typemap{$$rectype} $$host";
|
---|
| 3582 | } else {
|
---|
| 3583 | $logdata{entry} .= " '$$host $typemap{$$rectype} $$val";
|
---|
| 3584 | }
|
---|
| 3585 |
|
---|
[287] | 3586 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
| 3587 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]"
|
---|
| 3588 | if $typemap{$$rectype} eq 'SRV';
|
---|
[425] | 3589 | $logdata{entry} .= "', TTL $ttl";
|
---|
| 3590 | $logdata{entry} .= ", location ".getLoc($dbh, $location)->{description} if $location;
|
---|
[287] | 3591 |
|
---|
[90] | 3592 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3593 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3594 | local $dbh->{AutoCommit} = 0;
|
---|
| 3595 | local $dbh->{RaiseError} = 1;
|
---|
[2] | 3596 |
|
---|
[90] | 3597 | eval {
|
---|
[236] | 3598 | $dbh->do("INSERT INTO "._rectable($defrec, $revrec)." ($fields) VALUES ($vallen)",
|
---|
[90] | 3599 | undef, @vallist);
|
---|
[287] | 3600 | _log($dbh, %logdata);
|
---|
[90] | 3601 | $dbh->commit;
|
---|
| 3602 | };
|
---|
| 3603 | if ($@) {
|
---|
| 3604 | my $msg = $@;
|
---|
| 3605 | eval { $dbh->rollback; };
|
---|
[289] | 3606 | if ($config{log_failures}) {
|
---|
| 3607 | $logdata{entry} = "Failed adding ".($defrec eq 'y' ? 'default ' : '').
|
---|
| 3608 | "record '$$host $typemap{$$rectype} $$val', TTL $ttl ($msg)";
|
---|
| 3609 | _log($dbh, %logdata);
|
---|
| 3610 | $dbh->commit;
|
---|
| 3611 | }
|
---|
[90] | 3612 | return ('FAIL',$msg);
|
---|
| 3613 | }
|
---|
[2] | 3614 |
|
---|
[287] | 3615 | $resultstr = $logdata{entry};
|
---|
[226] | 3616 | return ($retcode, $retmsg);
|
---|
[90] | 3617 |
|
---|
[2] | 3618 | } # end addRec()
|
---|
| 3619 |
|
---|
| 3620 |
|
---|
[16] | 3621 | ## DNSDB::updateRec()
|
---|
| 3622 | # Update a record
|
---|
[273] | 3623 | # Takes a database handle, default and reverse flags, record ID, immediate parent ID, and new record data.
|
---|
| 3624 | # Returns a status code and message
|
---|
[16] | 3625 | sub updateRec {
|
---|
| 3626 | $errstr = '';
|
---|
[17] | 3627 |
|
---|
[16] | 3628 | my $dbh = shift;
|
---|
| 3629 | my $defrec = shift;
|
---|
[272] | 3630 | my $revrec = shift;
|
---|
[16] | 3631 | my $id = shift;
|
---|
[272] | 3632 | my $parid = shift; # immediate parent entity that we're descending from to update the record
|
---|
[16] | 3633 |
|
---|
[273] | 3634 | # all records have these
|
---|
[16] | 3635 | my $host = shift;
|
---|
[272] | 3636 | my $hostbk = $$host; # Keep a backup copy of the original, so we can WARN if the update mangles the domain
|
---|
| 3637 | my $rectype = shift;
|
---|
[16] | 3638 | my $val = shift;
|
---|
| 3639 | my $ttl = shift;
|
---|
[389] | 3640 | my $location = shift; # may be empty/null/undef depending on caller
|
---|
| 3641 | $location = '' if !$location;
|
---|
[16] | 3642 |
|
---|
[417] | 3643 | # Spaces are evil.
|
---|
| 3644 | $$host =~ s/^\s+//;
|
---|
| 3645 | $$host =~ s/\s+$//;
|
---|
[418] | 3646 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
[417] | 3647 | # Leading or trailng spaces could be legit in TXT records.
|
---|
| 3648 | $$val =~ s/^\s+//;
|
---|
| 3649 | $$val =~ s/\s+$//;
|
---|
| 3650 | }
|
---|
| 3651 |
|
---|
[272] | 3652 | # prep for validation
|
---|
| 3653 | my $addr = NetAddr::IP->new($$val);
|
---|
| 3654 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
[16] | 3655 |
|
---|
[272] | 3656 | my $domid = 0;
|
---|
| 3657 | my $revid = 0;
|
---|
| 3658 |
|
---|
| 3659 | my $retcode = 'OK'; # assume everything will go OK
|
---|
| 3660 | my $retmsg = '';
|
---|
| 3661 |
|
---|
[273] | 3662 | # do simple validation first
|
---|
[272] | 3663 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
|
---|
| 3664 |
|
---|
| 3665 | # Quick check on hostname parts. Note the regex is more forgiving than the error message;
|
---|
| 3666 | # domain names technically are case-insensitive, and we use printf-like % codes for a couple
|
---|
| 3667 | # of types. Other things may also be added to validate default records of several flavours.
|
---|
[273] | 3668 | return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z - . _)")
|
---|
[350] | 3669 | if $defrec eq 'n' && ($revrec eq 'y' ? $$rectype != $reverse_typemap{TXT} : 1) &&
|
---|
| 3670 | $$host !~ /^[0-9a-z_%.-]+$/i;
|
---|
[272] | 3671 |
|
---|
[273] | 3672 | # only MX and SRV will use these
|
---|
[288] | 3673 | my $dist = shift || 0;
|
---|
| 3674 | my $weight = shift || 0;
|
---|
| 3675 | my $port = shift || 0;
|
---|
[16] | 3676 |
|
---|
[272] | 3677 | my $fields;
|
---|
| 3678 | my @vallist;
|
---|
[16] | 3679 |
|
---|
[273] | 3680 | # get old record data so we have the right parent ID
|
---|
| 3681 | # and for logging (eventually)
|
---|
| 3682 | my $oldrec = getRecLine($dbh, $defrec, $revrec, $id);
|
---|
[223] | 3683 |
|
---|
[272] | 3684 | # Call the validation sub for the type requested.
|
---|
| 3685 | # Note the ID to pass here is the *parent*, not the record
|
---|
| 3686 | ($retcode,$retmsg) = $validators{$$rectype}($dbh, (defrec => $defrec, revrec => $revrec,
|
---|
| 3687 | id => ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})),
|
---|
| 3688 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
| 3689 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
| 3690 | fields => \$fields, vallist => \@vallist,
|
---|
| 3691 | update => $id) );
|
---|
| 3692 |
|
---|
| 3693 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
| 3694 |
|
---|
[273] | 3695 | # Set up database fields and bind parameters. Note only the optional fields
|
---|
| 3696 | # (distance, weight, port, secondary parent ID) are added in the validation call above
|
---|
[448] | 3697 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
| 3698 | push @vallist, ($$host,$$rectype,$$val,$ttl,
|
---|
[273] | 3699 | ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})) );
|
---|
[272] | 3700 |
|
---|
[448] | 3701 | # locations are not for default records, silly coder!
|
---|
| 3702 | if ($defrec eq 'n') {
|
---|
| 3703 | $fields .= ",location";
|
---|
| 3704 | push @vallist, $location;
|
---|
| 3705 | }
|
---|
| 3706 |
|
---|
[273] | 3707 | # hack hack PTHUI
|
---|
| 3708 | # need to forcibly make sure we disassociate a record with a parent it's no longer related to.
|
---|
| 3709 | # eg, PTR records may not have a domain parent, or A/AAAA records may not have a revzone parent.
|
---|
| 3710 | # mainly needed for crossover types that got coerced down to "standard" types
|
---|
| 3711 | if ($defrec eq 'n') {
|
---|
| 3712 | if ($$rectype == $reverse_typemap{PTR}) {
|
---|
| 3713 | $fields .= ",domain_id";
|
---|
| 3714 | push @vallist, 0;
|
---|
| 3715 | }
|
---|
| 3716 | if ($$rectype == $reverse_typemap{A} || $$rectype == $reverse_typemap{AAAA}) {
|
---|
| 3717 | $fields .= ",rdns_id";
|
---|
| 3718 | push @vallist, 0;
|
---|
| 3719 | }
|
---|
| 3720 | }
|
---|
[345] | 3721 | # fix fat-finger-originated record type changes
|
---|
| 3722 | if ($$rectype == 65285) {
|
---|
| 3723 | $fields .= ",rdns_id" if $revrec eq 'n';
|
---|
| 3724 | $fields .= ",domain_id" if $revrec eq 'y';
|
---|
| 3725 | push @vallist, 0;
|
---|
| 3726 | }
|
---|
[341] | 3727 | if ($defrec eq 'n') {
|
---|
| 3728 | $domid = $parid if $revrec eq 'n';
|
---|
| 3729 | $revid = $parid if $revrec eq 'y';
|
---|
| 3730 | }
|
---|
[272] | 3731 |
|
---|
[288] | 3732 | # Put together the success log entry. Horrible kludge from addRec() copied as-is since
|
---|
| 3733 | # we don't know whether the passed arguments or retrieved values for domain_id and rdns_id
|
---|
| 3734 | # will be maintained (due to "not-in-zone" validation changes)
|
---|
| 3735 | my %logdata;
|
---|
[341] | 3736 | $logdata{domain_id} = $domid;
|
---|
| 3737 | $logdata{rdns_id} = $revid;
|
---|
[288] | 3738 | my @ftmp = split /,/, $fields;
|
---|
| 3739 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
| 3740 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
| 3741 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
| 3742 | }
|
---|
| 3743 | $logdata{group_id} = $parid if $defrec eq 'y';
|
---|
| 3744 | $logdata{group_id} = parentID($dbh,
|
---|
| 3745 | (id => $parid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) )
|
---|
| 3746 | if $defrec eq 'n';
|
---|
[328] | 3747 | $logdata{entry} = "Updated ".($defrec eq 'y' ? 'default record' : 'record')." from\n";
|
---|
| 3748 | # NS records for revzones get special treatment
|
---|
| 3749 | if ($revrec eq 'y' && $$rectype == 2) {
|
---|
| 3750 | $logdata{entry} .= " '$oldrec->{val} $typemap{$oldrec->{type}} $oldrec->{host}";
|
---|
| 3751 | } else {
|
---|
| 3752 | $logdata{entry} .= " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
| 3753 | }
|
---|
[288] | 3754 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
| 3755 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
| 3756 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
[425] | 3757 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
| 3758 | $logdata{entry} .= ", location ".getLoc($dbh, $oldrec->{location})->{description} if $oldrec->{location};
|
---|
| 3759 | $logdata{entry} .= "\nto\n";
|
---|
[328] | 3760 | # More NS special
|
---|
| 3761 | if ($revrec eq 'y' && $$rectype == 2) {
|
---|
| 3762 | $logdata{entry} .= "'$$val $typemap{$$rectype} $$host";
|
---|
| 3763 | } else {
|
---|
| 3764 | $logdata{entry} .= "'$$host $typemap{$$rectype} $$val";
|
---|
| 3765 | }
|
---|
[288] | 3766 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
| 3767 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$$rectype} eq 'SRV';
|
---|
[425] | 3768 | $logdata{entry} .= "', TTL $ttl";
|
---|
| 3769 | $logdata{entry} .= ", location ".getLoc($dbh, $location)->{description} if $location;
|
---|
[288] | 3770 |
|
---|
[90] | 3771 | local $dbh->{AutoCommit} = 0;
|
---|
| 3772 | local $dbh->{RaiseError} = 1;
|
---|
| 3773 |
|
---|
[341] | 3774 | # Fiddle the field list into something suitable for updates
|
---|
| 3775 | $fields =~ s/,/=?,/g;
|
---|
| 3776 | $fields .= "=?";
|
---|
| 3777 |
|
---|
[90] | 3778 | eval {
|
---|
[273] | 3779 | $dbh->do("UPDATE "._rectable($defrec,$revrec)." SET $fields WHERE record_id=?", undef, (@vallist, $id) );
|
---|
[288] | 3780 | _log($dbh, %logdata);
|
---|
[130] | 3781 | $dbh->commit;
|
---|
[90] | 3782 | };
|
---|
| 3783 | if ($@) {
|
---|
| 3784 | my $msg = $@;
|
---|
[288] | 3785 | eval { $dbh->rollback; };
|
---|
[289] | 3786 | if ($config{log_failures}) {
|
---|
| 3787 | $logdata{entry} = "Failed updating ".($defrec eq 'y' ? 'default ' : '').
|
---|
| 3788 | "record '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
| 3789 | _log($dbh, %logdata);
|
---|
| 3790 | $dbh->commit;
|
---|
| 3791 | }
|
---|
[90] | 3792 | return ('FAIL', $msg);
|
---|
| 3793 | }
|
---|
| 3794 |
|
---|
[288] | 3795 | $resultstr = $logdata{entry};
|
---|
[272] | 3796 | return ($retcode, $retmsg);
|
---|
[16] | 3797 | } # end updateRec()
|
---|
| 3798 |
|
---|
| 3799 |
|
---|
[3] | 3800 | ## DNSDB::delRec()
|
---|
| 3801 | # Delete a record.
|
---|
| 3802 | sub delRec {
|
---|
| 3803 | $errstr = '';
|
---|
| 3804 | my $dbh = shift;
|
---|
| 3805 | my $defrec = shift;
|
---|
[243] | 3806 | my $revrec = shift;
|
---|
[3] | 3807 | my $id = shift;
|
---|
| 3808 |
|
---|
[290] | 3809 | my $oldrec = getRecLine($dbh, $defrec, $revrec, $id);
|
---|
[3] | 3810 |
|
---|
[290] | 3811 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 3812 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 3813 | local $dbh->{AutoCommit} = 0;
|
---|
| 3814 | local $dbh->{RaiseError} = 1;
|
---|
[3] | 3815 |
|
---|
[290] | 3816 | # Put together the log entry
|
---|
| 3817 | my %logdata;
|
---|
| 3818 | $logdata{domain_id} = $oldrec->{domain_id};
|
---|
| 3819 | $logdata{rdns_id} = $oldrec->{rdns_id};
|
---|
| 3820 | $logdata{group_id} = $oldrec->{group_id} if $defrec eq 'y';
|
---|
| 3821 | $logdata{group_id} = parentID($dbh,
|
---|
| 3822 | (id => $oldrec->{domain_id}, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) )
|
---|
| 3823 | if $defrec eq 'n';
|
---|
| 3824 | $logdata{entry} = "Deleted ".($defrec eq 'y' ? 'default record ' : 'record ').
|
---|
| 3825 | "'$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
| 3826 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
| 3827 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
| 3828 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
[425] | 3829 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
| 3830 | $logdata{entry} .= ", location ".getLoc($dbh, $oldrec->{location})->{description} if $oldrec->{location};
|
---|
[290] | 3831 |
|
---|
| 3832 | eval {
|
---|
| 3833 | my $sth = $dbh->do("DELETE FROM "._rectable($defrec,$revrec)." WHERE record_id=?", undef, ($id));
|
---|
| 3834 | _log($dbh, %logdata);
|
---|
| 3835 | $dbh->commit;
|
---|
| 3836 | };
|
---|
| 3837 | if ($@) {
|
---|
| 3838 | my $msg = $@;
|
---|
| 3839 | eval { $dbh->rollback; };
|
---|
| 3840 | if ($config{log_failures}) {
|
---|
| 3841 | $logdata{entry} = "Error deleting ".($defrec eq 'y' ? 'default record' : 'record').
|
---|
| 3842 | " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
| 3843 | _log($dbh, %logdata);
|
---|
| 3844 | $dbh->commit;
|
---|
| 3845 | }
|
---|
| 3846 | return ('FAIL', $msg);
|
---|
| 3847 | }
|
---|
| 3848 |
|
---|
| 3849 | return ('OK',$logdata{entry});
|
---|
[3] | 3850 | } # end delRec()
|
---|
| 3851 |
|
---|
| 3852 |
|
---|
[323] | 3853 | ## DNSDB::getLogCount()
|
---|
| 3854 | # Get a count of log entries
|
---|
| 3855 | # Takes a database handle and a hash containing at least:
|
---|
| 3856 | # - Entity ID and entity type as the primary log "slice"
|
---|
| 3857 | sub getLogCount {
|
---|
| 3858 | my $dbh = shift;
|
---|
| 3859 |
|
---|
| 3860 | my %args = @_;
|
---|
| 3861 |
|
---|
| 3862 | my @filterargs;
|
---|
| 3863 | ##fixme: which fields do we want to filter on?
|
---|
| 3864 | # push @filterargs,
|
---|
| 3865 |
|
---|
| 3866 | $errstr = 'Missing primary parent ID and/or type';
|
---|
| 3867 | # fail early if we don't have a "prime" ID to look for log entries for
|
---|
| 3868 | return if !$args{id};
|
---|
| 3869 |
|
---|
| 3870 | # or if the prime id type is missing or invalid
|
---|
| 3871 | return if !$args{logtype};
|
---|
| 3872 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
| 3873 | $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
|
---|
| 3874 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
|
---|
| 3875 |
|
---|
| 3876 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
| 3877 |
|
---|
| 3878 | my $sql = "SELECT count(*) FROM log ".
|
---|
| 3879 | "WHERE $id_col{$args{logtype}}=?".
|
---|
| 3880 | ($args{filter} ? " AND entry ~* ?" : '');
|
---|
| 3881 | my ($count) = $dbh->selectrow_array($sql, undef, ($args{id}, @filterargs) );
|
---|
| 3882 | $errstr = $dbh->errstr if !$count;
|
---|
| 3883 | return $count;
|
---|
| 3884 | } # end getLogCount()
|
---|
| 3885 |
|
---|
| 3886 |
|
---|
| 3887 | ## DNSDB::getLogEntries()
|
---|
| 3888 | # Get a list of log entries
|
---|
| 3889 | # Takes arguments as with getLogCount() above, plus optional:
|
---|
| 3890 | # - sort field
|
---|
| 3891 | # - sort order
|
---|
| 3892 | # - offset for pagination
|
---|
| 3893 | sub getLogEntries {
|
---|
| 3894 | my $dbh = shift;
|
---|
| 3895 |
|
---|
| 3896 | my %args = @_;
|
---|
| 3897 |
|
---|
| 3898 | my @filterargs;
|
---|
| 3899 |
|
---|
| 3900 | # fail early if we don't have a "prime" ID to look for log entries for
|
---|
| 3901 | return if !$args{id};
|
---|
| 3902 |
|
---|
| 3903 | # or if the prime id type is missing or invalid
|
---|
| 3904 | return if !$args{logtype};
|
---|
| 3905 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
| 3906 | $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
|
---|
| 3907 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
|
---|
| 3908 |
|
---|
| 3909 | # Sorting defaults
|
---|
| 3910 | $args{sortby} = 'stamp' if !$args{sortby};
|
---|
| 3911 | $args{sortorder} = 'DESC' if !$args{sortorder};
|
---|
[397] | 3912 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
[323] | 3913 |
|
---|
[324] | 3914 | my %sortmap = (fname => 'name', username => 'email', entry => 'entry', stamp => 'stamp');
|
---|
[323] | 3915 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
| 3916 |
|
---|
| 3917 | my $sql = "SELECT user_id AS userid, email AS useremail, name AS userfname, entry AS logentry, ".
|
---|
| 3918 | "date_trunc('second',stamp) AS logtime ".
|
---|
| 3919 | "FROM log ".
|
---|
| 3920 | "WHERE $id_col{$args{logtype}}=?".
|
---|
| 3921 | ($args{filter} ? " AND entry ~* ?" : '').
|
---|
[324] | 3922 | " ORDER BY $args{sortby} $args{sortorder}, log_id $args{sortorder}".
|
---|
[323] | 3923 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
|
---|
| 3924 | my $loglist = $dbh->selectall_arrayref($sql, { Slice => {} }, ($args{id}, @filterargs) );
|
---|
| 3925 | $errstr = $dbh->errstr if !$loglist;
|
---|
| 3926 | return $loglist;
|
---|
| 3927 | } # end getLogEntries()
|
---|
| 3928 |
|
---|
| 3929 |
|
---|
[452] | 3930 | ## IPDB::getRevPattern()
|
---|
| 3931 | # Get the narrowest template pattern applicable to a passed CIDR address (may be a netblock or an IP)
|
---|
| 3932 | sub getRevPattern {
|
---|
| 3933 | my $dbh = shift;
|
---|
| 3934 | my $cidr = shift;
|
---|
| 3935 | my $group = shift || 1; # just in case
|
---|
| 3936 |
|
---|
| 3937 | my ($revpatt) = $dbh->selectrow_array("SELECT r.host FROM records r JOIN revzones z ON r.rdns_id=z.rdns_id ".
|
---|
[455] | 3938 | "WHERE (r.type=65282 OR r.type=65283) AND z.group_id=? AND CAST (r.val AS inet) >>= ? ".
|
---|
[452] | 3939 | "ORDER BY CAST (r.val AS inet) DESC LIMIT 1", undef, ($group, $cidr) );
|
---|
| 3940 | return $revpatt;
|
---|
| 3941 | } # end getRevPattern()
|
---|
| 3942 |
|
---|
| 3943 |
|
---|
[225] | 3944 | ## DNSDB::getTypelist()
|
---|
| 3945 | # Get a list of record types for various UI dropdowns
|
---|
| 3946 | # Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A)
|
---|
| 3947 | # Returns an arrayref to list of hashrefs perfect for HTML::Template
|
---|
| 3948 | sub getTypelist {
|
---|
| 3949 | my $dbh = shift;
|
---|
| 3950 | my $recgroup = shift;
|
---|
| 3951 | my $type = shift || $reverse_typemap{A};
|
---|
| 3952 |
|
---|
| 3953 | # also accepting $webvar{revrec}!
|
---|
| 3954 | $recgroup = 'f' if $recgroup eq 'n';
|
---|
| 3955 | $recgroup = 'r' if $recgroup eq 'y';
|
---|
| 3956 |
|
---|
| 3957 | my $sql = "SELECT val,name FROM rectypes WHERE ";
|
---|
| 3958 | if ($recgroup eq 'r') {
|
---|
| 3959 | # reverse zone types
|
---|
| 3960 | $sql .= "stdflag=2 OR stdflag=3";
|
---|
| 3961 | } elsif ($recgroup eq 'l') {
|
---|
| 3962 | # DNS lookup types. Note we avoid our custom types >= 65280, since those are entirely internal.
|
---|
| 3963 | $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280";
|
---|
| 3964 | } else {
|
---|
| 3965 | # default; forward zone types. technically $type eq 'f' but not worth the error message.
|
---|
| 3966 | $sql .= "stdflag=1 OR stdflag=2";
|
---|
| 3967 | }
|
---|
| 3968 | $sql .= " ORDER BY listorder";
|
---|
| 3969 |
|
---|
| 3970 | my $sth = $dbh->prepare($sql);
|
---|
| 3971 | $sth->execute;
|
---|
| 3972 | my @typelist;
|
---|
| 3973 | while (my ($rval,$rname) = $sth->fetchrow_array()) {
|
---|
| 3974 | my %row = ( recval => $rval, recname => $rname );
|
---|
| 3975 | $row{tselect} = 1 if $rval == $type;
|
---|
| 3976 | push @typelist, \%row;
|
---|
| 3977 | }
|
---|
| 3978 |
|
---|
| 3979 | # Add SOA on lookups since it's not listed in other dropdowns.
|
---|
| 3980 | if ($recgroup eq 'l') {
|
---|
| 3981 | my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
|
---|
| 3982 | $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
|
---|
| 3983 | push @typelist, \%row;
|
---|
| 3984 | }
|
---|
| 3985 |
|
---|
| 3986 | return \@typelist;
|
---|
| 3987 | } # end getTypelist()
|
---|
| 3988 |
|
---|
| 3989 |
|
---|
[254] | 3990 | ## DNSDB::parentID()
|
---|
| 3991 | # Get ID of entity that is nearest parent to requested id
|
---|
| 3992 | # Takes a database handle and a hash of entity ID, entity type, optional parent type flag
|
---|
| 3993 | # (domain/reverse zone or group), and optional default/live and forward/reverse flags
|
---|
| 3994 | # Returns the ID or undef on failure
|
---|
| 3995 | sub parentID {
|
---|
[116] | 3996 | my $dbh = shift;
|
---|
| 3997 |
|
---|
[254] | 3998 | my %args = @_;
|
---|
[116] | 3999 |
|
---|
[254] | 4000 | # clean up the parent-type. Set it to group if not set; coerce revzone to domain for simpler logic
|
---|
| 4001 | $args{partype} = 'group' if !$args{partype};
|
---|
| 4002 | $args{partype} = 'domain' if $args{partype} eq 'revzone';
|
---|
[116] | 4003 |
|
---|
[254] | 4004 | # clean up defrec and revrec. default to live record, forward zone
|
---|
| 4005 | $args{defrec} = 'n' if !$args{defrec};
|
---|
| 4006 | $args{revrec} = 'n' if !$args{revrec};
|
---|
[116] | 4007 |
|
---|
[254] | 4008 | if ($par_type{$args{partype}} eq 'domain') {
|
---|
| 4009 | # only live records can have a domain/zone parent
|
---|
| 4010 | return unless ($args{type} eq 'record' && $args{defrec} eq 'n');
|
---|
| 4011 | my $result = $dbh->selectrow_hashref("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
| 4012 | " FROM records WHERE record_id = ?",
|
---|
| 4013 | undef, ($args{id}) ) or return;
|
---|
| 4014 | return $result;
|
---|
| 4015 | } else {
|
---|
| 4016 | # snag some arguments that will either fall through or be overwritten to save some code duplication
|
---|
| 4017 | my $tmpid = $args{id};
|
---|
| 4018 | my $type = $args{type};
|
---|
| 4019 | if ($type eq 'record' && $args{defrec} eq 'n') {
|
---|
| 4020 | # Live records go through the records table first.
|
---|
| 4021 | ($tmpid) = $dbh->selectrow_array("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
| 4022 | " FROM records WHERE record_id = ?",
|
---|
| 4023 | undef, ($args{id}) ) or return;
|
---|
| 4024 | $type = ($args{revrec} eq 'n' ? 'domain' : 'revzone');
|
---|
| 4025 | }
|
---|
| 4026 | my ($result) = $dbh->selectrow_array("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
|
---|
| 4027 | undef, ($tmpid) );
|
---|
| 4028 | return $result;
|
---|
| 4029 | }
|
---|
| 4030 | # should be impossible to get here with even remotely sane arguments
|
---|
| 4031 | return;
|
---|
| 4032 | } # end parentID()
|
---|
[116] | 4033 |
|
---|
| 4034 |
|
---|
[117] | 4035 | ## DNSDB::isParent()
|
---|
| 4036 | # Returns true if $id1 is a parent of $id2, false otherwise
|
---|
| 4037 | sub isParent {
|
---|
| 4038 | my $dbh = shift;
|
---|
| 4039 | my $id1 = shift;
|
---|
| 4040 | my $type1 = shift;
|
---|
| 4041 | my $id2 = shift;
|
---|
| 4042 | my $type2 = shift;
|
---|
| 4043 | ##todo: immediate, secondary, full (default)
|
---|
| 4044 |
|
---|
[157] | 4045 | # Return false on invalid types
|
---|
[244] | 4046 | return 0 if !grep /^$type1$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
| 4047 | return 0 if !grep /^$type2$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
[157] | 4048 |
|
---|
[117] | 4049 | # Return false on impossible relations
|
---|
| 4050 | return 0 if $type1 eq 'record'; # nothing may be a child of a record
|
---|
| 4051 | return 0 if $type1 eq 'defrec'; # nothing may be a child of a record
|
---|
[244] | 4052 | return 0 if $type1 eq 'defrevrec'; # nothing may be a child of a record
|
---|
[117] | 4053 | return 0 if $type1 eq 'user'; # nothing may be child of a user
|
---|
| 4054 | return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record
|
---|
[244] | 4055 | return 0 if $type1 eq 'revzone' && $type2 ne 'record';# reverse zone may not be a parent of anything other than a record
|
---|
[117] | 4056 |
|
---|
[186] | 4057 | # ennnhhhh.... if we're passed an id of 0, it will never be found. usual
|
---|
| 4058 | # case would be the UI creating a new <thing>, and so we don't have an ID for
|
---|
| 4059 | # <thing> to look up yet. in that case the UI should check the parent as well.
|
---|
| 4060 | return 0 if $id1 == 0; # nothing can have a parent id of 0
|
---|
| 4061 | return 1 if $id2 == 0; # anything could have a child id of 0 (or "unknown")
|
---|
| 4062 |
|
---|
[117] | 4063 | # group 1 is the ultimate root parent
|
---|
| 4064 | return 1 if $type1 eq 'group' && $id1 == 1;
|
---|
| 4065 |
|
---|
[155] | 4066 | # groups are always (a) parent of themselves
|
---|
| 4067 | return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2;
|
---|
| 4068 |
|
---|
[117] | 4069 | my $id = $id2;
|
---|
| 4070 | my $type = $type2;
|
---|
| 4071 | my $foundparent = 0;
|
---|
[155] | 4072 |
|
---|
[244] | 4073 | # Records are the only entity with two possible parents. We need to split the parent checks on
|
---|
| 4074 | # domain/rdns.
|
---|
| 4075 | if ($type eq 'record') {
|
---|
| 4076 | my ($dom,$rdns) = $dbh->selectrow_array("SELECT domain_id,rdns_id FROM records WHERE record_id=?",
|
---|
| 4077 | undef, ($id));
|
---|
| 4078 | # check immediate parent against request
|
---|
| 4079 | return 1 if $type1 eq 'domain' && $id1 == $dom;
|
---|
| 4080 | return 1 if $type1 eq 'revzone' && $id1 == $rdns;
|
---|
| 4081 | # if request is group, check *both* parents. Only check if the parent is nonzero though.
|
---|
| 4082 | return 1 if $dom && isParent($dbh, $id1, $type1, $dom, 'domain');
|
---|
| 4083 | return 1 if $rdns && isParent($dbh, $id1, $type1, $rdns, 'revzone');
|
---|
| 4084 | # exit here since we've executed the loop below by proxy in the above recursive calls.
|
---|
| 4085 | return 0;
|
---|
| 4086 | }
|
---|
| 4087 |
|
---|
| 4088 | # almost the same loop as getParents() above
|
---|
[186] | 4089 | my $limiter = 0;
|
---|
[117] | 4090 | while (1) {
|
---|
[155] | 4091 | my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
|
---|
[117] | 4092 | my $result = $dbh->selectrow_hashref($sql,
|
---|
[157] | 4093 | undef, ($id) );
|
---|
[186] | 4094 | if (!$result) {
|
---|
| 4095 | $limiter++;
|
---|
[244] | 4096 | ##fixme: how often will this happen on a live site? fail at max limiter <n>?
|
---|
[186] | 4097 | warn "no results looking for $sql with id $id (depth $limiter)\n";
|
---|
| 4098 | last;
|
---|
| 4099 | }
|
---|
[157] | 4100 | if ($result && $result->{$par_col{$type}} == $id1) {
|
---|
[117] | 4101 | $foundparent = 1;
|
---|
| 4102 | last;
|
---|
[157] | 4103 | } else {
|
---|
| 4104 | ##fixme: do we care about trying to return a "no such record/domain/user/group" error?
|
---|
[244] | 4105 | # should be impossible to create an inconsistent DB just with API calls.
|
---|
[157] | 4106 | warn $dbh->errstr." $sql, $id" if $dbh->errstr;
|
---|
[117] | 4107 | }
|
---|
| 4108 | # group 1 is its own parent. need this here more to break strange loops than for detecting a parent
|
---|
| 4109 | last if $result->{$par_col{$type}} == 1;
|
---|
[152] | 4110 | $id = $result->{$par_col{$type}};
|
---|
[117] | 4111 | $type = $par_type{$type};
|
---|
| 4112 | }
|
---|
| 4113 |
|
---|
| 4114 | return $foundparent;
|
---|
| 4115 | } # end isParent()
|
---|
| 4116 |
|
---|
| 4117 |
|
---|
[275] | 4118 | ## DNSDB::zoneStatus()
|
---|
| 4119 | # Returns and optionally sets a zone's status
|
---|
| 4120 | # Takes a database handle, domain/revzone ID, forward/reverse flag, and optionally a status argument
|
---|
| 4121 | # Returns status, or undef on errors.
|
---|
| 4122 | sub zoneStatus {
|
---|
[3] | 4123 | my $dbh = shift;
|
---|
| 4124 | my $id = shift;
|
---|
[275] | 4125 | my $revrec = shift;
|
---|
| 4126 | my $newstatus = shift || 'mu';
|
---|
[3] | 4127 |
|
---|
| 4128 | return undef if $id !~ /^\d+$/;
|
---|
| 4129 |
|
---|
[283] | 4130 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4131 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4132 | local $dbh->{AutoCommit} = 0;
|
---|
| 4133 | local $dbh->{RaiseError} = 1;
|
---|
| 4134 |
|
---|
[275] | 4135 | if ($newstatus ne 'mu') {
|
---|
[283] | 4136 | # ooo, fun! let's see what we were passed for status
|
---|
| 4137 | eval {
|
---|
| 4138 | $newstatus = 0 if $newstatus eq 'domoff';
|
---|
| 4139 | $newstatus = 1 if $newstatus eq 'domon';
|
---|
| 4140 | $dbh->do("UPDATE ".($revrec eq 'n' ? 'domains' : 'revzones')." SET status=? WHERE ".
|
---|
[275] | 4141 | ($revrec eq 'n' ? 'domain_id' : 'rdns_id')."=?", undef, ($newstatus,$id) );
|
---|
[283] | 4142 |
|
---|
| 4143 | ##fixme switch to more consise "Enabled <domain"/"Disabled <domain>" as with users?
|
---|
| 4144 | $resultstr = "Changed ".($revrec eq 'n' ? domainName($dbh, $id) : revName($dbh, $id)).
|
---|
| 4145 | " state to ".($newstatus ? 'active' : 'inactive');
|
---|
| 4146 |
|
---|
| 4147 | my %loghash;
|
---|
| 4148 | $loghash{domain_id} = $id if $revrec eq 'n';
|
---|
| 4149 | $loghash{rdns_id} = $id if $revrec eq 'y';
|
---|
| 4150 | $loghash{group_id} = parentID($dbh,
|
---|
| 4151 | (id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) );
|
---|
| 4152 | $loghash{entry} = $resultstr;
|
---|
| 4153 | _log($dbh, %loghash);
|
---|
| 4154 |
|
---|
| 4155 | $dbh->commit;
|
---|
| 4156 | };
|
---|
| 4157 | if ($@) {
|
---|
| 4158 | my $msg = $@;
|
---|
| 4159 | eval { $dbh->rollback; };
|
---|
| 4160 | $resultstr = '';
|
---|
| 4161 | $errstr = $msg;
|
---|
| 4162 | return;
|
---|
| 4163 | }
|
---|
[3] | 4164 | }
|
---|
| 4165 |
|
---|
[275] | 4166 | my ($status) = $dbh->selectrow_array("SELECT status FROM ".
|
---|
| 4167 | ($revrec eq 'n' ? "domains WHERE domain_id=?" : "revzones WHERE rdns_id=?"),
|
---|
| 4168 | undef, ($id) );
|
---|
[3] | 4169 | return $status;
|
---|
[275] | 4170 | } # end zoneStatus()
|
---|
[3] | 4171 |
|
---|
| 4172 |
|
---|
[452] | 4173 | ## DNSDB::getZonesByCIDR()
|
---|
| 4174 | # Get a list of zone names and IDs that records for a passed CIDR block are within.
|
---|
| 4175 | sub getZonesByCIDR {
|
---|
| 4176 | my $dbh = shift;
|
---|
| 4177 | my %args = @_;
|
---|
| 4178 |
|
---|
| 4179 | my $result = $dbh->selectall_arrayref("SELECT rdns_id,revnet FROM revzones WHERE revnet >>= ? OR revnet <<= ?",
|
---|
| 4180 | { Slice => {} }, ($args{cidr}, $args{cidr}) );
|
---|
| 4181 | return $result;
|
---|
| 4182 | } # end getZonesByCIDR()
|
---|
| 4183 |
|
---|
| 4184 |
|
---|
[33] | 4185 | ## DNSDB::importAXFR
|
---|
| 4186 | # Import a domain via AXFR
|
---|
[37] | 4187 | # Takes AXFR host, domain to transfer, group to put the domain in,
|
---|
| 4188 | # and optionally:
|
---|
| 4189 | # - active/inactive state flag (defaults to active)
|
---|
| 4190 | # - overwrite-SOA flag (defaults to off)
|
---|
| 4191 | # - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
|
---|
| 4192 | # Returns a status code (OK, WARN, or FAIL) and message - message should be blank
|
---|
| 4193 | # if status is OK, but WARN includes conditions that are not fatal but should
|
---|
| 4194 | # really be reported.
|
---|
[33] | 4195 | sub importAXFR {
|
---|
| 4196 | my $dbh = shift;
|
---|
[35] | 4197 | my $ifrom_in = shift;
|
---|
[301] | 4198 | my $zone = shift;
|
---|
[33] | 4199 | my $group = shift;
|
---|
[436] | 4200 | my $status = shift;
|
---|
| 4201 | $status = (defined($status) ? $status : 0); # force sane semantics, and allow passing "null" (inactive) status
|
---|
[33] | 4202 | my $rwsoa = shift || 0;
|
---|
| 4203 | my $rwns = shift || 0;
|
---|
[436] | 4204 | my $newttl = shift;
|
---|
[301] | 4205 | my $merge = shift || 0; # do we attempt to merge A/AAAA and PTR records whenever possible?
|
---|
| 4206 | # do we overload this with the fixme below?
|
---|
[33] | 4207 | ##fixme: add mode to delete&replace, merge+overwrite, merge new?
|
---|
| 4208 |
|
---|
[37] | 4209 | my $nrecs = 0;
|
---|
| 4210 | my $soaflag = 0;
|
---|
| 4211 | my $nsflag = 0;
|
---|
| 4212 | my $warnmsg = '';
|
---|
| 4213 | my $ifrom;
|
---|
[33] | 4214 |
|
---|
[301] | 4215 | my $rev = 'n';
|
---|
[302] | 4216 | my $code = 'OK';
|
---|
| 4217 | my $msg = 'foobar?';
|
---|
[301] | 4218 |
|
---|
[35] | 4219 | # choke on possible bad setting in ifrom
|
---|
[37] | 4220 | # IPv4 and v6, and valid hostnames!
|
---|
[35] | 4221 | ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
| 4222 | return ('FAIL', "Bad AXFR source host $ifrom")
|
---|
| 4223 | unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
| 4224 |
|
---|
[301] | 4225 | my $errmsg;
|
---|
| 4226 |
|
---|
| 4227 | my $zone_id;
|
---|
| 4228 | my $domain_id = 0;
|
---|
| 4229 | my $rdns_id = 0;
|
---|
| 4230 | my $cidr;
|
---|
| 4231 |
|
---|
| 4232 | # magic happens! detect if we're importing a domain or a reverse zone
|
---|
| 4233 | # while we're at it, figure out what the CIDR netblock is (if we got a .arpa)
|
---|
| 4234 | # or what the formal .arpa zone is (if we got a CIDR netblock)
|
---|
| 4235 | # Handles sub-octet v4 zones in the format specified in the Cricket Book, 2nd Ed, p217-218
|
---|
| 4236 |
|
---|
| 4237 | if ($zone =~ m{(?:\.arpa\.?|/\d+)$}) {
|
---|
| 4238 | # we seem to have a reverse zone
|
---|
| 4239 | $rev = 'y';
|
---|
| 4240 |
|
---|
| 4241 | if ($zone =~ /\.arpa\.?$/) {
|
---|
| 4242 | # we have a formal reverse zone. call _zone2cidr and get the CIDR block.
|
---|
| 4243 | ($code,$msg) = _zone2cidr($zone);
|
---|
| 4244 | return ($code, $msg) if $code eq 'FAIL';
|
---|
| 4245 | $cidr = $msg;
|
---|
| 4246 | } elsif ($zone =~ m|^[\d.]+/\d+$|) {
|
---|
| 4247 | # v4 revzone, CIDR netblock
|
---|
| 4248 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 4249 | $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
| 4250 | } elsif ($zone =~ m|^[a-fA-F\d:]+/\d+$|) {
|
---|
| 4251 | # v6 revzone, CIDR netblock
|
---|
| 4252 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
| 4253 | return ('FAIL', "$zone is not a nibble-aligned block") if $cidr->masklen % 4 != 0;
|
---|
| 4254 | $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.');
|
---|
| 4255 | } else {
|
---|
| 4256 | # there is. no. else!
|
---|
| 4257 | return ('FAIL', "Unknown zone name format");
|
---|
| 4258 | }
|
---|
| 4259 |
|
---|
| 4260 | # quick check to start to see if we've already got one
|
---|
| 4261 |
|
---|
| 4262 | ($zone_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?",
|
---|
| 4263 | undef, ("$cidr"));
|
---|
| 4264 | $rdns_id = $zone_id;
|
---|
| 4265 | } else {
|
---|
| 4266 | # default to domain
|
---|
[349] | 4267 | ($zone_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
[301] | 4268 | undef, ($zone));
|
---|
| 4269 | $domain_id = $zone_id;
|
---|
| 4270 | }
|
---|
| 4271 |
|
---|
| 4272 | return ('FAIL', ($rev eq 'n' ? 'Domain' : 'Reverse zone')." already exists") if $zone_id;
|
---|
| 4273 |
|
---|
[303] | 4274 | # little local utility sub to swap $val and $host for revzone records.
|
---|
| 4275 | sub _revswap {
|
---|
| 4276 | my $rechost = shift;
|
---|
| 4277 | my $recdata = shift;
|
---|
| 4278 |
|
---|
| 4279 | if ($rechost =~ /\.in-addr\.arpa\.?$/) {
|
---|
| 4280 | $rechost =~ s/\.in-addr\.arpa\.?$//;
|
---|
| 4281 | $rechost = join '.', reverse split /\./, $rechost;
|
---|
| 4282 | } else {
|
---|
| 4283 | $rechost =~ s/\.ip6\.arpa\.?$//;
|
---|
| 4284 | my @nibs = reverse split /\./, $rechost;
|
---|
| 4285 | $rechost = '';
|
---|
| 4286 | my $nc;
|
---|
| 4287 | foreach (@nibs) {
|
---|
| 4288 | $rechost.= $_;
|
---|
| 4289 | $rechost .= ":" if ++$nc % 4 == 0 && $nc < 32;
|
---|
| 4290 | }
|
---|
[307] | 4291 | $rechost .= ":" if $nc < 32 && $rechost !~ /\*$/; # close netblock records?
|
---|
| 4292 | ##fixme: there's a case that ends up with a partial entry here:
|
---|
| 4293 | # ip:add:re:ss::
|
---|
| 4294 | # can't reproduce after letting it sit overnight after discovery. :(
|
---|
| 4295 | #print "$rechost\n";
|
---|
[303] | 4296 | # canonicalize with NetAddr::IP
|
---|
| 4297 | $rechost = NetAddr::IP->new($rechost)->addr unless $rechost =~ /\*$/;
|
---|
| 4298 | }
|
---|
| 4299 | return ($recdata,$rechost)
|
---|
| 4300 | }
|
---|
| 4301 |
|
---|
| 4302 |
|
---|
[33] | 4303 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
| 4304 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
| 4305 | local $dbh->{AutoCommit} = 0;
|
---|
| 4306 | local $dbh->{RaiseError} = 1;
|
---|
| 4307 |
|
---|
[301] | 4308 | my $sth;
|
---|
| 4309 | eval {
|
---|
[34] | 4310 |
|
---|
[301] | 4311 | if ($rev eq 'n') {
|
---|
[33] | 4312 | ##fixme: serial
|
---|
[301] | 4313 | $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef, ($zone,$group,$status) );
|
---|
| 4314 | # get domain id so we can do the records
|
---|
| 4315 | ($zone_id) = $dbh->selectrow_array("SELECT currval('domains_domain_id_seq')");
|
---|
| 4316 | $domain_id = $zone_id;
|
---|
| 4317 | _log($dbh, (group_id => $group, domain_id => $domain_id,
|
---|
| 4318 | entry => "[Added ".($status ? 'active' : 'inactive')." domain $zone via AXFR]") );
|
---|
| 4319 | } else {
|
---|
| 4320 | ##fixme: serial
|
---|
| 4321 | $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef, ($cidr,$group,$status) );
|
---|
| 4322 | # get revzone id so we can do the records
|
---|
| 4323 | ($zone_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
| 4324 | $rdns_id = $zone_id;
|
---|
| 4325 | _log($dbh, (group_id => $group, rdns_id => $rdns_id,
|
---|
[303] | 4326 | entry => "[Added ".($status ? 'active' : 'inactive')." reverse zone $cidr via AXFR]") );
|
---|
[301] | 4327 | }
|
---|
[33] | 4328 |
|
---|
[35] | 4329 | ## bizarre DBI<->Net::DNS interaction bug:
|
---|
| 4330 | ## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
|
---|
[37] | 4331 | ## fixed, apparently I was doing *something* odd, but not certain what it was that
|
---|
| 4332 | ## caused a commit instead of barfing
|
---|
[35] | 4333 |
|
---|
[34] | 4334 | my $res = Net::DNS::Resolver->new;
|
---|
[35] | 4335 | $res->nameservers($ifrom);
|
---|
[301] | 4336 | $res->axfr_start($zone)
|
---|
[35] | 4337 | or die "Couldn't begin AXFR\n";
|
---|
[34] | 4338 |
|
---|
[301] | 4339 | $sth = $dbh->prepare("INSERT INTO records (domain_id,rdns_id,host,type,val,distance,weight,port,ttl)".
|
---|
| 4340 | " VALUES (?,?,?,?,?,?,?,?,?)");
|
---|
| 4341 |
|
---|
[307] | 4342 | # Stash info about sub-octet v4 revzones here so we don't have
|
---|
| 4343 | # to store the CNAMEs used to delegate a suboctet zone
|
---|
| 4344 | # $suboct{zone}{ns}[] -> array of nameservers
|
---|
| 4345 | # $suboct{zone}{cname}[] -> array of extant CNAMEs (Just In Case someone did something bizarre)
|
---|
| 4346 | ## commented pending actual use of this data. for now, we'll just
|
---|
| 4347 | ## auto-(re)create the CNAMEs in revzones on export
|
---|
| 4348 | # my %suboct;
|
---|
| 4349 |
|
---|
[35] | 4350 | while (my $rr = $res->axfr_next()) {
|
---|
[301] | 4351 |
|
---|
| 4352 | my $val;
|
---|
| 4353 | my $distance = 0;
|
---|
| 4354 | my $weight = 0;
|
---|
| 4355 | my $port = 0;
|
---|
[303] | 4356 | my $logfrag = '';
|
---|
[301] | 4357 |
|
---|
[33] | 4358 | my $type = $rr->type;
|
---|
[301] | 4359 | my $host = $rr->name;
|
---|
[436] | 4360 | my $ttl = ($newttl ? $newttl : $rr->ttl); # allow force-override TTLs
|
---|
[35] | 4361 |
|
---|
[37] | 4362 | $soaflag = 1 if $type eq 'SOA';
|
---|
| 4363 | $nsflag = 1 if $type eq 'NS';
|
---|
[35] | 4364 |
|
---|
[34] | 4365 | # "Primary" types:
|
---|
| 4366 | # A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
|
---|
| 4367 | # maybe KEY
|
---|
| 4368 |
|
---|
[302] | 4369 | # BIND supports:
|
---|
| 4370 | # [standard]
|
---|
| 4371 | # A AAAA CNAME MX NS PTR SOA TXT
|
---|
| 4372 | # [variously experimental, obsolete, or obscure]
|
---|
| 4373 | # 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
|
---|
| 4374 | # ... if one can ever find the right magic to format them correctly
|
---|
| 4375 |
|
---|
| 4376 | # Net::DNS supports:
|
---|
| 4377 | # RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
|
---|
| 4378 | # EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
|
---|
| 4379 | # DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
|
---|
| 4380 |
|
---|
[35] | 4381 | # nasty big ugly case-like thing here, since we have to do *some* different
|
---|
| 4382 | # processing depending on the record. le sigh.
|
---|
| 4383 |
|
---|
[105] | 4384 | ##fixme: what record types other than TXT can/will have >255-byte payloads?
|
---|
| 4385 |
|
---|
[34] | 4386 | if ($type eq 'A') {
|
---|
[301] | 4387 | $val = $rr->address;
|
---|
[34] | 4388 | } elsif ($type eq 'NS') {
|
---|
[37] | 4389 | # hmm. should we warn here if subdomain NS'es are left alone?
|
---|
[301] | 4390 | next if ($rwns && ($rr->name eq $zone));
|
---|
[302] | 4391 | if ($rev eq 'y') {
|
---|
| 4392 | # revzones have records more or less reversed from forward zones.
|
---|
| 4393 | my ($tmpcode,$tmpmsg) = _zone2cidr($host);
|
---|
[401] | 4394 | die "Error converting NS record: $tmpmsg\n" if $tmpcode eq 'FAIL'; # hmm. may not make sense...
|
---|
[302] | 4395 | $val = "$tmpmsg";
|
---|
| 4396 | $host = $rr->nsdname;
|
---|
[303] | 4397 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
[307] | 4398 | # Tag and preserve. For now this is commented for a no-op, but we have Ideas for
|
---|
| 4399 | # another custom storage type ("DELEGATE") that will use these subzone-delegation records
|
---|
| 4400 | #if ($val ne "$cidr") {
|
---|
| 4401 | # push @{$suboct{$val}{ns}}, $host;
|
---|
| 4402 | #}
|
---|
[302] | 4403 | } else {
|
---|
| 4404 | $val = $rr->nsdname;
|
---|
| 4405 | }
|
---|
[35] | 4406 | $nsflag = 1;
|
---|
[34] | 4407 | } elsif ($type eq 'CNAME') {
|
---|
[302] | 4408 | if ($rev eq 'y') {
|
---|
[303] | 4409 | # hmm. do we even want to bother with storing these at this level? Sub-octet delegation
|
---|
| 4410 | # by CNAME is essentially a record-publication hack, and we want to just represent the
|
---|
| 4411 | # "true" logical intentions as far down the stack as we can from the UI.
|
---|
| 4412 | ($host,$val) = _revswap($host,$rr->cname);
|
---|
| 4413 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
[307] | 4414 | # Tag and preserve in case we want to commit them as-is later, but mostly we don't care.
|
---|
| 4415 | # Commented pending actually doing something with possibly new type DELEGATE
|
---|
| 4416 | #my $tmprev = $host;
|
---|
| 4417 | #$tmprev =~ s/^\d+\.//;
|
---|
| 4418 | #($code,$tmprev) = _zone2cidr($tmprev);
|
---|
| 4419 | #push @{$suboct{"$tmprev"}{cname}}, $val;
|
---|
| 4420 | # Silently skip CNAMEs in revzones.
|
---|
| 4421 | next;
|
---|
[302] | 4422 | } else {
|
---|
| 4423 | $val = $rr->cname;
|
---|
| 4424 | }
|
---|
[34] | 4425 | } elsif ($type eq 'SOA') {
|
---|
[37] | 4426 | next if $rwsoa;
|
---|
[307] | 4427 | $host = $rr->rname.":".$rr->mname;
|
---|
[301] | 4428 | $val = $rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum;
|
---|
[35] | 4429 | $soaflag = 1;
|
---|
[34] | 4430 | } elsif ($type eq 'PTR') {
|
---|
[303] | 4431 | ($host,$val) = _revswap($host,$rr->ptrdname);
|
---|
| 4432 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
[34] | 4433 | # hmm. PTR records should not be in forward zones.
|
---|
| 4434 | } elsif ($type eq 'MX') {
|
---|
[301] | 4435 | $val = $rr->exchange;
|
---|
| 4436 | $distance = $rr->preference;
|
---|
[34] | 4437 | } elsif ($type eq 'TXT') {
|
---|
| 4438 | ##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
|
---|
| 4439 | ## but don't really seem enthusiastic about it.
|
---|
[303] | 4440 | #print "should use rdatastr:\n\t".$rr->rdatastr."\n or char_str_list:\n\t".join(' ',$rr->char_str_list())."\n";
|
---|
| 4441 | # rdatastr returns a BIND-targetted logical string, including opening and closing quotes
|
---|
| 4442 | # char_str_list returns a list of the individual string fragments in the record
|
---|
[307] | 4443 | # txtdata returns the more useful all-in-one form (since we want to push such protocol
|
---|
| 4444 | # details as far down the stack as we can)
|
---|
[303] | 4445 | # NB: this may turn out to be more troublesome if we ever have need of >512-byte TXT records.
|
---|
| 4446 | if ($rev eq 'y') {
|
---|
| 4447 | ($host,$val) = _revswap($host,$rr->txtdata);
|
---|
| 4448 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
| 4449 | } else {
|
---|
| 4450 | $val = $rr->txtdata;
|
---|
| 4451 | }
|
---|
[34] | 4452 | } elsif ($type eq 'SPF') {
|
---|
| 4453 | ##fixme: and the same caveat here, since it is apparently a clone of ::TXT
|
---|
[301] | 4454 | $val = $rr->txtdata;
|
---|
[34] | 4455 | } elsif ($type eq 'AAAA') {
|
---|
[301] | 4456 | $val = $rr->address;
|
---|
[34] | 4457 | } elsif ($type eq 'SRV') {
|
---|
[301] | 4458 | $val = $rr->target;
|
---|
| 4459 | $distance = $rr->priority;
|
---|
| 4460 | $weight = $rr->weight;
|
---|
| 4461 | $port = $rr->port;
|
---|
[34] | 4462 | } elsif ($type eq 'KEY') {
|
---|
[35] | 4463 | # we don't actually know what to do with these...
|
---|
[301] | 4464 | $val = $rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname;
|
---|
[35] | 4465 | } else {
|
---|
[301] | 4466 | $val = $rr->rdatastr;
|
---|
[35] | 4467 | # Finding a different record type is not fatal.... just problematic.
|
---|
[37] | 4468 | # We may not be able to export it correctly.
|
---|
[35] | 4469 | $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
|
---|
[33] | 4470 | }
|
---|
| 4471 |
|
---|
[303] | 4472 | my $logentry = "[AXFR ".($rev eq 'n' ? $zone : $cidr)."] ";
|
---|
[34] | 4473 |
|
---|
[307] | 4474 | if ($merge) {
|
---|
| 4475 | if ($rev eq 'n') {
|
---|
| 4476 | # importing a domain; we have A and AAAA records that could be merged with matching PTR records
|
---|
| 4477 | my $etype;
|
---|
| 4478 | my ($erdns,$erid,$ettl) = $dbh->selectrow_array("SELECT rdns_id,record_id,ttl FROM records ".
|
---|
| 4479 | "WHERE host=? AND val=? AND type=12",
|
---|
| 4480 | undef, ($host, $val) );
|
---|
| 4481 | if ($erid) {
|
---|
| 4482 | if ($type eq 'A') { # PTR -> A+PTR
|
---|
| 4483 | $etype = 65280;
|
---|
| 4484 | $logentry .= "Merged A record with existing PTR record '$host A+PTR $val', TTL $ettl";
|
---|
| 4485 | }
|
---|
| 4486 | if ($type eq 'AAAA') { # PTR -> AAAA+PTR
|
---|
| 4487 | $etype = 65281;
|
---|
| 4488 | $logentry .= "Merged AAAA record with existing PTR record '$host AAAA+PTR $val', TTL $ettl";
|
---|
| 4489 | }
|
---|
| 4490 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
| 4491 | $dbh->do("UPDATE records SET domain_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
| 4492 | ($domain_id, $ettl, $etype, $erid));
|
---|
| 4493 | $nrecs++;
|
---|
| 4494 | _log($dbh, (group_id => $group, domain_id => $domain_id, rdns_id => $erdns, entry => $logentry) );
|
---|
| 4495 | next; # while axfr_next
|
---|
| 4496 | }
|
---|
| 4497 | } # $rev eq 'n'
|
---|
| 4498 | else {
|
---|
| 4499 | # importing a revzone, we have PTR records that could be merged with matching A/AAAA records
|
---|
| 4500 | my ($domid,$erid,$ettl,$etype) = $dbh->selectrow_array("SELECT domain_id,record_id,ttl,type FROM records ".
|
---|
| 4501 | "WHERE host=? AND val=? AND (type=1 OR type=28)",
|
---|
| 4502 | undef, ($host, $val) );
|
---|
| 4503 | if ($erid) {
|
---|
| 4504 | if ($etype == 1) { # A -> A+PTR
|
---|
| 4505 | $etype = 65280;
|
---|
| 4506 | $logentry .= "Merged PTR record with existing matching A record '$host A+PTR $val', TTL $ettl";
|
---|
| 4507 | }
|
---|
| 4508 | if ($etype == 28) { # AAAA -> AAAA+PTR
|
---|
| 4509 | $etype = 65281;
|
---|
| 4510 | $logentry .= "Merged PTR record with existing matching AAAA record '$host AAAA+PTR $val', TTL $ettl";
|
---|
| 4511 | }
|
---|
| 4512 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
| 4513 | $dbh->do("UPDATE records SET rdns_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
| 4514 | ($rdns_id, $ettl, $etype, $erid));
|
---|
| 4515 | $nrecs++;
|
---|
| 4516 | _log($dbh, (group_id => $group, domain_id => $domid, rdns_id => $rdns_id, entry => $logentry) );
|
---|
| 4517 | next; # while axfr_next
|
---|
| 4518 | }
|
---|
| 4519 | } # $rev eq 'y'
|
---|
| 4520 | } # if $merge
|
---|
[34] | 4521 |
|
---|
[302] | 4522 | # Insert the new record
|
---|
[301] | 4523 | $sth->execute($domain_id, $rdns_id, $host, $reverse_typemap{$type}, $val,
|
---|
| 4524 | $distance, $weight, $port, $ttl);
|
---|
| 4525 |
|
---|
[37] | 4526 | $nrecs++;
|
---|
[34] | 4527 |
|
---|
[301] | 4528 | if ($type eq 'SOA') {
|
---|
| 4529 | # also !$rwsoa, but if that's set, it should be impossible to get here.
|
---|
| 4530 | my @tmp1 = split /:/, $host;
|
---|
| 4531 | my @tmp2 = split /:/, $val;
|
---|
| 4532 | $logentry .= "Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
| 4533 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl";
|
---|
[303] | 4534 | } elsif ($logfrag) {
|
---|
| 4535 | # special case for log entries we need to meddle with a little.
|
---|
| 4536 | $logentry .= $logfrag;
|
---|
[301] | 4537 | } else {
|
---|
| 4538 | $logentry .= "Added record '$host $type";
|
---|
| 4539 | $logentry .= " [distance $distance]" if $type eq 'MX';
|
---|
| 4540 | $logentry .= " [priority $distance] [weight $weight] [port $port]" if $type eq 'SRV';
|
---|
| 4541 | $logentry .= " $val', TTL $ttl";
|
---|
| 4542 | }
|
---|
| 4543 | _log($dbh, (group_id => $group, domain_id => $domain_id, rdns_id => $rdns_id, entry => $logentry) );
|
---|
| 4544 |
|
---|
[37] | 4545 | } # while axfr_next
|
---|
| 4546 |
|
---|
[307] | 4547 | # Detect and handle delegated subzones
|
---|
| 4548 | # Placeholder for when we decide what to actually do with this, see previous comments in NS and CNAME handling.
|
---|
| 4549 | #foreach (keys %suboct) {
|
---|
| 4550 | # print "found ".($suboct{$_}{ns} ? @{$suboct{$_}{ns}} : '0')." NS records and ".
|
---|
| 4551 | # ($suboct{$_}{cname} ? @{$suboct{$_}{cname}} : '0')." CNAMEs for $_\n";
|
---|
| 4552 | #}
|
---|
| 4553 |
|
---|
[37] | 4554 | # Overwrite SOA record
|
---|
| 4555 | if ($rwsoa) {
|
---|
| 4556 | $soaflag = 1;
|
---|
| 4557 | my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
|
---|
| 4558 | my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
| 4559 | $sthgetsoa->execute($group,$reverse_typemap{SOA});
|
---|
| 4560 | while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
|
---|
[301] | 4561 | $host =~ s/DOMAIN/$zone/g;
|
---|
| 4562 | $val =~ s/DOMAIN/$zone/g;
|
---|
| 4563 | $sthputsoa->execute($zone_id,$host,$reverse_typemap{SOA},$val,$ttl);
|
---|
[34] | 4564 | }
|
---|
[37] | 4565 | }
|
---|
[34] | 4566 |
|
---|
[37] | 4567 | # Overwrite NS records
|
---|
| 4568 | if ($rwns) {
|
---|
| 4569 | $nsflag = 1;
|
---|
| 4570 | my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
|
---|
| 4571 | my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
| 4572 | $sthgetns->execute($group,$reverse_typemap{NS});
|
---|
| 4573 | while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
|
---|
[301] | 4574 | $host =~ s/DOMAIN/$zone/g;
|
---|
| 4575 | $val =~ s/DOMAIN/$zone/g;
|
---|
| 4576 | $sthputns->execute($zone_id,$host,$reverse_typemap{NS},$val,$ttl);
|
---|
[37] | 4577 | }
|
---|
| 4578 | }
|
---|
[34] | 4579 |
|
---|
[35] | 4580 | die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
|
---|
| 4581 | die "Bad zone: No SOA record!\n" if !$soaflag;
|
---|
| 4582 | die "Bad zone: No NS records!\n" if !$nsflag;
|
---|
| 4583 |
|
---|
[37] | 4584 | $dbh->commit;
|
---|
[35] | 4585 |
|
---|
[33] | 4586 | };
|
---|
| 4587 |
|
---|
| 4588 | if ($@) {
|
---|
| 4589 | my $msg = $@;
|
---|
| 4590 | eval { $dbh->rollback; };
|
---|
[34] | 4591 | return ('FAIL',$msg." $warnmsg");
|
---|
[33] | 4592 | } else {
|
---|
[35] | 4593 | return ('WARN', $warnmsg) if $warnmsg;
|
---|
[91] | 4594 | return ('OK',"Imported OK");
|
---|
[33] | 4595 | }
|
---|
| 4596 |
|
---|
[37] | 4597 | # it should be impossible to get here.
|
---|
[34] | 4598 | return ('WARN',"OOOK!");
|
---|
[33] | 4599 | } # end importAXFR()
|
---|
| 4600 |
|
---|
| 4601 |
|
---|
[302] | 4602 | ## DNSDB::importBIND()
|
---|
| 4603 | sub importBIND {
|
---|
| 4604 | } # end importBIND()
|
---|
| 4605 |
|
---|
| 4606 |
|
---|
| 4607 | ## DNSDB::import_tinydns()
|
---|
| 4608 | sub import_tinydns {
|
---|
| 4609 | } # end import_tinydns()
|
---|
| 4610 |
|
---|
| 4611 |
|
---|
[103] | 4612 | ## DNSDB::export()
|
---|
| 4613 | # Export the DNS database, or a part of it
|
---|
| 4614 | # Takes database handle, export type, optional arguments depending on type
|
---|
| 4615 | # Writes zone data to targets as appropriate for type
|
---|
| 4616 | sub export {
|
---|
| 4617 | my $dbh = shift;
|
---|
| 4618 | my $target = shift;
|
---|
| 4619 |
|
---|
| 4620 | if ($target eq 'tiny') {
|
---|
| 4621 | __export_tiny($dbh,@_);
|
---|
| 4622 | }
|
---|
| 4623 | # elsif ($target eq 'foo') {
|
---|
| 4624 | # __export_foo($dbh,@_);
|
---|
| 4625 | #}
|
---|
| 4626 | # etc
|
---|
| 4627 |
|
---|
| 4628 | } # end export()
|
---|
| 4629 |
|
---|
| 4630 |
|
---|
| 4631 | ## DNSDB::__export_tiny
|
---|
| 4632 | # Internal sub to implement tinyDNS (compatible) export
|
---|
| 4633 | # Takes database handle, filehandle to write export to, optional argument(s)
|
---|
| 4634 | # to determine which data gets exported
|
---|
| 4635 | sub __export_tiny {
|
---|
| 4636 | my $dbh = shift;
|
---|
| 4637 | my $datafile = shift;
|
---|
| 4638 |
|
---|
| 4639 | ##fixme: slurp up further options to specify particular zone(s) to export
|
---|
| 4640 |
|
---|
| 4641 | ##fixme: fail if $datafile isn't an open, writable file
|
---|
| 4642 |
|
---|
| 4643 | # easy case - export all evarything
|
---|
| 4644 | # not-so-easy case - export item(s) specified
|
---|
| 4645 | # todo: figure out what kind of list we use to export items
|
---|
| 4646 |
|
---|
[329] | 4647 | # raw packet in unknown format: first byte indicates length
|
---|
| 4648 | # of remaining data, allows up to 255 raw bytes
|
---|
| 4649 |
|
---|
[372] | 4650 | # Locations/views - worth including in the caching setup?
|
---|
| 4651 | my $lochash = $dbh->selectall_hashref("SELECT location,iplist FROM locations", 'location');
|
---|
| 4652 | foreach my $location (keys %$lochash) {
|
---|
[375] | 4653 | foreach my $ipprefix (split /[,\s]+/, $lochash->{$location}{iplist}) {
|
---|
| 4654 | $ipprefix =~ s/\s+//g;
|
---|
[449] | 4655 | $ipprefix = new NetAddr::IP $ipprefix;
|
---|
| 4656 | ##fixme: how to handle IPv6?
|
---|
| 4657 | next if $ipprefix->{isv6};
|
---|
| 4658 | # have to account for /nn CIDR entries. tinydns only speaks octet-sliced prefix.
|
---|
| 4659 | if ($ipprefix->masklen <= 8) {
|
---|
| 4660 | foreach ($ipprefix->split(8)) {
|
---|
| 4661 | my $tmp = $_->addr;
|
---|
| 4662 | $tmp =~ s/\.\d+\.\d+\.\d+$//;
|
---|
| 4663 | print $datafile "%$location:$tmp\n";
|
---|
| 4664 | }
|
---|
| 4665 | } elsif ($ipprefix->masklen <= 16) {
|
---|
| 4666 | foreach ($ipprefix->split(16)) {
|
---|
| 4667 | my $tmp = $_->addr;
|
---|
| 4668 | $tmp =~ s/\.\d+\.\d+$//;
|
---|
| 4669 | print $datafile "%$location:$tmp\n";
|
---|
| 4670 | }
|
---|
| 4671 | } elsif ($ipprefix->masklen <= 24) {
|
---|
| 4672 | foreach ($ipprefix->split(24)) {
|
---|
| 4673 | my $tmp = $_->addr;
|
---|
| 4674 | $tmp =~ s/\.\d+$//;
|
---|
| 4675 | print $datafile "%$location:$tmp\n";
|
---|
| 4676 | }
|
---|
| 4677 | } else {
|
---|
| 4678 | foreach ($ipprefix->split(32)) {
|
---|
| 4679 | print $datafile "%$location:".$_->addr."\n";
|
---|
| 4680 | }
|
---|
| 4681 | }
|
---|
[372] | 4682 | }
|
---|
| 4683 | print $datafile "%$location\n" if !$lochash->{$location}{iplist};
|
---|
| 4684 | }
|
---|
| 4685 |
|
---|
[329] | 4686 | # tracking hash so we don't double-export A+PTR or AAAA+PTR records.
|
---|
| 4687 | my %recflags;
|
---|
| 4688 |
|
---|
[368] | 4689 | my $domsth = $dbh->prepare("SELECT domain_id,domain,status,changed FROM domains WHERE status=1");
|
---|
[372] | 4690 | my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
[368] | 4691 | "FROM records WHERE domain_id=? AND type < 65280"); # Just exclude all types relating to rDNS
|
---|
[372] | 4692 | my $zonesth = $dbh->prepare("UPDATE domains SET changed='n' WHERE domain_id=?");
|
---|
[103] | 4693 | $domsth->execute();
|
---|
[368] | 4694 | while (my ($domid,$dom,$domstat,$changed) = $domsth->fetchrow_array) {
|
---|
| 4695 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
| 4696 | # O_NOFOLLOW
|
---|
| 4697 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
| 4698 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
| 4699 | # still be followed.
|
---|
| 4700 | # but that doesn't help other platforms. :/
|
---|
| 4701 | sysopen(ZONECACHE, "$config{exportcache}/$dom", O_RDWR|O_CREAT);
|
---|
| 4702 | flock(ZONECACHE, LOCK_EX);
|
---|
| 4703 | if ($changed || -s "$config{exportcache}/$dom" == 0) {
|
---|
| 4704 | $recsth->execute($domid);
|
---|
[372] | 4705 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc) = $recsth->fetchrow_array) {
|
---|
[368] | 4706 | next if $recflags{$recid};
|
---|
[108] | 4707 |
|
---|
[372] | 4708 | $loc = '' if !$loc; # de-nullify - just in case
|
---|
| 4709 | ##fixme: handle case of record-with-location-that-doesn't-exist better.
|
---|
| 4710 | # note this currently fails safe (tested) - records with a location that
|
---|
| 4711 | # doesn't exist will not be sent to any client
|
---|
| 4712 | # $loc = '' if !$lochash->{$loc};
|
---|
| 4713 |
|
---|
[108] | 4714 | ##fixme: record validity timestamp. tinydns supports fiddling with timestamps.
|
---|
| 4715 | # note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
|
---|
| 4716 | # timestamps are TAI64
|
---|
| 4717 | # ~~ 2^62 + time()
|
---|
[368] | 4718 | my $stamp = '';
|
---|
[108] | 4719 |
|
---|
[368] | 4720 | # support tinydns' auto-TTL
|
---|
| 4721 | $ttl = '' if $ttl == '0';
|
---|
[367] | 4722 |
|
---|
[417] | 4723 | # Spaces are evil.
|
---|
[441] | 4724 | $host =~ s/^\s+//;
|
---|
| 4725 | $host =~ s/\s+$//;
|
---|
| 4726 | if ($typemap{$type} ne 'TXT') {
|
---|
[417] | 4727 | # Leading or trailng spaces could be legit in TXT records.
|
---|
[441] | 4728 | $val =~ s/^\s+//;
|
---|
| 4729 | $val =~ s/\s+$//;
|
---|
[417] | 4730 | }
|
---|
| 4731 |
|
---|
[368] | 4732 | _printrec_tiny(*ZONECACHE, 'n', \%recflags,
|
---|
| 4733 | $dom, $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp)
|
---|
| 4734 | if *ZONECACHE;
|
---|
[450] | 4735 |
|
---|
[368] | 4736 | # in case the zone shrunk, get rid of garbage at the end of the file.
|
---|
| 4737 | truncate(ZONECACHE, tell(ZONECACHE));
|
---|
| 4738 |
|
---|
| 4739 | $recflags{$recid} = 1;
|
---|
| 4740 | } # while ($recsth)
|
---|
| 4741 | }
|
---|
[450] | 4742 | # stream from cache, whether freshly created or existing
|
---|
| 4743 | print $datafile $_ while <ZONECACHE>;
|
---|
[368] | 4744 | close ZONECACHE;
|
---|
| 4745 | # mark domain as unmodified
|
---|
| 4746 | $zonesth->execute($domid);
|
---|
[329] | 4747 | } # while ($domsth)
|
---|
| 4748 |
|
---|
[368] | 4749 | my $revsth = $dbh->prepare("SELECT rdns_id,revnet,status,changed FROM revzones WHERE status=1 ".
|
---|
[337] | 4750 | "ORDER BY masklen(revnet) DESC");
|
---|
[372] | 4751 |
|
---|
[344] | 4752 | # For reasons unknown, we can't sanely UNION these statements. Feh.
|
---|
| 4753 | # Supposedly it should work though (note last 3 lines):
|
---|
| 4754 | ## PG manual
|
---|
| 4755 | #UNION Clause
|
---|
| 4756 | #
|
---|
| 4757 | #The UNION clause has this general form:
|
---|
| 4758 | #
|
---|
| 4759 | # select_statement UNION [ ALL ] select_statement
|
---|
| 4760 | #
|
---|
| 4761 | #select_statement is any SELECT statement without an ORDER BY, LIMIT, FOR UPDATE, or FOR SHARE clause. (ORDER BY
|
---|
| 4762 | #and LIMIT can be attached to a subexpression if it is enclosed in parentheses. Without parentheses, these
|
---|
| 4763 | #clauses will be taken to apply to the result of the UNION, not to its right-hand input expression.)
|
---|
[372] | 4764 | my $soasth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
[344] | 4765 | "FROM records WHERE rdns_id=? AND type=6");
|
---|
[372] | 4766 | $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
[337] | 4767 | "FROM records WHERE rdns_id=? AND not type=6 ".
|
---|
[344] | 4768 | "ORDER BY masklen(CAST(val AS inet)) DESC, CAST(val AS inet)");
|
---|
[372] | 4769 | $zonesth = $dbh->prepare("UPDATE revzones SET changed='n' WHERE rdns_id=?");
|
---|
[329] | 4770 | $revsth->execute();
|
---|
[368] | 4771 | while (my ($revid,$revzone,$revstat,$changed) = $revsth->fetchrow_array) {
|
---|
| 4772 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
| 4773 | # O_NOFOLLOW
|
---|
| 4774 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
| 4775 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
| 4776 | # still be followed.
|
---|
| 4777 | # but that doesn't help other platforms. :/
|
---|
| 4778 | my $tmpzone = NetAddr::IP->new($revzone);
|
---|
| 4779 | sysopen(ZONECACHE, "$config{exportcache}/".$tmpzone->network->addr, O_RDWR|O_CREAT);
|
---|
| 4780 | flock(ZONECACHE, LOCK_EX);
|
---|
| 4781 | if ($changed || -s "$config{exportcache}/".$tmpzone->network->addr == 0) {
|
---|
| 4782 | # need to fetch this separately since the rest of the records all (should) have real IPs in val
|
---|
| 4783 | $soasth->execute($revid);
|
---|
| 4784 | my (@zsoa) = $soasth->fetchrow_array();
|
---|
[445] | 4785 | _printrec_tiny(*ZONECACHE,'y',\%recflags,$revzone,
|
---|
| 4786 | $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],'');
|
---|
[344] | 4787 |
|
---|
[368] | 4788 | $recsth->execute($revid);
|
---|
[372] | 4789 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc) = $recsth->fetchrow_array) {
|
---|
[368] | 4790 | next if $recflags{$recid};
|
---|
[329] | 4791 |
|
---|
[372] | 4792 | $loc = '' if !$loc; # de-nullify - just in case
|
---|
| 4793 | ##fixme: handle case of record-with-location-that-doesn't-exist better.
|
---|
| 4794 | # note this currently fails safe (tested) - records with a location that
|
---|
| 4795 | # doesn't exist will not be sent to any client
|
---|
| 4796 | # $loc = '' if !$lochash->{$loc};
|
---|
| 4797 |
|
---|
[329] | 4798 | ##fixme: record validity timestamp. tinydns supports fiddling with timestamps.
|
---|
| 4799 | # note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
|
---|
| 4800 | # timestamps are TAI64
|
---|
| 4801 | # ~~ 2^62 + time()
|
---|
[368] | 4802 | my $stamp = '';
|
---|
[329] | 4803 |
|
---|
[368] | 4804 | # support tinydns' auto-TTL
|
---|
| 4805 | $ttl = '' if $ttl == '0';
|
---|
[367] | 4806 |
|
---|
[368] | 4807 | _printrec_tiny(*ZONECACHE, 'y', \%recflags, $revzone,
|
---|
| 4808 | $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp)
|
---|
| 4809 | if *ZONECACHE;
|
---|
[329] | 4810 |
|
---|
[450] | 4811 | # in case the zone shrunk, get rid of garbage at the end of the file.
|
---|
| 4812 | truncate(ZONECACHE, tell(ZONECACHE));
|
---|
| 4813 |
|
---|
[368] | 4814 | $recflags{$recid} = 1;
|
---|
| 4815 | } # while ($recsth)
|
---|
| 4816 | }
|
---|
[450] | 4817 | # stream from cache, whether freshly created or existing
|
---|
| 4818 | print $datafile $_ while <ZONECACHE>;
|
---|
[368] | 4819 | close ZONECACHE;
|
---|
[450] | 4820 | # mark zone as unmodified
|
---|
[368] | 4821 | $zonesth->execute($revid);
|
---|
[329] | 4822 | } # while ($domsth)
|
---|
| 4823 |
|
---|
| 4824 | } # end __export_tiny()
|
---|
| 4825 |
|
---|
| 4826 |
|
---|
| 4827 | # Utility sub for __export_tiny above
|
---|
| 4828 | sub _printrec_tiny {
|
---|
| 4829 | my ($datafile,$revrec,$recflags,$zone,$host,$type,$val,$dist,$weight,$port,$ttl,$loc,$stamp) = @_;
|
---|
| 4830 |
|
---|
| 4831 | ## Convert a bare number into an octal-coded pair of octets.
|
---|
| 4832 | # Take optional arg to indicate a decimal or hex input. Defaults to hex.
|
---|
| 4833 | sub octalize {
|
---|
| 4834 | my $tmp = shift;
|
---|
| 4835 | my $srctype = shift || 'h'; # default assumes hex string
|
---|
| 4836 | $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
|
---|
| 4837 | $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
|
---|
| 4838 | my @o = ($tmp =~ /^(..)(..)$/); # split into octets
|
---|
| 4839 | return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);;
|
---|
| 4840 | }
|
---|
| 4841 |
|
---|
[339] | 4842 | ## WARNING: This works to export even the whole Internet's worth of IP space...
|
---|
| 4843 | ## if you have the disk/RAM to handle the dataset, and you call this sub based on /16-sized chunks
|
---|
| 4844 | ## A /16 took ~3 seconds with a handful of separate records; adding a /8 pushed export time out to ~13m:40s
|
---|
| 4845 | ## 0/0 is estimated to take ~54 hours and ~256G of disk
|
---|
| 4846 | ## RAM usage depends on how many non-template entries you have in the set.
|
---|
| 4847 | ## This should probably be done on record addition rather than export; large blocks may need to be done in a
|
---|
| 4848 | ## forked process
|
---|
| 4849 | sub __publish_subnet {
|
---|
| 4850 | my $sub = shift;
|
---|
| 4851 | my $recflags = shift;
|
---|
| 4852 | my $hpat = shift;
|
---|
| 4853 | my $fh = shift;
|
---|
| 4854 | my $ttl = shift;
|
---|
| 4855 | my $stamp = shift;
|
---|
| 4856 | my $loc = shift;
|
---|
| 4857 | my $ptronly = shift || 0;
|
---|
| 4858 |
|
---|
| 4859 | my $iplist = $sub->splitref(32);
|
---|
| 4860 | foreach (@$iplist) {
|
---|
| 4861 | my $ip = $_->addr;
|
---|
| 4862 | # make as if we split the non-octet-aligned block into octet-aligned blocks as with SOA
|
---|
| 4863 | next if $ip =~ /\.(0|255)$/;
|
---|
| 4864 | next if $$recflags{$ip};
|
---|
| 4865 | $$recflags{$ip}++;
|
---|
| 4866 | my $rec = $hpat; # start fresh with the template for each IP
|
---|
| 4867 | _template4_expand(\$rec, $ip);
|
---|
| 4868 | print $fh ($ptronly ? "^"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$rec" : "=$rec:$ip").
|
---|
| 4869 | ":$ttl:$stamp:$loc\n";
|
---|
| 4870 | }
|
---|
| 4871 | }
|
---|
| 4872 |
|
---|
[103] | 4873 | ##fixme? append . to all host/val hostnames
|
---|
| 4874 | if ($typemap{$type} eq 'SOA') {
|
---|
| 4875 |
|
---|
| 4876 | # host contains pri-ns:responsible
|
---|
| 4877 | # val is abused to contain refresh:retry:expire:minttl
|
---|
| 4878 | ##fixme: "manual" serial vs tinydns-autoserial
|
---|
[202] | 4879 | # let's be explicit about abusing $host and $val
|
---|
| 4880 | my ($email, $primary) = (split /:/, $host)[0,1];
|
---|
| 4881 | my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
|
---|
[330] | 4882 | if ($revrec eq 'y') {
|
---|
[337] | 4883 | ##fixme: have to publish SOA records for each v4 /24 in sub-/16, and each /16 in sub-/8
|
---|
| 4884 | # what about v6?
|
---|
| 4885 | # -> only need SOA for local chunks offset from reverse delegation boundaries, so v6 is fine
|
---|
[330] | 4886 | $zone = NetAddr::IP->new($zone);
|
---|
[337] | 4887 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
| 4888 | if (!$zone->{isv6} && ($zone->masklen < 24) && ($zone->masklen % 8 != 0)) {
|
---|
| 4889 | foreach my $szone ($zone->split($zone->masklen + (8 - $zone->masklen % 8))) {
|
---|
| 4890 | $szone = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
| 4891 | print $datafile "Z$szone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
|
---|
| 4892 | }
|
---|
| 4893 | return; # skips "default" bits just below
|
---|
| 4894 | }
|
---|
[330] | 4895 | $zone = _ZONE($zone, 'ZONE', 'r', '.').($zone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 4896 | }
|
---|
[329] | 4897 | print $datafile "Z$zone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
|
---|
[103] | 4898 |
|
---|
| 4899 | } elsif ($typemap{$type} eq 'A') {
|
---|
| 4900 |
|
---|
[108] | 4901 | print $datafile "+$host:$val:$ttl:$stamp:$loc\n";
|
---|
[103] | 4902 |
|
---|
| 4903 | } elsif ($typemap{$type} eq 'NS') {
|
---|
| 4904 |
|
---|
[330] | 4905 | if ($revrec eq 'y') {
|
---|
| 4906 | $val = NetAddr::IP->new($val);
|
---|
[345] | 4907 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
| 4908 | if (!$val->{isv6} && ($val->masklen < 24) && ($val->masklen % 8 != 0)) {
|
---|
[346] | 4909 | foreach my $szone ($val->split($val->masklen + (8 - $val->masklen % 8))) {
|
---|
[345] | 4910 | my $szone2 = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
[346] | 4911 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
[345] | 4912 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n";
|
---|
[346] | 4913 | $$recflags{$szone2} = $val->masklen;
|
---|
[345] | 4914 | }
|
---|
[346] | 4915 | } elsif ($val->{isv6} && ($val->masklen < 64) && ($val->masklen % 4 !=0)) {
|
---|
| 4916 | foreach my $szone ($val->split($val->masklen + (4 - $val->masklen % 4))) {
|
---|
| 4917 | my $szone2 = _ZONE($szone, 'ZONE.ip6.arpa', 'r', '.');
|
---|
| 4918 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
| 4919 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n";
|
---|
| 4920 | $$recflags{$szone2} = $val->masklen;
|
---|
| 4921 | }
|
---|
| 4922 | } else {
|
---|
| 4923 | my $val2 = _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
| 4924 | print $datafile "\&$val2"."::$host:$ttl:$stamp:$loc\n";
|
---|
| 4925 | $$recflags{$val2} = $val->masklen;
|
---|
[345] | 4926 | }
|
---|
[330] | 4927 | } else {
|
---|
| 4928 | print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n";
|
---|
| 4929 | }
|
---|
[103] | 4930 |
|
---|
| 4931 | } elsif ($typemap{$type} eq 'AAAA') {
|
---|
| 4932 |
|
---|
| 4933 | print $datafile ":$host:28:";
|
---|
| 4934 | my $altgrp = 0;
|
---|
| 4935 | my @altconv;
|
---|
[108] | 4936 | # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
|
---|
[103] | 4937 | foreach (split /:/, $val) {
|
---|
| 4938 | if (/^$/) {
|
---|
| 4939 | # flag blank entry; this is a series of 0's of (currently) unknown length
|
---|
| 4940 | $altconv[$altgrp++] = 's';
|
---|
| 4941 | } else {
|
---|
| 4942 | # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
|
---|
| 4943 | $altconv[$altgrp++] = octalize($_)
|
---|
| 4944 | }
|
---|
| 4945 | }
|
---|
| 4946 | foreach my $octet (@altconv) {
|
---|
| 4947 | # if not 's', output
|
---|
| 4948 | print $datafile $octet unless $octet =~ /^s$/;
|
---|
| 4949 | # if 's', output (9-array length)x literal '\000\000'
|
---|
| 4950 | print $datafile '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
|
---|
| 4951 | }
|
---|
[108] | 4952 | print $datafile ":$ttl:$stamp:$loc\n";
|
---|
[103] | 4953 |
|
---|
| 4954 | } elsif ($typemap{$type} eq 'MX') {
|
---|
| 4955 |
|
---|
[108] | 4956 | print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n";
|
---|
[103] | 4957 |
|
---|
| 4958 | } elsif ($typemap{$type} eq 'TXT') {
|
---|
| 4959 |
|
---|
| 4960 | ##fixme: split v-e-r-y long TXT strings? will need to do so for BIND export, at least
|
---|
[350] | 4961 | if ($revrec eq 'n') {
|
---|
| 4962 | $val =~ s/:/\\072/g; # may need to replace other symbols
|
---|
| 4963 | print $datafile "'$host:$val:$ttl:$stamp:$loc\n";
|
---|
| 4964 | } else {
|
---|
| 4965 | $host =~ s/:/\\072/g; # may need to replace other symbols
|
---|
| 4966 | my $val2 = NetAddr::IP->new($val);
|
---|
| 4967 | print $datafile "'"._ZONE($val2, 'ZONE', 'r', '.').($val2->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
| 4968 | ":$host:$ttl:$stamp:$loc\n";
|
---|
| 4969 | }
|
---|
[103] | 4970 |
|
---|
| 4971 | # by-hand TXT
|
---|
| 4972 | #:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
|
---|
| 4973 | #@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
|
---|
| 4974 | #'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
|
---|
| 4975 |
|
---|
| 4976 | #txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
|
---|
| 4977 | #: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
|
---|
| 4978 |
|
---|
| 4979 | # very long TXT record as brought in by axfr-get
|
---|
| 4980 | # note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
|
---|
| 4981 | # also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
|
---|
| 4982 | #:longtxt.deepnet.cx:16:
|
---|
| 4983 | #\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
|
---|
| 4984 | #\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.
|
---|
| 4985 | #\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.
|
---|
| 4986 | #:3600
|
---|
| 4987 |
|
---|
| 4988 | } elsif ($typemap{$type} eq 'CNAME') {
|
---|
| 4989 |
|
---|
[372] | 4990 | if ($revrec eq 'n') {
|
---|
| 4991 | print $datafile "C$host:$val:$ttl:$stamp:$loc\n";
|
---|
| 4992 | } else {
|
---|
| 4993 | my $val2 = NetAddr::IP->new($val);
|
---|
| 4994 | print $datafile "C"._ZONE($val2, 'ZONE', 'r', '.').($val2->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
| 4995 | ":$host:$ttl:$stamp:$loc\n";
|
---|
| 4996 | }
|
---|
[103] | 4997 |
|
---|
| 4998 | } elsif ($typemap{$type} eq 'SRV') {
|
---|
| 4999 |
|
---|
| 5000 | # data is two-byte values for priority, weight, port, in that order,
|
---|
| 5001 | # followed by length/string data
|
---|
| 5002 |
|
---|
| 5003 | print $datafile ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
|
---|
| 5004 |
|
---|
| 5005 | $val .= '.' if $val !~ /\.$/;
|
---|
| 5006 | foreach (split /\./, $val) {
|
---|
| 5007 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
| 5008 | }
|
---|
[108] | 5009 | print $datafile "\\000:$ttl:$stamp:$loc\n";
|
---|
[103] | 5010 |
|
---|
| 5011 | } elsif ($typemap{$type} eq 'RP') {
|
---|
| 5012 |
|
---|
| 5013 | # RP consists of two mostly free-form strings.
|
---|
| 5014 | # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
|
---|
| 5015 | # The second is the "hostname" of a TXT record with more info.
|
---|
| 5016 | print $datafile ":$host:17:";
|
---|
| 5017 | my ($who,$what) = split /\s/, $val;
|
---|
| 5018 | foreach (split /\./, $who) {
|
---|
| 5019 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
| 5020 | }
|
---|
| 5021 | print $datafile '\000';
|
---|
| 5022 | foreach (split /\./, $what) {
|
---|
| 5023 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
| 5024 | }
|
---|
[108] | 5025 | print $datafile "\\000:$ttl:$stamp:$loc\n";
|
---|
[103] | 5026 |
|
---|
| 5027 | } elsif ($typemap{$type} eq 'PTR') {
|
---|
| 5028 |
|
---|
[332] | 5029 | $zone = NetAddr::IP->new($zone);
|
---|
[337] | 5030 | $$recflags{$val}++;
|
---|
[332] | 5031 | if (!$zone->{isv6} && $zone->masklen > 24) {
|
---|
| 5032 | ($val) = ($val =~ /\.(\d+)$/);
|
---|
| 5033 | print $datafile "^$val."._ZONE($zone, 'ZONE', 'r', '.').'.in-addr.arpa'.
|
---|
| 5034 | ":$host:ttl:$stamp:$loc\n";
|
---|
| 5035 | } else {
|
---|
| 5036 | $val = NetAddr::IP->new($val);
|
---|
| 5037 | print $datafile "^".
|
---|
| 5038 | _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
[334] | 5039 | ":$host:$ttl:$stamp:$loc\n";
|
---|
[332] | 5040 | }
|
---|
[103] | 5041 |
|
---|
[333] | 5042 | } elsif ($type == 65280) { # A+PTR
|
---|
[334] | 5043 |
|
---|
[337] | 5044 | $$recflags{$val}++;
|
---|
[334] | 5045 | print $datafile "=$host:$val:$ttl:$stamp:$loc\n";
|
---|
| 5046 |
|
---|
[333] | 5047 | } elsif ($type == 65281) { # AAAA+PTR
|
---|
| 5048 |
|
---|
[337] | 5049 | #$$recflags{$val}++;
|
---|
[333] | 5050 | # treat these as two separate records. since tinydns doesn't have
|
---|
| 5051 | # a native combined type, we have to create them separately anyway.
|
---|
| 5052 | if ($revrec eq 'n') {
|
---|
| 5053 | $type = 28;
|
---|
| 5054 | } else {
|
---|
| 5055 | $type = 12;
|
---|
| 5056 | }
|
---|
[334] | 5057 | _printrec_tiny($datafile,$revrec,$recflags,$zone,$host,$type,$val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
[335] | 5058 | ##fixme: add a config flag to indicate use of the patch from http://www.fefe.de/dns/
|
---|
| 5059 | # type 6 is for AAAA+PTR, type 3 is for AAAA
|
---|
[333] | 5060 |
|
---|
| 5061 | } elsif ($type == 65282) { # PTR template
|
---|
[335] | 5062 |
|
---|
| 5063 | # only useful for v4 with standard DNS software, since this expands all
|
---|
| 5064 | # IPs in $zone (or possibly $val?) with autogenerated records
|
---|
[337] | 5065 | $val = NetAddr::IP->new($val);
|
---|
| 5066 | return if $val->{isv6};
|
---|
[336] | 5067 |
|
---|
[339] | 5068 | if ($val->masklen <= 16) {
|
---|
| 5069 | foreach my $sub ($val->split(16)) {
|
---|
| 5070 | __publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, 1);
|
---|
| 5071 | }
|
---|
| 5072 | } else {
|
---|
| 5073 | __publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, 1);
|
---|
[337] | 5074 | }
|
---|
[335] | 5075 |
|
---|
[333] | 5076 | } elsif ($type == 65283) { # A+PTR template
|
---|
[335] | 5077 |
|
---|
[337] | 5078 | $val = NetAddr::IP->new($val);
|
---|
| 5079 | # Just In Case. An A+PTR should be impossible to add to a v6 revzone via API.
|
---|
| 5080 | return if $val->{isv6};
|
---|
[339] | 5081 |
|
---|
| 5082 | if ($val->masklen <= 16) {
|
---|
| 5083 | foreach my $sub ($val->split(16)) {
|
---|
| 5084 | __publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, 0);
|
---|
| 5085 | }
|
---|
| 5086 | } else {
|
---|
| 5087 | __publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, 0);
|
---|
[337] | 5088 | }
|
---|
[335] | 5089 |
|
---|
[333] | 5090 | } elsif ($type == 65284) { # AAAA+PTR template
|
---|
[335] | 5091 | # Stub for completeness. Could be exported to DNS software that supports
|
---|
| 5092 | # some degree of internal automagic in generic-record-creation
|
---|
| 5093 | # (eg http://search.cpan.org/dist/AllKnowingDNS/ )
|
---|
[333] | 5094 |
|
---|
[345] | 5095 | } elsif ($type == 65285) { # Delegation
|
---|
| 5096 | # This is intended for reverse zones, but may prove useful in forward zones.
|
---|
| 5097 |
|
---|
[346] | 5098 | # All delegations need to create one or more NS records. The NS record handler knows what to do.
|
---|
| 5099 | _printrec_tiny($datafile,$revrec,$recflags,$zone,$host,$reverse_typemap{'NS'},
|
---|
| 5100 | $val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
| 5101 | if ($revrec eq 'y') {
|
---|
| 5102 | # In the case of a sub-/24 v4 reverse delegation, we need to generate CNAMEs
|
---|
| 5103 | # to redirect all of the individual IP lookups as well.
|
---|
| 5104 | # Not sure how this would actually resolve if a /24 or larger was delegated
|
---|
| 5105 | # one way, and a sub-/24 in that >=/24 was delegated elsewhere...
|
---|
| 5106 | my $dblock = NetAddr::IP->new($val);
|
---|
| 5107 | if (!$dblock->{isv6} && $dblock->masklen > 24) {
|
---|
| 5108 | my @subs = $dblock->split;
|
---|
| 5109 | foreach (@subs) {
|
---|
| 5110 | next if $$recflags{"$_"};
|
---|
| 5111 | my ($oct) = ($_->addr =~ /(\d+)$/);
|
---|
| 5112 | print $datafile "C"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$oct.".
|
---|
| 5113 | _ZONE($dblock, 'ZONE.in-addr.arpa', 'r', '.').":$ttl:$stamp:$loc\n";
|
---|
| 5114 | $$recflags{"$_"}++;
|
---|
| 5115 | }
|
---|
| 5116 | }
|
---|
| 5117 | }
|
---|
[345] | 5118 |
|
---|
[364] | 5119 | ##
|
---|
| 5120 | ## Uncommon types. These will need better UI support Any Day Sometime Maybe(TM).
|
---|
| 5121 | ##
|
---|
| 5122 |
|
---|
| 5123 | } elsif ($type == 44) { # SSHFP
|
---|
| 5124 | my ($algo,$fpt,$fp) = split /\s+/, $val;
|
---|
| 5125 |
|
---|
| 5126 | my $rec = sprintf ":$host:44:\\%0.3o\\%0.3o", $algo, $fpt;
|
---|
| 5127 | while (my ($byte) = ($fp =~ /^(..)/) ) {
|
---|
| 5128 | $rec .= sprintf "\\%0.3o", hex($byte);
|
---|
| 5129 | $fp =~ s/^..//;
|
---|
| 5130 | }
|
---|
| 5131 | print $datafile "$rec:$ttl:$stamp:$loc\n";
|
---|
| 5132 |
|
---|
[345] | 5133 | } else {
|
---|
[108] | 5134 | # raw record. we don't know what's in here, so we ASS-U-ME the user has
|
---|
| 5135 | # put it in correctly, since either the user is messing directly with the
|
---|
| 5136 | # database, or the record was imported via AXFR
|
---|
| 5137 | # <split by char>
|
---|
| 5138 | # convert anything not a-zA-Z0-9.- to octal coding
|
---|
| 5139 |
|
---|
| 5140 | ##fixme: add flag to export "unknown" record types - note we'll probably end up
|
---|
| 5141 | # mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
|
---|
| 5142 | #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
|
---|
| 5143 |
|
---|
[103] | 5144 | } # record type if-else
|
---|
| 5145 |
|
---|
[329] | 5146 | } # end _printrec_tiny()
|
---|
[103] | 5147 |
|
---|
| 5148 |
|
---|
[197] | 5149 | ## DNSDB::mailNotify()
|
---|
[283] | 5150 | # Sends notification mail to recipients regarding a DNSDB operation
|
---|
[197] | 5151 | sub mailNotify {
|
---|
| 5152 | my $dbh = shift;
|
---|
| 5153 | my ($subj,$message) = @_;
|
---|
| 5154 |
|
---|
| 5155 | return if $config{mailhost} eq 'smtp.example.com'; # do nothing if still using default SMTP host.
|
---|
| 5156 |
|
---|
| 5157 | my $mailer = Net::SMTP->new($config{mailhost}, Hello => "dnsadmin.$config{domain}");
|
---|
| 5158 |
|
---|
| 5159 | my $mailsender = ($config{mailsender} ? $config{mailsender} : $config{mailnotify});
|
---|
| 5160 |
|
---|
| 5161 | $mailer->mail($mailsender);
|
---|
| 5162 | $mailer->to($config{mailnotify});
|
---|
[198] | 5163 | $mailer->data("From: \"$config{mailname}\" <$mailsender>\n",
|
---|
| 5164 | "To: <$config{mailnotify}>\n",
|
---|
[197] | 5165 | "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
|
---|
| 5166 | "Subject: $subj\n",
|
---|
| 5167 | "X-Mailer: DNSAdmin Notify v".sprintf("%.1d",$DNSDB::VERSION)."\n",
|
---|
| 5168 | "Organization: $config{orgname}\n",
|
---|
| 5169 | "\n$message\n");
|
---|
| 5170 | $mailer->quit;
|
---|
| 5171 | }
|
---|
| 5172 |
|
---|
[2] | 5173 | # shut Perl up
|
---|
| 5174 | 1;
|
---|