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