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