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