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