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