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