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