| 1 | # dns/trunk/DNSDB.pm | 
|---|
| 2 | # Abstraction functions for DNS administration | 
|---|
| 3 | ## | 
|---|
| 4 | # $Id: DNSDB.pm 518 2013-06-07 22:41:45Z kdeugau $ | 
|---|
| 5 | # Copyright 2008-2013 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 | ## | 
|---|
| 20 |  | 
|---|
| 21 | package DNSDB; | 
|---|
| 22 |  | 
|---|
| 23 | use strict; | 
|---|
| 24 | use warnings; | 
|---|
| 25 | use Exporter; | 
|---|
| 26 | use DBI; | 
|---|
| 27 | use Net::DNS; | 
|---|
| 28 | use Crypt::PasswdMD5; | 
|---|
| 29 | use Net::SMTP; | 
|---|
| 30 | use NetAddr::IP qw(:lower); | 
|---|
| 31 | use POSIX; | 
|---|
| 32 | use Fcntl qw(:flock); | 
|---|
| 33 |  | 
|---|
| 34 | use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS); | 
|---|
| 35 |  | 
|---|
| 36 | $VERSION        = 1.1;  ##VERSION## | 
|---|
| 37 | @ISA            = qw(Exporter); | 
|---|
| 38 | @EXPORT_OK      = qw( | 
|---|
| 39 | &initGlobals &login &initActionLog | 
|---|
| 40 | &getPermissions &changePermissions &comparePermissions | 
|---|
| 41 | &changeGroup | 
|---|
| 42 | &connectDB &finish | 
|---|
| 43 | &addDomain &delZone &domainName &revName &domainID &revID &addRDNS | 
|---|
| 44 | &getZoneCount &getZoneList &getZoneLocation | 
|---|
| 45 | &addGroup &delGroup &getChildren &groupName | 
|---|
| 46 | &getGroupCount &getGroupList | 
|---|
| 47 | &addUser &updateUser &delUser &userFullName &userStatus &getUserData | 
|---|
| 48 | &getUserCount &getUserList &getUserDropdown | 
|---|
| 49 | &addLoc &updateLoc &delLoc &getLoc | 
|---|
| 50 | &getLocCount &getLocList &getLocDropdown | 
|---|
| 51 | &getSOA &updateSOA &getRecLine &getRecList &getRecCount | 
|---|
| 52 | &addRec &updateRec &delRec | 
|---|
| 53 | &getLogCount &getLogEntries | 
|---|
| 54 | &getRevPattern | 
|---|
| 55 | &getTypelist | 
|---|
| 56 | &parentID | 
|---|
| 57 | &isParent | 
|---|
| 58 | &zoneStatus &getZonesByCIDR &importAXFR | 
|---|
| 59 | &export | 
|---|
| 60 | &mailNotify | 
|---|
| 61 | %typemap %reverse_typemap | 
|---|
| 62 | @permtypes $permlist %permchains | 
|---|
| 63 | ); | 
|---|
| 64 |  | 
|---|
| 65 | @EXPORT         = qw(%typemap %reverse_typemap @permtypes $permlist %permchains); | 
|---|
| 66 | %EXPORT_TAGS    = ( ALL => [qw( | 
|---|
| 67 | &initGlobals &login &initActionLog | 
|---|
| 68 | &getPermissions &changePermissions &comparePermissions | 
|---|
| 69 | &changeGroup | 
|---|
| 70 | &connectDB &finish | 
|---|
| 71 | &addDomain &delZone &domainName &revName &domainID &revID &addRDNS | 
|---|
| 72 | &getZoneCount &getZoneList &getZoneLocation | 
|---|
| 73 | &addGroup &delGroup &getChildren &groupName | 
|---|
| 74 | &getGroupCount &getGroupList | 
|---|
| 75 | &addUser &updateUser &delUser &userFullName &userStatus &getUserData | 
|---|
| 76 | &getUserCount &getUserList &getUserDropdown | 
|---|
| 77 | &addLoc &updateLoc &delLoc &getLoc | 
|---|
| 78 | &getLocCount &getLocList &getLocDropdown | 
|---|
| 79 | &getSOA &updateSOA &getRecLine &getRecList &getRecCount | 
|---|
| 80 | &addRec &updateRec &delRec | 
|---|
| 81 | &getLogCount &getLogEntries | 
|---|
| 82 | &getRevPattern | 
|---|
| 83 | &getTypelist | 
|---|
| 84 | &parentID | 
|---|
| 85 | &isParent | 
|---|
| 86 | &zoneStatus &getZonesByCIDR &importAXFR | 
|---|
| 87 | &export | 
|---|
| 88 | &mailNotify | 
|---|
| 89 | %typemap %reverse_typemap | 
|---|
| 90 | @permtypes $permlist %permchains | 
|---|
| 91 | )] | 
|---|
| 92 | ); | 
|---|
| 93 |  | 
|---|
| 94 | our $errstr = ''; | 
|---|
| 95 | our $resultstr = ''; | 
|---|
| 96 |  | 
|---|
| 97 | # Arguably defined wholly in the db, but little reason to change without supporting code changes | 
|---|
| 98 | # group_view, user_view permissions? separate rDNS permission(s)? | 
|---|
| 99 | our @permtypes = qw ( | 
|---|
| 100 | group_edit      group_create    group_delete | 
|---|
| 101 | user_edit       user_create     user_delete | 
|---|
| 102 | domain_edit     domain_create   domain_delete | 
|---|
| 103 | record_edit     record_create   record_delete   record_locchg | 
|---|
| 104 | location_edit   location_create location_delete location_view | 
|---|
| 105 | self_edit       admin | 
|---|
| 106 | ); | 
|---|
| 107 | our $permlist = join(',',@permtypes); | 
|---|
| 108 |  | 
|---|
| 109 | # Some permissions more or less require certain others. | 
|---|
| 110 | our %permchains = ( | 
|---|
| 111 | user_edit       => 'self_edit', | 
|---|
| 112 | location_edit   => 'location_view', | 
|---|
| 113 | location_create => 'location_view', | 
|---|
| 114 | location_delete => 'location_view', | 
|---|
| 115 | record_locchg   => 'location_view', | 
|---|
| 116 | ); | 
|---|
| 117 |  | 
|---|
| 118 | # DNS record type map and reverse map. | 
|---|
| 119 | # loaded from the database, from http://www.iana.org/assignments/dns-parameters | 
|---|
| 120 | our %typemap; | 
|---|
| 121 | our %reverse_typemap; | 
|---|
| 122 |  | 
|---|
| 123 | ## (Semi)private variables | 
|---|
| 124 |  | 
|---|
| 125 | # Hash of functions for validating record types.  Filled in initGlobals() since | 
|---|
| 126 | # it relies on visibility flags from the rectypes table in the DB | 
|---|
| 127 | my %validators; | 
|---|
| 128 |  | 
|---|
| 129 | # Entity-relationship reference hashes. | 
|---|
| 130 | my %par_tbl = ( | 
|---|
| 131 | group   => 'groups', | 
|---|
| 132 | user    => 'users', | 
|---|
| 133 | defrec  => 'default_records', | 
|---|
| 134 | defrevrec       => 'default_rev_records', | 
|---|
| 135 | domain  => 'domains', | 
|---|
| 136 | revzone => 'revzones', | 
|---|
| 137 | record  => 'records' | 
|---|
| 138 | ); | 
|---|
| 139 | my %id_col = ( | 
|---|
| 140 | group   => 'group_id', | 
|---|
| 141 | user    => 'user_id', | 
|---|
| 142 | defrec  => 'record_id', | 
|---|
| 143 | defrevrec       => 'record_id', | 
|---|
| 144 | domain  => 'domain_id', | 
|---|
| 145 | revzone => 'rdns_id', | 
|---|
| 146 | record  => 'record_id' | 
|---|
| 147 | ); | 
|---|
| 148 | my %par_col = ( | 
|---|
| 149 | group   => 'parent_group_id', | 
|---|
| 150 | user    => 'group_id', | 
|---|
| 151 | defrec  => 'group_id', | 
|---|
| 152 | defrevrec       => 'group_id', | 
|---|
| 153 | domain  => 'group_id', | 
|---|
| 154 | revzone => 'group_id', | 
|---|
| 155 | record  => 'domain_id' | 
|---|
| 156 | ); | 
|---|
| 157 | my %par_type = ( | 
|---|
| 158 | group   => 'group', | 
|---|
| 159 | user    => 'group', | 
|---|
| 160 | defrec  => 'group', | 
|---|
| 161 | defrevrec       => 'group', | 
|---|
| 162 | domain  => 'group', | 
|---|
| 163 | revzone => 'group', | 
|---|
| 164 | record  => 'domain' | 
|---|
| 165 | ); | 
|---|
| 166 |  | 
|---|
| 167 | ## | 
|---|
| 168 | ## Constructor and destructor | 
|---|
| 169 | ## | 
|---|
| 170 |  | 
|---|
| 171 | sub new { | 
|---|
| 172 | my $this = shift; | 
|---|
| 173 | my $class = ref($this) || $this; | 
|---|
| 174 | my %args = @_; | 
|---|
| 175 |  | 
|---|
| 176 | # Prepopulate a basic config.  Note some of these *will* cause errors if left unset. | 
|---|
| 177 | # note:  add appropriate stanzas in __cfgload() to parse these | 
|---|
| 178 | my %defconfig = ( | 
|---|
| 179 | # The only configuration option not loadable from a config file. | 
|---|
| 180 | configfile => '/etc/dnsdb/dnsdb.conf', | 
|---|
| 181 |  | 
|---|
| 182 | # Database connection info | 
|---|
| 183 | dbname  => 'dnsdb', | 
|---|
| 184 | dbuser  => 'dnsdb', | 
|---|
| 185 | dbpass  => 'secret', | 
|---|
| 186 | dbhost  => '', | 
|---|
| 187 |  | 
|---|
| 188 | # Email notice settings | 
|---|
| 189 | mailhost        => 'smtp.example.com', | 
|---|
| 190 | mailnotify      => 'dnsdb@example.com', # to | 
|---|
| 191 | mailsender      => 'dnsdb@example.com', # from | 
|---|
| 192 | mailname        => 'DNS Administration', | 
|---|
| 193 | orgname         => 'Example Corp', | 
|---|
| 194 | domain          => 'example.com', | 
|---|
| 195 |  | 
|---|
| 196 | # Template directory | 
|---|
| 197 | templatedir     => 'templates/', | 
|---|
| 198 | # fmeh.  this is a real web path, not a logical internal one.  hm.. | 
|---|
| 199 | #               cssdir  => 'templates/', | 
|---|
| 200 | sessiondir      => 'session/', | 
|---|
| 201 | exportcache     => 'cache/', | 
|---|
| 202 |  | 
|---|
| 203 | # Session params | 
|---|
| 204 | timeout         => '1h',        # passed as-is to CGI::Session | 
|---|
| 205 |  | 
|---|
| 206 | # Other miscellanea | 
|---|
| 207 | log_failures    => 1,   # log all evarthing by default | 
|---|
| 208 | perpage         => 15, | 
|---|
| 209 | max_fcgi_requests => 100,       # reasonable default? | 
|---|
| 210 | ); | 
|---|
| 211 |  | 
|---|
| 212 | # Config file parse calls. | 
|---|
| 213 | # If we are passed a blank argument for $args{configfile}, | 
|---|
| 214 | #   we should NOT parse the default config file - we will | 
|---|
| 215 | #   rely on hardcoded defaults OR caller-specified values. | 
|---|
| 216 | # If we are passed a non-blank argument, parse that file. | 
|---|
| 217 | # If no config file is specified, parse the default one. | 
|---|
| 218 | my %siteconfig; | 
|---|
| 219 | if (defined($args{configfile})) { | 
|---|
| 220 | if ($args{configfile}) { | 
|---|
| 221 | return if !__cfgload($args{configfile}, \%siteconfig); | 
|---|
| 222 | } | 
|---|
| 223 | } else { | 
|---|
| 224 | return if !__cfgload($defconfig{configfile}, \%siteconfig); | 
|---|
| 225 | } | 
|---|
| 226 |  | 
|---|
| 227 | # Assemble the object.  Apply configuration hashes in order of precedence. | 
|---|
| 228 | my $self = { | 
|---|
| 229 | # Hardcoded defaults | 
|---|
| 230 | %defconfig, | 
|---|
| 231 | # Default config file OR caller-specified one, loaded above | 
|---|
| 232 | %siteconfig, | 
|---|
| 233 | # Caller-specified arguments | 
|---|
| 234 | %args | 
|---|
| 235 | }; | 
|---|
| 236 | bless $self, $class; | 
|---|
| 237 |  | 
|---|
| 238 | # Try to connect to the DB, and initialize a number of handy globals. | 
|---|
| 239 | $self->{dbh} = connectDB($self->{dbname}, $self->{dbuser}, $self->{dbpass}, $self->{dbhost}) or return; | 
|---|
| 240 | $self->initGlobals(); | 
|---|
| 241 |  | 
|---|
| 242 | return $self; | 
|---|
| 243 | } | 
|---|
| 244 |  | 
|---|
| 245 | sub DESTROY { | 
|---|
| 246 | my $self = shift; | 
|---|
| 247 | $self->{dbh}->disconnect if $self->{dbh}; | 
|---|
| 248 | } | 
|---|
| 249 |  | 
|---|
| 250 | sub errstr { $DNSDB::errstr; } | 
|---|
| 251 |  | 
|---|
| 252 | ## | 
|---|
| 253 | ## utility functions | 
|---|
| 254 | ## | 
|---|
| 255 |  | 
|---|
| 256 | ## DNSDB::_rectable() | 
|---|
| 257 | # Takes default+rdns flags, returns appropriate table name | 
|---|
| 258 | sub _rectable { | 
|---|
| 259 | my $def = shift; | 
|---|
| 260 | my $rev = shift; | 
|---|
| 261 |  | 
|---|
| 262 | return 'records' if $def ne 'y'; | 
|---|
| 263 | return 'default_records' if $rev ne 'y'; | 
|---|
| 264 | return 'default_rev_records'; | 
|---|
| 265 | } # end _rectable() | 
|---|
| 266 |  | 
|---|
| 267 | ## DNSDB::_recparent() | 
|---|
| 268 | # Takes default+rdns flags, returns appropriate parent-id column name | 
|---|
| 269 | sub _recparent { | 
|---|
| 270 | my $def = shift; | 
|---|
| 271 | my $rev = shift; | 
|---|
| 272 |  | 
|---|
| 273 | return 'group_id' if $def eq 'y'; | 
|---|
| 274 | return 'rdns_id' if $rev eq 'y'; | 
|---|
| 275 | return 'domain_id'; | 
|---|
| 276 | } # end _recparent() | 
|---|
| 277 |  | 
|---|
| 278 | ## DNSDB::_ipparent() | 
|---|
| 279 | # Check an IP to be added in a reverse zone to see if it's really in the requested parent. | 
|---|
| 280 | # Takes default and reverse flags, IP (fragment) to check, parent zone ID, | 
|---|
| 281 | # and a reference to a NetAddr::IP object (also used to pass back a fully-reconstructed IP for | 
|---|
| 282 | # database insertion) | 
|---|
| 283 | sub _ipparent { | 
|---|
| 284 | my $self = shift; | 
|---|
| 285 | my $dbh = $self->{dbh}; | 
|---|
| 286 | my $defrec = shift; | 
|---|
| 287 | my $revrec = shift; | 
|---|
| 288 | my $val = shift; | 
|---|
| 289 | my $id = shift; | 
|---|
| 290 | my $addr = shift; | 
|---|
| 291 |  | 
|---|
| 292 | return if $revrec ne 'y';     # this sub not useful in forward zones | 
|---|
| 293 |  | 
|---|
| 294 | $$addr = NetAddr::IP->new($$val);      #necessary? | 
|---|
| 295 |  | 
|---|
| 296 | # subsub to split, reverse, and overlay an IP fragment on a netblock | 
|---|
| 297 | sub __rev_overlay { | 
|---|
| 298 | my $splitme = shift;        # ':' or '.', m'lud? | 
|---|
| 299 | my $parnet = shift; | 
|---|
| 300 | my $val = shift; | 
|---|
| 301 | my $addr = shift; | 
|---|
| 302 |  | 
|---|
| 303 | my $joinme = $splitme; | 
|---|
| 304 | $splitme = '\.' if $splitme eq '.'; | 
|---|
| 305 | my @working = reverse(split($splitme, $parnet->addr)); | 
|---|
| 306 | my @parts = reverse(split($splitme, $$val)); | 
|---|
| 307 | for (my $i = 0; $i <= $#parts; $i++) { | 
|---|
| 308 | $working[$i] = $parts[$i]; | 
|---|
| 309 | } | 
|---|
| 310 | my $checkme = NetAddr::IP->new(join($joinme, reverse(@working))) or return 0; | 
|---|
| 311 | return 0 unless $checkme->within($parnet); | 
|---|
| 312 | $$addr = $checkme;  # force "correct" IP to be recorded. | 
|---|
| 313 | return 1; | 
|---|
| 314 | } | 
|---|
| 315 |  | 
|---|
| 316 | my ($parstr) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id = ?", undef, ($id)); | 
|---|
| 317 | my $parnet = NetAddr::IP->new($parstr); | 
|---|
| 318 |  | 
|---|
| 319 | # Fail early on v6-in-v4 or v4-in-v6.  We're not accepting these ATM. | 
|---|
| 320 | return 0 if $parnet->addr =~ /\./ && $$val =~ /:/; | 
|---|
| 321 | return 0 if $parnet->addr =~ /:/ && $$val =~ /\./; | 
|---|
| 322 |  | 
|---|
| 323 | if ($$addr && ($$val =~ /^[\da-fA-F][\da-fA-F:]+[\da-fA-F]$/ || $$val =~ m|/\d+$|)) { | 
|---|
| 324 | # the only case where NetAddr::IP's acceptance of legitimate IPs is "correct" is for a proper IPv6 address, | 
|---|
| 325 | # or a netblock (only expected on templates) | 
|---|
| 326 | # the rest we have to restructure before fiddling.  *sigh* | 
|---|
| 327 | return 1 if $$addr->within($parnet); | 
|---|
| 328 | } else { | 
|---|
| 329 | # We don't have a complete IP in $$val (yet)... unless we have a netblock | 
|---|
| 330 | if ($parnet->addr =~ /:/) { | 
|---|
| 331 | $$val =~ s/^:+//;  # gotta strip'em all... | 
|---|
| 332 | return __rev_overlay(':', $parnet, $val, $addr); | 
|---|
| 333 | } | 
|---|
| 334 | if ($parnet->addr =~ /\./) { | 
|---|
| 335 | $$val =~ s/^\.+//; | 
|---|
| 336 | return __rev_overlay('.', $parnet, $val, $addr); | 
|---|
| 337 | } | 
|---|
| 338 | # should be impossible to get here... | 
|---|
| 339 | } | 
|---|
| 340 | # ... and here. | 
|---|
| 341 | # can't do nuttin' in forward zones | 
|---|
| 342 | } # end _ipparent() | 
|---|
| 343 |  | 
|---|
| 344 | ## DNSDB::_hostparent() | 
|---|
| 345 | # A little different than _ipparent above;  this tries to *find* the parent zone of a hostname | 
|---|
| 346 | # Takes a hostname. | 
|---|
| 347 | # Returns the domain ID of the parent domain if one was found. | 
|---|
| 348 | sub _hostparent { | 
|---|
| 349 | my $self = shift; | 
|---|
| 350 | my $dbh = $self->{dbh}; | 
|---|
| 351 | my $hname = shift; | 
|---|
| 352 |  | 
|---|
| 353 | $hname =~ s/^\*\.//;  # this should be impossible to find in the domains table. | 
|---|
| 354 | my @hostbits = split /\./, $hname; | 
|---|
| 355 | my $sth = $dbh->prepare("SELECT count(*),domain_id FROM domains WHERE lower(domain) = lower(?) GROUP BY domain_id"); | 
|---|
| 356 | foreach (@hostbits) { | 
|---|
| 357 | $sth->execute($hname); | 
|---|
| 358 | my ($found, $parid) = $sth->fetchrow_array; | 
|---|
| 359 | if ($found) { | 
|---|
| 360 | return $parid; | 
|---|
| 361 | } | 
|---|
| 362 | $hname =~ s/^$_\.//; | 
|---|
| 363 | } | 
|---|
| 364 | } # end _hostparent() | 
|---|
| 365 |  | 
|---|
| 366 | ## DNSDB::_log() | 
|---|
| 367 | # Log an action | 
|---|
| 368 | # Takes a log entry hash containing at least: | 
|---|
| 369 | #  group_id, log entry | 
|---|
| 370 | # and optionally one or more of: | 
|---|
| 371 | #  domain_id, rdns_id | 
|---|
| 372 | # The %userdata hash provides the user ID, username, and fullname | 
|---|
| 373 | sub _log { | 
|---|
| 374 | my $self = shift; | 
|---|
| 375 | my $dbh = $self->{dbh}; | 
|---|
| 376 |  | 
|---|
| 377 | my %args = @_; | 
|---|
| 378 |  | 
|---|
| 379 | $args{rdns_id} = 0 if !$args{rdns_id}; | 
|---|
| 380 | $args{domain_id} = 0 if !$args{domain_id}; | 
|---|
| 381 |  | 
|---|
| 382 | ##fixme:  farm out the actual logging to different subs for file, syslog, internal, etc based on config | 
|---|
| 383 | #  if ($self->{log_channel} eq 'sql') { | 
|---|
| 384 | $dbh->do("INSERT INTO log (domain_id,rdns_id,group_id,entry,user_id,email,name) VALUES (?,?,?,?,?,?,?)", | 
|---|
| 385 | undef, | 
|---|
| 386 | ($args{domain_id}, $args{rdns_id}, $args{group_id}, $args{entry}, | 
|---|
| 387 | $self->{loguserid}, $self->{logusername}, $self->{logfullname}) ); | 
|---|
| 388 | #  } elsif ($self->{log_channel} eq 'file') { | 
|---|
| 389 | #  } elsif ($self->{log_channel} eq 'syslog') { | 
|---|
| 390 | #  } | 
|---|
| 391 | } # end _log | 
|---|
| 392 |  | 
|---|
| 393 |  | 
|---|
| 394 | ## | 
|---|
| 395 | ## Record validation subs. | 
|---|
| 396 | ## | 
|---|
| 397 |  | 
|---|
| 398 | ## All of these subs take substantially the same arguments: | 
|---|
| 399 | # a hash containing at least the following keys: | 
|---|
| 400 | #  - defrec (default/live flag) | 
|---|
| 401 | #  - revrec (forward/reverse flag) | 
|---|
| 402 | #  - id (parent entity ID) | 
|---|
| 403 | #  - host (hostname) | 
|---|
| 404 | #  - rectype | 
|---|
| 405 | #  - val (IP, hostname [CNAME/MX/SRV] or text) | 
|---|
| 406 | #  - addr (NetAddr::IP object from val.  May be undef.) | 
|---|
| 407 | # MX and SRV record validation also expect distance, and SRV records expect weight and port as well. | 
|---|
| 408 | # host, rectype, and addr should be references as these may be modified in validation | 
|---|
| 409 |  | 
|---|
| 410 | # A record | 
|---|
| 411 | sub _validate_1 { | 
|---|
| 412 | my $self = shift; | 
|---|
| 413 | my $dbh = $self->{dbh}; | 
|---|
| 414 |  | 
|---|
| 415 | my %args = @_; | 
|---|
| 416 |  | 
|---|
| 417 | return ('FAIL', 'Reverse zones cannot contain A records') if $args{revrec} eq 'y'; | 
|---|
| 418 |  | 
|---|
| 419 | # Coerce all hostnames to end in ".DOMAIN" for group/default records, | 
|---|
| 420 | # or the intended parent domain for live records. | 
|---|
| 421 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id})); | 
|---|
| 422 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/; | 
|---|
| 423 |  | 
|---|
| 424 | # Check IP is well-formed, and that it's a v4 address | 
|---|
| 425 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable. | 
|---|
| 426 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address") | 
|---|
| 427 | unless ${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/; | 
|---|
| 428 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address") | 
|---|
| 429 | unless $args{addr} && !$args{addr}->{isv6}; | 
|---|
| 430 | # coerce IP/value to normalized form for storage | 
|---|
| 431 | ${$args{val}} = $args{addr}->addr; | 
|---|
| 432 |  | 
|---|
| 433 | return ('OK','OK'); | 
|---|
| 434 | } # done A record | 
|---|
| 435 |  | 
|---|
| 436 | # NS record | 
|---|
| 437 | sub _validate_2 { | 
|---|
| 438 | my $self = shift; | 
|---|
| 439 | my $dbh = $self->{dbh}; | 
|---|
| 440 |  | 
|---|
| 441 | my %args = @_; | 
|---|
| 442 |  | 
|---|
| 443 | # Check that the target of the record is within the parent. | 
|---|
| 444 | # Yes, host<->val are mixed up here;  can't see a way to avoid it.  :( | 
|---|
| 445 | if ($args{defrec} eq 'n') { | 
|---|
| 446 | # Check if IP/address/zone/"subzone" is within the parent | 
|---|
| 447 | if ($args{revrec} eq 'y') { | 
|---|
| 448 | my $tmpip = NetAddr::IP->new(${$args{val}}); | 
|---|
| 449 | my $pname = $self->revName($args{id}); | 
|---|
| 450 | return ('FAIL',"${$args{val}} not within $pname") | 
|---|
| 451 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$tmpip); | 
|---|
| 452 | # Sub the returned thing for ZONE?  This could get stupid if you have typos... | 
|---|
| 453 | ${$args{val}} =~ s/ZONE/$tmpip->address/; | 
|---|
| 454 | } else { | 
|---|
| 455 | my $pname = $self->domainName($args{id}); | 
|---|
| 456 | ${$args{host}} = $pname if ${$args{host}} !~ /\.$pname$/; | 
|---|
| 457 | } | 
|---|
| 458 | } else { | 
|---|
| 459 | # Default reverse NS records should always refer to the implied parent | 
|---|
| 460 | ${$args{host}} = 'DOMAIN' if $args{revrec} eq 'n'; | 
|---|
| 461 | ${$args{val}} = 'ZONE' if $args{revrec} eq 'y'; | 
|---|
| 462 | } | 
|---|
| 463 |  | 
|---|
| 464 | # Let this lie for now.  Needs more magic. | 
|---|
| 465 | #  # Check IP is well-formed, and that it's a v4 address | 
|---|
| 466 | #  return ('FAIL',"A record must be a valid IPv4 address") | 
|---|
| 467 | #       unless $addr && !$addr->{isv6}; | 
|---|
| 468 | #  # coerce IP/value to normalized form for storage | 
|---|
| 469 | #  $$val = $addr->addr; | 
|---|
| 470 |  | 
|---|
| 471 | return ('OK','OK'); | 
|---|
| 472 | } # done NS record | 
|---|
| 473 |  | 
|---|
| 474 | # CNAME record | 
|---|
| 475 | sub _validate_5 { | 
|---|
| 476 | my $self = shift; | 
|---|
| 477 | my $dbh = $self->{dbh}; | 
|---|
| 478 |  | 
|---|
| 479 | my %args = @_; | 
|---|
| 480 |  | 
|---|
| 481 | # Not really true, but these are only useful for delegating smaller-than-/24 IP blocks. | 
|---|
| 482 | # This is fundamentally a messy operation and should really just be taken care of by the | 
|---|
| 483 | # export process, not manual maintenance of the necessary records. | 
|---|
| 484 | return ('FAIL', 'Reverse zones cannot contain CNAME records') if $args{revrec} eq 'y'; | 
|---|
| 485 |  | 
|---|
| 486 | # Coerce all hostnames to end in ".DOMAIN" for group/default records, | 
|---|
| 487 | # or the intended parent domain for live records. | 
|---|
| 488 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id})); | 
|---|
| 489 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/; | 
|---|
| 490 |  | 
|---|
| 491 | return ('OK','OK'); | 
|---|
| 492 | } # done CNAME record | 
|---|
| 493 |  | 
|---|
| 494 | # SOA record | 
|---|
| 495 | sub _validate_6 { | 
|---|
| 496 | # Smart monkeys won't stick their fingers in here;  we have | 
|---|
| 497 | # separate dedicated routines to deal with SOA records. | 
|---|
| 498 | return ('OK','OK'); | 
|---|
| 499 | } # done SOA record | 
|---|
| 500 |  | 
|---|
| 501 | # PTR record | 
|---|
| 502 | sub _validate_12 { | 
|---|
| 503 | my $self = shift; | 
|---|
| 504 | my $dbh = $self->{dbh}; | 
|---|
| 505 |  | 
|---|
| 506 | my %args = @_; | 
|---|
| 507 |  | 
|---|
| 508 | if ($args{revrec} eq 'y') { | 
|---|
| 509 | if ($args{defrec} eq 'n') { | 
|---|
| 510 | return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".$self->revName($args{id})) | 
|---|
| 511 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr}); | 
|---|
| 512 | ${$args{val}} = $args{addr}->addr; | 
|---|
| 513 | } else { | 
|---|
| 514 | if (${$args{val}} =~ /\./) { | 
|---|
| 515 | # looks like a v4 or fragment | 
|---|
| 516 | if (${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/) { | 
|---|
| 517 | # woo!  a complete IP!  validate it and normalize, or fail. | 
|---|
| 518 | $args{addr} = NetAddr::IP->new(${$args{val}}) | 
|---|
| 519 | or return ('FAIL', "IP/value looks like IPv4 but isn't valid"); | 
|---|
| 520 | ${$args{val}} = $args{addr}->addr; | 
|---|
| 521 | } else { | 
|---|
| 522 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/; | 
|---|
| 523 | } | 
|---|
| 524 | } elsif (${$args{val}} =~ /[a-f:]/) { | 
|---|
| 525 | # looks like a v6 or fragment | 
|---|
| 526 | ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/; | 
|---|
| 527 | if ($args{addr}) { | 
|---|
| 528 | if ($args{addr}->addr =~ /^0/) { | 
|---|
| 529 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/; | 
|---|
| 530 | } else { | 
|---|
| 531 | ${$args{val}} = $args{addr}->addr; | 
|---|
| 532 | } | 
|---|
| 533 | } | 
|---|
| 534 | } else { | 
|---|
| 535 | # bare number (probably).  These could be v4 or v6, so we'll | 
|---|
| 536 | # expand on these on creation of a reverse zone. | 
|---|
| 537 | ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/; | 
|---|
| 538 | } | 
|---|
| 539 | ${$args{host}} =~ s/\.*$/\.$self->{domain}/ if ${$args{host}} !~ /(?:$self->{domain}|ADMINDOMAIN)$/; | 
|---|
| 540 | } | 
|---|
| 541 |  | 
|---|
| 542 | # Multiple PTR records do NOT generally do what most people believe they do, | 
|---|
| 543 | # and tend to fail in the most awkward way possible.  Check and warn. | 
|---|
| 544 | # We use $val instead of $addr->addr since we may be in a defrec, and may have eg "ZONE::42" or "ZONE.12" | 
|---|
| 545 |  | 
|---|
| 546 | my @checkvals = (${$args{val}}); | 
|---|
| 547 | if (${$args{val}} =~ /,/) { | 
|---|
| 548 | # push . and :: variants into checkvals if val has , | 
|---|
| 549 | my $tmp; | 
|---|
| 550 | ($tmp = ${$args{val}}) =~ s/,/./; | 
|---|
| 551 | push @checkvals, $tmp; | 
|---|
| 552 | ($tmp = ${$args{val}}) =~ s/,/::/; | 
|---|
| 553 | push @checkvals, $tmp; | 
|---|
| 554 | } | 
|---|
| 555 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ?"); | 
|---|
| 556 | foreach my $checkme (@checkvals) { | 
|---|
| 557 | if ($args{update}) { | 
|---|
| 558 | # Record update.  There should usually be an existing PTR (the record being updated) | 
|---|
| 559 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}). | 
|---|
| 560 | " WHERE val = ?", undef, ($checkme)) }; | 
|---|
| 561 | return ('WARN', "PTR record for $checkme already exists;  adding another will probably not do what you want") | 
|---|
| 562 | if @ptrs && (!grep /^$args{update}$/, @ptrs); | 
|---|
| 563 | } else { | 
|---|
| 564 | # New record.  Always warn if a PTR exists | 
|---|
| 565 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}). | 
|---|
| 566 | " WHERE val = ?", undef, ($checkme)); | 
|---|
| 567 | return ('WARN', "PTR record for $checkme already exists;  adding another will probably not do what you want") | 
|---|
| 568 | if $ptrcount; | 
|---|
| 569 | } | 
|---|
| 570 | } | 
|---|
| 571 |  | 
|---|
| 572 | } else { | 
|---|
| 573 | # Not absolutely true but only useful if you hack things up for sub-/24 v4 reverse delegations | 
|---|
| 574 | # Simpler to just create the reverse zone and grant access for the customer to edit it, and create direct | 
|---|
| 575 | # PTR records on export | 
|---|
| 576 | return ('FAIL',"Forward zones cannot contain PTR records"); | 
|---|
| 577 | } | 
|---|
| 578 |  | 
|---|
| 579 | return ('OK','OK'); | 
|---|
| 580 | } # done PTR record | 
|---|
| 581 |  | 
|---|
| 582 | # MX record | 
|---|
| 583 | sub _validate_15 { | 
|---|
| 584 | my $self = shift; | 
|---|
| 585 | my $dbh = $self->{dbh}; | 
|---|
| 586 |  | 
|---|
| 587 | my %args = @_; | 
|---|
| 588 |  | 
|---|
| 589 | # Not absolutely true but WTF use is an MX record for a reverse zone? | 
|---|
| 590 | return ('FAIL', 'Reverse zones cannot contain MX records') if $args{revrec} eq 'y'; | 
|---|
| 591 |  | 
|---|
| 592 | return ('FAIL', "Distance is required for MX records") unless defined(${$args{dist}}); | 
|---|
| 593 | ${$args{dist}} =~ s/\s*//g; | 
|---|
| 594 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/; | 
|---|
| 595 |  | 
|---|
| 596 | ${$args{fields}} = "distance,"; | 
|---|
| 597 | push @{$args{vallist}}, ${$args{dist}}; | 
|---|
| 598 |  | 
|---|
| 599 | # Coerce all hostnames to end in ".DOMAIN" for group/default records, | 
|---|
| 600 | # or the intended parent domain for live records. | 
|---|
| 601 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id})); | 
|---|
| 602 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/; | 
|---|
| 603 |  | 
|---|
| 604 | # hmm..  this might work.  except possibly for something pointing to "deadbeef.ca".  <g> | 
|---|
| 605 | #  if ($type == $reverse_typemap{NS} || $type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) { | 
|---|
| 606 | #    if ($val =~ /^\s*[\da-f:.]+\s*$/) { | 
|---|
| 607 | #      return ('FAIL',"$val is not a valid IP address") if !$addr; | 
|---|
| 608 | #    } | 
|---|
| 609 | #  } | 
|---|
| 610 |  | 
|---|
| 611 | return ('OK','OK'); | 
|---|
| 612 | } # done MX record | 
|---|
| 613 |  | 
|---|
| 614 | # TXT record | 
|---|
| 615 | sub _validate_16 { | 
|---|
| 616 | # Could arguably put a WARN return here on very long (>512) records | 
|---|
| 617 | return ('OK','OK'); | 
|---|
| 618 | } # done TXT record | 
|---|
| 619 |  | 
|---|
| 620 | # RP record | 
|---|
| 621 | sub _validate_17 { | 
|---|
| 622 | # Probably have to validate these some day | 
|---|
| 623 | return ('OK','OK'); | 
|---|
| 624 | } # done RP record | 
|---|
| 625 |  | 
|---|
| 626 | # AAAA record | 
|---|
| 627 | sub _validate_28 { | 
|---|
| 628 | my $self = shift; | 
|---|
| 629 | my $dbh = $self->{dbh}; | 
|---|
| 630 |  | 
|---|
| 631 | my %args = @_; | 
|---|
| 632 |  | 
|---|
| 633 | return ('FAIL', 'Reverse zones cannot contain AAAA records') if $args{revrec} eq 'y'; | 
|---|
| 634 |  | 
|---|
| 635 | # Coerce all hostnames to end in ".DOMAIN" for group/default records, | 
|---|
| 636 | # or the intended parent domain for live records. | 
|---|
| 637 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id})); | 
|---|
| 638 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/; | 
|---|
| 639 |  | 
|---|
| 640 | # Check IP is well-formed, and that it's a v6 address | 
|---|
| 641 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address") | 
|---|
| 642 | unless $args{addr} && $args{addr}->{isv6}; | 
|---|
| 643 | # coerce IP/value to normalized form for storage | 
|---|
| 644 | ${$args{val}} = $args{addr}->addr; | 
|---|
| 645 |  | 
|---|
| 646 | return ('OK','OK'); | 
|---|
| 647 | } # done AAAA record | 
|---|
| 648 |  | 
|---|
| 649 | # SRV record | 
|---|
| 650 | sub _validate_33 { | 
|---|
| 651 | my $self = shift; | 
|---|
| 652 | my $dbh = $self->{dbh}; | 
|---|
| 653 |  | 
|---|
| 654 | my %args = @_; | 
|---|
| 655 |  | 
|---|
| 656 | # Not absolutely true but WTF use is an SRV record for a reverse zone? | 
|---|
| 657 | return ('FAIL', 'Reverse zones cannot contain SRV records') if $args{revrec} eq 'y'; | 
|---|
| 658 |  | 
|---|
| 659 | return ('FAIL', "Distance is required for SRV records") unless defined(${$args{dist}}); | 
|---|
| 660 | ${$args{dist}} =~ s/\s*//g; | 
|---|
| 661 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/; | 
|---|
| 662 |  | 
|---|
| 663 | return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]") | 
|---|
| 664 | unless ${$args{host}} =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/; | 
|---|
| 665 | return ('FAIL',"Port and weight are required for SRV records") | 
|---|
| 666 | unless defined(${$args{weight}}) && defined(${$args{port}}); | 
|---|
| 667 | ${$args{weight}} =~ s/\s*//g; | 
|---|
| 668 | ${$args{port}} =~ s/\s*//g; | 
|---|
| 669 |  | 
|---|
| 670 | return ('FAIL',"Port and weight are required, and must be numeric") | 
|---|
| 671 | unless ${$args{weight}} =~ /^\d+$/ && ${$args{port}} =~ /^\d+$/; | 
|---|
| 672 |  | 
|---|
| 673 | ${$args{fields}} = "distance,weight,port,"; | 
|---|
| 674 | push @{$args{vallist}}, (${$args{dist}}, ${$args{weight}}, ${$args{port}}); | 
|---|
| 675 |  | 
|---|
| 676 | # Coerce all hostnames to end in ".DOMAIN" for group/default records, | 
|---|
| 677 | # or the intended parent domain for live records. | 
|---|
| 678 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id})); | 
|---|
| 679 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/; | 
|---|
| 680 |  | 
|---|
| 681 | return ('OK','OK'); | 
|---|
| 682 | } # done SRV record | 
|---|
| 683 |  | 
|---|
| 684 | # Now the custom types | 
|---|
| 685 |  | 
|---|
| 686 | # A+PTR record.  With a very little bit of magic we can also use this sub to validate AAAA+PTR.  Whee! | 
|---|
| 687 | sub _validate_65280 { | 
|---|
| 688 | my $self = shift; | 
|---|
| 689 | my $dbh = $self->{dbh}; | 
|---|
| 690 |  | 
|---|
| 691 | my %args = @_; | 
|---|
| 692 |  | 
|---|
| 693 | my $code = 'OK'; | 
|---|
| 694 | my $msg = 'OK'; | 
|---|
| 695 |  | 
|---|
| 696 | if ($args{defrec} eq 'n') { | 
|---|
| 697 | # live record;  revrec determines whether we validate the PTR or A component first. | 
|---|
| 698 |  | 
|---|
| 699 | if ($args{revrec} eq 'y') { | 
|---|
| 700 | ($code,$msg) = $self->_validate_12(%args); | 
|---|
| 701 | return ($code,$msg) if $code eq 'FAIL'; | 
|---|
| 702 |  | 
|---|
| 703 | # check A+PTR is really v4 | 
|---|
| 704 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address") | 
|---|
| 705 | if ${$args{rectype}} == 65280 && $args{addr}->{isv6}; | 
|---|
| 706 | # check AAAA+PTR is really v6 | 
|---|
| 707 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address") | 
|---|
| 708 | if ${$args{rectype}} == 65281 && !$args{addr}->{isv6}; | 
|---|
| 709 |  | 
|---|
| 710 | # Check if the reqested domain exists.  If not, coerce the type down to PTR and warn. | 
|---|
| 711 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) { | 
|---|
| 712 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added'). | 
|---|
| 713 | " as PTR instead of $typemap{${$args{rectype}}};  domain not found for ${$args{host}}"; | 
|---|
| 714 | $msg .= "\n$addmsg" if $code eq 'WARN'; | 
|---|
| 715 | $msg = $addmsg if $code eq 'OK'; | 
|---|
| 716 | ${$args{rectype}} = $reverse_typemap{PTR}; | 
|---|
| 717 | return ('WARN', $msg); | 
|---|
| 718 | } | 
|---|
| 719 |  | 
|---|
| 720 | # Add domain ID to field list and values | 
|---|
| 721 | ${$args{fields}} .= "domain_id,"; | 
|---|
| 722 | push @{$args{vallist}}, ${$args{domid}}; | 
|---|
| 723 |  | 
|---|
| 724 | } else { | 
|---|
| 725 | ($code,$msg) = $self->_validate_1(%args) if ${$args{rectype}} == 65280; | 
|---|
| 726 | ($code,$msg) = $self->_validate_28(%args) if ${$args{rectype}} == 65281; | 
|---|
| 727 | return ($code,$msg) if $code eq 'FAIL'; | 
|---|
| 728 |  | 
|---|
| 729 | # Check if the requested reverse zone exists - note, an IP fragment won't | 
|---|
| 730 | # work here since we don't *know* which parent to put it in. | 
|---|
| 731 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls. | 
|---|
| 732 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?". | 
|---|
| 733 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}})); | 
|---|
| 734 | if (!$revid) { | 
|---|
| 735 | $msg = "Record ".($args{update} ? 'updated' : 'added')." as ".(${$args{rectype}} == 65280 ? 'A' : 'AAAA'). | 
|---|
| 736 | " instead of $typemap{${$args{rectype}}};  reverse zone not found for ${$args{val}}"; | 
|---|
| 737 | ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA}); | 
|---|
| 738 | return ('WARN', $msg); | 
|---|
| 739 | } | 
|---|
| 740 |  | 
|---|
| 741 | # Check for duplicate PTRs.  Note we don't have to play games with $code and $msg, because | 
|---|
| 742 | # by definition there can't be duplicate PTRs if the reverse zone isn't managed here. | 
|---|
| 743 | if ($args{update}) { | 
|---|
| 744 | # Record update.  There should usually be an existing PTR (the record being updated) | 
|---|
| 745 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}). | 
|---|
| 746 | " WHERE val = ?", undef, (${$args{val}})) }; | 
|---|
| 747 | if (@ptrs && (!grep /^$args{update}$/, @ptrs)) { | 
|---|
| 748 | $msg = "PTR record for ${$args{val}} already exists;  adding another will probably not do what you want"; | 
|---|
| 749 | $code = 'WARN'; | 
|---|
| 750 | } | 
|---|
| 751 | } else { | 
|---|
| 752 | # New record.  Always warn if a PTR exists | 
|---|
| 753 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}). | 
|---|
| 754 | " WHERE val = ?", undef, (${$args{val}})); | 
|---|
| 755 | $msg = "PTR record for ${$args{val}} already exists;  adding another will probably not do what you want" | 
|---|
| 756 | if $ptrcount; | 
|---|
| 757 | $code = 'WARN' if $ptrcount; | 
|---|
| 758 | } | 
|---|
| 759 |  | 
|---|
| 760 | #      my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}). | 
|---|
| 761 | #       " WHERE val = ?", undef, ${$args{val}}); | 
|---|
| 762 | #      if ($ptrcount) { | 
|---|
| 763 | #        my $curid = $dbh->selectrow_array("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}). | 
|---|
| 764 | #               " WHERE val = ? | 
|---|
| 765 | #       $msg = "PTR record for ${$args{val}} already exists;  adding another will probably not do what you want"; | 
|---|
| 766 | #       $code = 'WARN'; | 
|---|
| 767 | #      } | 
|---|
| 768 |  | 
|---|
| 769 | ${$args{fields}} .= "rdns_id,"; | 
|---|
| 770 | push @{$args{vallist}}, $revid; | 
|---|
| 771 | } | 
|---|
| 772 |  | 
|---|
| 773 | } else {      # defrec eq 'y' | 
|---|
| 774 | if ($args{revrec} eq 'y') { | 
|---|
| 775 | ($code,$msg) = $self->_validate_12(%args); | 
|---|
| 776 | return ($code,$msg) if $code eq 'FAIL'; | 
|---|
| 777 | if (${$args{rectype}} == 65280) { | 
|---|
| 778 | return ('FAIL',"A+PTR record must be a valid IPv4 address or fragment") | 
|---|
| 779 | if ${$args{val}} =~ /:/; | 
|---|
| 780 | ${$args{val}} =~ s/^ZONE,/ZONE./;       # Clean up after uncertain IP-fragment-type from _validate_12 | 
|---|
| 781 | } elsif (${$args{rectype}} == 65281) { | 
|---|
| 782 | return ('FAIL',"AAAA+PTR record must be a valid IPv6 address or fragment") | 
|---|
| 783 | if ${$args{val}} =~ /\./; | 
|---|
| 784 | ${$args{val}} =~ s/^ZONE,/ZONE::/;      # Clean up after uncertain IP-fragment-type from _validate_12 | 
|---|
| 785 | } | 
|---|
| 786 | } else { | 
|---|
| 787 | # This is easy.  I also can't see a real use-case for A/AAAA+PTR in *all* forward | 
|---|
| 788 | # domains, since you wouldn't be able to substitute both domain and reverse zone | 
|---|
| 789 | # sanely, and you'd end up with guaranteed over-replicated PTR records that would | 
|---|
| 790 | # confuse the hell out of pretty much anything that uses them. | 
|---|
| 791 | ##fixme: make this a config flag? | 
|---|
| 792 | return ('FAIL', "$typemap{${$args{rectype}}} records not allowed in default domains"); | 
|---|
| 793 | } | 
|---|
| 794 | } | 
|---|
| 795 |  | 
|---|
| 796 | return ($code, $msg); | 
|---|
| 797 | } # done A+PTR record | 
|---|
| 798 |  | 
|---|
| 799 | # AAAA+PTR record | 
|---|
| 800 | # A+PTR above has been magicked to handle AAAA+PTR as well. | 
|---|
| 801 | sub _validate_65281 { | 
|---|
| 802 | return _validate_65280(@_); | 
|---|
| 803 | } # done AAAA+PTR record | 
|---|
| 804 |  | 
|---|
| 805 | # PTR template record | 
|---|
| 806 | sub _validate_65282 { | 
|---|
| 807 | my $self = shift; | 
|---|
| 808 | my $dbh = $self->{dbh}; | 
|---|
| 809 |  | 
|---|
| 810 | my %args = @_; | 
|---|
| 811 |  | 
|---|
| 812 | # we're *this* >.< close to being able to just call _validate_12... unfortunately we can't, quite. | 
|---|
| 813 | if ($args{revrec} eq 'y') { | 
|---|
| 814 | if ($args{defrec} eq 'n') { | 
|---|
| 815 | return ('FAIL', "Template block ${$args{val}} is not within ".$self->revName($args{id})) | 
|---|
| 816 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr}); | 
|---|
| 817 | ##fixme:  warn if $args{val} is not /31 or larger block? | 
|---|
| 818 | ${$args{val}} = "$args{addr}"; | 
|---|
| 819 | } else { | 
|---|
| 820 | if (${$args{val}} =~ /\./) { | 
|---|
| 821 | # looks like a v4 or fragment | 
|---|
| 822 | if (${$args{val}} =~ m|^\d+\.\d+\.\d+\.\d+(?:/\d+)?$|) { | 
|---|
| 823 | # woo!  a complete IP!  validate it and normalize, or fail. | 
|---|
| 824 | $args{addr} = NetAddr::IP->new(${$args{val}}) | 
|---|
| 825 | or return ('FAIL', "IP/value looks like IPv4 but isn't valid"); | 
|---|
| 826 | ${$args{val}} = "$args{addr}"; | 
|---|
| 827 | } else { | 
|---|
| 828 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/; | 
|---|
| 829 | } | 
|---|
| 830 | } elsif (${$args{val}} =~ /[a-f:]/) { | 
|---|
| 831 | # looks like a v6 or fragment | 
|---|
| 832 | ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/; | 
|---|
| 833 | if ($args{addr}) { | 
|---|
| 834 | if ($args{addr}->addr =~ /^0/) { | 
|---|
| 835 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/; | 
|---|
| 836 | } else { | 
|---|
| 837 | ${$args{val}} = "$args{addr}"; | 
|---|
| 838 | } | 
|---|
| 839 | } | 
|---|
| 840 | } else { | 
|---|
| 841 | # bare number (probably).  These could be v4 or v6, so we'll | 
|---|
| 842 | # expand on these on creation of a reverse zone. | 
|---|
| 843 | ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/; | 
|---|
| 844 | } | 
|---|
| 845 | } | 
|---|
| 846 | ##fixme:  validate %-patterns? | 
|---|
| 847 |  | 
|---|
| 848 | # Unlike single PTR records, there is absolutely no way to sanely support multiple | 
|---|
| 849 | # PTR templates for the same block, since they expect to expand to all the individual | 
|---|
| 850 | # IPs on export.  Nested templates should be supported though. | 
|---|
| 851 |  | 
|---|
| 852 | my @checkvals = (${$args{val}}); | 
|---|
| 853 | if (${$args{val}} =~ /,/) { | 
|---|
| 854 | # push . and :: variants into checkvals if val has , | 
|---|
| 855 | my $tmp; | 
|---|
| 856 | ($tmp = ${$args{val}}) =~ s/,/./; | 
|---|
| 857 | push @checkvals, $tmp; | 
|---|
| 858 | ($tmp = ${$args{val}}) =~ s/,/::/; | 
|---|
| 859 | push @checkvals, $tmp; | 
|---|
| 860 | } | 
|---|
| 861 | ##fixme:  this feels wrong still - need to restrict template pseudorecords to One Of Each | 
|---|
| 862 | # Per Netblock such that they don't conflict on export | 
|---|
| 863 | my $typeck; | 
|---|
| 864 | # type 65282 -> ptr template -> look for any of 65282, 65283, 65284 | 
|---|
| 865 | $typeck = 'type=65283 OR type=65284' if ${$args{rectype}} == 65282; | 
|---|
| 866 | # type 65283 -> a+ptr template -> v4 -> look for 65282 or 65283 | 
|---|
| 867 | $typeck = 'type=65283' if ${$args{rectype}} == 65282; | 
|---|
| 868 | # type 65284 -> aaaa+ptr template -> v6 -> look for 65282 or 65284 | 
|---|
| 869 | $typeck = 'type=65284' if ${$args{rectype}} == 65282; | 
|---|
| 870 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ? ". | 
|---|
| 871 | "AND (type=65282 OR $typeck)"); | 
|---|
| 872 | foreach my $checkme (@checkvals) { | 
|---|
| 873 | $pcsth->execute($checkme); | 
|---|
| 874 | my ($rc) = $pcsth->fetchrow_array; | 
|---|
| 875 | return ('FAIL', "Only one template pseudorecord may exist for a given IP block") if $rc > 1; | 
|---|
| 876 | } | 
|---|
| 877 |  | 
|---|
| 878 | } else { | 
|---|
| 879 | return ('FAIL', "Forward zones cannot contain PTR records"); | 
|---|
| 880 | } | 
|---|
| 881 |  | 
|---|
| 882 | return ('OK','OK'); | 
|---|
| 883 | } # done PTR template record | 
|---|
| 884 |  | 
|---|
| 885 | # A+PTR template record | 
|---|
| 886 | sub _validate_65283 { | 
|---|
| 887 | my $self = shift; | 
|---|
| 888 | my $dbh = $self->{dbh}; | 
|---|
| 889 |  | 
|---|
| 890 | my %args = @_; | 
|---|
| 891 |  | 
|---|
| 892 | my ($code,$msg) = ('OK','OK'); | 
|---|
| 893 |  | 
|---|
| 894 | ##fixme:  need to fiddle things since A+PTR templates are acceptable in live | 
|---|
| 895 | # forward zones but not default records | 
|---|
| 896 | if ($args{defrec} eq 'n') { | 
|---|
| 897 | if ($args{revrec} eq 'n') { | 
|---|
| 898 | ($code,$msg) = $self->_validate_1(%args) if ${$args{rectype}} == 65280; | 
|---|
| 899 | ($code,$msg) = $self->_validate_28(%args) if ${$args{rectype}} == 65281; | 
|---|
| 900 | return ($code,$msg) if $code eq 'FAIL'; | 
|---|
| 901 |  | 
|---|
| 902 | # Check if the requested reverse zone exists - note, an IP fragment won't | 
|---|
| 903 | # work here since we don't *know* which parent to put it in. | 
|---|
| 904 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls. | 
|---|
| 905 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?". | 
|---|
| 906 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}})); | 
|---|
| 907 | # Fail if no match;  we can't coerce a PTR-template type down to not include the PTR bit currently. | 
|---|
| 908 | if (!$revid) { | 
|---|
| 909 | $msg = "Can't ".($args{update} ? 'update' : 'add')." ${$args{host}}/${$args{val}} as ". | 
|---|
| 910 | "$typemap{${$args{rectype}}}:  reverse zone not found for ${$args{val}}"; | 
|---|
| 911 | ##fixme:  add A template, AAAA template types? | 
|---|
| 912 | #       ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA}); | 
|---|
| 913 | return ('FAIL', $msg); | 
|---|
| 914 | } | 
|---|
| 915 |  | 
|---|
| 916 | # Add reverse zone ID to field list and values | 
|---|
| 917 | ${$args{fields}} .= "rdns_id,"; | 
|---|
| 918 | push @{$args{vallist}}, $revid; | 
|---|
| 919 |  | 
|---|
| 920 | } else { | 
|---|
| 921 | return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".$self->revName($args{id})) | 
|---|
| 922 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr}); | 
|---|
| 923 | ${$args{val}} = "$args{addr}"; | 
|---|
| 924 |  | 
|---|
| 925 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) { | 
|---|
| 926 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added'). | 
|---|
| 927 | " as PTR template instead of $typemap{${$args{rectype}}};  domain not found for ${$args{host}}"; | 
|---|
| 928 | $msg .= "\n$addmsg" if $code eq 'WARN'; | 
|---|
| 929 | $msg = $addmsg if $code eq 'OK'; | 
|---|
| 930 | ${$args{rectype}} = 65282; | 
|---|
| 931 | return ('WARN', $msg); | 
|---|
| 932 | } | 
|---|
| 933 |  | 
|---|
| 934 | # Add domain ID to field list and values | 
|---|
| 935 | ${$args{fields}} .= "domain_id,"; | 
|---|
| 936 | push @{$args{vallist}}, ${$args{domid}}; | 
|---|
| 937 | } | 
|---|
| 938 |  | 
|---|
| 939 | } else { | 
|---|
| 940 | my ($code,$msg) = $self->_validate_65282(%args); | 
|---|
| 941 | return ($code, $msg) if $code eq 'FAIL'; | 
|---|
| 942 | # get domain, check against ${$args{name}} | 
|---|
| 943 | } | 
|---|
| 944 |  | 
|---|
| 945 | return ('OK','OK'); | 
|---|
| 946 | } # done AAAA+PTR template record | 
|---|
| 947 |  | 
|---|
| 948 | # AAAA+PTR template record | 
|---|
| 949 | sub _validate_65284 { | 
|---|
| 950 | return ('OK','OK'); | 
|---|
| 951 | } # done AAAA+PTR template record | 
|---|
| 952 |  | 
|---|
| 953 | # Delegation record | 
|---|
| 954 | # This is essentially a specialized clone of the NS record, primarily useful | 
|---|
| 955 | # for delegating IPv4 sub-/24 reverse blocks | 
|---|
| 956 | sub _validate_65285 { | 
|---|
| 957 | my $self = shift; | 
|---|
| 958 | my $dbh = $self->{dbh}; | 
|---|
| 959 |  | 
|---|
| 960 | my %args = @_; | 
|---|
| 961 |  | 
|---|
| 962 | # Almost, but not quite, identical to NS record validation. | 
|---|
| 963 |  | 
|---|
| 964 | # Check that the target of the record is within the parent. | 
|---|
| 965 | # Yes, host<->val are mixed up here;  can't see a way to avoid it.  :( | 
|---|
| 966 | if ($args{defrec} eq 'n') { | 
|---|
| 967 | # Check if IP/address/zone/"subzone" is within the parent | 
|---|
| 968 | if ($args{revrec} eq 'y') { | 
|---|
| 969 | my $tmpip = NetAddr::IP->new(${$args{val}}); | 
|---|
| 970 | my $pname = $self->revName($args{id}); | 
|---|
| 971 | return ('FAIL',"${$args{val}} not within $pname") | 
|---|
| 972 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$tmpip); | 
|---|
| 973 | # Normalize | 
|---|
| 974 | ${$args{val}} = "$tmpip"; | 
|---|
| 975 | } else { | 
|---|
| 976 | my $pname = $self->domainName($args{id}); | 
|---|
| 977 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/; | 
|---|
| 978 | } | 
|---|
| 979 | } else { | 
|---|
| 980 | return ('FAIL',"Delegation records are not permitted in default record sets"); | 
|---|
| 981 | } | 
|---|
| 982 | return ('OK','OK'); | 
|---|
| 983 | } | 
|---|
| 984 |  | 
|---|
| 985 |  | 
|---|
| 986 | ## | 
|---|
| 987 | ## Record data substitution subs | 
|---|
| 988 | ## | 
|---|
| 989 |  | 
|---|
| 990 | # Replace ZONE in hostname, or create (most of) the actual proper zone name | 
|---|
| 991 | sub _ZONE { | 
|---|
| 992 | my $zone = shift; | 
|---|
| 993 | my $string = shift; | 
|---|
| 994 | my $fr = shift || 'f';        # flag for forward/reverse order?  nb: ignored for IP | 
|---|
| 995 | my $sep = shift || '-';       # Separator character - unlikely we'll ever need more than . or - | 
|---|
| 996 |  | 
|---|
| 997 | my $prefix; | 
|---|
| 998 |  | 
|---|
| 999 | $string =~ s/,/./ if !$zone->{isv6}; | 
|---|
| 1000 | $string =~ s/,/::/ if $zone->{isv6}; | 
|---|
| 1001 |  | 
|---|
| 1002 | # Subbing ZONE in the host.  We need to properly ID the netblock range | 
|---|
| 1003 | # The subbed text should have "network IP with trailing zeros stripped" for | 
|---|
| 1004 | # blocks lined up on octet (for v4) or hex-quad (for v6) boundaries | 
|---|
| 1005 | # For blocks that do NOT line up on these boundaries, we take the most | 
|---|
| 1006 | # significant octet or 16-bit chunk of the "broadcast" IP and append it | 
|---|
| 1007 | # after a double-dash | 
|---|
| 1008 | # ie: | 
|---|
| 1009 | # 8.0.0.0/6 -> 8.0.0.0 -> 11.255.255.255;  sub should be 8--11 | 
|---|
| 1010 | # 10.0.0.0/12 -> 10.0.0.0 -> 10.0.0.0 -> 10.15.255.255;  sub should be 10-0--15 | 
|---|
| 1011 | # 192.168.4.0/22 -> 192.168.4.0 -> 192.168.7.255;  sub should be 192-168-4--7 | 
|---|
| 1012 | # 192.168.0.8/29 -> 192.168.0.8 -> 192.168.0.15;  sub should be 192-168-0-8--15 | 
|---|
| 1013 | # Similar for v6 | 
|---|
| 1014 |  | 
|---|
| 1015 | if (!$zone->{isv6}) { # IPv4 | 
|---|
| 1016 |  | 
|---|
| 1017 | $prefix = $zone->network->addr;     # Just In Case someone managed to slip in | 
|---|
| 1018 | # a funky subnet that had host bits set. | 
|---|
| 1019 | my $bc = $zone->broadcast->addr; | 
|---|
| 1020 |  | 
|---|
| 1021 | if ($zone->masklen > 24) { | 
|---|
| 1022 | $bc =~ s/^\d+\.\d+\.\d+\.//; | 
|---|
| 1023 | } elsif ($zone->masklen > 16) { | 
|---|
| 1024 | $prefix =~ s/\.0$//; | 
|---|
| 1025 | $bc =~ s/^\d+\.\d+\.//; | 
|---|
| 1026 | } elsif ($zone->masklen > 8) { | 
|---|
| 1027 | $bc =~ s/^\d+\.//; | 
|---|
| 1028 | $prefix =~ s/\.0\.0$//; | 
|---|
| 1029 | } else { | 
|---|
| 1030 | $prefix =~ s/\.0\.0\.0$//; | 
|---|
| 1031 | } | 
|---|
| 1032 | if ($zone->masklen % 8) { | 
|---|
| 1033 | $bc =~ s/(\.255)+$//; | 
|---|
| 1034 | $prefix .= "--$bc";       #"--".zone->masklen;    # use range or mask length? | 
|---|
| 1035 | } | 
|---|
| 1036 | if ($fr eq 'f') { | 
|---|
| 1037 | $prefix =~ s/\.+/$sep/g; | 
|---|
| 1038 | } else { | 
|---|
| 1039 | $prefix = join($sep, reverse(split(/\./, $prefix))); | 
|---|
| 1040 | } | 
|---|
| 1041 |  | 
|---|
| 1042 | } else { # IPv6 | 
|---|
| 1043 |  | 
|---|
| 1044 | if ($fr eq 'f') { | 
|---|
| 1045 |  | 
|---|
| 1046 | $prefix = $zone->network->addr;   # Just In Case someone managed to slip in | 
|---|
| 1047 | # a funky subnet that had host bits set. | 
|---|
| 1048 | my $bc = $zone->broadcast->addr; | 
|---|
| 1049 | if (($zone->masklen % 16) != 0) { | 
|---|
| 1050 | # Strip trailing :0 off $prefix, and :ffff off the broadcast IP | 
|---|
| 1051 | for (my $i=0; $i<(7-int($zone->masklen / 16)); $i++) { | 
|---|
| 1052 | $prefix =~ s/:0$//; | 
|---|
| 1053 | $bc =~ s/:ffff$//; | 
|---|
| 1054 | } | 
|---|
| 1055 | # Strip the leading 16-bit chunks off the front of the broadcast IP | 
|---|
| 1056 | $bc =~ s/^([a-f0-9]+:)+//; | 
|---|
| 1057 | # Append the remaining 16-bit chunk to the prefix after "--" | 
|---|
| 1058 | $prefix .= "--$bc"; | 
|---|
| 1059 | } else { | 
|---|
| 1060 | # Strip off :0 from the end until we reach the netblock length. | 
|---|
| 1061 | for (my $i=0; $i<(8-$zone->masklen / 16); $i++) { | 
|---|
| 1062 | $prefix =~ s/:0$//; | 
|---|
| 1063 | } | 
|---|
| 1064 | } | 
|---|
| 1065 | # Actually deal with the separator | 
|---|
| 1066 | $prefix =~ s/:/$sep/g; | 
|---|
| 1067 |  | 
|---|
| 1068 | } else {    # $fr eq 'f' | 
|---|
| 1069 |  | 
|---|
| 1070 | $prefix = $zone->network->full;   # Just In Case someone managed to slip in | 
|---|
| 1071 | # a funky subnet that had host bits set. | 
|---|
| 1072 | my $bc = $zone->broadcast->full; | 
|---|
| 1073 | $prefix =~ s/://g;        # clean these out since they're not spaced right for this case | 
|---|
| 1074 | $bc =~ s/://g; | 
|---|
| 1075 | # Strip trailing 0 off $prefix, and f off the broadcast IP, to match the mask length | 
|---|
| 1076 | for (my $i=0; $i<(31-int($zone->masklen / 4)); $i++) { | 
|---|
| 1077 | $prefix =~ s/0$//; | 
|---|
| 1078 | $bc =~ s/f$//; | 
|---|
| 1079 | } | 
|---|
| 1080 | # Split and reverse the order of the nibbles in the network/broadcast IPs | 
|---|
| 1081 | # trim another 0 for nibble-aligned blocks first, but only if we really have a block, not an IP | 
|---|
| 1082 | $prefix =~ s/0$// if $zone->masklen % 4 == 0 && $zone->masklen != 128; | 
|---|
| 1083 | my @nbits = reverse split //, $prefix; | 
|---|
| 1084 | my @bbits = reverse split //, $bc; | 
|---|
| 1085 | # Handle the sub-nibble case.  Eww.  I feel dirty supporting this... | 
|---|
| 1086 | $nbits[0] = "$nbits[0]-$bbits[0]" if ($zone->masklen % 4) != 0; | 
|---|
| 1087 | # Glue it back together | 
|---|
| 1088 | $prefix = join($sep, @nbits); | 
|---|
| 1089 |  | 
|---|
| 1090 | }   # $fr ne 'f' | 
|---|
| 1091 |  | 
|---|
| 1092 | } # $zone->{isv6} | 
|---|
| 1093 |  | 
|---|
| 1094 | # Do the substitution, finally | 
|---|
| 1095 | $string =~ s/ZONE/$prefix/; | 
|---|
| 1096 | $string =~ s/--/-/ if $sep ne '-';    # - as separator needs extra help for sub-octet v4 netblocks | 
|---|
| 1097 | return $string; | 
|---|
| 1098 | } # done _ZONE() | 
|---|
| 1099 |  | 
|---|
| 1100 | # Not quite a substitution sub, but placed here as it's basically the inverse of above; | 
|---|
| 1101 | # given the .arpa zone name, return the CIDR netblock the zone is for. | 
|---|
| 1102 | # Supports v4 non-octet/non-classful netblocks as per the method outlined in the Grasshopper Book (2nd Ed p217-218) | 
|---|
| 1103 | # Does NOT support non-quad v6 netblocks via the same scheme;  it shouldn't ever be necessary. | 
|---|
| 1104 | # Takes a nominal .arpa zone name, returns a success code and NetAddr::IP, or a fail code and message | 
|---|
| 1105 | sub _zone2cidr { | 
|---|
| 1106 | my $zone = shift; | 
|---|
| 1107 |  | 
|---|
| 1108 | my $cidr; | 
|---|
| 1109 | my $tmpcidr; | 
|---|
| 1110 | my $warnmsg = ''; | 
|---|
| 1111 |  | 
|---|
| 1112 | if ($zone =~ /\.in-addr\.arpa\.?$/) { | 
|---|
| 1113 | # v4 revzone, formal zone name type | 
|---|
| 1114 | my $tmpzone = $zone; | 
|---|
| 1115 | $tmpzone =~ s/\.in-addr\.arpa\.?//; | 
|---|
| 1116 | return ('FAIL', "Non-numerics in apparent IPv4 reverse zone name") if $tmpzone !~ /^(?:\d+-)?[\d\.]+$/; | 
|---|
| 1117 |  | 
|---|
| 1118 | # Snag the octet pieces | 
|---|
| 1119 | my @octs = split /\./, $tmpzone; | 
|---|
| 1120 |  | 
|---|
| 1121 | # Map result of a range manipulation to a mask length change.  Cheaper than finding the 2-root of $octets[0]+1. | 
|---|
| 1122 | # Note we will not support /31 blocks, mostly due to issues telling "24-31" -> .24/29 apart from | 
|---|
| 1123 | # "24-31" -> .24/31", with a litte bit of "/31 is icky". | 
|---|
| 1124 | my %maskmap = (  3 => 2,  7 => 3, 15 => 4, 31 => 5, 63 => 6, 127 => 7, | 
|---|
| 1125 | 30 => 2, 29 => 3, 28 => 4, 27 => 5, 26 => 6,  25 => 7 | 
|---|
| 1126 | ); | 
|---|
| 1127 |  | 
|---|
| 1128 | # Handle "range" blocks, eg, 80-83.168.192.in-addr.arpa (192.168.80.0/22) | 
|---|
| 1129 | # Need to take the size of the range to offset the basic octet-based mask length, | 
|---|
| 1130 | # and make sure the first number in the range gets used as the network address for the block | 
|---|
| 1131 | # Alternate form:  The second number is actually the real netmask, not the end of the range. | 
|---|
| 1132 | my $masklen = 0; | 
|---|
| 1133 | if ($octs[0] =~ /^((\d+)-(\d+))$/) {        # take the range... | 
|---|
| 1134 | if (24 < $3 && $3 < 31) { | 
|---|
| 1135 | # we have a real netmask | 
|---|
| 1136 | $masklen = -$maskmap{$3}; | 
|---|
| 1137 | } else { | 
|---|
| 1138 | # we have a range.  NB:  only real CIDR ranges are supported | 
|---|
| 1139 | $masklen -= $maskmap{-(eval $1)};       # find the mask base... | 
|---|
| 1140 | } | 
|---|
| 1141 | $octs[0] = $2;    # set the base octet of the range... | 
|---|
| 1142 | } | 
|---|
| 1143 | @octs = reverse @octs;      # We can reverse the octet pieces now that we've extracted and munged any ranges | 
|---|
| 1144 |  | 
|---|
| 1145 | # arguably we should only allow sub-octet range/mask in-addr.arpa | 
|---|
| 1146 | # specifications in the least significant octet, but the code is | 
|---|
| 1147 | # simpler if we deal with sub-octet delegations at any level. | 
|---|
| 1148 |  | 
|---|
| 1149 | # Now we find the "true" mask with the aid of the "base" calculated above | 
|---|
| 1150 | if ($#octs == 0) { | 
|---|
| 1151 | $masklen += 8; | 
|---|
| 1152 | $tmpcidr = "$octs[0].0.0.0/$masklen";     # really hope we don't see one of these very often. | 
|---|
| 1153 | } elsif ($#octs == 1) { | 
|---|
| 1154 | $masklen += 16; | 
|---|
| 1155 | $tmpcidr = "$octs[0].$octs[1].0.0/$masklen"; | 
|---|
| 1156 | } elsif ($#octs == 2) { | 
|---|
| 1157 | $masklen += 24; | 
|---|
| 1158 | $tmpcidr = "$octs[0].$octs[1].$octs[2].0/$masklen"; | 
|---|
| 1159 | } else { | 
|---|
| 1160 | $masklen += 32; | 
|---|
| 1161 | $tmpcidr = "$octs[0].$octs[1].$octs[2].$octs[3]/$masklen"; | 
|---|
| 1162 | } | 
|---|
| 1163 |  | 
|---|
| 1164 | } elsif ($zone =~ /\.ip6\.arpa$/) { | 
|---|
| 1165 | # v6 revzone, formal zone name type | 
|---|
| 1166 | my $tmpzone = $zone; | 
|---|
| 1167 | $tmpzone =~ s/\.ip6\.arpa\.?//; | 
|---|
| 1168 | ##fixme:  if-n-when we decide we can support sub-nibble v6 zone names, we'll need to change this segment | 
|---|
| 1169 | return ('FAIL', "Non-hexadecimals in apparent IPv6 reverse zone name") if $tmpzone !~ /^[a-fA-F\d\.]+$/; | 
|---|
| 1170 | my @quads = reverse(split(/\./, $tmpzone)); | 
|---|
| 1171 | $warnmsg .= "Apparent sub-/64 IPv6 reverse zone\n" if $#quads > 15; | 
|---|
| 1172 | my $nc; | 
|---|
| 1173 | foreach (@quads) { | 
|---|
| 1174 | $tmpcidr .= $_; | 
|---|
| 1175 | $tmpcidr .= ":" if ++$nc % 4 == 0; | 
|---|
| 1176 | } | 
|---|
| 1177 | my $nq = 1 if $nc % 4 != 0; | 
|---|
| 1178 | my $mask = $nc * 4; # need to do this here because we probably increment it below | 
|---|
| 1179 | while ($nc++ % 4 != 0) { | 
|---|
| 1180 | $tmpcidr .= "0"; | 
|---|
| 1181 | } | 
|---|
| 1182 | $tmpcidr .= ($nq ? '::' : ':')."/$mask"; | 
|---|
| 1183 | } | 
|---|
| 1184 |  | 
|---|
| 1185 | # Just to be sure, use NetAddr::IP to validate.  Saves a lot of nasty regex watching for valid octet values. | 
|---|
| 1186 | return ('FAIL', "Invalid zone $zone (apparent netblock $tmpcidr)") | 
|---|
| 1187 | unless $cidr = NetAddr::IP->new($tmpcidr); | 
|---|
| 1188 |  | 
|---|
| 1189 | if ($warnmsg) { | 
|---|
| 1190 | $errstr = $warnmsg; | 
|---|
| 1191 | return ('WARN', $cidr); | 
|---|
| 1192 | } | 
|---|
| 1193 | return ('OK', $cidr); | 
|---|
| 1194 | } # done _zone2cidr() | 
|---|
| 1195 |  | 
|---|
| 1196 | # Record template %-parameter expansion, IPv4.  Note that IPv6 doesn't | 
|---|
| 1197 | # really have a sane way to handle this type of expansion at the moment | 
|---|
| 1198 | # due to the size of the address space. | 
|---|
| 1199 | # Takes a reference to a template string to be expanded, and an IP to use in the replacement. | 
|---|
| 1200 | sub _template4_expand { | 
|---|
| 1201 | my $tmpl = shift; | 
|---|
| 1202 | my $ip = shift; | 
|---|
| 1203 |  | 
|---|
| 1204 | my @ipparts = split /\./, $ip; | 
|---|
| 1205 | my @iphex; | 
|---|
| 1206 | my @ippad; | 
|---|
| 1207 | for (@ipparts) { | 
|---|
| 1208 | push @iphex, sprintf("%x", $_); | 
|---|
| 1209 | push @ippad, sprintf("%0.3u", $_); | 
|---|
| 1210 | } | 
|---|
| 1211 |  | 
|---|
| 1212 | # IP substitutions in template records: | 
|---|
| 1213 | #major patterns: | 
|---|
| 1214 | #dashed IP, forward and reverse | 
|---|
| 1215 | #dotted IP, forward and reverse (even if forward is... dumb) | 
|---|
| 1216 | # -> %r for reverse, %i for forward, leading - or . to indicate separator, defaults to - | 
|---|
| 1217 | # %r or %-r   => %4d-%3d-%2d-%1d | 
|---|
| 1218 | # %.r         => %4d.%3d.%2d.%1d | 
|---|
| 1219 | # %i or %-i   => %1d-%2d-%3d-%4d | 
|---|
| 1220 | # %.i         => %1d.%2d.%3d.%4d | 
|---|
| 1221 | $$tmpl =~ s/\%r/\%4d-\%3d-\%2d-\%1d/g; | 
|---|
| 1222 | $$tmpl =~ s/\%([-.])r/\%4d$1\%3d$1\%2d$1\%1d/g; | 
|---|
| 1223 | $$tmpl =~ s/\%i/\%1d-\%2d-\%3d-\%4d/g; | 
|---|
| 1224 | $$tmpl =~ s/\%([-.])i/\%1d$1\%2d$1\%3d$1\%4d/g; | 
|---|
| 1225 |  | 
|---|
| 1226 | #hex-coded IP | 
|---|
| 1227 | # %h | 
|---|
| 1228 | $$tmpl =~ s/\%h/$iphex[0]$iphex[1]$iphex[2]$iphex[3]/g; | 
|---|
| 1229 |  | 
|---|
| 1230 | #IP as decimal-coded 32-bit value | 
|---|
| 1231 | # %d | 
|---|
| 1232 | my $iptmp = $ipparts[0]*256*256*256 + $ipparts[1]*256*256 + $ipparts[2]*256 + $ipparts[3]; | 
|---|
| 1233 | $$tmpl =~ s/\%d/$iptmp/g; | 
|---|
| 1234 |  | 
|---|
| 1235 | #minor patterns (per-octet) | 
|---|
| 1236 | # %[1234][dh0] | 
|---|
| 1237 | #octet | 
|---|
| 1238 | #hex-coded octet | 
|---|
| 1239 | #0-padded octet | 
|---|
| 1240 | $$tmpl =~ s/\%([1234])d/$ipparts[$1-1]/g; | 
|---|
| 1241 | $$tmpl =~ s/\%([1234])h/$iphex[$1-1]/g; | 
|---|
| 1242 | $$tmpl =~ s/\%([1234])0/$ippad[$1-1]/g; | 
|---|
| 1243 | } # _template4_expand() | 
|---|
| 1244 |  | 
|---|
| 1245 |  | 
|---|
| 1246 | ## | 
|---|
| 1247 | ## Initialization and cleanup subs | 
|---|
| 1248 | ## | 
|---|
| 1249 |  | 
|---|
| 1250 | ## DNSDB::__cfgload() | 
|---|
| 1251 | # Private sub to parse a config file and load it into %config | 
|---|
| 1252 | # Takes a filename and a hashref to put the parsed entries in | 
|---|
| 1253 | sub __cfgload { | 
|---|
| 1254 | $errstr = ''; | 
|---|
| 1255 | my $cfgfile = shift; | 
|---|
| 1256 | my $cfg = shift; | 
|---|
| 1257 |  | 
|---|
| 1258 | if (open CFG, "<$cfgfile") { | 
|---|
| 1259 | while (<CFG>) { | 
|---|
| 1260 | chomp; | 
|---|
| 1261 | s/^\s*//; | 
|---|
| 1262 | next if /^#/; | 
|---|
| 1263 | next if /^$/; | 
|---|
| 1264 | # hmm.  more complex bits in this file might require [heading] headers, maybe? | 
|---|
| 1265 | #    $mode = $1 if /^\[(a-z)+]/; | 
|---|
| 1266 | # DB connect info | 
|---|
| 1267 | $cfg->{dbname}    = $1 if /^dbname\s*=\s*([a-z0-9_.-]+)/i; | 
|---|
| 1268 | $cfg->{dbuser}    = $1 if /^dbuser\s*=\s*([a-z0-9_.-]+)/i; | 
|---|
| 1269 | $cfg->{dbpass}    = $1 if /^dbpass\s*=\s*([a-z0-9_.-]+)/i; | 
|---|
| 1270 | $cfg->{dbhost}    = $1 if /^dbhost\s*=\s*([a-z0-9_.-]+)/i; | 
|---|
| 1271 | # Mail settings | 
|---|
| 1272 | $cfg->{mailhost}          = $1 if /^mailhost\s*=\s*([a-z0-9_.-]+)/i; | 
|---|
| 1273 | $cfg->{mailnotify}        = $1 if /^mailnotify\s*=\s*([a-z0-9_.\@-]+)/i; | 
|---|
| 1274 | $cfg->{mailsender}        = $1 if /^mailsender\s*=\s*([a-z0-9_.\@-]+)/i; | 
|---|
| 1275 | $cfg->{mailname}          = $1 if /^mailname\s*=\s*([a-z0-9\s_.-]+)/i; | 
|---|
| 1276 | $cfg->{orgname}           = $1 if /^orgname\s*=\s*([a-z0-9\s_.,'-]+)/i; | 
|---|
| 1277 | $cfg->{domain}            = $1 if /^domain\s*=\s*([a-z0-9_.-]+)/i; | 
|---|
| 1278 | # session - note this is fed directly to CGI::Session | 
|---|
| 1279 | $cfg->{timeout}           = $1 if /^[tT][iI][mM][eE][oO][uU][tT]\s*=\s*(\d+[smhdwMy]?)/; | 
|---|
| 1280 | $cfg->{sessiondir}        = $1 if m{^sessiondir\s*=\s*([a-z0-9/_.-]+)}i; | 
|---|
| 1281 | # misc | 
|---|
| 1282 | $cfg->{log_failures}      = $1 if /^log_failures\s*=\s*([a-z01]+)/i; | 
|---|
| 1283 | $cfg->{perpage}           = $1 if /^perpage\s*=\s*(\d+)/i; | 
|---|
| 1284 | $cfg->{exportcache}       = $1 if m{^exportcache\s*=\s*([a-z0-9/_.-]+)}i; | 
|---|
| 1285 | # not supported in dns.cgi yet | 
|---|
| 1286 | #      $cfg->{templatedir}      = $1 if m{^templatedir\s*=\s*([a-z0-9/_.-]+)}i; | 
|---|
| 1287 | #      $cfg->{templateoverride} = $1 if m{^templateoverride\s*=\s*([a-z0-9/_.-]+)}i; | 
|---|
| 1288 | # RPC options | 
|---|
| 1289 | $cfg->{rpcmode}           = $1 if /^rpc_mode\s*=\s*(socket|HTTP|XMLRPC)\s*$/i; | 
|---|
| 1290 | $cfg->{maxfcgi}           = $1 if /^max_fcgi_requests\s*=\s*(\d+)\s*$/i; | 
|---|
| 1291 | if (my ($tmp) = /^rpc_iplist\s*=\s*(.+)/i) { | 
|---|
| 1292 | my @ips = split /[,\s]+/, $tmp; | 
|---|
| 1293 | my $rpcsys = shift @ips; | 
|---|
| 1294 | push @{$cfg->{rpcacl}{$rpcsys}}, @ips; | 
|---|
| 1295 | } | 
|---|
| 1296 | } | 
|---|
| 1297 | close CFG; | 
|---|
| 1298 | } else { | 
|---|
| 1299 | $errstr = "Couldn't load configuration file $cfgfile: $!"; | 
|---|
| 1300 | return; | 
|---|
| 1301 | } | 
|---|
| 1302 | return 1; | 
|---|
| 1303 | } # end __cfgload() | 
|---|
| 1304 |  | 
|---|
| 1305 |  | 
|---|
| 1306 | ## DNSDB::connectDB() | 
|---|
| 1307 | # Creates connection to DNS database. | 
|---|
| 1308 | # Requires the database name, username, and password. | 
|---|
| 1309 | # Returns a handle to the db or undef on failure. | 
|---|
| 1310 | # Set up for a PostgreSQL db;  could be any transactional DBMS with the | 
|---|
| 1311 | # right changes. | 
|---|
| 1312 | # Called by new();  not intended to be called publicly. | 
|---|
| 1313 | sub connectDB { | 
|---|
| 1314 | $errstr = ''; | 
|---|
| 1315 | my $dbname = shift; | 
|---|
| 1316 | my $user = shift; | 
|---|
| 1317 | my $pass = shift; | 
|---|
| 1318 | my $dbh; | 
|---|
| 1319 | my $DSN = "DBI:Pg:dbname=$dbname"; | 
|---|
| 1320 |  | 
|---|
| 1321 | my $host = shift; | 
|---|
| 1322 | $DSN .= ";host=$host" if $host; | 
|---|
| 1323 |  | 
|---|
| 1324 | # Note that we want to autocommit by default, and we will turn it off locally as necessary. | 
|---|
| 1325 | # We may not want to print gobbledygook errors;  YMMV.  Have to ponder that further. | 
|---|
| 1326 | $dbh = DBI->connect($DSN, $user, $pass, { | 
|---|
| 1327 | AutoCommit => 1, | 
|---|
| 1328 | PrintError => 0 | 
|---|
| 1329 | }); | 
|---|
| 1330 | if (!$dbh) { | 
|---|
| 1331 | $errstr = $DBI::errstr; | 
|---|
| 1332 | return; | 
|---|
| 1333 | } | 
|---|
| 1334 | #) if(!$dbh); | 
|---|
| 1335 |  | 
|---|
| 1336 | local $dbh->{RaiseError} = 1; | 
|---|
| 1337 |  | 
|---|
| 1338 | eval { | 
|---|
| 1339 | ##fixme:  initialize the DB if we can't find the table (since, by definition, there's | 
|---|
| 1340 | # nothing there if we can't select from it...) | 
|---|
| 1341 | my $tblsth = $dbh->prepare("SELECT count(*) FROM pg_catalog.pg_class WHERE relkind='r' AND relname=?"); | 
|---|
| 1342 | my ($tblcount) = $dbh->selectrow_array($tblsth, undef, ('misc')); | 
|---|
| 1343 | #  return (undef,$DBI::errstr) if $dbh->err; | 
|---|
| 1344 |  | 
|---|
| 1345 | #if ($tblcount == 0) { | 
|---|
| 1346 | #  # create tables one at a time, checking for each. | 
|---|
| 1347 | #  return (undef, "check table misc missing"); | 
|---|
| 1348 | #} | 
|---|
| 1349 |  | 
|---|
| 1350 | # Return here if we can't select. | 
|---|
| 1351 | # This should retrieve the dbversion key. | 
|---|
| 1352 | my $sth = $dbh->prepare("SELECT key,value FROM misc WHERE misc_id=1"); | 
|---|
| 1353 | $sth->execute(); | 
|---|
| 1354 | #  return (undef,$DBI::errstr) if ($sth->err); | 
|---|
| 1355 |  | 
|---|
| 1356 | ##fixme:  do stuff to the DB on version mismatch | 
|---|
| 1357 | # x.y series should upgrade on $DNSDB::VERSION > misc(key=>version) | 
|---|
| 1358 | # DB should be downward-compatible;  column defaults should give sane (if possibly | 
|---|
| 1359 | # useless-and-needs-help) values in columns an older software stack doesn't know about. | 
|---|
| 1360 |  | 
|---|
| 1361 | # See if the select returned anything (or null data).  This should | 
|---|
| 1362 | # succeed if the select executed, but... | 
|---|
| 1363 | $sth->fetchrow(); | 
|---|
| 1364 | #  return (undef,$DBI::errstr)  if ($sth->err); | 
|---|
| 1365 |  | 
|---|
| 1366 | $sth->finish; | 
|---|
| 1367 |  | 
|---|
| 1368 | }; # wrapped DB checks | 
|---|
| 1369 | if ($@) { | 
|---|
| 1370 | $errstr = $@; | 
|---|
| 1371 | return; | 
|---|
| 1372 | } | 
|---|
| 1373 |  | 
|---|
| 1374 | # If we get here, we should be OK. | 
|---|
| 1375 | return $dbh; | 
|---|
| 1376 | } # end connectDB | 
|---|
| 1377 |  | 
|---|
| 1378 |  | 
|---|
| 1379 | ## DNSDB::finish() | 
|---|
| 1380 | # Cleans up after database handles and so on. | 
|---|
| 1381 | # Requires a database handle | 
|---|
| 1382 | sub finish { | 
|---|
| 1383 | my $self = shift; | 
|---|
| 1384 | $self->{dbh}->disconnect; | 
|---|
| 1385 | } # end finish | 
|---|
| 1386 |  | 
|---|
| 1387 |  | 
|---|
| 1388 | ## DNSDB::initGlobals() | 
|---|
| 1389 | # Initialize global variables | 
|---|
| 1390 | # NB: this does NOT include web-specific session variables! | 
|---|
| 1391 | sub initGlobals { | 
|---|
| 1392 | my $self = shift; | 
|---|
| 1393 | my $dbh = $self->{dbh}; | 
|---|
| 1394 |  | 
|---|
| 1395 | # load record types from database | 
|---|
| 1396 | my $sth = $dbh->prepare("SELECT val,name,stdflag FROM rectypes"); | 
|---|
| 1397 | $sth->execute; | 
|---|
| 1398 | while (my ($recval,$recname,$stdflag) = $sth->fetchrow_array()) { | 
|---|
| 1399 | $typemap{$recval} = $recname; | 
|---|
| 1400 | $reverse_typemap{$recname} = $recval; | 
|---|
| 1401 | # now we fill the record validation function hash | 
|---|
| 1402 | if ($stdflag < 5) { | 
|---|
| 1403 | my $fn = "_validate_$recval"; | 
|---|
| 1404 | $validators{$recval} = \&$fn; | 
|---|
| 1405 | } else { | 
|---|
| 1406 | my $fn = "sub { return ('FAIL','Type $recval ($recname) not supported'); }"; | 
|---|
| 1407 | $validators{$recval} = eval $fn; | 
|---|
| 1408 | } | 
|---|
| 1409 | } | 
|---|
| 1410 | } # end initGlobals | 
|---|
| 1411 |  | 
|---|
| 1412 |  | 
|---|
| 1413 | ## DNSDB::initRPC() | 
|---|
| 1414 | # Takes a remote username and remote fullname. | 
|---|
| 1415 | # Sets up the RPC logging-pseudouser if needed. | 
|---|
| 1416 | # Sets the %userdata hash for logging. | 
|---|
| 1417 | # Returns undef on failure | 
|---|
| 1418 | sub initRPC { | 
|---|
| 1419 | my $self = shift; | 
|---|
| 1420 | my $dbh = $self->{dbh}; | 
|---|
| 1421 | my %args  = @_; | 
|---|
| 1422 |  | 
|---|
| 1423 | return if !$args{username}; | 
|---|
| 1424 | return if !$args{fullname}; | 
|---|
| 1425 |  | 
|---|
| 1426 | $args{username} = "$args{username}/$args{rpcsys}"; | 
|---|
| 1427 |  | 
|---|
| 1428 | my $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status". | 
|---|
| 1429 | " FROM users WHERE username=?", undef, ($args{username}) ); | 
|---|
| 1430 | if (!$tmpuser) { | 
|---|
| 1431 | $dbh->do("INSERT INTO users (username,password,firstname,type) VALUES (?,'RPC',?,'R')", undef, | 
|---|
| 1432 | ($args{username}, $args{fullname}) ); | 
|---|
| 1433 | $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status". | 
|---|
| 1434 | " FROM users WHERE username=?", undef, ($args{username}) ); | 
|---|
| 1435 | } | 
|---|
| 1436 | $tmpuser->{lastname} = '' if !$tmpuser->{lastname}; | 
|---|
| 1437 | $self->{loguserid} = $tmpuser->{userid}; | 
|---|
| 1438 | $self->{logusername} = $tmpuser->{username}; | 
|---|
| 1439 | $self->{logfullname} = "$tmpuser->{firstname} $tmpuser->{lastname} ($args{rpcsys})"; | 
|---|
| 1440 | return 1 if $tmpuser; | 
|---|
| 1441 | } # end initRPC() | 
|---|
| 1442 |  | 
|---|
| 1443 |  | 
|---|
| 1444 | ## DNSDB::login() | 
|---|
| 1445 | # Takes a database handle, username and password | 
|---|
| 1446 | # Returns a userdata hash (UID, GID, username, fullname parts) if username exists, | 
|---|
| 1447 | # password matches the one on file, and account is not disabled | 
|---|
| 1448 | # Returns undef otherwise | 
|---|
| 1449 | sub login { | 
|---|
| 1450 | my $self = shift; | 
|---|
| 1451 | my $dbh = $self->{dbh}; | 
|---|
| 1452 | my $user = shift; | 
|---|
| 1453 | my $pass = shift; | 
|---|
| 1454 |  | 
|---|
| 1455 | my $userinfo = $dbh->selectrow_hashref("SELECT user_id,group_id,password,firstname,lastname,status". | 
|---|
| 1456 | " FROM users WHERE username=?", | 
|---|
| 1457 | undef, ($user) ); | 
|---|
| 1458 | return if !$userinfo; | 
|---|
| 1459 | return if !$userinfo->{status}; | 
|---|
| 1460 |  | 
|---|
| 1461 | if ($userinfo->{password} =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) { | 
|---|
| 1462 | # native passwords (crypt-md5) | 
|---|
| 1463 | return if $userinfo->{password} ne unix_md5_crypt($pass,$1); | 
|---|
| 1464 | } elsif ($userinfo->{password} =~ /^[0-9a-f]{32}$/) { | 
|---|
| 1465 | # VegaDNS import (hex-coded MD5) | 
|---|
| 1466 | return if $userinfo->{password} ne md5_hex($pass); | 
|---|
| 1467 | } else { | 
|---|
| 1468 | # plaintext (convenient now and then) | 
|---|
| 1469 | return if $userinfo->{password} ne $pass; | 
|---|
| 1470 | } | 
|---|
| 1471 |  | 
|---|
| 1472 | return $userinfo; | 
|---|
| 1473 | } # end login() | 
|---|
| 1474 |  | 
|---|
| 1475 |  | 
|---|
| 1476 | ## DNSDB::initActionLog() | 
|---|
| 1477 | # Set up action logging.  Takes a database handle and user ID | 
|---|
| 1478 | # Sets some internal globals and Does The Right Thing to set up a logging channel. | 
|---|
| 1479 | # This sets up _log() to spew out log entries to the defined channel without worrying | 
|---|
| 1480 | # about having to open a file or a syslog channel | 
|---|
| 1481 | ##fixme Need to call _initActionLog_blah() for various logging channels, configured | 
|---|
| 1482 | # via dnsdb.conf, in $self->{log_channel} or something | 
|---|
| 1483 | # See https://secure.deepnet.cx/trac/dnsadmin/ticket/21 | 
|---|
| 1484 | sub initActionLog { | 
|---|
| 1485 | my $self = shift; | 
|---|
| 1486 | my $dbh = $self->{dbh}; | 
|---|
| 1487 | my $uid = shift; | 
|---|
| 1488 |  | 
|---|
| 1489 | return if !$uid; | 
|---|
| 1490 |  | 
|---|
| 1491 | # snag user info for logging.  there's got to be a way to not have to pass this back | 
|---|
| 1492 | # and forth from a caller, but web usage means no persistence we can rely on from | 
|---|
| 1493 | # the server side. | 
|---|
| 1494 | my ($username,$fullname) = $dbh->selectrow_array("SELECT username, firstname || ' ' || lastname". | 
|---|
| 1495 | " FROM users WHERE user_id=?", undef, ($uid)); | 
|---|
| 1496 | ##fixme: errors are unpossible! | 
|---|
| 1497 |  | 
|---|
| 1498 | $self->{logusername} = $username; | 
|---|
| 1499 | $self->{loguserid} = $uid; | 
|---|
| 1500 | $self->{logfullname} = $fullname; | 
|---|
| 1501 |  | 
|---|
| 1502 | # convert to real check once we have other logging channels | 
|---|
| 1503 | # if ($self->{log_channel} eq 'sql') { | 
|---|
| 1504 | #   Open Log, Sez Me! | 
|---|
| 1505 | # } | 
|---|
| 1506 |  | 
|---|
| 1507 | } # end initActionLog | 
|---|
| 1508 |  | 
|---|
| 1509 |  | 
|---|
| 1510 | ## DNSDB::getPermissions() | 
|---|
| 1511 | # Get permissions from DB | 
|---|
| 1512 | # Requires DB handle, group or user flag, ID, and hashref. | 
|---|
| 1513 | sub getPermissions { | 
|---|
| 1514 | my $self = shift; | 
|---|
| 1515 | my $dbh = $self->{dbh}; | 
|---|
| 1516 |  | 
|---|
| 1517 | my $type = shift; | 
|---|
| 1518 | my $id = shift; | 
|---|
| 1519 | my $hash = shift; | 
|---|
| 1520 |  | 
|---|
| 1521 | my $sql = qq( | 
|---|
| 1522 | SELECT | 
|---|
| 1523 | p.admin,p.self_edit, | 
|---|
| 1524 | p.group_create,p.group_edit,p.group_delete, | 
|---|
| 1525 | p.user_create,p.user_edit,p.user_delete, | 
|---|
| 1526 | p.domain_create,p.domain_edit,p.domain_delete, | 
|---|
| 1527 | p.record_create,p.record_edit,p.record_delete,p.record_locchg, | 
|---|
| 1528 | p.location_create,p.location_edit,p.location_delete,p.location_view | 
|---|
| 1529 | FROM permissions p | 
|---|
| 1530 | ); | 
|---|
| 1531 | if ($type eq 'group') { | 
|---|
| 1532 | $sql .= qq( | 
|---|
| 1533 | JOIN groups g ON g.permission_id=p.permission_id | 
|---|
| 1534 | WHERE g.group_id=? | 
|---|
| 1535 | ); | 
|---|
| 1536 | } else { | 
|---|
| 1537 | $sql .= qq( | 
|---|
| 1538 | JOIN users u ON u.permission_id=p.permission_id | 
|---|
| 1539 | WHERE u.user_id=? | 
|---|
| 1540 | ); | 
|---|
| 1541 | } | 
|---|
| 1542 |  | 
|---|
| 1543 | my $sth = $dbh->prepare($sql); | 
|---|
| 1544 |  | 
|---|
| 1545 | ##fixme?  we don't trap other plain SELECT errors | 
|---|
| 1546 | $sth->execute($id); | 
|---|
| 1547 |  | 
|---|
| 1548 | #  my $permref = $sth->fetchrow_hashref; | 
|---|
| 1549 | #  return $permref; | 
|---|
| 1550 | #  $hash = $permref; | 
|---|
| 1551 | # Eww.  Need to learn how to forcibly drop a hashref onto an existing hash. | 
|---|
| 1552 | ($hash->{admin},$hash->{self_edit}, | 
|---|
| 1553 | $hash->{group_create},$hash->{group_edit},$hash->{group_delete}, | 
|---|
| 1554 | $hash->{user_create},$hash->{user_edit},$hash->{user_delete}, | 
|---|
| 1555 | $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete}, | 
|---|
| 1556 | $hash->{record_create},$hash->{record_edit},$hash->{record_delete},$hash->{record_locchg}, | 
|---|
| 1557 | $hash->{location_create},$hash->{location_edit},$hash->{location_delete},$hash->{location_view} | 
|---|
| 1558 | ) = $sth->fetchrow_array; | 
|---|
| 1559 |  | 
|---|
| 1560 | } # end getPermissions() | 
|---|
| 1561 |  | 
|---|
| 1562 |  | 
|---|
| 1563 | ## DNSDB::changePermissions() | 
|---|
| 1564 | # Update an ACL entry | 
|---|
| 1565 | # Takes a db handle, type, owner-id, and hashref for the changed permissions. | 
|---|
| 1566 | sub changePermissions { | 
|---|
| 1567 | my $self = shift; | 
|---|
| 1568 | my $dbh = $self->{dbh}; | 
|---|
| 1569 | my $type = shift; | 
|---|
| 1570 | my $id = shift; | 
|---|
| 1571 | my $newperms = shift; | 
|---|
| 1572 | my $inherit = shift || 0; | 
|---|
| 1573 |  | 
|---|
| 1574 | my $resultmsg = ''; | 
|---|
| 1575 |  | 
|---|
| 1576 | # see if we're switching from inherited to custom.  for bonus points, | 
|---|
| 1577 | # snag the permid and parent permid anyway, since we'll need the permid | 
|---|
| 1578 | # to set/alter custom perms, and both if we're switching from custom to | 
|---|
| 1579 | # inherited. | 
|---|
| 1580 | my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id,". | 
|---|
| 1581 | ($type eq 'user' ? 'u.group_id,u.username' : 'u.parent_group_id,u.group_name'). | 
|---|
| 1582 | " FROM ".($type eq 'user' ? 'users' : 'groups')." u ". | 
|---|
| 1583 | " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ". | 
|---|
| 1584 | " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?"); | 
|---|
| 1585 | $sth->execute($id); | 
|---|
| 1586 |  | 
|---|
| 1587 | my ($wasinherited,$permid,$parpermid,$parid,$name) = $sth->fetchrow_array; | 
|---|
| 1588 |  | 
|---|
| 1589 | # hack phtoui | 
|---|
| 1590 | # group id 1 is "special" in that it's it's own parent (err...  possibly.) | 
|---|
| 1591 | # may make its parent id 0 which doesn't exist, and as a bonus is Perl-false. | 
|---|
| 1592 | $wasinherited = 0 if ($type eq 'group' && $id == 1); | 
|---|
| 1593 |  | 
|---|
| 1594 | local $dbh->{AutoCommit} = 0; | 
|---|
| 1595 | local $dbh->{RaiseError} = 1; | 
|---|
| 1596 |  | 
|---|
| 1597 | # Wrap all the SQL in a transaction | 
|---|
| 1598 | eval { | 
|---|
| 1599 | if ($inherit) { | 
|---|
| 1600 |  | 
|---|
| 1601 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ". | 
|---|
| 1602 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) ); | 
|---|
| 1603 | $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) ); | 
|---|
| 1604 |  | 
|---|
| 1605 | } else { | 
|---|
| 1606 |  | 
|---|
| 1607 | if ($wasinherited) {      # munge new permission entry in if we're switching from inherited perms | 
|---|
| 1608 | ##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users | 
|---|
| 1609 | # ... if'n'when we have groups with fully inherited permissions. | 
|---|
| 1610 | # SQL is coo | 
|---|
| 1611 | $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ". | 
|---|
| 1612 | "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) ); | 
|---|
| 1613 | ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ". | 
|---|
| 1614 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) ); | 
|---|
| 1615 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ". | 
|---|
| 1616 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) ); | 
|---|
| 1617 | } | 
|---|
| 1618 |  | 
|---|
| 1619 | # and now set the permissions we were passed | 
|---|
| 1620 | foreach (@permtypes) { | 
|---|
| 1621 | if (defined ($newperms->{$_})) { | 
|---|
| 1622 | $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) ); | 
|---|
| 1623 | } | 
|---|
| 1624 | } | 
|---|
| 1625 |  | 
|---|
| 1626 | } # (inherited->)? custom | 
|---|
| 1627 |  | 
|---|
| 1628 | if ($type eq 'user') { | 
|---|
| 1629 | $resultmsg = "Updated permissions for user $name"; | 
|---|
| 1630 | } else { | 
|---|
| 1631 | $resultmsg = "Updated default permissions for group $name"; | 
|---|
| 1632 | } | 
|---|
| 1633 | $self->_log(group_id => ($type eq 'user' ? $parid : $id), entry => $resultmsg); | 
|---|
| 1634 | $dbh->commit; | 
|---|
| 1635 | }; # end eval | 
|---|
| 1636 | if ($@) { | 
|---|
| 1637 | my $msg = $@; | 
|---|
| 1638 | eval { $dbh->rollback; }; | 
|---|
| 1639 | return ('FAIL',"Error changing permissions: $msg"); | 
|---|
| 1640 | } | 
|---|
| 1641 |  | 
|---|
| 1642 | return ('OK',$resultmsg); | 
|---|
| 1643 | } # end changePermissions() | 
|---|
| 1644 |  | 
|---|
| 1645 |  | 
|---|
| 1646 | ## DNSDB::comparePermissions() | 
|---|
| 1647 | # Compare two permission hashes | 
|---|
| 1648 | # Returns '>', '<', '=', '!' | 
|---|
| 1649 | sub comparePermissions { | 
|---|
| 1650 | my $p1 = shift; | 
|---|
| 1651 | my $p2 = shift; | 
|---|
| 1652 |  | 
|---|
| 1653 | my $retval = '=';     # assume equality until proven otherwise | 
|---|
| 1654 |  | 
|---|
| 1655 | no warnings "uninitialized"; | 
|---|
| 1656 |  | 
|---|
| 1657 | foreach (@permtypes) { | 
|---|
| 1658 | next if $p1->{$_} == $p2->{$_};     # equal is good | 
|---|
| 1659 | if ($p1->{$_} && !$p2->{$_}) { | 
|---|
| 1660 | if ($retval eq '<') {     # if we've already found an unequal pair where | 
|---|
| 1661 | $retval = '!';          # $p2 has more access, and we now find a pair | 
|---|
| 1662 | last;                   # where $p1 has more access, the overall access | 
|---|
| 1663 | }                         # is neither greater or lesser, it's unequal. | 
|---|
| 1664 | $retval = '>'; | 
|---|
| 1665 | } | 
|---|
| 1666 | if (!$p1->{$_} && $p2->{$_}) { | 
|---|
| 1667 | if ($retval eq '>') {     # if we've already found an unequal pair where | 
|---|
| 1668 | $retval = '!';          # $p1 has more access, and we now find a pair | 
|---|
| 1669 | last;                   # where $p2 has more access, the overall access | 
|---|
| 1670 | }                         # is neither greater or lesser, it's unequal. | 
|---|
| 1671 | $retval = '<'; | 
|---|
| 1672 | } | 
|---|
| 1673 | } | 
|---|
| 1674 | return $retval; | 
|---|
| 1675 | } # end comparePermissions() | 
|---|
| 1676 |  | 
|---|
| 1677 |  | 
|---|
| 1678 | ## DNSDB::changeGroup() | 
|---|
| 1679 | # Change group ID of an entity | 
|---|
| 1680 | # Takes a database handle, entity type, entity ID, and new group ID | 
|---|
| 1681 | sub changeGroup { | 
|---|
| 1682 | my $self = shift; | 
|---|
| 1683 | my $dbh = $self->{dbh}; | 
|---|
| 1684 | my $type = shift; | 
|---|
| 1685 | my $id = shift; | 
|---|
| 1686 | my $newgrp = shift; | 
|---|
| 1687 |  | 
|---|
| 1688 | ##fixme:  fail on not enough args | 
|---|
| 1689 | #return ('FAIL', "Missing | 
|---|
| 1690 |  | 
|---|
| 1691 | return ('FAIL', "Can't change the group of a $type") | 
|---|
| 1692 | unless grep /^$type$/, ('domain','revzone','user','group');     # could be extended for defrecs? | 
|---|
| 1693 |  | 
|---|
| 1694 | # Collect some names for logging and messages | 
|---|
| 1695 | my $entname; | 
|---|
| 1696 | if ($type eq 'domain') { | 
|---|
| 1697 | $entname = $self->domainName($id); | 
|---|
| 1698 | } elsif ($type eq 'revzone') { | 
|---|
| 1699 | $entname = $self->revName($id); | 
|---|
| 1700 | } elsif ($type eq 'user') { | 
|---|
| 1701 | $entname = $self->userFullName($id, '%u'); | 
|---|
| 1702 | } elsif ($type eq 'group') { | 
|---|
| 1703 | $entname = $self->groupName($id); | 
|---|
| 1704 | } | 
|---|
| 1705 |  | 
|---|
| 1706 | my ($oldgid) = $dbh->selectrow_array("SELECT group_id FROM $par_tbl{$type} WHERE $id_col{$type}=?", | 
|---|
| 1707 | undef, ($id)); | 
|---|
| 1708 | my $oldgname = $self->groupName($oldgid); | 
|---|
| 1709 | my $newgname = $self->groupName($newgrp); | 
|---|
| 1710 |  | 
|---|
| 1711 | return ('FAIL', "Can't move things into a group that doesn't exist") if !$newgname; | 
|---|
| 1712 |  | 
|---|
| 1713 | return ('WARN', "Nothing to do, new group is the same as the old group") if $oldgid == $newgrp; | 
|---|
| 1714 |  | 
|---|
| 1715 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 1716 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 1717 | local $dbh->{AutoCommit} = 0; | 
|---|
| 1718 | local $dbh->{RaiseError} = 1; | 
|---|
| 1719 |  | 
|---|
| 1720 | eval { | 
|---|
| 1721 | $dbh->do("UPDATE $par_tbl{$type} SET group_id=? WHERE $id_col{$type}=?", undef, ($newgrp, $id)); | 
|---|
| 1722 | # Log the change in both the old and new groups | 
|---|
| 1723 | $self->_log(group_id => $oldgid, entry => "Moved $type $entname from $oldgname to $newgname"); | 
|---|
| 1724 | $self->_log(group_id => $newgrp, entry => "Moved $type $entname from $oldgname to $newgname"); | 
|---|
| 1725 | $dbh->commit; | 
|---|
| 1726 | }; | 
|---|
| 1727 | if ($@) { | 
|---|
| 1728 | my $msg = $@; | 
|---|
| 1729 | eval { $dbh->rollback; }; | 
|---|
| 1730 | if ($self->{log_failures}) { | 
|---|
| 1731 | $self->_log(group_id => $oldgid, entry => "Error moving $type $entname to $newgname: $msg"); | 
|---|
| 1732 | $dbh->commit;     # since we enabled transactions earlier | 
|---|
| 1733 | } | 
|---|
| 1734 | return ('FAIL',"Error moving $type $entname to $newgname: $msg"); | 
|---|
| 1735 | } | 
|---|
| 1736 |  | 
|---|
| 1737 | return ('OK',"Moved $type $entname from $oldgname to $newgname"); | 
|---|
| 1738 | } # end changeGroup() | 
|---|
| 1739 |  | 
|---|
| 1740 |  | 
|---|
| 1741 | ## | 
|---|
| 1742 | ## Processing subs | 
|---|
| 1743 | ## | 
|---|
| 1744 |  | 
|---|
| 1745 | ## DNSDB::addDomain() | 
|---|
| 1746 | # Add a domain | 
|---|
| 1747 | # Takes a database handle, domain name, numeric group, boolean(ish) state (active/inactive), | 
|---|
| 1748 | # and user info hash (for logging). | 
|---|
| 1749 | # Returns a status code and message | 
|---|
| 1750 | sub addDomain { | 
|---|
| 1751 | $errstr = ''; | 
|---|
| 1752 | my $self = shift; | 
|---|
| 1753 | my $dbh = $self->{dbh}; | 
|---|
| 1754 | my $domain = shift; | 
|---|
| 1755 | return ('FAIL',"Domain must not be blank\n") if !$domain; | 
|---|
| 1756 | my $group = shift; | 
|---|
| 1757 | return ('FAIL',"Group must be specified\n") if !defined($group); | 
|---|
| 1758 | my $state = shift; | 
|---|
| 1759 | return ('FAIL',"Domain status must be specified\n") if !defined($state); | 
|---|
| 1760 | my $defloc = shift || ''; | 
|---|
| 1761 |  | 
|---|
| 1762 | $state = 1 if $state =~ /^active$/; | 
|---|
| 1763 | $state = 1 if $state =~ /^on$/; | 
|---|
| 1764 | $state = 0 if $state =~ /^inactive$/; | 
|---|
| 1765 | $state = 0 if $state =~ /^off$/; | 
|---|
| 1766 |  | 
|---|
| 1767 | return ('FAIL',"Invalid domain status") if $state !~ /^\d+$/; | 
|---|
| 1768 |  | 
|---|
| 1769 | return ('FAIL', "Invalid characters in domain") if $domain !~ /^[a-zA-Z0-9_.-]+$/; | 
|---|
| 1770 |  | 
|---|
| 1771 | my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)"); | 
|---|
| 1772 | my $dom_id; | 
|---|
| 1773 |  | 
|---|
| 1774 | # quick check to start to see if we've already got one | 
|---|
| 1775 | $sth->execute($domain); | 
|---|
| 1776 | ($dom_id) = $sth->fetchrow_array; | 
|---|
| 1777 |  | 
|---|
| 1778 | return ('FAIL', "Domain already exists") if $dom_id; | 
|---|
| 1779 |  | 
|---|
| 1780 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 1781 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 1782 | local $dbh->{AutoCommit} = 0; | 
|---|
| 1783 | local $dbh->{RaiseError} = 1; | 
|---|
| 1784 |  | 
|---|
| 1785 | # Wrap all the SQL in a transaction | 
|---|
| 1786 | eval { | 
|---|
| 1787 | # insert the domain... | 
|---|
| 1788 | $dbh->do("INSERT INTO domains (domain,group_id,status,default_location) VALUES (?,?,?,?)", undef, | 
|---|
| 1789 | ($domain, $group, $state, $defloc)); | 
|---|
| 1790 |  | 
|---|
| 1791 | # get the ID... | 
|---|
| 1792 | ($dom_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)", | 
|---|
| 1793 | undef, ($domain)); | 
|---|
| 1794 |  | 
|---|
| 1795 | $self->_log(domain_id => $dom_id, group_id => $group, | 
|---|
| 1796 | entry => "Added ".($state ? 'active' : 'inactive')." domain $domain"); | 
|---|
| 1797 |  | 
|---|
| 1798 | # ... and now we construct the standard records from the default set.  NB:  group should be variable. | 
|---|
| 1799 | my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?"); | 
|---|
| 1800 | my $sth_in = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,distance,weight,port,ttl,location)". | 
|---|
| 1801 | " VALUES ($dom_id,?,?,?,?,?,?,?,?)"); | 
|---|
| 1802 | $sth->execute($group); | 
|---|
| 1803 | while (my ($host, $type, $val, $dist, $weight, $port, $ttl) = $sth->fetchrow_array()) { | 
|---|
| 1804 | $host =~ s/DOMAIN/$domain/g; | 
|---|
| 1805 | $val =~ s/DOMAIN/$domain/g; | 
|---|
| 1806 | $sth_in->execute($host, $type, $val, $dist, $weight, $port, $ttl, $defloc); | 
|---|
| 1807 | if ($typemap{$type} eq 'SOA') { | 
|---|
| 1808 | my @tmp1 = split /:/, $host; | 
|---|
| 1809 | my @tmp2 = split /:/, $val; | 
|---|
| 1810 | $self->_log(domain_id => $dom_id, group_id => $group, | 
|---|
| 1811 | entry => "[new $domain] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ". | 
|---|
| 1812 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"); | 
|---|
| 1813 | } else { | 
|---|
| 1814 | my $logentry = "[new $domain] Added record '$host $typemap{$type}"; | 
|---|
| 1815 | $logentry .= " [distance $dist]" if $typemap{$type} eq 'MX'; | 
|---|
| 1816 | $logentry .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$type} eq 'SRV'; | 
|---|
| 1817 | $self->_log(domain_id => $dom_id, group_id => $group, | 
|---|
| 1818 | entry => $logentry." $val', TTL $ttl"); | 
|---|
| 1819 | } | 
|---|
| 1820 | } | 
|---|
| 1821 |  | 
|---|
| 1822 | # once we get here, we should have suceeded. | 
|---|
| 1823 | $dbh->commit; | 
|---|
| 1824 | }; # end eval | 
|---|
| 1825 |  | 
|---|
| 1826 | if ($@) { | 
|---|
| 1827 | my $msg = $@; | 
|---|
| 1828 | eval { $dbh->rollback; }; | 
|---|
| 1829 | $self->_log(group_id => $group, entry => "Failed adding domain $domain ($msg)") | 
|---|
| 1830 | if $self->{log_failures}; | 
|---|
| 1831 | $dbh->commit;       # since we enabled transactions earlier | 
|---|
| 1832 | return ('FAIL',$msg); | 
|---|
| 1833 | } else { | 
|---|
| 1834 | return ('OK',$dom_id); | 
|---|
| 1835 | } | 
|---|
| 1836 | } # end addDomain | 
|---|
| 1837 |  | 
|---|
| 1838 |  | 
|---|
| 1839 | ## DNSDB::delZone() | 
|---|
| 1840 | # Delete a forward or reverse zone. | 
|---|
| 1841 | # Takes a database handle, zone ID, and forward/reverse flag. | 
|---|
| 1842 | # for now, just delete the records, then the domain. | 
|---|
| 1843 | # later we may want to archive it in some way instead (status code 2, for example?) | 
|---|
| 1844 | sub delZone { | 
|---|
| 1845 | my $self = shift; | 
|---|
| 1846 | my $dbh = $self->{dbh}; | 
|---|
| 1847 | my $zoneid = shift; | 
|---|
| 1848 | my $revrec = shift; | 
|---|
| 1849 |  | 
|---|
| 1850 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 1851 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 1852 | local $dbh->{AutoCommit} = 0; | 
|---|
| 1853 | local $dbh->{RaiseError} = 1; | 
|---|
| 1854 |  | 
|---|
| 1855 | my $msg = ''; | 
|---|
| 1856 | my $failmsg = ''; | 
|---|
| 1857 | my $zone = ($revrec eq 'n' ? $self->domainName($zoneid) : $self->revName($zoneid)); | 
|---|
| 1858 |  | 
|---|
| 1859 | return ('FAIL', ($revrec eq 'n' ? 'Domain' : 'Reverse zone')." ID $zoneid doesn't exist") if !$zone; | 
|---|
| 1860 |  | 
|---|
| 1861 | # Set this up here since we may use if if $self->{log_failures} is enabled | 
|---|
| 1862 | my %loghash; | 
|---|
| 1863 | $loghash{domain_id} = $zoneid if $revrec eq 'n'; | 
|---|
| 1864 | $loghash{rdns_id} = $zoneid if $revrec eq 'y'; | 
|---|
| 1865 | $loghash{group_id} = $self->parentID( | 
|---|
| 1866 | id => $zoneid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec); | 
|---|
| 1867 |  | 
|---|
| 1868 | # Wrap all the SQL in a transaction | 
|---|
| 1869 | eval { | 
|---|
| 1870 | # Disentangle custom record types before removing the | 
|---|
| 1871 | # ones that are only in the zone to be deleted | 
|---|
| 1872 | if ($revrec eq 'n') { | 
|---|
| 1873 | my $sth = $dbh->prepare("UPDATE records SET type=?,domain_id=0 WHERE domain_id=? AND type=?"); | 
|---|
| 1874 | $failmsg = "Failure converting multizone types to single-zone"; | 
|---|
| 1875 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65280); | 
|---|
| 1876 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65281); | 
|---|
| 1877 | $sth->execute(65282, $zoneid, 65283); | 
|---|
| 1878 | $sth->execute(65282, $zoneid, 65284); | 
|---|
| 1879 | $failmsg = "Failure removing domain records"; | 
|---|
| 1880 | $dbh->do("DELETE FROM records WHERE domain_id=?", undef, ($zoneid)); | 
|---|
| 1881 | $failmsg = "Failure removing domain"; | 
|---|
| 1882 | $dbh->do("DELETE FROM domains WHERE domain_id=?", undef, ($zoneid)); | 
|---|
| 1883 | } else { | 
|---|
| 1884 | my $sth = $dbh->prepare("UPDATE records SET type=?,rdns_id=0 WHERE rdns_id=? AND type=?"); | 
|---|
| 1885 | $failmsg = "Failure converting multizone types to single-zone"; | 
|---|
| 1886 | $sth->execute($reverse_typemap{A}, $zoneid, 65280); | 
|---|
| 1887 | $sth->execute($reverse_typemap{AAAA}, $zoneid, 65281); | 
|---|
| 1888 | # We don't have an "A template" or "AAAA template" type, although it might be useful for symmetry. | 
|---|
| 1889 | #      $sth->execute(65286?, $zoneid, 65283); | 
|---|
| 1890 | #      $sth->execute(65286?, $zoneid, 65284); | 
|---|
| 1891 | $failmsg = "Failure removing reverse records"; | 
|---|
| 1892 | $dbh->do("DELETE FROM records WHERE rdns_id=?", undef, ($zoneid)); | 
|---|
| 1893 | $failmsg = "Failure removing reverse zone"; | 
|---|
| 1894 | $dbh->do("DELETE FROM revzones WHERE rdns_id=?", undef, ($zoneid)); | 
|---|
| 1895 | } | 
|---|
| 1896 |  | 
|---|
| 1897 | $msg = "Deleted ".($revrec eq 'n' ? 'domain' : 'reverse zone')." $zone"; | 
|---|
| 1898 | $loghash{entry} = $msg; | 
|---|
| 1899 | $self->_log(%loghash); | 
|---|
| 1900 |  | 
|---|
| 1901 | # once we get here, we should have suceeded. | 
|---|
| 1902 | $dbh->commit; | 
|---|
| 1903 | }; # end eval | 
|---|
| 1904 |  | 
|---|
| 1905 | if ($@) { | 
|---|
| 1906 | $msg = $@; | 
|---|
| 1907 | eval { $dbh->rollback; }; | 
|---|
| 1908 | $loghash{entry} = "Error deleting $zone: $msg ($failmsg)"; | 
|---|
| 1909 | if ($self->{log_failures}) { | 
|---|
| 1910 | $self->_log(%loghash); | 
|---|
| 1911 | $dbh->commit;     # since we enabled transactions earlier | 
|---|
| 1912 | } | 
|---|
| 1913 | return ('FAIL', $loghash{entry}); | 
|---|
| 1914 | } else { | 
|---|
| 1915 | return ('OK', $msg); | 
|---|
| 1916 | } | 
|---|
| 1917 |  | 
|---|
| 1918 | } # end delZone() | 
|---|
| 1919 |  | 
|---|
| 1920 |  | 
|---|
| 1921 | ## DNSDB::domainName() | 
|---|
| 1922 | # Return the domain name based on a domain ID | 
|---|
| 1923 | # Takes a database handle and the domain ID | 
|---|
| 1924 | # Returns the domain name or undef on failure | 
|---|
| 1925 | sub domainName { | 
|---|
| 1926 | $errstr = ''; | 
|---|
| 1927 | my $self = shift; | 
|---|
| 1928 | my $dbh = $self->{dbh}; | 
|---|
| 1929 | my $domid = shift; | 
|---|
| 1930 | my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) ); | 
|---|
| 1931 | $errstr = $DBI::errstr if !$domname; | 
|---|
| 1932 | return $domname if $domname; | 
|---|
| 1933 | } # end domainName() | 
|---|
| 1934 |  | 
|---|
| 1935 |  | 
|---|
| 1936 | ## DNSDB::revName() | 
|---|
| 1937 | # Return the reverse zone name based on an rDNS ID | 
|---|
| 1938 | # Takes a database handle and the rDNS ID | 
|---|
| 1939 | # Returns the reverse zone name or undef on failure | 
|---|
| 1940 | sub revName { | 
|---|
| 1941 | $errstr = ''; | 
|---|
| 1942 | my $self = shift; | 
|---|
| 1943 | my $dbh = $self->{dbh}; | 
|---|
| 1944 | my $revid = shift; | 
|---|
| 1945 | my ($revname) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id=?", undef, ($revid) ); | 
|---|
| 1946 | $errstr = $DBI::errstr if !$revname; | 
|---|
| 1947 | return $revname if $revname; | 
|---|
| 1948 | } # end revName() | 
|---|
| 1949 |  | 
|---|
| 1950 |  | 
|---|
| 1951 | ## DNSDB::domainID() | 
|---|
| 1952 | # Takes a database handle and domain name | 
|---|
| 1953 | # Returns the domain ID number | 
|---|
| 1954 | sub domainID { | 
|---|
| 1955 | $errstr = ''; | 
|---|
| 1956 | my $self = shift; | 
|---|
| 1957 | my $dbh = $self->{dbh}; | 
|---|
| 1958 | my $domain = shift; | 
|---|
| 1959 | my ($domid) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)", | 
|---|
| 1960 | undef, ($domain) ); | 
|---|
| 1961 | if (!$domid) { | 
|---|
| 1962 | if ($dbh->err) { | 
|---|
| 1963 | $errstr = $DBI::errstr; | 
|---|
| 1964 | } else { | 
|---|
| 1965 | $errstr = "Domain $domain not present"; | 
|---|
| 1966 | } | 
|---|
| 1967 | } | 
|---|
| 1968 | return $domid if $domid; | 
|---|
| 1969 | } # end domainID() | 
|---|
| 1970 |  | 
|---|
| 1971 |  | 
|---|
| 1972 | ## DNSDB::revID() | 
|---|
| 1973 | # Takes a database handle and reverse zone name | 
|---|
| 1974 | # Returns the rDNS ID number | 
|---|
| 1975 | sub revID { | 
|---|
| 1976 | $errstr = ''; | 
|---|
| 1977 | my $self = shift; | 
|---|
| 1978 | my $dbh = $self->{dbh}; | 
|---|
| 1979 | my $revzone = shift; | 
|---|
| 1980 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ($revzone) ); | 
|---|
| 1981 | if (!$revid) { | 
|---|
| 1982 | if ($dbh->err) { | 
|---|
| 1983 | $errstr = $DBI::errstr; | 
|---|
| 1984 | } else { | 
|---|
| 1985 | $errstr = "Reverse zone $revzone not present"; | 
|---|
| 1986 | } | 
|---|
| 1987 | } | 
|---|
| 1988 | return $revid if $revid; | 
|---|
| 1989 | } # end revID() | 
|---|
| 1990 |  | 
|---|
| 1991 |  | 
|---|
| 1992 | ## DNSDB::addRDNS | 
|---|
| 1993 | # Adds a reverse DNS zone | 
|---|
| 1994 | # Takes a database handle, CIDR block, reverse DNS pattern, numeric group, | 
|---|
| 1995 | # and boolean(ish) state (active/inactive) | 
|---|
| 1996 | # Returns a status code and message | 
|---|
| 1997 | sub addRDNS { | 
|---|
| 1998 | my $self = shift; | 
|---|
| 1999 | my $dbh = $self->{dbh}; | 
|---|
| 2000 | my $zone = NetAddr::IP->new(shift); | 
|---|
| 2001 |  | 
|---|
| 2002 | return ('FAIL',"Zone name must be a valid CIDR netblock") unless ($zone && $zone->addr !~ /^0/); | 
|---|
| 2003 | my $revpatt = shift;  # construct a custom (A/AAAA+)? PTR template record | 
|---|
| 2004 | my $group = shift; | 
|---|
| 2005 | my $state = shift; | 
|---|
| 2006 | my $defloc = shift || ''; | 
|---|
| 2007 |  | 
|---|
| 2008 | $state = 1 if $state =~ /^active$/; | 
|---|
| 2009 | $state = 1 if $state =~ /^on$/; | 
|---|
| 2010 | $state = 0 if $state =~ /^inactive$/; | 
|---|
| 2011 | $state = 0 if $state =~ /^off$/; | 
|---|
| 2012 |  | 
|---|
| 2013 | return ('FAIL',"Invalid zone status") if $state !~ /^\d+$/; | 
|---|
| 2014 |  | 
|---|
| 2015 | # quick check to start to see if we've already got one | 
|---|
| 2016 | my ($rdns_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ("$zone")); | 
|---|
| 2017 |  | 
|---|
| 2018 | return ('FAIL', "Zone already exists") if $rdns_id; | 
|---|
| 2019 |  | 
|---|
| 2020 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 2021 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 2022 | local $dbh->{AutoCommit} = 0; | 
|---|
| 2023 | local $dbh->{RaiseError} = 1; | 
|---|
| 2024 |  | 
|---|
| 2025 | my $warnstr = ''; | 
|---|
| 2026 | my $defttl = 3600;    # 1 hour should be reasonable.  And unless things have gone horribly | 
|---|
| 2027 | # wrong, we should have a value to override this anyway. | 
|---|
| 2028 |  | 
|---|
| 2029 | # Wrap all the SQL in a transaction | 
|---|
| 2030 | eval { | 
|---|
| 2031 | # insert the zone... | 
|---|
| 2032 | $dbh->do("INSERT INTO revzones (revnet,group_id,status,default_location) VALUES (?,?,?,?)", undef, | 
|---|
| 2033 | ($zone, $group, $state, $defloc) ); | 
|---|
| 2034 |  | 
|---|
| 2035 | # get the ID... | 
|---|
| 2036 | ($rdns_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')"); | 
|---|
| 2037 |  | 
|---|
| 2038 | $self->_log(rdns_id => $rdns_id, group_id => $group, | 
|---|
| 2039 | entry => "Added ".($state ? 'active' : 'inactive')." reverse zone $zone"); | 
|---|
| 2040 |  | 
|---|
| 2041 | # ... and now we construct the standard records from the default set.  NB:  group should be variable. | 
|---|
| 2042 | my $sth = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?"); | 
|---|
| 2043 | my $sth_in = $dbh->prepare("INSERT INTO records (rdns_id,domain_id,host,type,val,ttl,location)". | 
|---|
| 2044 | " VALUES ($rdns_id,?,?,?,?,?,?)"); | 
|---|
| 2045 | $sth->execute($group); | 
|---|
| 2046 | while (my ($host,$type,$val,$ttl) = $sth->fetchrow_array()) { | 
|---|
| 2047 | # Silently skip v4/v6 mismatches.  This is not an error, this is expected. | 
|---|
| 2048 | if ($zone->{isv6}) { | 
|---|
| 2049 | next if ($type == 65280 || $type == 65283); | 
|---|
| 2050 | } else { | 
|---|
| 2051 | next if ($type == 65281 || $type == 65284); | 
|---|
| 2052 | } | 
|---|
| 2053 |  | 
|---|
| 2054 | $host =~ s/ADMINDOMAIN/$self->{domain}/g; | 
|---|
| 2055 |  | 
|---|
| 2056 | # Check to make sure the IP stubs will fit in the zone.  Under most usage failures here should be rare. | 
|---|
| 2057 | # On failure, tack a note on to a warning string and continue without adding this record. | 
|---|
| 2058 | # While we're at it, we substitute $zone for ZONE in the value. | 
|---|
| 2059 | if ($val eq 'ZONE') { | 
|---|
| 2060 | # If we've got a pattern, we skip the default record version on (A+)PTR-template types | 
|---|
| 2061 | next if $revpatt && ($type == 65282 || $type == 65283); | 
|---|
| 2062 | ##fixme?  do we care if we have multiple whole-zone templates? | 
|---|
| 2063 | $val = $zone->network; | 
|---|
| 2064 | } elsif ($val =~ /ZONE/) { | 
|---|
| 2065 | my $tmpval = $val; | 
|---|
| 2066 | $tmpval =~ s/ZONE//; | 
|---|
| 2067 | # Bend the rules and allow single-trailing-number PTR or PTR template records to be inserted | 
|---|
| 2068 | # as either v4 or v6.  May make this an off-by-default config flag | 
|---|
| 2069 | # Note that the origin records that may trigger this **SHOULD** already have ZONE,\d | 
|---|
| 2070 | if ($type == 12 || $type == 65282) { | 
|---|
| 2071 | $tmpval =~ s/[,.]/::/ if ($tmpval =~ /^[,.]\d+$/ && $zone->{isv6}); | 
|---|
| 2072 | $tmpval =~ s/[,:]+/./ if ($tmpval =~ /^(?:,|::)\d+$/ && !$zone->{isv6}); | 
|---|
| 2073 | } | 
|---|
| 2074 | my $addr; | 
|---|
| 2075 | if ($self->_ipparent('n', 'y', \$tmpval, $rdns_id, \$addr)) { | 
|---|
| 2076 | $val = $addr->addr; | 
|---|
| 2077 | } else { | 
|---|
| 2078 | $warnstr .= "\nDefault record '$val $typemap{$type} $host' doesn't fit in $zone, skipping"; | 
|---|
| 2079 | next; | 
|---|
| 2080 | } | 
|---|
| 2081 | } | 
|---|
| 2082 |  | 
|---|
| 2083 | # Substitute $zone for ZONE in the hostname, but only for non-NS records. | 
|---|
| 2084 | # NS records get this substitution on the value instead. | 
|---|
| 2085 | $host = _ZONE($zone, $host) if $type != 2; | 
|---|
| 2086 |  | 
|---|
| 2087 | # Fill in the forward domain ID if we can find it, otherwise: | 
|---|
| 2088 | # Coerce type down to PTR or PTR template if we can't | 
|---|
| 2089 | my $domid = 0; | 
|---|
| 2090 | if ($type >= 65280) { | 
|---|
| 2091 | if (!($domid = $self->_hostparent($host))) { | 
|---|
| 2092 | $warnstr .= "\nRecord added as PTR instead of $typemap{$type};  domain not found for $host"; | 
|---|
| 2093 | $type = $reverse_typemap{PTR}; | 
|---|
| 2094 | $domid = 0;   # just to be explicit. | 
|---|
| 2095 | } | 
|---|
| 2096 | } | 
|---|
| 2097 |  | 
|---|
| 2098 | $sth_in->execute($domid,$host,$type,$val,$ttl,$defloc); | 
|---|
| 2099 |  | 
|---|
| 2100 | if ($typemap{$type} eq 'SOA') { | 
|---|
| 2101 | my @tmp1 = split /:/, $host; | 
|---|
| 2102 | my @tmp2 = split /:/, $val; | 
|---|
| 2103 | $self->_log(rdns_id => $rdns_id, group_id => $group, | 
|---|
| 2104 | entry => "[new $zone] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ". | 
|---|
| 2105 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"); | 
|---|
| 2106 | $defttl = $tmp2[3]; | 
|---|
| 2107 | } else { | 
|---|
| 2108 | my $logentry = "[new $zone] Added record '$host $typemap{$type} $val', TTL $ttl"; | 
|---|
| 2109 | $logentry .= ", default location ".$self->getLoc($defloc)->{description} if $defloc; | 
|---|
| 2110 | $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group, entry => $logentry); | 
|---|
| 2111 | } | 
|---|
| 2112 | } | 
|---|
| 2113 |  | 
|---|
| 2114 | # Generate record based on provided pattern. | 
|---|
| 2115 | if ($revpatt) { | 
|---|
| 2116 | my $host; | 
|---|
| 2117 | my $type = ($zone->{isv6} ? 65284 : 65283); | 
|---|
| 2118 | my $val = $zone->network; | 
|---|
| 2119 |  | 
|---|
| 2120 | # Substitute $zone for ZONE in the hostname. | 
|---|
| 2121 | $host = _ZONE($zone, $revpatt); | 
|---|
| 2122 |  | 
|---|
| 2123 | my $domid = 0; | 
|---|
| 2124 | if (!($domid = $self->_hostparent($host))) { | 
|---|
| 2125 | $warnstr .= "\nDefault pattern added as PTR template instead of $typemap{$type};  domain not found for $host"; | 
|---|
| 2126 | $type = 65282; | 
|---|
| 2127 | $domid = 0;     # just to be explicit. | 
|---|
| 2128 | } | 
|---|
| 2129 |  | 
|---|
| 2130 | $sth_in->execute($domid,$host,$type,$val,$defttl,$defloc); | 
|---|
| 2131 | my $logentry = "[new $zone] Added record '$host $typemap{$type}"; | 
|---|
| 2132 | $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group, | 
|---|
| 2133 | entry => $logentry." $val', TTL $defttl from pattern"); | 
|---|
| 2134 | } | 
|---|
| 2135 |  | 
|---|
| 2136 | # If there are warnings (presumably about default records skipped for cause) log them | 
|---|
| 2137 | $self->_log(rdns_id => $rdns_id, group_id => $group, entry => "Warning(s) adding $zone:$warnstr") | 
|---|
| 2138 | if $warnstr; | 
|---|
| 2139 |  | 
|---|
| 2140 | # once we get here, we should have suceeded. | 
|---|
| 2141 | $dbh->commit; | 
|---|
| 2142 | }; # end eval | 
|---|
| 2143 |  | 
|---|
| 2144 | if ($@) { | 
|---|
| 2145 | my $msg = $@; | 
|---|
| 2146 | eval { $dbh->rollback; }; | 
|---|
| 2147 | $self->_log(group_id => $group, entry => "Failed adding reverse zone $zone ($msg)") | 
|---|
| 2148 | if $self->{log_failures}; | 
|---|
| 2149 | $dbh->commit;       # since we enabled transactions earlier | 
|---|
| 2150 | return ('FAIL',$msg); | 
|---|
| 2151 | } else { | 
|---|
| 2152 | my $retcode = 'OK'; | 
|---|
| 2153 | if ($warnstr) { | 
|---|
| 2154 | $resultstr = $warnstr; | 
|---|
| 2155 | $retcode = 'WARN'; | 
|---|
| 2156 | } | 
|---|
| 2157 | return ($retcode, $rdns_id); | 
|---|
| 2158 | } | 
|---|
| 2159 |  | 
|---|
| 2160 | } # end addRDNS() | 
|---|
| 2161 |  | 
|---|
| 2162 |  | 
|---|
| 2163 | ## DNSDB::getZoneCount | 
|---|
| 2164 | # Get count of zones in group or groups | 
|---|
| 2165 | # Takes a database handle and hash containing: | 
|---|
| 2166 | #  - the "current" group | 
|---|
| 2167 | #  - an array of "acceptable" groups | 
|---|
| 2168 | #  - a flag for forward/reverse zones | 
|---|
| 2169 | #  - Optionally accept a "starts with" and/or "contains" filter argument | 
|---|
| 2170 | # Returns an integer count of the resulting zone list. | 
|---|
| 2171 | sub getZoneCount { | 
|---|
| 2172 | my $self = shift; | 
|---|
| 2173 | my $dbh = $self->{dbh}; | 
|---|
| 2174 |  | 
|---|
| 2175 | my %args = @_; | 
|---|
| 2176 |  | 
|---|
| 2177 | # Fail on bad curgroup argument.  There's no sane fallback on this one. | 
|---|
| 2178 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) { | 
|---|
| 2179 | $errstr = "Bad or missing curgroup argument"; | 
|---|
| 2180 | return; | 
|---|
| 2181 | } | 
|---|
| 2182 | # Fail on bad childlist argument.  This could be sanely ignored if bad, maybe. | 
|---|
| 2183 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) { | 
|---|
| 2184 | $errstr = "Bad childlist argument"; | 
|---|
| 2185 | return; | 
|---|
| 2186 | } | 
|---|
| 2187 |  | 
|---|
| 2188 | my @filterargs; | 
|---|
| 2189 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/; | 
|---|
| 2190 | push @filterargs, "^$args{startwith}" if $args{startwith}; | 
|---|
| 2191 | $args{filter} =~ s/\./\[\.\]/g if $args{filter};      # only match literal dots, usually in reverse zones | 
|---|
| 2192 | push @filterargs, $args{filter} if $args{filter}; | 
|---|
| 2193 |  | 
|---|
| 2194 | my $sql; | 
|---|
| 2195 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read | 
|---|
| 2196 | if ($args{revrec} eq 'n') { | 
|---|
| 2197 | $sql = "SELECT count(*) FROM domains". | 
|---|
| 2198 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")". | 
|---|
| 2199 | ($args{startwith} ? " AND domain ~* ?" : ''). | 
|---|
| 2200 | ($args{filter} ? " AND domain ~* ?" : ''); | 
|---|
| 2201 | } else { | 
|---|
| 2202 | $sql = "SELECT count(*) FROM revzones". | 
|---|
| 2203 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")". | 
|---|
| 2204 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : ''). | 
|---|
| 2205 | ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : ''); | 
|---|
| 2206 | } | 
|---|
| 2207 | my ($count) = $dbh->selectrow_array($sql, undef, @filterargs); | 
|---|
| 2208 | return $count; | 
|---|
| 2209 | } # end getZoneCount() | 
|---|
| 2210 |  | 
|---|
| 2211 |  | 
|---|
| 2212 | ## DNSDB::getZoneList() | 
|---|
| 2213 | # Get a list of zones in the specified group(s) | 
|---|
| 2214 | # Takes the same arguments as getZoneCount() above | 
|---|
| 2215 | # Returns a reference to an array of hashrefs suitable for feeding to HTML::Template | 
|---|
| 2216 | sub getZoneList { | 
|---|
| 2217 | my $self = shift; | 
|---|
| 2218 | my $dbh = $self->{dbh}; | 
|---|
| 2219 |  | 
|---|
| 2220 | my %args = @_; | 
|---|
| 2221 |  | 
|---|
| 2222 | my @zonelist; | 
|---|
| 2223 |  | 
|---|
| 2224 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC'); | 
|---|
| 2225 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/; | 
|---|
| 2226 |  | 
|---|
| 2227 | # Fail on bad curgroup argument.  There's no sane fallback on this one. | 
|---|
| 2228 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) { | 
|---|
| 2229 | $errstr = "Bad or missing curgroup argument"; | 
|---|
| 2230 | return; | 
|---|
| 2231 | } | 
|---|
| 2232 | # Fail on bad childlist argument.  This could be sanely ignored if bad, maybe. | 
|---|
| 2233 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) { | 
|---|
| 2234 | $errstr = "Bad childlist argument"; | 
|---|
| 2235 | return; | 
|---|
| 2236 | } | 
|---|
| 2237 |  | 
|---|
| 2238 | my @filterargs; | 
|---|
| 2239 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/; | 
|---|
| 2240 | push @filterargs, "^$args{startwith}" if $args{startwith}; | 
|---|
| 2241 | $args{filter} =~ s/\./\[\.\]/g if $args{filter};      # only match literal dots, usually in reverse zones | 
|---|
| 2242 | push @filterargs, $args{filter} if $args{filter}; | 
|---|
| 2243 |  | 
|---|
| 2244 | my $sql; | 
|---|
| 2245 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read | 
|---|
| 2246 | if ($args{revrec} eq 'n') { | 
|---|
| 2247 | $args{sortby} = 'domain' if !$args{sortby} || !grep /^$args{sortby}$/, ('domain','group','status'); | 
|---|
| 2248 | $sql = "SELECT domain_id,domain,status,groups.group_name AS group FROM domains". | 
|---|
| 2249 | " INNER JOIN groups ON domains.group_id=groups.group_id". | 
|---|
| 2250 | " WHERE domains.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")". | 
|---|
| 2251 | ($args{startwith} ? " AND domain ~* ?" : ''). | 
|---|
| 2252 | ($args{filter} ? " AND domain ~* ?" : ''); | 
|---|
| 2253 | } else { | 
|---|
| 2254 | ##fixme:  arguably startwith here is irrelevant.  depends on the UI though. | 
|---|
| 2255 | $args{sortby} = 'revnet' if !$args{sortby} || !grep /^$args{sortby}$/, ('revnet','group','status'); | 
|---|
| 2256 | $sql = "SELECT rdns_id,revnet,status,groups.group_name AS group FROM revzones". | 
|---|
| 2257 | " INNER JOIN groups ON revzones.group_id=groups.group_id". | 
|---|
| 2258 | " WHERE revzones.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")". | 
|---|
| 2259 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : ''). | 
|---|
| 2260 | ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : ''); | 
|---|
| 2261 | } | 
|---|
| 2262 | # A common tail. | 
|---|
| 2263 | $sql .= " ORDER BY ".($args{sortby} eq 'group' ? 'groups.group_name' : $args{sortby})." $args{sortorder} ". | 
|---|
| 2264 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage}". | 
|---|
| 2265 | " OFFSET ".$args{offset}*$self->{perpage}); | 
|---|
| 2266 | my $sth = $dbh->prepare($sql); | 
|---|
| 2267 | $sth->execute(@filterargs); | 
|---|
| 2268 | my $rownum = 0; | 
|---|
| 2269 |  | 
|---|
| 2270 | while (my @data = $sth->fetchrow_array) { | 
|---|
| 2271 | my %row; | 
|---|
| 2272 | $row{domain_id} = $data[0]; | 
|---|
| 2273 | $row{domain} = $data[1]; | 
|---|
| 2274 | $row{status} = $data[2]; | 
|---|
| 2275 | $row{group} = $data[3]; | 
|---|
| 2276 | push @zonelist, \%row; | 
|---|
| 2277 | } | 
|---|
| 2278 |  | 
|---|
| 2279 | return \@zonelist; | 
|---|
| 2280 | } # end getZoneList() | 
|---|
| 2281 |  | 
|---|
| 2282 |  | 
|---|
| 2283 | ## DNSDB::getZoneLocation() | 
|---|
| 2284 | # Retrieve the default location for a zone. | 
|---|
| 2285 | # Takes a database handle, forward/reverse flag, and zone ID | 
|---|
| 2286 | sub getZoneLocation { | 
|---|
| 2287 | my $self = shift; | 
|---|
| 2288 | my $dbh = $self->{dbh}; | 
|---|
| 2289 | my $revrec = shift; | 
|---|
| 2290 | my $zoneid = shift; | 
|---|
| 2291 |  | 
|---|
| 2292 | my ($loc) = $dbh->selectrow_array("SELECT default_location FROM ". | 
|---|
| 2293 | ($revrec eq 'n' ? 'domains WHERE domain_id = ?' : 'revzones WHERE rdns_id = ?'), | 
|---|
| 2294 | undef, ($zoneid)); | 
|---|
| 2295 | return $loc; | 
|---|
| 2296 | } # end getZoneLocation() | 
|---|
| 2297 |  | 
|---|
| 2298 |  | 
|---|
| 2299 | ## DNSDB::addGroup() | 
|---|
| 2300 | # Add a group | 
|---|
| 2301 | # Takes a database handle, group name, parent group, hashref for permissions, | 
|---|
| 2302 | # and optional template-vs-cloneme flag for the default records | 
|---|
| 2303 | # Returns a status code and message | 
|---|
| 2304 | sub addGroup { | 
|---|
| 2305 | $errstr = ''; | 
|---|
| 2306 | my $self = shift; | 
|---|
| 2307 | my $dbh = $self->{dbh}; | 
|---|
| 2308 | my $groupname = shift; | 
|---|
| 2309 | my $pargroup = shift; | 
|---|
| 2310 | my $permissions = shift; | 
|---|
| 2311 |  | 
|---|
| 2312 | # 0 indicates "custom", hardcoded. | 
|---|
| 2313 | # Any other value clones that group's default records, if it exists. | 
|---|
| 2314 | my $inherit = shift || 0; | 
|---|
| 2315 | ##fixme:  need a flag to indicate clone records or <?> ? | 
|---|
| 2316 |  | 
|---|
| 2317 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 2318 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 2319 | local $dbh->{AutoCommit} = 0; | 
|---|
| 2320 | local $dbh->{RaiseError} = 1; | 
|---|
| 2321 |  | 
|---|
| 2322 | my ($group_id) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($groupname)); | 
|---|
| 2323 |  | 
|---|
| 2324 | return ('FAIL', "Group already exists") if $group_id; | 
|---|
| 2325 |  | 
|---|
| 2326 | # Wrap all the SQL in a transaction | 
|---|
| 2327 | eval { | 
|---|
| 2328 | $dbh->do("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)", undef, ($pargroup, $groupname) ); | 
|---|
| 2329 |  | 
|---|
| 2330 | my ($groupid) = $dbh->selectrow_array("SELECT currval('groups_group_id_seq')"); | 
|---|
| 2331 |  | 
|---|
| 2332 | # We work through the whole set of permissions instead of specifying them so | 
|---|
| 2333 | # that when we add a new permission, we don't have to change the code anywhere | 
|---|
| 2334 | # that doesn't explicitly deal with that specific permission. | 
|---|
| 2335 | my @permvals; | 
|---|
| 2336 | foreach (@permtypes) { | 
|---|
| 2337 | if (!defined ($permissions->{$_})) { | 
|---|
| 2338 | push @permvals, 0; | 
|---|
| 2339 | } else { | 
|---|
| 2340 | push @permvals, $permissions->{$_}; | 
|---|
| 2341 | } | 
|---|
| 2342 | } | 
|---|
| 2343 | $dbh->do("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")", | 
|---|
| 2344 | undef, ($groupid, @permvals) ); | 
|---|
| 2345 | my ($permid) = $dbh->selectrow_array("SELECT currval('permissions_permission_id_seq')"); | 
|---|
| 2346 | $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid"); | 
|---|
| 2347 |  | 
|---|
| 2348 | # Default records | 
|---|
| 2349 | my $sthf = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ". | 
|---|
| 2350 | "VALUES ($groupid,?,?,?,?,?,?,?)"); | 
|---|
| 2351 | my $sthr = $dbh->prepare("INSERT INTO default_rev_records (group_id,host,type,val,ttl) ". | 
|---|
| 2352 | "VALUES ($groupid,?,?,?,?)"); | 
|---|
| 2353 | if ($inherit) { | 
|---|
| 2354 | # Duplicate records from parent.  Actually relying on inherited records feels | 
|---|
| 2355 | # very fragile, and it would be problematic to roll over at a later time. | 
|---|
| 2356 | my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?"); | 
|---|
| 2357 | $sth2->execute($pargroup); | 
|---|
| 2358 | while (my @clonedata = $sth2->fetchrow_array) { | 
|---|
| 2359 | $sthf->execute(@clonedata); | 
|---|
| 2360 | } | 
|---|
| 2361 | # And now the reverse records | 
|---|
| 2362 | $sth2 = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?"); | 
|---|
| 2363 | $sth2->execute($pargroup); | 
|---|
| 2364 | while (my @clonedata = $sth2->fetchrow_array) { | 
|---|
| 2365 | $sthr->execute(@clonedata); | 
|---|
| 2366 | } | 
|---|
| 2367 | } else { | 
|---|
| 2368 | ##fixme: Hardcoding is Bad, mmmmkaaaay? | 
|---|
| 2369 | # reasonable basic defaults for SOA, MX, NS, and minimal hosting | 
|---|
| 2370 | # could load from a config file, but somewhere along the line we need hardcoded bits. | 
|---|
| 2371 | $sthf->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400); | 
|---|
| 2372 | $sthf->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200); | 
|---|
| 2373 | $sthf->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200); | 
|---|
| 2374 | $sthf->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200); | 
|---|
| 2375 | $sthf->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200); | 
|---|
| 2376 | $sthf->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200); | 
|---|
| 2377 | # reasonable basic defaults for generic reverse zone.  Same as initial SQL tabledef. | 
|---|
| 2378 | $sthr->execute('hostmaster.ADMINDOMAIN:ns1.ADMINDOMAIN', 6, '10800:3600:604800:10800', 86400); | 
|---|
| 2379 | $sthr->execute('unused-%r.ADMINDOMAIN', 65283, 'ZONE', 3600); | 
|---|
| 2380 | } | 
|---|
| 2381 |  | 
|---|
| 2382 | $self->_log(group_id => $pargroup, entry => "Added group $groupname"); | 
|---|
| 2383 |  | 
|---|
| 2384 | # once we get here, we should have suceeded. | 
|---|
| 2385 | $dbh->commit; | 
|---|
| 2386 | }; # end eval | 
|---|
| 2387 |  | 
|---|
| 2388 | if ($@) { | 
|---|
| 2389 | my $msg = $@; | 
|---|
| 2390 | eval { $dbh->rollback; }; | 
|---|
| 2391 | if ($self->{log_failures}) { | 
|---|
| 2392 | $self->_log(group_id => $pargroup, entry => "Failed to add group $groupname: $msg"); | 
|---|
| 2393 | $dbh->commit; | 
|---|
| 2394 | } | 
|---|
| 2395 | return ('FAIL',$msg); | 
|---|
| 2396 | } | 
|---|
| 2397 |  | 
|---|
| 2398 | return ('OK','OK'); | 
|---|
| 2399 | } # end addGroup() | 
|---|
| 2400 |  | 
|---|
| 2401 |  | 
|---|
| 2402 | ## DNSDB::delGroup() | 
|---|
| 2403 | # Delete a group. | 
|---|
| 2404 | # Takes a group ID | 
|---|
| 2405 | # Returns a status code and message | 
|---|
| 2406 | sub delGroup { | 
|---|
| 2407 | my $self = shift; | 
|---|
| 2408 | my $dbh = $self->{dbh}; | 
|---|
| 2409 | my $groupid = shift; | 
|---|
| 2410 |  | 
|---|
| 2411 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 2412 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 2413 | local $dbh->{AutoCommit} = 0; | 
|---|
| 2414 | local $dbh->{RaiseError} = 1; | 
|---|
| 2415 |  | 
|---|
| 2416 | ##fixme:  locate "knowable" error conditions and deal with them before the eval | 
|---|
| 2417 | # ... or inside, whatever. | 
|---|
| 2418 | # -> domains still exist in group | 
|---|
| 2419 | # -> ... | 
|---|
| 2420 | my $failmsg = ''; | 
|---|
| 2421 | my $resultmsg = ''; | 
|---|
| 2422 |  | 
|---|
| 2423 | # collect some pieces for logging and error messages | 
|---|
| 2424 | my $groupname = $self->groupName($groupid); | 
|---|
| 2425 | my $parid = $self->parentID(id => $groupid, type => 'group'); | 
|---|
| 2426 |  | 
|---|
| 2427 | # Wrap all the SQL in a transaction | 
|---|
| 2428 | eval { | 
|---|
| 2429 | # Check for Things in the group | 
|---|
| 2430 | $failmsg = "Can't remove group $groupname"; | 
|---|
| 2431 | my ($grpcnt) = $dbh->selectrow_array("SELECT count(*) FROM groups WHERE parent_group_id=?", undef, ($groupid)); | 
|---|
| 2432 | die "$grpcnt groups still in group\n" if $grpcnt; | 
|---|
| 2433 | my ($domcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($groupid)); | 
|---|
| 2434 | die "$domcnt domains still in group\n" if $domcnt; | 
|---|
| 2435 | my ($revcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($groupid)); | 
|---|
| 2436 | die "$revcnt reverse zones still in group\n" if $revcnt; | 
|---|
| 2437 | my ($usercnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($groupid)); | 
|---|
| 2438 | die "$usercnt users still in group\n" if $usercnt; | 
|---|
| 2439 |  | 
|---|
| 2440 | $failmsg = "Failed to delete default records for $groupname"; | 
|---|
| 2441 | $dbh->do("DELETE from default_records WHERE group_id=?", undef, ($groupid)); | 
|---|
| 2442 | $failmsg = "Failed to delete default reverse records for $groupname"; | 
|---|
| 2443 | $dbh->do("DELETE from default_rev_records WHERE group_id=?", undef, ($groupid)); | 
|---|
| 2444 | $failmsg = "Failed to remove group $groupname"; | 
|---|
| 2445 | $dbh->do("DELETE from groups WHERE group_id=?", undef, ($groupid)); | 
|---|
| 2446 |  | 
|---|
| 2447 | $self->_log(group_id => $parid, entry => "Deleted group $groupname"); | 
|---|
| 2448 | $resultmsg = "Deleted group $groupname"; | 
|---|
| 2449 |  | 
|---|
| 2450 | # once we get here, we should have suceeded. | 
|---|
| 2451 | $dbh->commit; | 
|---|
| 2452 | }; # end eval | 
|---|
| 2453 |  | 
|---|
| 2454 | if ($@) { | 
|---|
| 2455 | my $msg = $@; | 
|---|
| 2456 | eval { $dbh->rollback; }; | 
|---|
| 2457 | if ($self->{log_failures}) { | 
|---|
| 2458 | $self->_log(group_id => $parid, entry => "$failmsg: $msg"); | 
|---|
| 2459 | $dbh->commit;     # since we enabled transactions earlier | 
|---|
| 2460 | } | 
|---|
| 2461 | return ('FAIL',"$failmsg: $msg"); | 
|---|
| 2462 | } | 
|---|
| 2463 |  | 
|---|
| 2464 | return ('OK',$resultmsg); | 
|---|
| 2465 | } # end delGroup() | 
|---|
| 2466 |  | 
|---|
| 2467 |  | 
|---|
| 2468 | ## DNSDB::getChildren() | 
|---|
| 2469 | # Get a list of all groups whose parent^n is group <n> | 
|---|
| 2470 | # Takes a database handle, group ID, reference to an array to put the group IDs in, | 
|---|
| 2471 | # and an optional flag to return only immediate children or all children-of-children | 
|---|
| 2472 | # default to returning all children | 
|---|
| 2473 | # Calls itself | 
|---|
| 2474 | sub getChildren { | 
|---|
| 2475 | $errstr = ''; | 
|---|
| 2476 | my $self = shift; | 
|---|
| 2477 | my $dbh = $self->{dbh}; | 
|---|
| 2478 | my $rootgroup = shift; | 
|---|
| 2479 | my $groupdest = shift; | 
|---|
| 2480 | my $immed = shift || 'all'; | 
|---|
| 2481 |  | 
|---|
| 2482 | # special break for default group;  otherwise we get stuck. | 
|---|
| 2483 | if ($rootgroup == 1) { | 
|---|
| 2484 | # by definition, group 1 is the Root Of All Groups | 
|---|
| 2485 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)". | 
|---|
| 2486 | ($immed ne 'all' ? " AND parent_group_id=1" : '')." ORDER BY group_name"); | 
|---|
| 2487 | $sth->execute; | 
|---|
| 2488 | while (my @this = $sth->fetchrow_array) { | 
|---|
| 2489 | push @$groupdest, @this; | 
|---|
| 2490 | } | 
|---|
| 2491 | } else { | 
|---|
| 2492 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=? ORDER BY group_name"); | 
|---|
| 2493 | $sth->execute($rootgroup); | 
|---|
| 2494 | return if $sth->rows == 0; | 
|---|
| 2495 | my @grouplist; | 
|---|
| 2496 | while (my ($group) = $sth->fetchrow_array) { | 
|---|
| 2497 | push @$groupdest, $group; | 
|---|
| 2498 | $self->getChildren($group, $groupdest) if $immed eq 'all'; | 
|---|
| 2499 | } | 
|---|
| 2500 | } | 
|---|
| 2501 | } # end getChildren() | 
|---|
| 2502 |  | 
|---|
| 2503 |  | 
|---|
| 2504 | ## DNSDB::groupName() | 
|---|
| 2505 | # Return the group name based on a group ID | 
|---|
| 2506 | # Takes a database handle and the group ID | 
|---|
| 2507 | # Returns the group name or undef on failure | 
|---|
| 2508 | sub groupName { | 
|---|
| 2509 | $errstr = ''; | 
|---|
| 2510 | my $self = shift; | 
|---|
| 2511 | my $dbh = $self->{dbh}; | 
|---|
| 2512 | my $groupid = shift; | 
|---|
| 2513 | my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?"); | 
|---|
| 2514 | $sth->execute($groupid); | 
|---|
| 2515 | my ($groupname) = $sth->fetchrow_array(); | 
|---|
| 2516 | $errstr = $DBI::errstr if !$groupname; | 
|---|
| 2517 | return $groupname if $groupname; | 
|---|
| 2518 | } # end groupName | 
|---|
| 2519 |  | 
|---|
| 2520 |  | 
|---|
| 2521 | ## DNSDB::getGroupCount() | 
|---|
| 2522 | # Get count of subgroups in group or groups | 
|---|
| 2523 | # Takes a database handle and hash containing: | 
|---|
| 2524 | #  - the "current" group | 
|---|
| 2525 | #  - an array of "acceptable" groups | 
|---|
| 2526 | #  - Optionally accept a "starts with" and/or "contains" filter argument | 
|---|
| 2527 | # Returns an integer count of the resulting group list. | 
|---|
| 2528 | sub getGroupCount { | 
|---|
| 2529 | my $self = shift; | 
|---|
| 2530 | my $dbh = $self->{dbh}; | 
|---|
| 2531 |  | 
|---|
| 2532 | my %args = @_; | 
|---|
| 2533 |  | 
|---|
| 2534 | # Fail on bad curgroup argument.  There's no sane fallback on this one. | 
|---|
| 2535 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) { | 
|---|
| 2536 | $errstr = "Bad or missing curgroup argument"; | 
|---|
| 2537 | return; | 
|---|
| 2538 | } | 
|---|
| 2539 | # Fail on bad childlist argument.  This could be sanely ignored if bad, maybe. | 
|---|
| 2540 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) { | 
|---|
| 2541 | $errstr = "Bad childlist argument"; | 
|---|
| 2542 | return; | 
|---|
| 2543 | } | 
|---|
| 2544 |  | 
|---|
| 2545 | my @filterargs; | 
|---|
| 2546 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/; | 
|---|
| 2547 | push @filterargs, "^$args{startwith}" if $args{startwith}; | 
|---|
| 2548 | push @filterargs, $args{filter} if $args{filter}; | 
|---|
| 2549 |  | 
|---|
| 2550 | my $sql = "SELECT count(*) FROM groups ". | 
|---|
| 2551 | "WHERE parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")". | 
|---|
| 2552 | ($args{startwith} ? " AND group_name ~* ?" : ''). | 
|---|
| 2553 | ($args{filter} ? " AND group_name ~* ?" : ''); | 
|---|
| 2554 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) ); | 
|---|
| 2555 | $errstr = $dbh->errstr if !$count; | 
|---|
| 2556 | return $count; | 
|---|
| 2557 | } # end getGroupCount | 
|---|
| 2558 |  | 
|---|
| 2559 |  | 
|---|
| 2560 | ## DNSDB::getGroupList() | 
|---|
| 2561 | # Get a list of sub^n-groups in the specified group(s) | 
|---|
| 2562 | # Takes the same arguments as getGroupCount() above | 
|---|
| 2563 | # Returns an arrayref containing hashrefs suitable for feeding straight to HTML::Template | 
|---|
| 2564 | sub getGroupList { | 
|---|
| 2565 | my $self = shift; | 
|---|
| 2566 | my $dbh = $self->{dbh}; | 
|---|
| 2567 |  | 
|---|
| 2568 | my %args = @_; | 
|---|
| 2569 |  | 
|---|
| 2570 | # Fail on bad curgroup argument.  There's no sane fallback on this one. | 
|---|
| 2571 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) { | 
|---|
| 2572 | $errstr = "Bad or missing curgroup argument"; | 
|---|
| 2573 | return; | 
|---|
| 2574 | } | 
|---|
| 2575 | # Fail on bad childlist argument.  This could be sanely ignored if bad, maybe. | 
|---|
| 2576 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) { | 
|---|
| 2577 | $errstr = "Bad childlist argument"; | 
|---|
| 2578 | return; | 
|---|
| 2579 | } | 
|---|
| 2580 |  | 
|---|
| 2581 | my @filterargs; | 
|---|
| 2582 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/; | 
|---|
| 2583 | push @filterargs, "^$args{startwith}" if $args{startwith}; | 
|---|
| 2584 | push @filterargs, $args{filter} if $args{filter}; | 
|---|
| 2585 |  | 
|---|
| 2586 | # protection against bad or missing arguments | 
|---|
| 2587 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC'); | 
|---|
| 2588 | $args{sortby} = 'group' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/; | 
|---|
| 2589 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/; | 
|---|
| 2590 |  | 
|---|
| 2591 | # munge sortby for columns in database | 
|---|
| 2592 | $args{sortby} = 'g.group_name' if $args{sortby} eq 'group'; | 
|---|
| 2593 | $args{sortby} = 'g2.group_name' if $args{sortby} eq 'parent'; | 
|---|
| 2594 |  | 
|---|
| 2595 | my $sql = q(SELECT g.group_id AS groupid, g.group_name AS groupname, g2.group_name AS pgroup | 
|---|
| 2596 | FROM groups g | 
|---|
| 2597 | INNER JOIN groups g2 ON g2.group_id=g.parent_group_id | 
|---|
| 2598 | ). | 
|---|
| 2599 | " WHERE g.parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")". | 
|---|
| 2600 | ($args{startwith} ? " AND g.group_name ~* ?" : ''). | 
|---|
| 2601 | ($args{filter} ? " AND g.group_name ~* ?" : ''). | 
|---|
| 2602 | " GROUP BY g.group_id, g.group_name, g2.group_name ". | 
|---|
| 2603 | " ORDER BY $args{sortby} $args{sortorder} ". | 
|---|
| 2604 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage}); | 
|---|
| 2605 | my $glist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) ); | 
|---|
| 2606 | $errstr = $dbh->errstr if !$glist; | 
|---|
| 2607 |  | 
|---|
| 2608 | # LEFT JOINs make the result set balloon beyond sanity just to include counts; | 
|---|
| 2609 | # this means there's lots of crunching needed to trim the result set back down. | 
|---|
| 2610 | # So instead we track the order of the groups, and push the counts into the | 
|---|
| 2611 | # arrayref result separately. | 
|---|
| 2612 | ##fixme:  put this whole sub in a transaction?  might be | 
|---|
| 2613 | # needed for accurate results on very busy systems. | 
|---|
| 2614 | ##fixme:  large group lists need prepared statements? | 
|---|
| 2615 | #my $ucsth = $dbh->prepare("SELECT count(*) FROM users WHERE group_id=?"); | 
|---|
| 2616 | #my $dcsth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?"); | 
|---|
| 2617 | #my $rcsth = $dbh->prepare("SELECT count(*) FROM revzones WHERE group_id=?"); | 
|---|
| 2618 | foreach (@{$glist}) { | 
|---|
| 2619 | my ($ucnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($$_{groupid})); | 
|---|
| 2620 | $$_{nusers} = $ucnt; | 
|---|
| 2621 | my ($dcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($$_{groupid})); | 
|---|
| 2622 | $$_{ndomains} = $dcnt; | 
|---|
| 2623 | my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($$_{groupid})); | 
|---|
| 2624 | $$_{nrevzones} = $rcnt; | 
|---|
| 2625 | } | 
|---|
| 2626 |  | 
|---|
| 2627 | return $glist; | 
|---|
| 2628 | } # end getGroupList | 
|---|
| 2629 |  | 
|---|
| 2630 |  | 
|---|
| 2631 | ## DNSDB::groupID() | 
|---|
| 2632 | # Return the group ID based on the group name | 
|---|
| 2633 | # Takes a database handle and the group name | 
|---|
| 2634 | # Returns the group ID or undef on failure | 
|---|
| 2635 | sub groupID { | 
|---|
| 2636 | $errstr = ''; | 
|---|
| 2637 | my $self = shift; | 
|---|
| 2638 | my $dbh = $self->{dbh}; | 
|---|
| 2639 | my $group = shift; | 
|---|
| 2640 | my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($group) ); | 
|---|
| 2641 | $errstr = $DBI::errstr if !$grpid; | 
|---|
| 2642 | return $grpid if $grpid; | 
|---|
| 2643 | } # end groupID() | 
|---|
| 2644 |  | 
|---|
| 2645 |  | 
|---|
| 2646 | ## DNSDB::addUser() | 
|---|
| 2647 | # Add a user. | 
|---|
| 2648 | # Takes a DB handle, username, group ID, password, state (active/inactive). | 
|---|
| 2649 | # Optionally accepts: | 
|---|
| 2650 | #   user type (user/admin)      - defaults to user | 
|---|
| 2651 | #   permissions string          - defaults to inherit from group | 
|---|
| 2652 | #      three valid forms: | 
|---|
| 2653 | #       i                    - Inherit permissions | 
|---|
| 2654 | #       c:<user_id>          - Clone permissions from <user_id> | 
|---|
| 2655 | #       C:<permission list>  - Set these specific permissions | 
|---|
| 2656 | #   first name                  - defaults to username | 
|---|
| 2657 | #   last name                   - defaults to blank | 
|---|
| 2658 | #   phone                       - defaults to blank (could put other data within column def) | 
|---|
| 2659 | # Returns (OK,<uid>) on success, (FAIL,<message>) on failure | 
|---|
| 2660 | sub addUser { | 
|---|
| 2661 | $errstr = ''; | 
|---|
| 2662 | my $self = shift; | 
|---|
| 2663 | my $dbh = $self->{dbh}; | 
|---|
| 2664 | my $username = shift; | 
|---|
| 2665 | my $group = shift; | 
|---|
| 2666 | my $pass = shift; | 
|---|
| 2667 | my $state = shift; | 
|---|
| 2668 |  | 
|---|
| 2669 | return ('FAIL', "Missing one or more required entries") if !defined($state); | 
|---|
| 2670 | return ('FAIL', "Username must not be blank") if !$username; | 
|---|
| 2671 |  | 
|---|
| 2672 | # Munge in some alternate state values | 
|---|
| 2673 | $state = 1 if $state =~ /^active$/; | 
|---|
| 2674 | $state = 1 if $state =~ /^on$/; | 
|---|
| 2675 | $state = 0 if $state =~ /^inactive$/; | 
|---|
| 2676 | $state = 0 if $state =~ /^off$/; | 
|---|
| 2677 |  | 
|---|
| 2678 | my $type = shift || 'u';      # create limited users by default - fwiw, not sure yet how this will interact with ACLs | 
|---|
| 2679 |  | 
|---|
| 2680 | my $permstring = shift || 'i';        # default is to inhert permissions from group | 
|---|
| 2681 |  | 
|---|
| 2682 | my $fname = shift || $username; | 
|---|
| 2683 | my $lname = shift || ''; | 
|---|
| 2684 | my $phone = shift || '';      # not going format-check | 
|---|
| 2685 |  | 
|---|
| 2686 | my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?"); | 
|---|
| 2687 | my $user_id; | 
|---|
| 2688 |  | 
|---|
| 2689 | # quick check to start to see if we've already got one | 
|---|
| 2690 | $sth->execute($username); | 
|---|
| 2691 | ($user_id) = $sth->fetchrow_array; | 
|---|
| 2692 |  | 
|---|
| 2693 | return ('FAIL', "User already exists") if $user_id; | 
|---|
| 2694 |  | 
|---|
| 2695 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 2696 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 2697 | local $dbh->{AutoCommit} = 0; | 
|---|
| 2698 | local $dbh->{RaiseError} = 1; | 
|---|
| 2699 |  | 
|---|
| 2700 | # Wrap all the SQL in a transaction | 
|---|
| 2701 | eval { | 
|---|
| 2702 | # insert the user...  note we set inherited perms by default since | 
|---|
| 2703 | # it's simple and cleans up some other bits of state | 
|---|
| 2704 | my $sth = $dbh->prepare("INSERT INTO users ". | 
|---|
| 2705 | "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ". | 
|---|
| 2706 | "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')"); | 
|---|
| 2707 | $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group); | 
|---|
| 2708 |  | 
|---|
| 2709 | # get the ID... | 
|---|
| 2710 | ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')"); | 
|---|
| 2711 |  | 
|---|
| 2712 | # Permissions!  Gotta set'em all! | 
|---|
| 2713 | die "Invalid permission string $permstring\n" | 
|---|
| 2714 | if $permstring !~ /^(?: | 
|---|
| 2715 | i       # inherit | 
|---|
| 2716 | |c:\d+  # clone | 
|---|
| 2717 | # custom.  no, the leading , is not a typo | 
|---|
| 2718 | |C:(?:,(?:group|user|domain|record|location|self)_(?:edit|create|delete|locchg|view))* | 
|---|
| 2719 | )$/x; | 
|---|
| 2720 | # bleh.  I'd call another function to do my dirty work, but we're in the middle of a transaction already. | 
|---|
| 2721 | if ($permstring ne 'i') { | 
|---|
| 2722 | # for cloned or custom permissions, we have to create a new permissions entry. | 
|---|
| 2723 | my $clonesrc = $group; | 
|---|
| 2724 | if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; } | 
|---|
| 2725 | $dbh->do("INSERT INTO permissions ($permlist,user_id) ". | 
|---|
| 2726 | "SELECT $permlist,? FROM permissions WHERE permission_id=". | 
|---|
| 2727 | "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)", | 
|---|
| 2728 | undef, ($user_id,$clonesrc) ); | 
|---|
| 2729 | $dbh->do("UPDATE users SET permission_id=". | 
|---|
| 2730 | "(SELECT permission_id FROM permissions WHERE user_id=?) ". | 
|---|
| 2731 | "WHERE user_id=?", undef, ($user_id, $user_id) ); | 
|---|
| 2732 | } | 
|---|
| 2733 | if ($permstring =~ /^C:/) { | 
|---|
| 2734 | # finally for custom permissions, we set the passed-in permissions (and unset | 
|---|
| 2735 | # any that might have been brought in by the clone operation above) | 
|---|
| 2736 | my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?", | 
|---|
| 2737 | undef, ($user_id) ); | 
|---|
| 2738 | foreach (@permtypes) { | 
|---|
| 2739 | if ($permstring =~ /,$_/) { | 
|---|
| 2740 | $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) ); | 
|---|
| 2741 | } else { | 
|---|
| 2742 | $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) ); | 
|---|
| 2743 | } | 
|---|
| 2744 | } | 
|---|
| 2745 | } | 
|---|
| 2746 |  | 
|---|
| 2747 | $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) ); | 
|---|
| 2748 |  | 
|---|
| 2749 | ##fixme: add another table to hold name/email for log table? | 
|---|
| 2750 |  | 
|---|
| 2751 | $self->_log(group_id => $group, entry => "Added user $username ($fname $lname)"); | 
|---|
| 2752 | # once we get here, we should have suceeded. | 
|---|
| 2753 | $dbh->commit; | 
|---|
| 2754 | }; # end eval | 
|---|
| 2755 |  | 
|---|
| 2756 | if ($@) { | 
|---|
| 2757 | my $msg = $@; | 
|---|
| 2758 | eval { $dbh->rollback; }; | 
|---|
| 2759 | if ($self->{log_failures}) { | 
|---|
| 2760 | $self->_log(group_id => $group, entry => "Error adding user $username: $msg"); | 
|---|
| 2761 | $dbh->commit;     # since we enabled transactions earlier | 
|---|
| 2762 | } | 
|---|
| 2763 | return ('FAIL',"Error adding user $username: $msg"); | 
|---|
| 2764 | } | 
|---|
| 2765 |  | 
|---|
| 2766 | return ('OK',"User $username ($fname $lname) added"); | 
|---|
| 2767 | } # end addUser | 
|---|
| 2768 |  | 
|---|
| 2769 |  | 
|---|
| 2770 | ## DNSDB::getUserCount() | 
|---|
| 2771 | # Get count of users in group | 
|---|
| 2772 | # Takes a database handle and hash containing at least the current group, and optionally: | 
|---|
| 2773 | # - a reference list of secondary groups | 
|---|
| 2774 | # - a filter string | 
|---|
| 2775 | # - a "Starts with" string | 
|---|
| 2776 | sub getUserCount { | 
|---|
| 2777 | my $self = shift; | 
|---|
| 2778 | my $dbh = $self->{dbh}; | 
|---|
| 2779 |  | 
|---|
| 2780 | my %args = @_; | 
|---|
| 2781 |  | 
|---|
| 2782 | # Fail on bad curgroup argument.  There's no sane fallback on this one. | 
|---|
| 2783 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) { | 
|---|
| 2784 | $errstr = "Bad or missing curgroup argument"; | 
|---|
| 2785 | return; | 
|---|
| 2786 | } | 
|---|
| 2787 | # Fail on bad childlist argument.  This could be sanely ignored if bad, maybe. | 
|---|
| 2788 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) { | 
|---|
| 2789 | $errstr = "Bad childlist argument"; | 
|---|
| 2790 | return; | 
|---|
| 2791 | } | 
|---|
| 2792 |  | 
|---|
| 2793 | my @filterargs; | 
|---|
| 2794 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/; | 
|---|
| 2795 | push @filterargs, "^$args{startwith}" if $args{startwith}; | 
|---|
| 2796 | push @filterargs, $args{filter} if $args{filter}; | 
|---|
| 2797 |  | 
|---|
| 2798 | my $sql = "SELECT count(*) FROM users ". | 
|---|
| 2799 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")". | 
|---|
| 2800 | ($args{startwith} ? " AND username ~* ?" : ''). | 
|---|
| 2801 | ($args{filter} ? " AND username ~* ?" : ''); | 
|---|
| 2802 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) ); | 
|---|
| 2803 | $errstr = $dbh->errstr if !$count; | 
|---|
| 2804 | return $count; | 
|---|
| 2805 | } # end getUserCount() | 
|---|
| 2806 |  | 
|---|
| 2807 |  | 
|---|
| 2808 | ## DNSDB::getUserList() | 
|---|
| 2809 | # Get list of users | 
|---|
| 2810 | # Takes the same arguments as getUserCount() above, plus optional: | 
|---|
| 2811 | # - sort field | 
|---|
| 2812 | # - sort order | 
|---|
| 2813 | # - offset/return-all-everything flag (defaults to $perpage records) | 
|---|
| 2814 | sub getUserList { | 
|---|
| 2815 | my $self = shift; | 
|---|
| 2816 | my $dbh = $self->{dbh}; | 
|---|
| 2817 |  | 
|---|
| 2818 | my %args = @_; | 
|---|
| 2819 |  | 
|---|
| 2820 | # Fail on bad curgroup argument.  There's no sane fallback on this one. | 
|---|
| 2821 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) { | 
|---|
| 2822 | $errstr = "Bad or missing curgroup argument"; | 
|---|
| 2823 | return; | 
|---|
| 2824 | } | 
|---|
| 2825 | # Fail on bad childlist argument.  This could be sanely ignored if bad, maybe. | 
|---|
| 2826 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) { | 
|---|
| 2827 | $errstr = "Bad childlist argument"; | 
|---|
| 2828 | return; | 
|---|
| 2829 | } | 
|---|
| 2830 |  | 
|---|
| 2831 | my @filterargs; | 
|---|
| 2832 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/; | 
|---|
| 2833 | push @filterargs, "^$args{startwith}" if $args{startwith}; | 
|---|
| 2834 | push @filterargs, $args{filter} if $args{filter}; | 
|---|
| 2835 |  | 
|---|
| 2836 | # better to request sorts on "simple" names, but it means we need to map it to real columns | 
|---|
| 2837 | my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status', | 
|---|
| 2838 | fname => 'fname'); | 
|---|
| 2839 | $args{sortby} = $sortmap{$args{sortby}}; | 
|---|
| 2840 |  | 
|---|
| 2841 | # protection against bad or missing arguments | 
|---|
| 2842 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC'); | 
|---|
| 2843 | $args{sortby} = 'u.username' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/; | 
|---|
| 2844 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/; | 
|---|
| 2845 |  | 
|---|
| 2846 | my $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ". | 
|---|
| 2847 | "FROM users u ". | 
|---|
| 2848 | "INNER JOIN groups g ON u.group_id=g.group_id ". | 
|---|
| 2849 | "WHERE u.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")". | 
|---|
| 2850 | ($args{startwith} ? " AND u.username ~* ?" : ''). | 
|---|
| 2851 | ($args{filter} ? " AND u.username ~* ?" : ''). | 
|---|
| 2852 | " AND NOT u.type = 'R' ". | 
|---|
| 2853 | " ORDER BY $args{sortby} $args{sortorder} ". | 
|---|
| 2854 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage}); | 
|---|
| 2855 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) ); | 
|---|
| 2856 | $errstr = $dbh->errstr if !$ulist; | 
|---|
| 2857 | return $ulist; | 
|---|
| 2858 | } # end getUserList() | 
|---|
| 2859 |  | 
|---|
| 2860 |  | 
|---|
| 2861 | ## DNSDB::getUserDropdown() | 
|---|
| 2862 | # Get a list of usernames for use in a dropdown menu. | 
|---|
| 2863 | # Takes a database handle, current group, and optional "tag this as selected" flag. | 
|---|
| 2864 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template | 
|---|
| 2865 | sub getUserDropdown { | 
|---|
| 2866 | my $self = shift; | 
|---|
| 2867 | my $dbh = $self->{dbh}; | 
|---|
| 2868 | my $grp = shift; | 
|---|
| 2869 | my $sel = shift || 0; | 
|---|
| 2870 |  | 
|---|
| 2871 | my $sth = $dbh->prepare("SELECT username,user_id FROM users WHERE group_id=?"); | 
|---|
| 2872 | $sth->execute($grp); | 
|---|
| 2873 |  | 
|---|
| 2874 | my @userlist; | 
|---|
| 2875 | while (my ($username,$uid) = $sth->fetchrow_array) { | 
|---|
| 2876 | my %row = ( | 
|---|
| 2877 | username => $username, | 
|---|
| 2878 | uid => $uid, | 
|---|
| 2879 | selected => ($sel == $uid ? 1 : 0) | 
|---|
| 2880 | ); | 
|---|
| 2881 | push @userlist, \%row; | 
|---|
| 2882 | } | 
|---|
| 2883 | return \@userlist; | 
|---|
| 2884 | } # end getUserDropdown() | 
|---|
| 2885 |  | 
|---|
| 2886 |  | 
|---|
| 2887 | ## DNSDB:: updateUser() | 
|---|
| 2888 | # Update general data about user | 
|---|
| 2889 | sub updateUser { | 
|---|
| 2890 | my $self = shift; | 
|---|
| 2891 | my $dbh = $self->{dbh}; | 
|---|
| 2892 |  | 
|---|
| 2893 | ##fixme:  tweak calling convention so that we can update any given bit of data | 
|---|
| 2894 | my $uid = shift; | 
|---|
| 2895 | my $username = shift; | 
|---|
| 2896 | my $group = shift; | 
|---|
| 2897 | my $pass = shift; | 
|---|
| 2898 | my $state = shift; | 
|---|
| 2899 | my $type = shift || 'u'; | 
|---|
| 2900 | my $fname = shift || $username; | 
|---|
| 2901 | my $lname = shift || ''; | 
|---|
| 2902 | my $phone = shift || '';      # not going format-check | 
|---|
| 2903 |  | 
|---|
| 2904 | my $resultmsg = ''; | 
|---|
| 2905 |  | 
|---|
| 2906 | # Munge in some alternate state values | 
|---|
| 2907 | $state = 1 if $state =~ /^active$/; | 
|---|
| 2908 | $state = 1 if $state =~ /^on$/; | 
|---|
| 2909 | $state = 0 if $state =~ /^inactive$/; | 
|---|
| 2910 | $state = 0 if $state =~ /^off$/; | 
|---|
| 2911 |  | 
|---|
| 2912 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 2913 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 2914 | local $dbh->{AutoCommit} = 0; | 
|---|
| 2915 | local $dbh->{RaiseError} = 1; | 
|---|
| 2916 |  | 
|---|
| 2917 | my $sth; | 
|---|
| 2918 |  | 
|---|
| 2919 | # Password can be left blank;  if so we assume there's one on file. | 
|---|
| 2920 | # Actual blank passwords are bad, mm'kay? | 
|---|
| 2921 | if (!$pass) { | 
|---|
| 2922 | ($pass) = $dbh->selectrow_array("SELECT password FROM users WHERE user_id=?", undef, ($uid)); | 
|---|
| 2923 | } else { | 
|---|
| 2924 | $pass = unix_md5_crypt($pass); | 
|---|
| 2925 | } | 
|---|
| 2926 |  | 
|---|
| 2927 | eval { | 
|---|
| 2928 | $dbh->do("UPDATE users SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?". | 
|---|
| 2929 | " WHERE user_id=?", undef, ($username, $pass, $fname, $lname, $phone, $type, $state, $uid)); | 
|---|
| 2930 | $resultmsg = "Updated user info for $username ($fname $lname)"; | 
|---|
| 2931 | $self->_log(group_id => $group, entry => $resultmsg); | 
|---|
| 2932 | $dbh->commit; | 
|---|
| 2933 | }; | 
|---|
| 2934 | if ($@) { | 
|---|
| 2935 | my $msg = $@; | 
|---|
| 2936 | eval { $dbh->rollback; }; | 
|---|
| 2937 | if ($self->{log_failures}) { | 
|---|
| 2938 | $self->_log(group_id => $group, entry => "Error updating user $username: $msg"); | 
|---|
| 2939 | $dbh->commit;     # since we enabled transactions earlier | 
|---|
| 2940 | } | 
|---|
| 2941 | return ('FAIL',"Error updating user $username: $msg"); | 
|---|
| 2942 | } | 
|---|
| 2943 |  | 
|---|
| 2944 | return ('OK',$resultmsg); | 
|---|
| 2945 | } # end updateUser() | 
|---|
| 2946 |  | 
|---|
| 2947 |  | 
|---|
| 2948 | ## DNSDB::delUser() | 
|---|
| 2949 | # Delete a user. | 
|---|
| 2950 | # Takes a database handle and user ID | 
|---|
| 2951 | # Returns a success/failure code and matching message | 
|---|
| 2952 | sub delUser { | 
|---|
| 2953 | my $self = shift; | 
|---|
| 2954 | my $dbh = $self->{dbh}; | 
|---|
| 2955 | my $userid = shift; | 
|---|
| 2956 |  | 
|---|
| 2957 | return ('FAIL',"Bad userid") if !defined($userid); | 
|---|
| 2958 |  | 
|---|
| 2959 | my $userdata = $self->getUserData($userid); | 
|---|
| 2960 |  | 
|---|
| 2961 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 2962 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 2963 | local $dbh->{AutoCommit} = 0; | 
|---|
| 2964 | local $dbh->{RaiseError} = 1; | 
|---|
| 2965 |  | 
|---|
| 2966 | eval { | 
|---|
| 2967 | $dbh->do("DELETE FROM users WHERE user_id=?", undef, ($userid)); | 
|---|
| 2968 | $self->_log(group_id => $userdata->{group_id}, | 
|---|
| 2969 | entry => "Deleted user ID $userid/".$userdata->{username}. | 
|---|
| 2970 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")"); | 
|---|
| 2971 | $dbh->commit; | 
|---|
| 2972 | }; | 
|---|
| 2973 | if ($@) { | 
|---|
| 2974 | my $msg = $@; | 
|---|
| 2975 | eval { $dbh->rollback; }; | 
|---|
| 2976 | if ($self->{log_failures}) { | 
|---|
| 2977 | $self->_log(group_id => $userdata->{group_id}, entry => "Error deleting user ID ". | 
|---|
| 2978 | "$userid/".$userdata->{username}.": $msg"); | 
|---|
| 2979 | $dbh->commit; | 
|---|
| 2980 | } | 
|---|
| 2981 | return ('FAIL',"Error deleting user $userid/".$userdata->{username}.": $msg"); | 
|---|
| 2982 | } | 
|---|
| 2983 |  | 
|---|
| 2984 | return ('OK',"Deleted user ".$userdata->{username}." (".$userdata->{firstname}." ".$userdata->{lastname}.")"); | 
|---|
| 2985 | } # end delUser | 
|---|
| 2986 |  | 
|---|
| 2987 |  | 
|---|
| 2988 | ## DNSDB::userFullName() | 
|---|
| 2989 | # Return a pretty string! | 
|---|
| 2990 | # Takes a user_id and optional printf-ish string to indicate which pieces where: | 
|---|
| 2991 | # %u for the username | 
|---|
| 2992 | # %f for the first name | 
|---|
| 2993 | # %l for the last name | 
|---|
| 2994 | # All other text in the passed string will be left as-is. | 
|---|
| 2995 | ##fixme:  need a "smart" option too, so that missing/null/blank first/last names don't give funky output | 
|---|
| 2996 | sub userFullName { | 
|---|
| 2997 | $errstr = ''; | 
|---|
| 2998 | my $self = shift; | 
|---|
| 2999 | my $dbh = $self->{dbh}; | 
|---|
| 3000 | my $userid = shift; | 
|---|
| 3001 | my $fullformat = shift || '%f %l (%u)'; | 
|---|
| 3002 | my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?"); | 
|---|
| 3003 | $sth->execute($userid); | 
|---|
| 3004 | my ($uname,$fname,$lname) = $sth->fetchrow_array(); | 
|---|
| 3005 | $errstr = $DBI::errstr if !$uname; | 
|---|
| 3006 |  | 
|---|
| 3007 | $fullformat =~ s/\%u/$uname/g; | 
|---|
| 3008 | $fullformat =~ s/\%f/$fname/g; | 
|---|
| 3009 | $fullformat =~ s/\%l/$lname/g; | 
|---|
| 3010 |  | 
|---|
| 3011 | return $fullformat; | 
|---|
| 3012 | } # end userFullName | 
|---|
| 3013 |  | 
|---|
| 3014 |  | 
|---|
| 3015 | ## DNSDB::userStatus() | 
|---|
| 3016 | # Sets and/or returns a user's status | 
|---|
| 3017 | # Takes a database handle, user ID and optionally a status argument | 
|---|
| 3018 | # Returns undef on errors. | 
|---|
| 3019 | sub userStatus { | 
|---|
| 3020 | my $self = shift; | 
|---|
| 3021 | my $dbh = $self->{dbh}; | 
|---|
| 3022 | my $id = shift; | 
|---|
| 3023 | my $newstatus = shift || 'mu'; | 
|---|
| 3024 |  | 
|---|
| 3025 | return undef if $id !~ /^\d+$/; | 
|---|
| 3026 |  | 
|---|
| 3027 | my $userdata = $self->getUserData($id); | 
|---|
| 3028 |  | 
|---|
| 3029 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 3030 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 3031 | local $dbh->{AutoCommit} = 0; | 
|---|
| 3032 | local $dbh->{RaiseError} = 1; | 
|---|
| 3033 |  | 
|---|
| 3034 | if ($newstatus ne 'mu') { | 
|---|
| 3035 | # ooo, fun!  let's see what we were passed for status | 
|---|
| 3036 | eval { | 
|---|
| 3037 | $newstatus = 0 if $newstatus eq 'useroff'; | 
|---|
| 3038 | $newstatus = 1 if $newstatus eq 'useron'; | 
|---|
| 3039 | $dbh->do("UPDATE users SET status=? WHERE user_id=?", undef, ($newstatus, $id)); | 
|---|
| 3040 |  | 
|---|
| 3041 | $resultstr = ($newstatus ? 'Enabled' : 'Disabled')." user ".$userdata->{username}. | 
|---|
| 3042 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")"; | 
|---|
| 3043 |  | 
|---|
| 3044 | my %loghash; | 
|---|
| 3045 | $loghash{group_id} = $self->parentID(id => $id, type => 'user'); | 
|---|
| 3046 | $loghash{entry} = $resultstr; | 
|---|
| 3047 | $self->_log(%loghash); | 
|---|
| 3048 |  | 
|---|
| 3049 | $dbh->commit; | 
|---|
| 3050 | }; | 
|---|
| 3051 | if ($@) { | 
|---|
| 3052 | my $msg = $@; | 
|---|
| 3053 | eval { $dbh->rollback; }; | 
|---|
| 3054 | $resultstr = ''; | 
|---|
| 3055 | $errstr = $msg; | 
|---|
| 3056 | ##fixme: failure logging? | 
|---|
| 3057 | return; | 
|---|
| 3058 | } | 
|---|
| 3059 | } | 
|---|
| 3060 |  | 
|---|
| 3061 | my ($status) = $dbh->selectrow_array("SELECT status FROM users WHERE user_id=?", undef, ($id)); | 
|---|
| 3062 | return $status; | 
|---|
| 3063 | } # end userStatus() | 
|---|
| 3064 |  | 
|---|
| 3065 |  | 
|---|
| 3066 | ## DNSDB::getUserData() | 
|---|
| 3067 | # Get misc user data for display | 
|---|
| 3068 | sub getUserData { | 
|---|
| 3069 | my $self = shift; | 
|---|
| 3070 | my $dbh = $self->{dbh}; | 
|---|
| 3071 | my $uid = shift; | 
|---|
| 3072 |  | 
|---|
| 3073 | my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ". | 
|---|
| 3074 | "FROM users WHERE user_id=?"); | 
|---|
| 3075 | $sth->execute($uid); | 
|---|
| 3076 | return $sth->fetchrow_hashref(); | 
|---|
| 3077 | } # end getUserData() | 
|---|
| 3078 |  | 
|---|
| 3079 |  | 
|---|
| 3080 | ## DNSDB::addLoc() | 
|---|
| 3081 | # Add a new location. | 
|---|
| 3082 | # Takes a database handle, group ID, short and long description, and a comma-separated | 
|---|
| 3083 | # list of IP addresses. | 
|---|
| 3084 | # Returns ('OK',<location>) on success, ('FAIL',<failmsg>) on failure | 
|---|
| 3085 | sub addLoc { | 
|---|
| 3086 | my $self = shift; | 
|---|
| 3087 | my $dbh = $self->{dbh}; | 
|---|
| 3088 | my $grp = shift; | 
|---|
| 3089 | my $shdesc = shift; | 
|---|
| 3090 | my $comments = shift; | 
|---|
| 3091 | my $iplist = shift; | 
|---|
| 3092 |  | 
|---|
| 3093 | # $shdesc gets set to the generated location ID if possible, but these can be de-undefined here. | 
|---|
| 3094 | $comments = '' if !$comments; | 
|---|
| 3095 | $iplist = '' if !$iplist; | 
|---|
| 3096 |  | 
|---|
| 3097 | my $loc; | 
|---|
| 3098 |  | 
|---|
| 3099 | # Generate a location ID.  This is, by spec, a two-character widget.  We'll use [a-z][a-z] | 
|---|
| 3100 | # for now;  676 locations should satisfy all but the largest of the huge networks. | 
|---|
| 3101 | # Not sure whether these are case-sensitive, or what other rules might apply - in any case | 
|---|
| 3102 | # the absolute maximum is 16K (256*256) since it's parsed by tinydns as a two-character field. | 
|---|
| 3103 |  | 
|---|
| 3104 | # add just after "my $origloc = $loc;": | 
|---|
| 3105 | #    # These expand the possible space from 26^2 to 52^2 [* note in testing only 2052 were achieved], | 
|---|
| 3106 | #    # and wrap it around. | 
|---|
| 3107 | #    # Yes, they skip a couple of possibles.  No, I don't care. | 
|---|
| 3108 | #    $loc = 'aA' if $loc eq 'zz'; | 
|---|
| 3109 | #    $loc = 'Aa' if $loc eq 'zZ'; | 
|---|
| 3110 | #    $loc = 'ZA' if $loc eq 'Zz'; | 
|---|
| 3111 | #    $loc = 'aa' if $loc eq 'ZZ'; | 
|---|
| 3112 |  | 
|---|
| 3113 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 3114 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 3115 | local $dbh->{AutoCommit} = 0; | 
|---|
| 3116 | local $dbh->{RaiseError} = 1; | 
|---|
| 3117 |  | 
|---|
| 3118 | ##fixme:  There is probably a far better way to do this.  Sequential increments | 
|---|
| 3119 | # are marginally less stupid that pure random generation though, and the existence | 
|---|
| 3120 | # check makes sure we don't stomp on an imported one. | 
|---|
| 3121 |  | 
|---|
| 3122 | eval { | 
|---|
| 3123 | # Get the "last" location.  Note this is the only use for loc_id, because selecting on location Does Funky Things | 
|---|
| 3124 | ($loc) = $dbh->selectrow_array("SELECT location FROM locations ORDER BY loc_id DESC LIMIT 1"); | 
|---|
| 3125 | ($loc) = ($loc =~ /^(..)/) if $loc; | 
|---|
| 3126 | my $origloc = $loc; | 
|---|
| 3127 | $loc = 'aa' if !$loc; | 
|---|
| 3128 | # Make a change... | 
|---|
| 3129 | $loc++; | 
|---|
| 3130 | # ... and keep changing if it exists | 
|---|
| 3131 | while ($dbh->selectrow_array("SELECT count(*) FROM locations WHERE location LIKE ?", undef, ($loc.'%'))) { | 
|---|
| 3132 | $loc++; | 
|---|
| 3133 | ($loc) = ($loc =~ /^(..)/); | 
|---|
| 3134 | die "too many locations in use, can't add another one\n" if $loc eq $origloc; | 
|---|
| 3135 | ##fixme: really need to handle this case faster somehow | 
|---|
| 3136 | #if $loc eq $origloc die "<thwap> bad admin:  all locations used, your network is too fragmented"; | 
|---|
| 3137 | } | 
|---|
| 3138 | # And now we should have a unique location.  tinydns fundamentally limits the | 
|---|
| 3139 | # number of these but there's no doc on what characters are valid. | 
|---|
| 3140 | $shdesc = $loc if !$shdesc; | 
|---|
| 3141 | $dbh->do("INSERT INTO locations (location, group_id, iplist, description, comments) VALUES (?,?,?,?,?)", | 
|---|
| 3142 | undef, ($loc, $grp, $iplist, $shdesc, $comments) ); | 
|---|
| 3143 | $self->_log(entry => "Added location ($shdesc, '$iplist')"); | 
|---|
| 3144 | $dbh->commit; | 
|---|
| 3145 | }; | 
|---|
| 3146 | if ($@) { | 
|---|
| 3147 | my $msg = $@; | 
|---|
| 3148 | eval { $dbh->rollback; }; | 
|---|
| 3149 | if ($self->{log_failures}) { | 
|---|
| 3150 | $shdesc = $loc if !$shdesc; | 
|---|
| 3151 | $self->_log(entry => "Failed adding location ($shdesc, '$iplist'): $msg"); | 
|---|
| 3152 | $dbh->commit; | 
|---|
| 3153 | } | 
|---|
| 3154 | return ('FAIL',$msg); | 
|---|
| 3155 | } | 
|---|
| 3156 |  | 
|---|
| 3157 | return ('OK',$loc); | 
|---|
| 3158 | } # end addLoc() | 
|---|
| 3159 |  | 
|---|
| 3160 |  | 
|---|
| 3161 | ## DNSDB::updateLoc() | 
|---|
| 3162 | # Update details of a location. | 
|---|
| 3163 | # Takes a database handle, location ID, group ID, short description, | 
|---|
| 3164 | # long comments/notes, and comma/space-separated IP list | 
|---|
| 3165 | # Returns a result code and message | 
|---|
| 3166 | sub updateLoc { | 
|---|
| 3167 | my $self = shift; | 
|---|
| 3168 | my $dbh = $self->{dbh}; | 
|---|
| 3169 | my $loc = shift; | 
|---|
| 3170 | my $grp = shift; | 
|---|
| 3171 | my $shdesc = shift; | 
|---|
| 3172 | my $comments = shift; | 
|---|
| 3173 | my $iplist = shift; | 
|---|
| 3174 |  | 
|---|
| 3175 | $shdesc = '' if !$shdesc; | 
|---|
| 3176 | $comments = '' if !$comments; | 
|---|
| 3177 | $iplist = '' if !$iplist; | 
|---|
| 3178 |  | 
|---|
| 3179 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 3180 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 3181 | local $dbh->{AutoCommit} = 0; | 
|---|
| 3182 | local $dbh->{RaiseError} = 1; | 
|---|
| 3183 |  | 
|---|
| 3184 | my $oldloc = $self->getLoc($loc); | 
|---|
| 3185 | my $okmsg = "Updated location (".$oldloc->{description}.", '".$oldloc->{iplist}."') to ($shdesc, '$iplist')"; | 
|---|
| 3186 |  | 
|---|
| 3187 | eval { | 
|---|
| 3188 | $dbh->do("UPDATE locations SET group_id=?,iplist=?,description=?,comments=? WHERE location=?", | 
|---|
| 3189 | undef, ($grp, $iplist, $shdesc, $comments, $loc) ); | 
|---|
| 3190 | $self->_log(entry => $okmsg); | 
|---|
| 3191 | $dbh->commit; | 
|---|
| 3192 | }; | 
|---|
| 3193 | if ($@) { | 
|---|
| 3194 | my $msg = $@; | 
|---|
| 3195 | eval { $dbh->rollback; }; | 
|---|
| 3196 | if ($self->{log_failures}) { | 
|---|
| 3197 | $shdesc = $loc if !$shdesc; | 
|---|
| 3198 | $self->_log(entry => "Failed updating location ($shdesc, '$iplist'): $msg"); | 
|---|
| 3199 | $dbh->commit; | 
|---|
| 3200 | } | 
|---|
| 3201 | return ('FAIL',$msg); | 
|---|
| 3202 | } | 
|---|
| 3203 |  | 
|---|
| 3204 | return ('OK',$okmsg); | 
|---|
| 3205 | } # end updateLoc() | 
|---|
| 3206 |  | 
|---|
| 3207 |  | 
|---|
| 3208 | ## DNSDB::delLoc() | 
|---|
| 3209 | sub delLoc { | 
|---|
| 3210 | my $self = shift; | 
|---|
| 3211 | my $dbh = $self->{dbh}; | 
|---|
| 3212 | my $loc = shift; | 
|---|
| 3213 |  | 
|---|
| 3214 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 3215 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 3216 | local $dbh->{AutoCommit} = 0; | 
|---|
| 3217 | local $dbh->{RaiseError} = 1; | 
|---|
| 3218 |  | 
|---|
| 3219 | my $oldloc = $self->getLoc($loc); | 
|---|
| 3220 | my $olddesc = ($oldloc->{description} ? $oldloc->{description} : $loc); | 
|---|
| 3221 | my $okmsg = "Deleted location ($olddesc, '".$oldloc->{iplist}."')"; | 
|---|
| 3222 |  | 
|---|
| 3223 | eval { | 
|---|
| 3224 | # Check for records with this location first.  Deleting a location without deleting records | 
|---|
| 3225 | # tagged for that location will render them unpublished without other warning. | 
|---|
| 3226 | my ($r) = $dbh->selectrow_array("SELECT record_id FROM records WHERE location=? LIMIT 1", undef, ($loc) ); | 
|---|
| 3227 | die "Records still exist in location $olddesc\n" if $r; | 
|---|
| 3228 | $dbh->do("DELETE FROM locations WHERE location=?", undef, ($loc) ); | 
|---|
| 3229 | $self->_log(entry => $okmsg); | 
|---|
| 3230 | $dbh->commit; | 
|---|
| 3231 | }; | 
|---|
| 3232 | if ($@) { | 
|---|
| 3233 | my $msg = $@; | 
|---|
| 3234 | eval { $dbh->rollback; }; | 
|---|
| 3235 | if ($self->{log_failures}) { | 
|---|
| 3236 | $self->_log(entry => "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg"); | 
|---|
| 3237 | $dbh->commit; | 
|---|
| 3238 | } | 
|---|
| 3239 | return ('FAIL', "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg"); | 
|---|
| 3240 | } | 
|---|
| 3241 |  | 
|---|
| 3242 | return ('OK',$okmsg); | 
|---|
| 3243 | } # end delLoc() | 
|---|
| 3244 |  | 
|---|
| 3245 |  | 
|---|
| 3246 | ## DNSDB::getLoc() | 
|---|
| 3247 | # Get details about a location/view | 
|---|
| 3248 | # Takes a database handle and location ID. | 
|---|
| 3249 | # Returns a reference to a hash containing the group ID, IP list, description, and comments/notes | 
|---|
| 3250 | sub getLoc { | 
|---|
| 3251 | my $self = shift; | 
|---|
| 3252 | my $dbh = $self->{dbh}; | 
|---|
| 3253 | my $loc = shift; | 
|---|
| 3254 |  | 
|---|
| 3255 | my $sth = $dbh->prepare("SELECT group_id,iplist,description,comments FROM locations WHERE location=?"); | 
|---|
| 3256 | $sth->execute($loc); | 
|---|
| 3257 | return $sth->fetchrow_hashref(); | 
|---|
| 3258 | } # end getLoc() | 
|---|
| 3259 |  | 
|---|
| 3260 |  | 
|---|
| 3261 | ## DNSDB::getLocCount() | 
|---|
| 3262 | # Get count of locations/views | 
|---|
| 3263 | # Takes a database handle and hash containing at least the current group, and optionally: | 
|---|
| 3264 | # - a reference list of secondary groups | 
|---|
| 3265 | # - a filter string | 
|---|
| 3266 | # - a "Starts with" string | 
|---|
| 3267 | sub getLocCount { | 
|---|
| 3268 | my $self = shift; | 
|---|
| 3269 | my $dbh = $self->{dbh}; | 
|---|
| 3270 |  | 
|---|
| 3271 | my %args = @_; | 
|---|
| 3272 |  | 
|---|
| 3273 | # Fail on bad curgroup argument.  There's no sane fallback on this one. | 
|---|
| 3274 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) { | 
|---|
| 3275 | $errstr = "Bad or missing curgroup argument"; | 
|---|
| 3276 | return; | 
|---|
| 3277 | } | 
|---|
| 3278 | # Fail on bad childlist argument.  This could be sanely ignored if bad, maybe. | 
|---|
| 3279 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) { | 
|---|
| 3280 | $errstr = "Bad childlist argument"; | 
|---|
| 3281 | return; | 
|---|
| 3282 | } | 
|---|
| 3283 |  | 
|---|
| 3284 | my @filterargs; | 
|---|
| 3285 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/; | 
|---|
| 3286 | push @filterargs, "^$args{startwith}" if $args{startwith}; | 
|---|
| 3287 | push @filterargs, $args{filter} if $args{filter}; | 
|---|
| 3288 |  | 
|---|
| 3289 | my $sql = "SELECT count(*) FROM locations ". | 
|---|
| 3290 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")". | 
|---|
| 3291 | ($args{startwith} ? " AND description ~* ?" : ''). | 
|---|
| 3292 | ($args{filter} ? " AND description ~* ?" : ''); | 
|---|
| 3293 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) ); | 
|---|
| 3294 | $errstr = $dbh->errstr if !$count; | 
|---|
| 3295 | return $count; | 
|---|
| 3296 | } # end getLocCount() | 
|---|
| 3297 |  | 
|---|
| 3298 |  | 
|---|
| 3299 | ## DNSDB::getLocList() | 
|---|
| 3300 | sub getLocList { | 
|---|
| 3301 | my $self = shift; | 
|---|
| 3302 | my $dbh = $self->{dbh}; | 
|---|
| 3303 |  | 
|---|
| 3304 | my %args = @_; | 
|---|
| 3305 |  | 
|---|
| 3306 | # Fail on bad curgroup argument.  There's no sane fallback on this one. | 
|---|
| 3307 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) { | 
|---|
| 3308 | $errstr = "Bad or missing curgroup argument"; | 
|---|
| 3309 | return; | 
|---|
| 3310 | } | 
|---|
| 3311 | # Fail on bad childlist argument.  This could be sanely ignored if bad, maybe. | 
|---|
| 3312 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) { | 
|---|
| 3313 | $errstr = "Bad childlist argument"; | 
|---|
| 3314 | return; | 
|---|
| 3315 | } | 
|---|
| 3316 |  | 
|---|
| 3317 | my @filterargs; | 
|---|
| 3318 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/; | 
|---|
| 3319 | push @filterargs, "^$args{startwith}" if $args{startwith}; | 
|---|
| 3320 | push @filterargs, $args{filter} if $args{filter}; | 
|---|
| 3321 |  | 
|---|
| 3322 | # better to request sorts on "simple" names, but it means we need to map it to real columns | 
|---|
| 3323 | #  my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status', | 
|---|
| 3324 | #       fname => 'fname'); | 
|---|
| 3325 | #  $args{sortby} = $sortmap{$args{sortby}}; | 
|---|
| 3326 |  | 
|---|
| 3327 | # protection against bad or missing arguments | 
|---|
| 3328 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC'); | 
|---|
| 3329 | $args{sortby} = 'l.description' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/; | 
|---|
| 3330 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/; | 
|---|
| 3331 |  | 
|---|
| 3332 | my $sql = "SELECT l.location, l.description, l.iplist, g.group_name ". | 
|---|
| 3333 | "FROM locations l ". | 
|---|
| 3334 | "INNER JOIN groups g ON l.group_id=g.group_id ". | 
|---|
| 3335 | "WHERE l.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")". | 
|---|
| 3336 | ($args{startwith} ? " AND l.description ~* ?" : ''). | 
|---|
| 3337 | ($args{filter} ? " AND l.description ~* ?" : ''). | 
|---|
| 3338 | " ORDER BY $args{sortby} $args{sortorder} ". | 
|---|
| 3339 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage}); | 
|---|
| 3340 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) ); | 
|---|
| 3341 | $errstr = $dbh->errstr if !$ulist; | 
|---|
| 3342 | return $ulist; | 
|---|
| 3343 | } # end getLocList() | 
|---|
| 3344 |  | 
|---|
| 3345 |  | 
|---|
| 3346 | ## DNSDB::getLocDropdown() | 
|---|
| 3347 | # Get a list of location names for use in a dropdown menu. | 
|---|
| 3348 | # Takes a database handle, current group, and optional "tag this as selected" flag. | 
|---|
| 3349 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template | 
|---|
| 3350 | sub getLocDropdown { | 
|---|
| 3351 | my $self = shift; | 
|---|
| 3352 | my $dbh = $self->{dbh}; | 
|---|
| 3353 | my $grp = shift; | 
|---|
| 3354 | my $sel = shift || ''; | 
|---|
| 3355 |  | 
|---|
| 3356 | my $sth = $dbh->prepare(qq( | 
|---|
| 3357 | SELECT description,location FROM locations | 
|---|
| 3358 | WHERE group_id=? | 
|---|
| 3359 | ORDER BY description | 
|---|
| 3360 | ) ); | 
|---|
| 3361 | $sth->execute($grp); | 
|---|
| 3362 |  | 
|---|
| 3363 | my @loclist; | 
|---|
| 3364 | push @loclist, { locname => "(Default/All)", loc => '', selected => ($sel ? 0 : ($sel eq '' ? 1 : 0)) }; | 
|---|
| 3365 | while (my ($locname, $loc) = $sth->fetchrow_array) { | 
|---|
| 3366 | my %row = ( | 
|---|
| 3367 | locname => $locname, | 
|---|
| 3368 | loc => $loc, | 
|---|
| 3369 | selected => ($sel eq $loc ? 1 : 0) | 
|---|
| 3370 | ); | 
|---|
| 3371 | push @loclist, \%row; | 
|---|
| 3372 | } | 
|---|
| 3373 | return \@loclist; | 
|---|
| 3374 | } # end getLocDropdown() | 
|---|
| 3375 |  | 
|---|
| 3376 |  | 
|---|
| 3377 | ## DNSDB::getSOA() | 
|---|
| 3378 | # Return all suitable fields from an SOA record in separate elements of a hash | 
|---|
| 3379 | # Takes a database handle, default/live flag, domain/reverse flag, and parent ID | 
|---|
| 3380 | sub getSOA { | 
|---|
| 3381 | $errstr = ''; | 
|---|
| 3382 | my $self = shift; | 
|---|
| 3383 | my $dbh = $self->{dbh}; | 
|---|
| 3384 | my $def = shift; | 
|---|
| 3385 | my $rev = shift; | 
|---|
| 3386 | my $id = shift; | 
|---|
| 3387 |  | 
|---|
| 3388 | # (ab)use distance and weight columns to store SOA data?  can't for default_rev_records... | 
|---|
| 3389 | # - should really attach serial to the zone parent somewhere | 
|---|
| 3390 |  | 
|---|
| 3391 | my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev). | 
|---|
| 3392 | " WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}"; | 
|---|
| 3393 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) ); | 
|---|
| 3394 | return if !$ret; | 
|---|
| 3395 | ##fixme:  stick a flag somewhere if the record doesn't exist.  by the API, this is an impossible case, but... | 
|---|
| 3396 |  | 
|---|
| 3397 | ($ret->{contact},$ret->{prins}) = split /:/, $ret->{host}; | 
|---|
| 3398 | delete $ret->{host}; | 
|---|
| 3399 | ($ret->{refresh},$ret->{retry},$ret->{expire},$ret->{minttl}) = split /:/, $ret->{val}; | 
|---|
| 3400 | delete $ret->{val}; | 
|---|
| 3401 |  | 
|---|
| 3402 | return $ret; | 
|---|
| 3403 | } # end getSOA() | 
|---|
| 3404 |  | 
|---|
| 3405 |  | 
|---|
| 3406 | ## DNSDB::updateSOA() | 
|---|
| 3407 | # Update the specified SOA record | 
|---|
| 3408 | # Takes a database handle, default/live flag, forward/reverse flag, and SOA data hash | 
|---|
| 3409 | # Returns a two-element list with a result code and message | 
|---|
| 3410 | sub updateSOA { | 
|---|
| 3411 | my $self = shift; | 
|---|
| 3412 | my $dbh = $self->{dbh}; | 
|---|
| 3413 | my $defrec = shift; | 
|---|
| 3414 | my $revrec = shift; | 
|---|
| 3415 |  | 
|---|
| 3416 | my %soa = @_; | 
|---|
| 3417 |  | 
|---|
| 3418 | my $oldsoa = $self->getSOA($defrec, $revrec, $soa{id}); | 
|---|
| 3419 |  | 
|---|
| 3420 | my $msg; | 
|---|
| 3421 | my %logdata; | 
|---|
| 3422 | if ($defrec eq 'n') { | 
|---|
| 3423 | $logdata{domain_id} = $soa{id} if $revrec eq 'n'; | 
|---|
| 3424 | $logdata{rdns_id} = $soa{id} if $revrec eq 'y'; | 
|---|
| 3425 | $logdata{group_id} = $self->parentID(id => $soa{id}, revrec => $revrec, | 
|---|
| 3426 | type => ($revrec eq 'n' ? 'domain' : 'revzone') ); | 
|---|
| 3427 | } else { | 
|---|
| 3428 | $logdata{group_id} = $soa{id}; | 
|---|
| 3429 | } | 
|---|
| 3430 | my $parname = ($defrec eq 'y' ? $self->groupName($soa{id}) : | 
|---|
| 3431 | ($revrec eq 'n' ? $self->domainName($soa{id}) : $self->revName($soa{id})) ); | 
|---|
| 3432 |  | 
|---|
| 3433 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 3434 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 3435 | local $dbh->{AutoCommit} = 0; | 
|---|
| 3436 | local $dbh->{RaiseError} = 1; | 
|---|
| 3437 |  | 
|---|
| 3438 | eval { | 
|---|
| 3439 | my $sql = "UPDATE "._rectable($defrec, $revrec)." SET host=?, val=?, ttl=? WHERE record_id=? AND type=6"; | 
|---|
| 3440 | $dbh->do($sql, undef, ("$soa{contact}:$soa{prins}", "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}", | 
|---|
| 3441 | $soa{ttl}, $oldsoa->{record_id}) ); | 
|---|
| 3442 | $msg = "Updated ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse ' : 'default ') : ''). | 
|---|
| 3443 | "SOA for $parname: ". | 
|---|
| 3444 | "(ns $oldsoa->{prins}, contact $oldsoa->{contact}, refresh $oldsoa->{refresh},". | 
|---|
| 3445 | " retry $oldsoa->{retry}, expire $oldsoa->{expire}, minTTL $oldsoa->{minttl}, TTL $oldsoa->{ttl}) to ". | 
|---|
| 3446 | "(ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},". | 
|---|
| 3447 | " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})"; | 
|---|
| 3448 |  | 
|---|
| 3449 | $logdata{entry} = $msg; | 
|---|
| 3450 | $self->_log(%logdata); | 
|---|
| 3451 |  | 
|---|
| 3452 | $dbh->commit; | 
|---|
| 3453 | }; | 
|---|
| 3454 | if ($@) { | 
|---|
| 3455 | $msg = $@; | 
|---|
| 3456 | eval { $dbh->rollback; }; | 
|---|
| 3457 | $logdata{entry} = "Error updating ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse zone ' : 'default ') : ''). | 
|---|
| 3458 | "SOA record for $parname: $msg"; | 
|---|
| 3459 | if ($self->{log_failures}) { | 
|---|
| 3460 | $self->_log(%logdata); | 
|---|
| 3461 | $dbh->commit; | 
|---|
| 3462 | } | 
|---|
| 3463 | return ('FAIL', $logdata{entry}); | 
|---|
| 3464 | } else { | 
|---|
| 3465 | return ('OK', $msg); | 
|---|
| 3466 | } | 
|---|
| 3467 | } # end updateSOA() | 
|---|
| 3468 |  | 
|---|
| 3469 |  | 
|---|
| 3470 | ## DNSDB::getRecLine() | 
|---|
| 3471 | # Return all data fields for a zone record in separate elements of a hash | 
|---|
| 3472 | # Takes a database handle, default/live flag, forward/reverse flag, and record ID | 
|---|
| 3473 | sub getRecLine { | 
|---|
| 3474 | $errstr = ''; | 
|---|
| 3475 | my $self = shift; | 
|---|
| 3476 | my $dbh = $self->{dbh}; | 
|---|
| 3477 | my $defrec = shift; | 
|---|
| 3478 | my $revrec = shift; | 
|---|
| 3479 | my $id = shift; | 
|---|
| 3480 |  | 
|---|
| 3481 | my $sql = "SELECT record_id,host,type,val,ttl". | 
|---|
| 3482 | ($defrec eq 'n' ? ',location' : ''). | 
|---|
| 3483 | ($revrec eq 'n' ? ',distance,weight,port' : ''). | 
|---|
| 3484 | (($defrec eq 'y') ? ',group_id FROM ' : ',domain_id,rdns_id FROM '). | 
|---|
| 3485 | _rectable($defrec,$revrec)." WHERE record_id=?"; | 
|---|
| 3486 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) ); | 
|---|
| 3487 |  | 
|---|
| 3488 | if ($dbh->err) { | 
|---|
| 3489 | $errstr = $DBI::errstr; | 
|---|
| 3490 | return undef; | 
|---|
| 3491 | } | 
|---|
| 3492 |  | 
|---|
| 3493 | if (!$ret) { | 
|---|
| 3494 | $errstr = "No such record"; | 
|---|
| 3495 | return undef; | 
|---|
| 3496 | } | 
|---|
| 3497 |  | 
|---|
| 3498 | # explicitly set a parent id | 
|---|
| 3499 | if ($defrec eq 'y') { | 
|---|
| 3500 | $ret->{parid} = $ret->{group_id}; | 
|---|
| 3501 | } else { | 
|---|
| 3502 | $ret->{parid} = (($revrec eq 'n') ? $ret->{domain_id} : $ret->{rdns_id}); | 
|---|
| 3503 | # and a secondary if we have a custom type that lives in both a forward and reverse zone | 
|---|
| 3504 | $ret->{secid} = (($revrec eq 'y') ? $ret->{domain_id} : $ret->{rdns_id}) if $ret->{type} > 65279; | 
|---|
| 3505 | } | 
|---|
| 3506 | $ret->{address} = $ret->{val};        # because. | 
|---|
| 3507 |  | 
|---|
| 3508 | return $ret; | 
|---|
| 3509 | } | 
|---|
| 3510 |  | 
|---|
| 3511 |  | 
|---|
| 3512 | ##fixme: should use above (getRecLine()) to get lines for below? | 
|---|
| 3513 | ## DNSDB::getRecList() | 
|---|
| 3514 | # Return records for a group or zone | 
|---|
| 3515 | # Takes a default/live flag, group or zone ID, start, | 
|---|
| 3516 | # number of records, sort field, and sort order | 
|---|
| 3517 | # Returns a reference to an array of hashes | 
|---|
| 3518 | sub getRecList { | 
|---|
| 3519 | $errstr = ''; | 
|---|
| 3520 | my $self = shift; | 
|---|
| 3521 | my $dbh = $self->{dbh}; | 
|---|
| 3522 |  | 
|---|
| 3523 | my %args = @_; | 
|---|
| 3524 |  | 
|---|
| 3525 | my @filterargs; | 
|---|
| 3526 |  | 
|---|
| 3527 | push @filterargs, $args{filter} if $args{filter}; | 
|---|
| 3528 |  | 
|---|
| 3529 | # protection against bad or missing arguments | 
|---|
| 3530 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC'); | 
|---|
| 3531 | my $defsort; | 
|---|
| 3532 | $defsort = 'host' if $args{revrec} eq 'n';     # default sort by host on domain record list | 
|---|
| 3533 | $defsort = 'val' if $args{revrec} eq 'y';      # default sort by IP on revzone record list | 
|---|
| 3534 | $args{sortby} = '' if !$args{sortby}; | 
|---|
| 3535 | $args{sortby} = $defsort if !$args{revrec}; | 
|---|
| 3536 | $args{sortby} = $defsort if $args{sortby} !~ /^[\w_,.]+$/; | 
|---|
| 3537 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/; | 
|---|
| 3538 | my $perpage = ($args{nrecs} ? $args{nrecs} : $self->{perpage}); | 
|---|
| 3539 |  | 
|---|
| 3540 | # sort reverse zones on IP, correctly | 
|---|
| 3541 | # do other fiddling with $args{sortby} while we're at it. | 
|---|
| 3542 | # whee!  multisort means just passing comma-separated fields in sortby! | 
|---|
| 3543 | my $newsort = ''; | 
|---|
| 3544 | foreach my $sf (split /,/, $args{sortby}) { | 
|---|
| 3545 | $sf = "r.$sf"; | 
|---|
| 3546 | $sf =~ s/r\.val/CAST (r.val AS inet)/ | 
|---|
| 3547 | if $args{revrec} eq 'y' && $args{defrec} eq 'n'; | 
|---|
| 3548 | $sf =~ s/r\.type/t.alphaorder/; | 
|---|
| 3549 | $newsort .= ",$sf"; | 
|---|
| 3550 | } | 
|---|
| 3551 | $newsort =~ s/^,//; | 
|---|
| 3552 |  | 
|---|
| 3553 | my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.ttl"; | 
|---|
| 3554 | $sql .= ",l.description AS locname" if $args{defrec} eq 'n'; | 
|---|
| 3555 | $sql .= ",r.distance,r.weight,r.port" if $args{revrec} eq 'n'; | 
|---|
| 3556 | $sql .= " FROM "._rectable($args{defrec},$args{revrec})." r "; | 
|---|
| 3557 | $sql .= "INNER JOIN rectypes t ON r.type=t.val ";     # for sorting by type alphabetically | 
|---|
| 3558 | $sql .= "LEFT JOIN locations l ON r.location=l.location " if $args{defrec} eq 'n'; | 
|---|
| 3559 | $sql .= "WHERE "._recparent($args{defrec},$args{revrec})." = ?"; | 
|---|
| 3560 | $sql .= " AND NOT r.type=$reverse_typemap{SOA}"; | 
|---|
| 3561 | $sql .= " AND (r.host ~* ? OR r.val ~* ?)" if $args{filter}; | 
|---|
| 3562 | $sql .= " ORDER BY $newsort $args{sortorder}"; | 
|---|
| 3563 | # ensure consistent ordering by sorting on record_id too | 
|---|
| 3564 | $sql .= ", record_id $args{sortorder}"; | 
|---|
| 3565 | $sql .= ($args{offset} eq 'all' ? '' : " LIMIT $perpage OFFSET ".$args{offset}*$perpage); | 
|---|
| 3566 |  | 
|---|
| 3567 | my @bindvars = ($args{id}); | 
|---|
| 3568 | push @bindvars, ($args{filter},$args{filter}) if $args{filter}; | 
|---|
| 3569 |  | 
|---|
| 3570 | my $ret = $dbh->selectall_arrayref($sql, { Slice => {} }, (@bindvars) ); | 
|---|
| 3571 | $errstr = "Error retrieving records: ".$dbh->errstr if !$ret; | 
|---|
| 3572 | return $ret; | 
|---|
| 3573 | } # end getRecList() | 
|---|
| 3574 |  | 
|---|
| 3575 |  | 
|---|
| 3576 | ## DNSDB::getRecCount() | 
|---|
| 3577 | # Return count of non-SOA records in zone (or default records in a group) | 
|---|
| 3578 | # Takes a database handle, default/live flag, reverse/forward flag, group/domain ID, | 
|---|
| 3579 | # and optional filtering modifier | 
|---|
| 3580 | # Returns the count | 
|---|
| 3581 | sub getRecCount { | 
|---|
| 3582 | my $self = shift; | 
|---|
| 3583 | my $dbh = $self->{dbh}; | 
|---|
| 3584 | my $defrec = shift; | 
|---|
| 3585 | my $revrec = shift; | 
|---|
| 3586 | my $id = shift; | 
|---|
| 3587 | my $filter = shift || ''; | 
|---|
| 3588 |  | 
|---|
| 3589 | # keep the nasties down, since we can't ?-sub this bit.  :/ | 
|---|
| 3590 | # note this is chars allowed in DNS hostnames | 
|---|
| 3591 | $filter =~ s/[^a-zA-Z0-9_.:-]//g; | 
|---|
| 3592 |  | 
|---|
| 3593 | my @bindvars = ($id); | 
|---|
| 3594 | push @bindvars, $filter if $filter; | 
|---|
| 3595 | my $sql = "SELECT count(*) FROM ". | 
|---|
| 3596 | _rectable($defrec,$revrec). | 
|---|
| 3597 | " WHERE "._recparent($defrec,$revrec)."=? ". | 
|---|
| 3598 | "AND NOT type=$reverse_typemap{SOA}". | 
|---|
| 3599 | ($filter ? " AND host ~* ?" : ''); | 
|---|
| 3600 | my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) ); | 
|---|
| 3601 |  | 
|---|
| 3602 | return $count; | 
|---|
| 3603 |  | 
|---|
| 3604 | } # end getRecCount() | 
|---|
| 3605 |  | 
|---|
| 3606 |  | 
|---|
| 3607 | ## DNSDB::addRec() | 
|---|
| 3608 | # Add a new record to a domain or a group's default records | 
|---|
| 3609 | # Takes a database handle, default/live flag, group/domain ID, | 
|---|
| 3610 | # host, type, value, and TTL | 
|---|
| 3611 | # Some types require additional detail: "distance" for MX and SRV, | 
|---|
| 3612 | # and weight/port for SRV | 
|---|
| 3613 | # Returns a status code and detail message in case of error | 
|---|
| 3614 | ##fixme:  pass a hash with the record data, not a series of separate values | 
|---|
| 3615 | sub addRec { | 
|---|
| 3616 | $errstr = ''; | 
|---|
| 3617 | my $self = shift; | 
|---|
| 3618 | my $dbh = $self->{dbh}; | 
|---|
| 3619 | my $defrec = shift; | 
|---|
| 3620 | my $revrec = shift; | 
|---|
| 3621 | my $id = shift;       # parent (group_id for defrecs, rdns_id for reverse records, | 
|---|
| 3622 | # domain_id for domain records) | 
|---|
| 3623 |  | 
|---|
| 3624 | my $host = shift; | 
|---|
| 3625 | my $rectype = shift;  # reference so we can coerce it if "+"-types can't find both zones | 
|---|
| 3626 | my $val = shift; | 
|---|
| 3627 | my $ttl = shift; | 
|---|
| 3628 | my $location = shift; | 
|---|
| 3629 | $location  = '' if !$location; | 
|---|
| 3630 |  | 
|---|
| 3631 | # Spaces are evil. | 
|---|
| 3632 | $$host =~ s/^\s+//; | 
|---|
| 3633 | $$host =~ s/\s+$//; | 
|---|
| 3634 | if ($typemap{$$rectype} ne 'TXT') { | 
|---|
| 3635 | # Leading or trailng spaces could be legit in TXT records. | 
|---|
| 3636 | $$val =~ s/^\s+//; | 
|---|
| 3637 | $$val =~ s/\s+$//; | 
|---|
| 3638 | } | 
|---|
| 3639 |  | 
|---|
| 3640 | # prep for validation | 
|---|
| 3641 | my $addr = NetAddr::IP->new($$val); | 
|---|
| 3642 | $$host =~ s/\.+$//;   # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI. | 
|---|
| 3643 |  | 
|---|
| 3644 | my $domid = 0; | 
|---|
| 3645 | my $revid = 0; | 
|---|
| 3646 |  | 
|---|
| 3647 | my $retcode = 'OK';   # assume everything will go OK | 
|---|
| 3648 | my $retmsg = ''; | 
|---|
| 3649 |  | 
|---|
| 3650 | # do simple validation first | 
|---|
| 3651 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/; | 
|---|
| 3652 |  | 
|---|
| 3653 | # Quick check on hostname parts.  Note the regex is more forgiving than the error message; | 
|---|
| 3654 | # domain names technically are case-insensitive, and we use printf-like % codes for a couple | 
|---|
| 3655 | # of types.  Other things may also be added to validate default records of several flavours. | 
|---|
| 3656 | return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z . _)") | 
|---|
| 3657 | if $defrec eq 'n' && ($revrec eq 'y' ? $$rectype != $reverse_typemap{TXT} : 1) && | 
|---|
| 3658 | $$host !~ /^[0-9a-z_%.-]+$/i; | 
|---|
| 3659 |  | 
|---|
| 3660 | # Collect these even if we're only doing a simple A record so we can call *any* validation sub | 
|---|
| 3661 | my $dist = shift; | 
|---|
| 3662 | my $weight = shift; | 
|---|
| 3663 | my $port = shift; | 
|---|
| 3664 |  | 
|---|
| 3665 | my $fields; | 
|---|
| 3666 | my @vallist; | 
|---|
| 3667 |  | 
|---|
| 3668 | # Call the validation sub for the type requested. | 
|---|
| 3669 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec, id => $id, | 
|---|
| 3670 | host => $host, rectype => $rectype, val => $val, addr => $addr, | 
|---|
| 3671 | dist => \$dist, port => \$port, weight => \$weight, | 
|---|
| 3672 | fields => \$fields, vallist => \@vallist); | 
|---|
| 3673 |  | 
|---|
| 3674 | return ($retcode,$retmsg) if $retcode eq 'FAIL'; | 
|---|
| 3675 |  | 
|---|
| 3676 | # Set up database fields and bind parameters | 
|---|
| 3677 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec); | 
|---|
| 3678 | push @vallist, ($$host,$$rectype,$$val,$ttl,$id); | 
|---|
| 3679 |  | 
|---|
| 3680 | # locations are not for default records, silly coder! | 
|---|
| 3681 | if ($defrec eq 'n') { | 
|---|
| 3682 | $fields .= ",location"; | 
|---|
| 3683 | push @vallist, $location; | 
|---|
| 3684 | } | 
|---|
| 3685 | my $vallen = '?'.(',?'x$#vallist); | 
|---|
| 3686 |  | 
|---|
| 3687 | # Put together the success log entry.  We have to use this horrible kludge | 
|---|
| 3688 | # because domain_id and rdns_id may or may not be present, and if they are, | 
|---|
| 3689 | # they're not at a guaranteed consistent index in the array.  wheee! | 
|---|
| 3690 | my %logdata; | 
|---|
| 3691 | my @ftmp = split /,/, $fields; | 
|---|
| 3692 | for (my $i=0; $i <= $#vallist; $i++) { | 
|---|
| 3693 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id'; | 
|---|
| 3694 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id'; | 
|---|
| 3695 | } | 
|---|
| 3696 | $logdata{group_id} = $id if $defrec eq 'y'; | 
|---|
| 3697 | $logdata{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) | 
|---|
| 3698 | if $defrec eq 'n'; | 
|---|
| 3699 | $logdata{entry} = "Added ".($defrec eq 'y' ? 'default record' : 'record'); | 
|---|
| 3700 | # NS records for revzones get special treatment | 
|---|
| 3701 | if ($revrec eq 'y' && $$rectype == 2) { | 
|---|
| 3702 | $logdata{entry} .= " '$$val $typemap{$$rectype} $$host"; | 
|---|
| 3703 | } else { | 
|---|
| 3704 | $logdata{entry} .= " '$$host $typemap{$$rectype} $$val"; | 
|---|
| 3705 | } | 
|---|
| 3706 |  | 
|---|
| 3707 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX'; | 
|---|
| 3708 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]" | 
|---|
| 3709 | if $typemap{$$rectype} eq 'SRV'; | 
|---|
| 3710 | $logdata{entry} .= "', TTL $ttl"; | 
|---|
| 3711 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location; | 
|---|
| 3712 |  | 
|---|
| 3713 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 3714 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 3715 | local $dbh->{AutoCommit} = 0; | 
|---|
| 3716 | local $dbh->{RaiseError} = 1; | 
|---|
| 3717 |  | 
|---|
| 3718 | eval { | 
|---|
| 3719 | $dbh->do("INSERT INTO "._rectable($defrec, $revrec)." ($fields) VALUES ($vallen)", | 
|---|
| 3720 | undef, @vallist); | 
|---|
| 3721 | $self->_log(%logdata); | 
|---|
| 3722 | $dbh->commit; | 
|---|
| 3723 | }; | 
|---|
| 3724 | if ($@) { | 
|---|
| 3725 | my $msg = $@; | 
|---|
| 3726 | eval { $dbh->rollback; }; | 
|---|
| 3727 | if ($self->{log_failures}) { | 
|---|
| 3728 | $logdata{entry} = "Failed adding ".($defrec eq 'y' ? 'default ' : ''). | 
|---|
| 3729 | "record '$$host $typemap{$$rectype} $$val', TTL $ttl ($msg)"; | 
|---|
| 3730 | $self->_log(%logdata); | 
|---|
| 3731 | $dbh->commit; | 
|---|
| 3732 | } | 
|---|
| 3733 | return ('FAIL',$msg); | 
|---|
| 3734 | } | 
|---|
| 3735 |  | 
|---|
| 3736 | $resultstr = $logdata{entry}; | 
|---|
| 3737 | return ($retcode, $retmsg); | 
|---|
| 3738 |  | 
|---|
| 3739 | } # end addRec() | 
|---|
| 3740 |  | 
|---|
| 3741 |  | 
|---|
| 3742 | ## DNSDB::updateRec() | 
|---|
| 3743 | # Update a record | 
|---|
| 3744 | # Takes a database handle, default and reverse flags, record ID, immediate parent ID, and new record data. | 
|---|
| 3745 | # Returns a status code and message | 
|---|
| 3746 | sub updateRec { | 
|---|
| 3747 | $errstr = ''; | 
|---|
| 3748 |  | 
|---|
| 3749 | my $self = shift; | 
|---|
| 3750 | my $dbh = $self->{dbh}; | 
|---|
| 3751 | my $defrec = shift; | 
|---|
| 3752 | my $revrec = shift; | 
|---|
| 3753 | my $id = shift; | 
|---|
| 3754 | my $parid = shift;    # immediate parent entity that we're descending from to update the record | 
|---|
| 3755 |  | 
|---|
| 3756 | # all records have these | 
|---|
| 3757 | my $host = shift; | 
|---|
| 3758 | my $hostbk = $$host;  # Keep a backup copy of the original, so we can WARN if the update mangles the domain | 
|---|
| 3759 | my $rectype = shift; | 
|---|
| 3760 | my $val = shift; | 
|---|
| 3761 | my $ttl = shift; | 
|---|
| 3762 | my $location = shift; # may be empty/null/undef depending on caller | 
|---|
| 3763 | $location  = '' if !$location; | 
|---|
| 3764 |  | 
|---|
| 3765 | # just set it to an empty string;  failures will be caught later. | 
|---|
| 3766 | $$host = '' if !$$host; | 
|---|
| 3767 |  | 
|---|
| 3768 | # Spaces are evil. | 
|---|
| 3769 | $$host =~ s/^\s+//; | 
|---|
| 3770 | $$host =~ s/\s+$//; | 
|---|
| 3771 | if ($typemap{$$rectype} ne 'TXT') { | 
|---|
| 3772 | # Leading or trailng spaces could be legit in TXT records. | 
|---|
| 3773 | $$val =~ s/^\s+//; | 
|---|
| 3774 | $$val =~ s/\s+$//; | 
|---|
| 3775 | } | 
|---|
| 3776 |  | 
|---|
| 3777 | # prep for validation | 
|---|
| 3778 | my $addr = NetAddr::IP->new($$val); | 
|---|
| 3779 | $$host =~ s/\.+$//;   # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI. | 
|---|
| 3780 |  | 
|---|
| 3781 | my $domid = 0; | 
|---|
| 3782 | my $revid = 0; | 
|---|
| 3783 |  | 
|---|
| 3784 | my $retcode = 'OK';   # assume everything will go OK | 
|---|
| 3785 | my $retmsg = ''; | 
|---|
| 3786 |  | 
|---|
| 3787 | # do simple validation first | 
|---|
| 3788 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/; | 
|---|
| 3789 |  | 
|---|
| 3790 | # Quick check on hostname parts.  Note the regex is more forgiving than the error message; | 
|---|
| 3791 | # domain names technically are case-insensitive, and we use printf-like % codes for a couple | 
|---|
| 3792 | # of types.  Other things may also be added to validate default records of several flavours. | 
|---|
| 3793 | return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z - . _)") | 
|---|
| 3794 | if $defrec eq 'n' && ($revrec eq 'y' ? $$rectype != $reverse_typemap{TXT} : 1) && | 
|---|
| 3795 | $$host !~ /^[0-9a-z_%.-]+$/i; | 
|---|
| 3796 |  | 
|---|
| 3797 | # only MX and SRV will use these | 
|---|
| 3798 | my $dist = shift || 0; | 
|---|
| 3799 | my $weight = shift || 0; | 
|---|
| 3800 | my $port = shift || 0; | 
|---|
| 3801 |  | 
|---|
| 3802 | my $fields; | 
|---|
| 3803 | my @vallist; | 
|---|
| 3804 |  | 
|---|
| 3805 | # get old record data so we have the right parent ID | 
|---|
| 3806 | # and for logging (eventually) | 
|---|
| 3807 | my $oldrec = $self->getRecLine($defrec, $revrec, $id); | 
|---|
| 3808 |  | 
|---|
| 3809 | # Call the validation sub for the type requested. | 
|---|
| 3810 | # Note the ID to pass here is the *parent*, not the record | 
|---|
| 3811 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec, | 
|---|
| 3812 | id => ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})), | 
|---|
| 3813 | host => $host, rectype => $rectype, val => $val, addr => $addr, | 
|---|
| 3814 | dist => \$dist, port => \$port, weight => \$weight, | 
|---|
| 3815 | fields => \$fields, vallist => \@vallist, | 
|---|
| 3816 | update => $id); | 
|---|
| 3817 |  | 
|---|
| 3818 | return ($retcode,$retmsg) if $retcode eq 'FAIL'; | 
|---|
| 3819 |  | 
|---|
| 3820 | # Set up database fields and bind parameters.  Note only the optional fields | 
|---|
| 3821 | # (distance, weight, port, secondary parent ID) are added in the validation call above | 
|---|
| 3822 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec); | 
|---|
| 3823 | push @vallist, ($$host,$$rectype,$$val,$ttl, | 
|---|
| 3824 | ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})) ); | 
|---|
| 3825 |  | 
|---|
| 3826 | # locations are not for default records, silly coder! | 
|---|
| 3827 | if ($defrec eq 'n') { | 
|---|
| 3828 | $fields .= ",location"; | 
|---|
| 3829 | push @vallist, $location; | 
|---|
| 3830 | } | 
|---|
| 3831 |  | 
|---|
| 3832 | # hack hack PTHUI | 
|---|
| 3833 | # need to forcibly make sure we disassociate a record with a parent it's no longer related to. | 
|---|
| 3834 | # eg, PTR records may not have a domain parent, or A/AAAA records may not have a revzone parent. | 
|---|
| 3835 | # mainly needed for crossover types that got coerced down to "standard" types | 
|---|
| 3836 | if ($defrec eq 'n') { | 
|---|
| 3837 | if ($$rectype == $reverse_typemap{PTR}) { | 
|---|
| 3838 | $fields .= ",domain_id"; | 
|---|
| 3839 | push @vallist, 0; | 
|---|
| 3840 | } | 
|---|
| 3841 | if ($$rectype == $reverse_typemap{A} || $$rectype == $reverse_typemap{AAAA}) { | 
|---|
| 3842 | $fields .= ",rdns_id"; | 
|---|
| 3843 | push @vallist, 0; | 
|---|
| 3844 | } | 
|---|
| 3845 | } | 
|---|
| 3846 | # fix fat-finger-originated record type changes | 
|---|
| 3847 | if ($$rectype == 65285) { | 
|---|
| 3848 | $fields .= ",rdns_id" if $revrec eq 'n'; | 
|---|
| 3849 | $fields .= ",domain_id" if $revrec eq 'y'; | 
|---|
| 3850 | push @vallist, 0; | 
|---|
| 3851 | } | 
|---|
| 3852 | if ($defrec eq 'n') { | 
|---|
| 3853 | $domid = $parid if $revrec eq 'n'; | 
|---|
| 3854 | $revid = $parid if $revrec eq 'y'; | 
|---|
| 3855 | } | 
|---|
| 3856 |  | 
|---|
| 3857 | # Put together the success log entry.  Horrible kludge from addRec() copied as-is since | 
|---|
| 3858 | # we don't know whether the passed arguments or retrieved values for domain_id and rdns_id | 
|---|
| 3859 | # will be maintained (due to "not-in-zone" validation changes) | 
|---|
| 3860 | my %logdata; | 
|---|
| 3861 | $logdata{domain_id} = $domid; | 
|---|
| 3862 | $logdata{rdns_id} = $revid; | 
|---|
| 3863 | my @ftmp = split /,/, $fields; | 
|---|
| 3864 | for (my $i=0; $i <= $#vallist; $i++) { | 
|---|
| 3865 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id'; | 
|---|
| 3866 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id'; | 
|---|
| 3867 | } | 
|---|
| 3868 | $logdata{group_id} = $parid if $defrec eq 'y'; | 
|---|
| 3869 | $logdata{group_id} = $self->parentID(id => $parid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) | 
|---|
| 3870 | if $defrec eq 'n'; | 
|---|
| 3871 | $logdata{entry} = "Updated ".($defrec eq 'y' ? 'default record' : 'record')." from\n"; | 
|---|
| 3872 | # NS records for revzones get special treatment | 
|---|
| 3873 | if ($revrec eq 'y' && $$rectype == 2) { | 
|---|
| 3874 | $logdata{entry} .= " '$oldrec->{val} $typemap{$oldrec->{type}} $oldrec->{host}"; | 
|---|
| 3875 | } else { | 
|---|
| 3876 | $logdata{entry} .= " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}"; | 
|---|
| 3877 | } | 
|---|
| 3878 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX'; | 
|---|
| 3879 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]" | 
|---|
| 3880 | if $typemap{$oldrec->{type}} eq 'SRV'; | 
|---|
| 3881 | $logdata{entry} .= "', TTL $oldrec->{ttl}"; | 
|---|
| 3882 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location}; | 
|---|
| 3883 | $logdata{entry} .= "\nto\n"; | 
|---|
| 3884 | # More NS special | 
|---|
| 3885 | if ($revrec eq 'y' && $$rectype == 2) { | 
|---|
| 3886 | $logdata{entry} .= "'$$val $typemap{$$rectype} $$host"; | 
|---|
| 3887 | } else { | 
|---|
| 3888 | $logdata{entry} .= "'$$host $typemap{$$rectype} $$val"; | 
|---|
| 3889 | } | 
|---|
| 3890 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX'; | 
|---|
| 3891 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$$rectype} eq 'SRV'; | 
|---|
| 3892 | $logdata{entry} .= "', TTL $ttl"; | 
|---|
| 3893 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location; | 
|---|
| 3894 |  | 
|---|
| 3895 | local $dbh->{AutoCommit} = 0; | 
|---|
| 3896 | local $dbh->{RaiseError} = 1; | 
|---|
| 3897 |  | 
|---|
| 3898 | # Fiddle the field list into something suitable for updates | 
|---|
| 3899 | $fields =~ s/,/=?,/g; | 
|---|
| 3900 | $fields .= "=?"; | 
|---|
| 3901 |  | 
|---|
| 3902 | eval { | 
|---|
| 3903 | $dbh->do("UPDATE "._rectable($defrec,$revrec)." SET $fields WHERE record_id=?", undef, (@vallist, $id) ); | 
|---|
| 3904 | $self->_log(%logdata); | 
|---|
| 3905 | $dbh->commit; | 
|---|
| 3906 | }; | 
|---|
| 3907 | if ($@) { | 
|---|
| 3908 | my $msg = $@; | 
|---|
| 3909 | eval { $dbh->rollback; }; | 
|---|
| 3910 | if ($self->{log_failures}) { | 
|---|
| 3911 | $logdata{entry} = "Failed updating ".($defrec eq 'y' ? 'default ' : ''). | 
|---|
| 3912 | "record '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)"; | 
|---|
| 3913 | $self->_log(%logdata); | 
|---|
| 3914 | $dbh->commit; | 
|---|
| 3915 | } | 
|---|
| 3916 | return ('FAIL', $msg); | 
|---|
| 3917 | } | 
|---|
| 3918 |  | 
|---|
| 3919 | $resultstr = $logdata{entry}; | 
|---|
| 3920 | return ($retcode, $retmsg); | 
|---|
| 3921 | } # end updateRec() | 
|---|
| 3922 |  | 
|---|
| 3923 |  | 
|---|
| 3924 | ## DNSDB::downconvert() | 
|---|
| 3925 | # A mostly internal (not exported) semiutilty sub to downconvert from pseudotype <x> | 
|---|
| 3926 | # to a compatible component type.  Only a handful of operations are valid, anything | 
|---|
| 3927 | # else is a null-op. | 
|---|
| 3928 | # Takes the record ID and the new type.  Returns boolean. | 
|---|
| 3929 | sub downconvert { | 
|---|
| 3930 | my $self = shift; | 
|---|
| 3931 | my $dbh = $self->{dbh}; | 
|---|
| 3932 | my $recid = shift; | 
|---|
| 3933 | my $newtype = shift; | 
|---|
| 3934 |  | 
|---|
| 3935 | # also, only work on live records;  little to no value trying to do this on default records. | 
|---|
| 3936 | my $rec = $self->getRecLine('n', 'y', $recid); | 
|---|
| 3937 |  | 
|---|
| 3938 | # hm? | 
|---|
| 3939 | #return 1 if !$rec; | 
|---|
| 3940 |  | 
|---|
| 3941 | return 1 if $rec->{type} < 65000;     # Only the reverse-record pseudotypes can be downconverted | 
|---|
| 3942 | return 1 if $rec->{type} == 65282;    # Nowhere to go | 
|---|
| 3943 |  | 
|---|
| 3944 | my $delpar; | 
|---|
| 3945 | my @sqlargs; | 
|---|
| 3946 | if ($rec->{type} == 65280) { | 
|---|
| 3947 | return 1 if $newtype != 1 && $newtype != 12; | 
|---|
| 3948 | $delpar = ($newtype == 1 ? 'rdns_id' : 'domain_id'); | 
|---|
| 3949 | push @sqlargs, 0, $newtype, $recid; | 
|---|
| 3950 | } elsif ($rec->{type} == 65281) { | 
|---|
| 3951 | return 1 if $newtype != 28 && $newtype != 12; | 
|---|
| 3952 | $delpar = ($newtype == 28 ? 'rdns_id' : 'domain_id'); | 
|---|
| 3953 | push @sqlargs, 0, $newtype, $recid; | 
|---|
| 3954 | } elsif ($rec->{type} == 65283) { | 
|---|
| 3955 | return 1 if $newtype != 65282; | 
|---|
| 3956 | $delpar = 'rdns_id'; | 
|---|
| 3957 | } elsif ($rec->{type} == 65284) { | 
|---|
| 3958 | return 1 if $newtype != 65282; | 
|---|
| 3959 | $delpar = 'rdns_id'; | 
|---|
| 3960 | } else { | 
|---|
| 3961 | # Your llama is on fire. | 
|---|
| 3962 | } | 
|---|
| 3963 |  | 
|---|
| 3964 | local $dbh->{AutoCommit} = 0; | 
|---|
| 3965 | local $dbh->{RaiseError} = 1; | 
|---|
| 3966 |  | 
|---|
| 3967 | eval { | 
|---|
| 3968 | $dbh->do("UPDATE records SET $delpar = ?, type = ? WHERE record_id = ?", undef, @sqlargs); | 
|---|
| 3969 | $dbh->commit; | 
|---|
| 3970 | }; | 
|---|
| 3971 | if ($@) { | 
|---|
| 3972 | $errstr = $@; | 
|---|
| 3973 | eval { $dbh->rollback; }; | 
|---|
| 3974 | return 0; | 
|---|
| 3975 | } | 
|---|
| 3976 | return 1; | 
|---|
| 3977 | } # end downconvert() | 
|---|
| 3978 |  | 
|---|
| 3979 |  | 
|---|
| 3980 | ## DNSDB::delRec() | 
|---|
| 3981 | # Delete a record. | 
|---|
| 3982 | sub delRec { | 
|---|
| 3983 | $errstr = ''; | 
|---|
| 3984 | my $self = shift; | 
|---|
| 3985 | my $dbh = $self->{dbh}; | 
|---|
| 3986 | my $defrec = shift; | 
|---|
| 3987 | my $revrec = shift; | 
|---|
| 3988 | my $id = shift; | 
|---|
| 3989 |  | 
|---|
| 3990 | my $oldrec = $self->getRecLine($defrec, $revrec, $id); | 
|---|
| 3991 |  | 
|---|
| 3992 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 3993 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 3994 | local $dbh->{AutoCommit} = 0; | 
|---|
| 3995 | local $dbh->{RaiseError} = 1; | 
|---|
| 3996 |  | 
|---|
| 3997 | # Put together the log entry | 
|---|
| 3998 | my %logdata; | 
|---|
| 3999 | $logdata{domain_id} = $oldrec->{domain_id}; | 
|---|
| 4000 | $logdata{rdns_id} = $oldrec->{rdns_id}; | 
|---|
| 4001 | $logdata{group_id} = $oldrec->{group_id} if $defrec eq 'y'; | 
|---|
| 4002 | $logdata{group_id} = $self->parentID(id => $oldrec->{domain_id}, type => ($revrec eq 'n' ? 'domain' : 'revzone'), | 
|---|
| 4003 | revrec => $revrec) | 
|---|
| 4004 | if $defrec eq 'n'; | 
|---|
| 4005 | $logdata{entry} = "Deleted ".($defrec eq 'y' ? 'default record ' : 'record '). | 
|---|
| 4006 | "'$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}"; | 
|---|
| 4007 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX'; | 
|---|
| 4008 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]" | 
|---|
| 4009 | if $typemap{$oldrec->{type}} eq 'SRV'; | 
|---|
| 4010 | $logdata{entry} .= "', TTL $oldrec->{ttl}"; | 
|---|
| 4011 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location}; | 
|---|
| 4012 |  | 
|---|
| 4013 | eval { | 
|---|
| 4014 | my $sth = $dbh->do("DELETE FROM "._rectable($defrec,$revrec)." WHERE record_id=?", undef, ($id)); | 
|---|
| 4015 | $self->_log(%logdata); | 
|---|
| 4016 | $dbh->commit; | 
|---|
| 4017 | }; | 
|---|
| 4018 | if ($@) { | 
|---|
| 4019 | my $msg = $@; | 
|---|
| 4020 | eval { $dbh->rollback; }; | 
|---|
| 4021 | if ($self->{log_failures}) { | 
|---|
| 4022 | $logdata{entry} = "Error deleting ".($defrec eq 'y' ? 'default record' : 'record'). | 
|---|
| 4023 | " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)"; | 
|---|
| 4024 | $self->_log(%logdata); | 
|---|
| 4025 | $dbh->commit; | 
|---|
| 4026 | } | 
|---|
| 4027 | return ('FAIL', $msg); | 
|---|
| 4028 | } | 
|---|
| 4029 |  | 
|---|
| 4030 | return ('OK',$logdata{entry}); | 
|---|
| 4031 | } # end delRec() | 
|---|
| 4032 |  | 
|---|
| 4033 |  | 
|---|
| 4034 | ## DNSDB::getLogCount() | 
|---|
| 4035 | # Get a count of log entries | 
|---|
| 4036 | # Takes a database handle and a hash containing at least: | 
|---|
| 4037 | # - Entity ID and entity type as the primary log "slice" | 
|---|
| 4038 | sub getLogCount { | 
|---|
| 4039 | my $self = shift; | 
|---|
| 4040 | my $dbh = $self->{dbh}; | 
|---|
| 4041 |  | 
|---|
| 4042 | my %args = @_; | 
|---|
| 4043 |  | 
|---|
| 4044 | my @filterargs; | 
|---|
| 4045 | ##fixme:  which fields do we want to filter on? | 
|---|
| 4046 | # push @filterargs, | 
|---|
| 4047 |  | 
|---|
| 4048 | $errstr = 'Missing primary parent ID and/or type'; | 
|---|
| 4049 | # fail early if we don't have a "prime" ID to look for log entries for | 
|---|
| 4050 | return if !$args{id}; | 
|---|
| 4051 |  | 
|---|
| 4052 | # or if the prime id type is missing or invalid | 
|---|
| 4053 | return if !$args{logtype}; | 
|---|
| 4054 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns';       # hack pthui | 
|---|
| 4055 | $args{logtype} = 'domain' if $args{logtype} eq 'dom';         # hack pthui | 
|---|
| 4056 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user'); | 
|---|
| 4057 |  | 
|---|
| 4058 | my $sql = "SELECT count(*) FROM log ". | 
|---|
| 4059 | "WHERE $id_col{$args{logtype}}=?". | 
|---|
| 4060 | ($args{filter} ? " AND entry ~* ?" : ''); | 
|---|
| 4061 | my ($count) = $dbh->selectrow_array($sql, undef, ($args{id}, @filterargs) ); | 
|---|
| 4062 | $errstr = $dbh->errstr if !$count; | 
|---|
| 4063 | return $count; | 
|---|
| 4064 | } # end getLogCount() | 
|---|
| 4065 |  | 
|---|
| 4066 |  | 
|---|
| 4067 | ## DNSDB::getLogEntries() | 
|---|
| 4068 | # Get a list of log entries | 
|---|
| 4069 | # Takes arguments as with getLogCount() above, plus optional: | 
|---|
| 4070 | # - sort field | 
|---|
| 4071 | # - sort order | 
|---|
| 4072 | # - offset for pagination | 
|---|
| 4073 | sub getLogEntries { | 
|---|
| 4074 | my $self = shift; | 
|---|
| 4075 | my $dbh = $self->{dbh}; | 
|---|
| 4076 |  | 
|---|
| 4077 | my %args = @_; | 
|---|
| 4078 |  | 
|---|
| 4079 | my @filterargs; | 
|---|
| 4080 |  | 
|---|
| 4081 | # fail early if we don't have a "prime" ID to look for log entries for | 
|---|
| 4082 | return if !$args{id}; | 
|---|
| 4083 |  | 
|---|
| 4084 | # or if the prime id type is missing or invalid | 
|---|
| 4085 | return if !$args{logtype}; | 
|---|
| 4086 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns';       # hack pthui | 
|---|
| 4087 | $args{logtype} = 'domain' if $args{logtype} eq 'dom';         # hack pthui | 
|---|
| 4088 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user'); | 
|---|
| 4089 |  | 
|---|
| 4090 | # Sorting defaults | 
|---|
| 4091 | $args{sortorder} = 'DESC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC'); | 
|---|
| 4092 | $args{sortby} = 'stamp' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/; | 
|---|
| 4093 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/; | 
|---|
| 4094 |  | 
|---|
| 4095 | my %sortmap = (fname => 'name', username => 'email', entry => 'entry', stamp => 'stamp'); | 
|---|
| 4096 | $args{sortby} = $sortmap{$args{sortby}}; | 
|---|
| 4097 |  | 
|---|
| 4098 | my $sql = "SELECT user_id AS userid, email AS useremail, name AS userfname, entry AS logentry, ". | 
|---|
| 4099 | "date_trunc('second',stamp) AS logtime ". | 
|---|
| 4100 | "FROM log ". | 
|---|
| 4101 | "WHERE $id_col{$args{logtype}}=?". | 
|---|
| 4102 | ($args{filter} ? " AND entry ~* ?" : ''). | 
|---|
| 4103 | " ORDER BY $args{sortby} $args{sortorder}, log_id $args{sortorder}". | 
|---|
| 4104 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage}); | 
|---|
| 4105 | my $loglist = $dbh->selectall_arrayref($sql, { Slice => {} }, ($args{id}, @filterargs) ); | 
|---|
| 4106 | $errstr = $dbh->errstr if !$loglist; | 
|---|
| 4107 | return $loglist; | 
|---|
| 4108 | } # end getLogEntries() | 
|---|
| 4109 |  | 
|---|
| 4110 |  | 
|---|
| 4111 | ## IPDB::getRevPattern() | 
|---|
| 4112 | # Get the narrowest template pattern applicable to a passed CIDR address (may be a netblock or an IP) | 
|---|
| 4113 | sub getRevPattern { | 
|---|
| 4114 | my $self = shift; | 
|---|
| 4115 | my $dbh = $self->{dbh}; | 
|---|
| 4116 | my $cidr = shift; | 
|---|
| 4117 | my $group = shift || 1;       # just in case | 
|---|
| 4118 |  | 
|---|
| 4119 | # for speed!  Casting and comparing even ~7K records takes ~2.5s, so narrow it down to one revzone first. | 
|---|
| 4120 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >>= ? AND group_id = ?", | 
|---|
| 4121 | undef, ($cidr, $group) ); | 
|---|
| 4122 |  | 
|---|
| 4123 | ##fixme?  may need to narrow things down more by octet-chopping and doing text comparisons before casting. | 
|---|
| 4124 | my ($revpatt) = $dbh->selectrow_array("SELECT host FROM records ". | 
|---|
| 4125 | "WHERE (type in (12,65280,65281,65282,65283,65284)) AND rdns_id = ? AND CAST (val AS inet) >>= ? ". | 
|---|
| 4126 | "ORDER BY CAST (val AS inet) DESC LIMIT 1", undef, ($revid, $cidr) ); | 
|---|
| 4127 | return $revpatt; | 
|---|
| 4128 | } # end getRevPattern() | 
|---|
| 4129 |  | 
|---|
| 4130 |  | 
|---|
| 4131 | ## DNSDB::getTypelist() | 
|---|
| 4132 | # Get a list of record types for various UI dropdowns | 
|---|
| 4133 | # Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A) | 
|---|
| 4134 | # Returns an arrayref to list of hashrefs perfect for HTML::Template | 
|---|
| 4135 | sub getTypelist { | 
|---|
| 4136 | my $self = shift; | 
|---|
| 4137 | my $dbh = $self->{dbh}; | 
|---|
| 4138 | my $recgroup = shift; | 
|---|
| 4139 | my $type = shift || $reverse_typemap{A}; | 
|---|
| 4140 |  | 
|---|
| 4141 | # also accepting $webvar{revrec}! | 
|---|
| 4142 | $recgroup = 'f' if $recgroup eq 'n'; | 
|---|
| 4143 | $recgroup = 'r' if $recgroup eq 'y'; | 
|---|
| 4144 |  | 
|---|
| 4145 | my $sql = "SELECT val,name FROM rectypes WHERE "; | 
|---|
| 4146 | if ($recgroup eq 'r') { | 
|---|
| 4147 | # reverse zone types | 
|---|
| 4148 | $sql .= "stdflag=2 OR stdflag=3"; | 
|---|
| 4149 | } elsif ($recgroup eq 'l') { | 
|---|
| 4150 | # DNS lookup types.  Note we avoid our custom types >= 65280, since those are entirely internal. | 
|---|
| 4151 | $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280"; | 
|---|
| 4152 | } else { | 
|---|
| 4153 | # default;  forward zone types.  technically $type eq 'f' but not worth the error message. | 
|---|
| 4154 | $sql .= "stdflag=1 OR stdflag=2"; | 
|---|
| 4155 | $sql .= " AND val < 65280" if $recgroup eq 'fo';  # An extra flag to trim off the pseudotypes as well. | 
|---|
| 4156 | } | 
|---|
| 4157 | $sql .= " ORDER BY listorder"; | 
|---|
| 4158 |  | 
|---|
| 4159 | my $sth = $dbh->prepare($sql); | 
|---|
| 4160 | $sth->execute; | 
|---|
| 4161 | my @typelist; | 
|---|
| 4162 | while (my ($rval,$rname) = $sth->fetchrow_array()) { | 
|---|
| 4163 | my %row = ( recval => $rval, recname => $rname ); | 
|---|
| 4164 | $row{tselect} = 1 if $rval == $type; | 
|---|
| 4165 | push @typelist, \%row; | 
|---|
| 4166 | } | 
|---|
| 4167 |  | 
|---|
| 4168 | # Add SOA on lookups since it's not listed in other dropdowns. | 
|---|
| 4169 | if ($recgroup eq 'l') { | 
|---|
| 4170 | my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' ); | 
|---|
| 4171 | $row{tselect} = 1 if $reverse_typemap{SOA} == $type; | 
|---|
| 4172 | push @typelist, \%row; | 
|---|
| 4173 | } | 
|---|
| 4174 |  | 
|---|
| 4175 | return \@typelist; | 
|---|
| 4176 | } # end getTypelist() | 
|---|
| 4177 |  | 
|---|
| 4178 |  | 
|---|
| 4179 | ## DNSDB::parentID() | 
|---|
| 4180 | # Get ID of entity that is nearest parent to requested id | 
|---|
| 4181 | # Takes a database handle and a hash of entity ID, entity type, optional parent type flag | 
|---|
| 4182 | # (domain/reverse zone or group), and optional default/live and forward/reverse flags | 
|---|
| 4183 | # Returns the ID or undef on failure | 
|---|
| 4184 | sub parentID { | 
|---|
| 4185 | my $self = shift; | 
|---|
| 4186 | my $dbh = $self->{dbh}; | 
|---|
| 4187 |  | 
|---|
| 4188 | my %args = @_; | 
|---|
| 4189 |  | 
|---|
| 4190 | # clean up the parent-type.  Set it to group if not set;  coerce revzone to domain for simpler logic | 
|---|
| 4191 | $args{partype} = 'group' if !$args{partype}; | 
|---|
| 4192 | $args{partype} = 'domain' if $args{partype} eq 'revzone'; | 
|---|
| 4193 |  | 
|---|
| 4194 | # clean up defrec and revrec.  default to live record, forward zone | 
|---|
| 4195 | $args{defrec} = 'n' if !$args{defrec}; | 
|---|
| 4196 | $args{revrec} = 'n' if !$args{revrec}; | 
|---|
| 4197 |  | 
|---|
| 4198 | if ($par_type{$args{partype}} eq 'domain') { | 
|---|
| 4199 | # only live records can have a domain/zone parent | 
|---|
| 4200 | return unless ($args{type} eq 'record' && $args{defrec} eq 'n'); | 
|---|
| 4201 | my $result = $dbh->selectrow_hashref("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id'). | 
|---|
| 4202 | " FROM records WHERE record_id = ?", | 
|---|
| 4203 | undef, ($args{id}) ) or return; | 
|---|
| 4204 | return $result; | 
|---|
| 4205 | } else { | 
|---|
| 4206 | # snag some arguments that will either fall through or be overwritten to save some code duplication | 
|---|
| 4207 | my $tmpid = $args{id}; | 
|---|
| 4208 | my $type = $args{type}; | 
|---|
| 4209 | if ($type eq 'record' && $args{defrec} eq 'n') { | 
|---|
| 4210 | # Live records go through the records table first. | 
|---|
| 4211 | ($tmpid) = $dbh->selectrow_array("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id'). | 
|---|
| 4212 | " FROM records WHERE record_id = ?", | 
|---|
| 4213 | undef, ($args{id}) ) or return; | 
|---|
| 4214 | $type = ($args{revrec} eq 'n' ? 'domain' : 'revzone'); | 
|---|
| 4215 | } | 
|---|
| 4216 | my ($result) = $dbh->selectrow_array("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?", | 
|---|
| 4217 | undef, ($tmpid) ); | 
|---|
| 4218 | return $result; | 
|---|
| 4219 | } | 
|---|
| 4220 | # should be impossible to get here with even remotely sane arguments | 
|---|
| 4221 | return; | 
|---|
| 4222 | } # end parentID() | 
|---|
| 4223 |  | 
|---|
| 4224 |  | 
|---|
| 4225 | ## DNSDB::isParent() | 
|---|
| 4226 | # Returns true if $id1 is a parent of $id2, false otherwise | 
|---|
| 4227 | sub isParent { | 
|---|
| 4228 | my $self = shift; | 
|---|
| 4229 | my $dbh = $self->{dbh}; | 
|---|
| 4230 | my $id1 = shift; | 
|---|
| 4231 | my $type1 = shift; | 
|---|
| 4232 | my $id2 = shift; | 
|---|
| 4233 | my $type2 = shift; | 
|---|
| 4234 | ##todo:  immediate, secondary, full (default) | 
|---|
| 4235 |  | 
|---|
| 4236 | # Return false on invalid types | 
|---|
| 4237 | return 0 if !grep /^$type1$/, ('record','defrec','defrevrec','user','domain','revzone','group'); | 
|---|
| 4238 | return 0 if !grep /^$type2$/, ('record','defrec','defrevrec','user','domain','revzone','group'); | 
|---|
| 4239 |  | 
|---|
| 4240 | # Return false on impossible relations | 
|---|
| 4241 | return 0 if $type1 eq 'record';       # nothing may be a child of a record | 
|---|
| 4242 | return 0 if $type1 eq 'defrec';       # nothing may be a child of a record | 
|---|
| 4243 | return 0 if $type1 eq 'defrevrec';    # nothing may be a child of a record | 
|---|
| 4244 | return 0 if $type1 eq 'user';         # nothing may be child of a user | 
|---|
| 4245 | return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record | 
|---|
| 4246 | return 0 if $type1 eq 'revzone' && $type2 ne 'record';# reverse zone may not be a parent of anything other than a record | 
|---|
| 4247 |  | 
|---|
| 4248 | # ennnhhhh....  if we're passed an id of 0, it will never be found.  usual | 
|---|
| 4249 | # case would be the UI creating a new <thing>, and so we don't have an ID for | 
|---|
| 4250 | # <thing> to look up yet.  in that case the UI should check the parent as well. | 
|---|
| 4251 | return 0 if $id1 == 0;        # nothing can have a parent id of 0 | 
|---|
| 4252 | return 1 if $id2 == 0;        # anything could have a child id of 0 (or "unknown") | 
|---|
| 4253 |  | 
|---|
| 4254 | # group 1 is the ultimate root parent | 
|---|
| 4255 | return 1 if $type1 eq 'group' && $id1 == 1; | 
|---|
| 4256 |  | 
|---|
| 4257 | # groups are always (a) parent of themselves | 
|---|
| 4258 | return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2; | 
|---|
| 4259 |  | 
|---|
| 4260 | my $id = $id2; | 
|---|
| 4261 | my $type = $type2; | 
|---|
| 4262 | my $foundparent = 0; | 
|---|
| 4263 |  | 
|---|
| 4264 | # Records are the only entity with two possible parents.  We need to split the parent checks on | 
|---|
| 4265 | # domain/rdns. | 
|---|
| 4266 | if ($type eq 'record') { | 
|---|
| 4267 | my ($dom,$rdns) = $dbh->selectrow_array("SELECT domain_id,rdns_id FROM records WHERE record_id=?", | 
|---|
| 4268 | undef, ($id)); | 
|---|
| 4269 | # check immediate parent against request | 
|---|
| 4270 | return 1 if $type1 eq 'domain' && $id1 == $dom; | 
|---|
| 4271 | return 1 if $type1 eq 'revzone' && $id1 == $rdns; | 
|---|
| 4272 | # if request is group, check *both* parents.  Only check if the parent is nonzero though. | 
|---|
| 4273 | return 1 if $dom && $self->isParent($id1, $type1, $dom, 'domain'); | 
|---|
| 4274 | return 1 if $rdns && $self->isParent($id1, $type1, $rdns, 'revzone'); | 
|---|
| 4275 | # exit here since we've executed the loop below by proxy in the above recursive calls. | 
|---|
| 4276 | return 0; | 
|---|
| 4277 | } | 
|---|
| 4278 |  | 
|---|
| 4279 | # almost the same loop as getParents() above | 
|---|
| 4280 | my $limiter = 0; | 
|---|
| 4281 | while (1) { | 
|---|
| 4282 | my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?"; | 
|---|
| 4283 | my $result = $dbh->selectrow_hashref($sql, | 
|---|
| 4284 | undef, ($id) ); | 
|---|
| 4285 | if (!$result) { | 
|---|
| 4286 | $limiter++; | 
|---|
| 4287 | ##fixme:  how often will this happen on a live site?  fail at max limiter <n>? | 
|---|
| 4288 | warn "no results looking for $sql with id $id (depth $limiter)\n"; | 
|---|
| 4289 | last; | 
|---|
| 4290 | } | 
|---|
| 4291 | if ($result && $result->{$par_col{$type}} == $id1) { | 
|---|
| 4292 | $foundparent = 1; | 
|---|
| 4293 | last; | 
|---|
| 4294 | } else { | 
|---|
| 4295 | ##fixme: do we care about trying to return a "no such record/domain/user/group" error? | 
|---|
| 4296 | # should be impossible to create an inconsistent DB just with API calls. | 
|---|
| 4297 | warn $dbh->errstr." $sql, $id" if $dbh->errstr; | 
|---|
| 4298 | } | 
|---|
| 4299 | # group 1 is its own parent.  need this here more to break strange loops than for detecting a parent | 
|---|
| 4300 | last if $result->{$par_col{$type}} == 1; | 
|---|
| 4301 | $id = $result->{$par_col{$type}}; | 
|---|
| 4302 | $type = $par_type{$type}; | 
|---|
| 4303 | } | 
|---|
| 4304 |  | 
|---|
| 4305 | return $foundparent; | 
|---|
| 4306 | } # end isParent() | 
|---|
| 4307 |  | 
|---|
| 4308 |  | 
|---|
| 4309 | ## DNSDB::zoneStatus() | 
|---|
| 4310 | # Returns and optionally sets a zone's status | 
|---|
| 4311 | # Takes a database handle, domain/revzone ID, forward/reverse flag, and optionally a status argument | 
|---|
| 4312 | # Returns status, or undef on errors. | 
|---|
| 4313 | sub zoneStatus { | 
|---|
| 4314 | my $self = shift; | 
|---|
| 4315 | my $dbh = $self->{dbh}; | 
|---|
| 4316 | my $id = shift; | 
|---|
| 4317 | my $revrec = shift; | 
|---|
| 4318 | my $newstatus = shift || 'mu'; | 
|---|
| 4319 |  | 
|---|
| 4320 | return undef if $id !~ /^\d+$/; | 
|---|
| 4321 |  | 
|---|
| 4322 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 4323 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 4324 | local $dbh->{AutoCommit} = 0; | 
|---|
| 4325 | local $dbh->{RaiseError} = 1; | 
|---|
| 4326 |  | 
|---|
| 4327 | if ($newstatus ne 'mu') { | 
|---|
| 4328 | # ooo, fun!  let's see what we were passed for status | 
|---|
| 4329 | eval { | 
|---|
| 4330 | $newstatus = 0 if $newstatus eq 'domoff'; | 
|---|
| 4331 | $newstatus = 1 if $newstatus eq 'domon'; | 
|---|
| 4332 | $dbh->do("UPDATE ".($revrec eq 'n' ? 'domains' : 'revzones')." SET status=? WHERE ". | 
|---|
| 4333 | ($revrec eq 'n' ? 'domain_id' : 'rdns_id')."=?", undef, ($newstatus,$id) ); | 
|---|
| 4334 |  | 
|---|
| 4335 | ##fixme  switch to more consise "Enabled <domain"/"Disabled <domain>" as with users? | 
|---|
| 4336 | $resultstr = "Changed ".($revrec eq 'n' ? $self->domainName($id) : $self->revName($id)). | 
|---|
| 4337 | " state to ".($newstatus ? 'active' : 'inactive'); | 
|---|
| 4338 |  | 
|---|
| 4339 | my %loghash; | 
|---|
| 4340 | $loghash{domain_id} = $id if $revrec eq 'n'; | 
|---|
| 4341 | $loghash{rdns_id} = $id if $revrec eq 'y'; | 
|---|
| 4342 | $loghash{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec); | 
|---|
| 4343 | $loghash{entry} = $resultstr; | 
|---|
| 4344 | $self->_log(%loghash); | 
|---|
| 4345 |  | 
|---|
| 4346 | $dbh->commit; | 
|---|
| 4347 | }; | 
|---|
| 4348 | if ($@) { | 
|---|
| 4349 | my $msg = $@; | 
|---|
| 4350 | eval { $dbh->rollback; }; | 
|---|
| 4351 | $resultstr = ''; | 
|---|
| 4352 | $errstr = $msg; | 
|---|
| 4353 | return; | 
|---|
| 4354 | } | 
|---|
| 4355 | } | 
|---|
| 4356 |  | 
|---|
| 4357 | my ($status) = $dbh->selectrow_array("SELECT status FROM ". | 
|---|
| 4358 | ($revrec eq 'n' ? "domains WHERE domain_id=?" : "revzones WHERE rdns_id=?"), | 
|---|
| 4359 | undef, ($id) ); | 
|---|
| 4360 | return $status; | 
|---|
| 4361 | } # end zoneStatus() | 
|---|
| 4362 |  | 
|---|
| 4363 |  | 
|---|
| 4364 | ## DNSDB::getZonesByCIDR() | 
|---|
| 4365 | # Get a list of zone names and IDs that records for a passed CIDR block are within. | 
|---|
| 4366 | sub getZonesByCIDR { | 
|---|
| 4367 | my $self = shift; | 
|---|
| 4368 | my $dbh = $self->{dbh}; | 
|---|
| 4369 | my %args = @_; | 
|---|
| 4370 |  | 
|---|
| 4371 | my $result = $dbh->selectall_arrayref("SELECT rdns_id,revnet FROM revzones WHERE revnet >>= ? OR revnet <<= ?", | 
|---|
| 4372 | { Slice => {} }, ($args{cidr}, $args{cidr}) ); | 
|---|
| 4373 | return $result; | 
|---|
| 4374 | } # end getZonesByCIDR() | 
|---|
| 4375 |  | 
|---|
| 4376 |  | 
|---|
| 4377 | ## DNSDB::importAXFR | 
|---|
| 4378 | # Import a domain via AXFR | 
|---|
| 4379 | # Takes AXFR host, domain to transfer, group to put the domain in, | 
|---|
| 4380 | # and an optional hash containing: | 
|---|
| 4381 | #  status - active/inactive state flag (defaults to active) | 
|---|
| 4382 | #  rwsoa - overwrite-SOA flag (defaults to off) | 
|---|
| 4383 | #  rwns - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records) | 
|---|
| 4384 | #  merge - flag to automerge A or AAAA records with matching PTR records | 
|---|
| 4385 | # Returns a status code (OK, WARN, or FAIL) and message - message should be blank | 
|---|
| 4386 | # if status is OK, but WARN includes conditions that are not fatal but should | 
|---|
| 4387 | # really be reported. | 
|---|
| 4388 | sub importAXFR { | 
|---|
| 4389 | my $self = shift; | 
|---|
| 4390 | my $dbh = $self->{dbh}; | 
|---|
| 4391 | my $ifrom_in = shift; | 
|---|
| 4392 | my $zone = shift; | 
|---|
| 4393 | my $group = shift; | 
|---|
| 4394 |  | 
|---|
| 4395 | my %args = @_; | 
|---|
| 4396 |  | 
|---|
| 4397 | ##fixme:  add mode to delete&replace, merge+overwrite, merge new? | 
|---|
| 4398 |  | 
|---|
| 4399 | $args{status} = (defined($args{status}) ? $args{status} : 0); | 
|---|
| 4400 | $args{status} = 1 if $args{status} eq 'on'; | 
|---|
| 4401 |  | 
|---|
| 4402 | my $nrecs = 0; | 
|---|
| 4403 | my $soaflag = 0; | 
|---|
| 4404 | my $nsflag = 0; | 
|---|
| 4405 | my $warnmsg = ''; | 
|---|
| 4406 | my $ifrom; | 
|---|
| 4407 |  | 
|---|
| 4408 | my $rev = 'n'; | 
|---|
| 4409 | my $code = 'OK'; | 
|---|
| 4410 | my $msg = 'foobar?'; | 
|---|
| 4411 |  | 
|---|
| 4412 | # choke on possible bad setting in ifrom | 
|---|
| 4413 | # IPv4 and v6, and valid hostnames! | 
|---|
| 4414 | ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i); | 
|---|
| 4415 | return ('FAIL', "Bad AXFR source host $ifrom") | 
|---|
| 4416 | unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i); | 
|---|
| 4417 |  | 
|---|
| 4418 | my $errmsg; | 
|---|
| 4419 |  | 
|---|
| 4420 | my $zone_id; | 
|---|
| 4421 | my $domain_id = 0; | 
|---|
| 4422 | my $rdns_id = 0; | 
|---|
| 4423 | my $cidr; | 
|---|
| 4424 |  | 
|---|
| 4425 | # magic happens!  detect if we're importing a domain or a reverse zone | 
|---|
| 4426 | # while we're at it, figure out what the CIDR netblock is (if we got a .arpa) | 
|---|
| 4427 | # or what the formal .arpa zone is (if we got a CIDR netblock) | 
|---|
| 4428 | # Handles sub-octet v4 zones in the format specified in the Cricket Book, 2nd Ed, p217-218 | 
|---|
| 4429 |  | 
|---|
| 4430 | if ($zone =~ m{(?:\.arpa\.?|/\d+)$}) { | 
|---|
| 4431 | # we seem to have a reverse zone | 
|---|
| 4432 | $rev = 'y'; | 
|---|
| 4433 |  | 
|---|
| 4434 | if ($zone =~ /\.arpa\.?$/) { | 
|---|
| 4435 | # we have a formal reverse zone.  call _zone2cidr and get the CIDR block. | 
|---|
| 4436 | ($code,$msg) = _zone2cidr($zone); | 
|---|
| 4437 | return ($code, $msg) if $code eq 'FAIL'; | 
|---|
| 4438 | $cidr = $msg; | 
|---|
| 4439 | } elsif ($zone =~ m|^[\d.]+/\d+$|) { | 
|---|
| 4440 | # v4 revzone, CIDR netblock | 
|---|
| 4441 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block"); | 
|---|
| 4442 | $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.'); | 
|---|
| 4443 | } elsif ($zone =~ m|^[a-fA-F\d:]+/\d+$|) { | 
|---|
| 4444 | # v6 revzone, CIDR netblock | 
|---|
| 4445 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block"); | 
|---|
| 4446 | return ('FAIL', "$zone is not a nibble-aligned block") if $cidr->masklen % 4 != 0; | 
|---|
| 4447 | $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.'); | 
|---|
| 4448 | } else { | 
|---|
| 4449 | # there is. no. else! | 
|---|
| 4450 | return ('FAIL', "Unknown zone name format"); | 
|---|
| 4451 | } | 
|---|
| 4452 |  | 
|---|
| 4453 | # quick check to start to see if we've already got one | 
|---|
| 4454 |  | 
|---|
| 4455 | ($zone_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", | 
|---|
| 4456 | undef, ("$cidr")); | 
|---|
| 4457 | $rdns_id = $zone_id; | 
|---|
| 4458 | } else { | 
|---|
| 4459 | # default to domain | 
|---|
| 4460 | ($zone_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)", | 
|---|
| 4461 | undef, ($zone)); | 
|---|
| 4462 | $domain_id = $zone_id; | 
|---|
| 4463 | } | 
|---|
| 4464 |  | 
|---|
| 4465 | return ('FAIL', ($rev eq 'n' ? 'Domain' : 'Reverse zone')." already exists") if $zone_id; | 
|---|
| 4466 |  | 
|---|
| 4467 | # little local utility sub to swap $val and $host for revzone records. | 
|---|
| 4468 | sub _revswap { | 
|---|
| 4469 | my $rechost = shift; | 
|---|
| 4470 | my $recdata = shift; | 
|---|
| 4471 |  | 
|---|
| 4472 | if ($rechost =~ /\.in-addr\.arpa\.?$/) { | 
|---|
| 4473 | $rechost =~ s/\.in-addr\.arpa\.?$//; | 
|---|
| 4474 | $rechost = join '.', reverse split /\./, $rechost; | 
|---|
| 4475 | } else { | 
|---|
| 4476 | $rechost =~ s/\.ip6\.arpa\.?$//; | 
|---|
| 4477 | my @nibs = reverse split /\./, $rechost; | 
|---|
| 4478 | $rechost = ''; | 
|---|
| 4479 | my $nc; | 
|---|
| 4480 | foreach (@nibs) { | 
|---|
| 4481 | $rechost.= $_; | 
|---|
| 4482 | $rechost .= ":" if ++$nc % 4 == 0 && $nc < 32; | 
|---|
| 4483 | } | 
|---|
| 4484 | $rechost .= ":" if $nc < 32 && $rechost !~ /\*$/; # close netblock records? | 
|---|
| 4485 | ##fixme:  there's a case that ends up with a partial entry here: | 
|---|
| 4486 | # ip:add:re:ss:: | 
|---|
| 4487 | # can't reproduce after letting it sit overnight after discovery.  :( | 
|---|
| 4488 | #print "$rechost\n"; | 
|---|
| 4489 | # canonicalize with NetAddr::IP | 
|---|
| 4490 | $rechost = NetAddr::IP->new($rechost)->addr unless $rechost =~ /\*$/; | 
|---|
| 4491 | } | 
|---|
| 4492 | return ($recdata,$rechost) | 
|---|
| 4493 | } | 
|---|
| 4494 |  | 
|---|
| 4495 |  | 
|---|
| 4496 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 4497 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 4498 | local $dbh->{AutoCommit} = 0; | 
|---|
| 4499 | local $dbh->{RaiseError} = 1; | 
|---|
| 4500 |  | 
|---|
| 4501 | my $sth; | 
|---|
| 4502 | eval { | 
|---|
| 4503 |  | 
|---|
| 4504 | if ($rev eq 'n') { | 
|---|
| 4505 | ##fixme:  serial | 
|---|
| 4506 | $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef, | 
|---|
| 4507 | ($zone, $group, $args{status}) ); | 
|---|
| 4508 | # get domain id so we can do the records | 
|---|
| 4509 | ($zone_id) = $dbh->selectrow_array("SELECT currval('domains_domain_id_seq')"); | 
|---|
| 4510 | $domain_id = $zone_id; | 
|---|
| 4511 | $self->_log(group_id => $group, domain_id => $domain_id, | 
|---|
| 4512 | entry => "[Added ".($args{status} ? 'active' : 'inactive')." domain $zone via AXFR]"); | 
|---|
| 4513 | } else { | 
|---|
| 4514 | ##fixme:  serial | 
|---|
| 4515 | $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef, | 
|---|
| 4516 | ($cidr,$group,$args{status}) ); | 
|---|
| 4517 | # get revzone id so we can do the records | 
|---|
| 4518 | ($zone_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')"); | 
|---|
| 4519 | $rdns_id = $zone_id; | 
|---|
| 4520 | $self->_log(group_id => $group, rdns_id => $rdns_id, | 
|---|
| 4521 | entry => "[Added ".($args{status} ? 'active' : 'inactive')." reverse zone $cidr via AXFR]"); | 
|---|
| 4522 | } | 
|---|
| 4523 |  | 
|---|
| 4524 | ## bizarre DBI<->Net::DNS interaction bug: | 
|---|
| 4525 | ## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while() | 
|---|
| 4526 | ## fixed, apparently I was doing *something* odd, but not certain what it was that | 
|---|
| 4527 | ## caused a commit instead of barfing | 
|---|
| 4528 |  | 
|---|
| 4529 | my $res = Net::DNS::Resolver->new; | 
|---|
| 4530 | $res->nameservers($ifrom); | 
|---|
| 4531 | $res->axfr_start($zone) | 
|---|
| 4532 | or die "Couldn't begin AXFR\n"; | 
|---|
| 4533 |  | 
|---|
| 4534 | $sth = $dbh->prepare("INSERT INTO records (domain_id,rdns_id,host,type,val,distance,weight,port,ttl)". | 
|---|
| 4535 | " VALUES (?,?,?,?,?,?,?,?,?)"); | 
|---|
| 4536 |  | 
|---|
| 4537 | # Stash info about sub-octet v4 revzones here so we don't have | 
|---|
| 4538 | # to store the CNAMEs used to delegate a suboctet zone | 
|---|
| 4539 | # $suboct{zone}{ns}[] -> array of nameservers | 
|---|
| 4540 | # $suboct{zone}{cname}[] -> array of extant CNAMEs (Just In Case someone did something bizarre) | 
|---|
| 4541 | ## commented pending actual use of this data.  for now, we'll just | 
|---|
| 4542 | ## auto-(re)create the CNAMEs in revzones on export | 
|---|
| 4543 | #    my %suboct; | 
|---|
| 4544 |  | 
|---|
| 4545 | while (my $rr = $res->axfr_next()) { | 
|---|
| 4546 |  | 
|---|
| 4547 | my $val; | 
|---|
| 4548 | my $distance = 0; | 
|---|
| 4549 | my $weight = 0; | 
|---|
| 4550 | my $port = 0; | 
|---|
| 4551 | my $logfrag = ''; | 
|---|
| 4552 |  | 
|---|
| 4553 | my $type = $rr->type; | 
|---|
| 4554 | my $host = $rr->name; | 
|---|
| 4555 | my $ttl = ($args{newttl} ? $args{newttl} : $rr->ttl);     # allow force-override TTLs | 
|---|
| 4556 |  | 
|---|
| 4557 | $soaflag = 1 if $type eq 'SOA'; | 
|---|
| 4558 | $nsflag = 1 if $type eq 'NS'; | 
|---|
| 4559 |  | 
|---|
| 4560 | # "Primary" types: | 
|---|
| 4561 | # A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF | 
|---|
| 4562 | # maybe KEY | 
|---|
| 4563 |  | 
|---|
| 4564 | # BIND supports: | 
|---|
| 4565 | # [standard] | 
|---|
| 4566 | # A AAAA CNAME MX NS PTR SOA TXT | 
|---|
| 4567 | # [variously experimental, obsolete, or obscure] | 
|---|
| 4568 | # 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 | 
|---|
| 4569 | # ... if one can ever find the right magic to format them correctly | 
|---|
| 4570 |  | 
|---|
| 4571 | # Net::DNS supports: | 
|---|
| 4572 | # RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO | 
|---|
| 4573 | # EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY | 
|---|
| 4574 | # DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem | 
|---|
| 4575 |  | 
|---|
| 4576 | # nasty big ugly case-like thing here, since we have to do *some* different | 
|---|
| 4577 | # processing depending on the record.  le sigh. | 
|---|
| 4578 |  | 
|---|
| 4579 | ##fixme:  what record types other than TXT can/will have >255-byte payloads? | 
|---|
| 4580 |  | 
|---|
| 4581 | if ($type eq 'A') { | 
|---|
| 4582 | $val = $rr->address; | 
|---|
| 4583 | } elsif ($type eq 'NS') { | 
|---|
| 4584 | # hmm.  should we warn here if subdomain NS'es are left alone? | 
|---|
| 4585 | next if ($args{rwns} && ($rr->name eq $zone)); | 
|---|
| 4586 | if ($rev eq 'y') { | 
|---|
| 4587 | # revzones have records more or less reversed from forward zones. | 
|---|
| 4588 | my ($tmpcode,$tmpmsg) = _zone2cidr($host); | 
|---|
| 4589 | die "Error converting NS record: $tmpmsg\n" if $tmpcode eq 'FAIL';    # hmm.  may not make sense... | 
|---|
| 4590 | $val = "$tmpmsg"; | 
|---|
| 4591 | $host = $rr->nsdname; | 
|---|
| 4592 | $logfrag = "Added record '$val $type $host', TTL $ttl"; | 
|---|
| 4593 | # Tag and preserve.  For now this is commented for a no-op, but we have Ideas for | 
|---|
| 4594 | # another custom storage type ("DELEGATE") that will use these subzone-delegation records | 
|---|
| 4595 | #if ($val ne "$cidr") { | 
|---|
| 4596 | #  push @{$suboct{$val}{ns}}, $host; | 
|---|
| 4597 | #} | 
|---|
| 4598 | } else { | 
|---|
| 4599 | $val = $rr->nsdname; | 
|---|
| 4600 | } | 
|---|
| 4601 | $nsflag = 1; | 
|---|
| 4602 | } elsif ($type eq 'CNAME') { | 
|---|
| 4603 | if ($rev eq 'y') { | 
|---|
| 4604 | # hmm.  do we even want to bother with storing these at this level?  Sub-octet delegation | 
|---|
| 4605 | # by CNAME is essentially a record-publication hack, and we want to just represent the | 
|---|
| 4606 | # "true" logical intentions as far down the stack as we can from the UI. | 
|---|
| 4607 | ($host,$val) = _revswap($host,$rr->cname); | 
|---|
| 4608 | $logfrag = "Added record '$val $type $host', TTL $ttl"; | 
|---|
| 4609 | # Tag and preserve in case we want to commit them as-is later, but mostly we don't care. | 
|---|
| 4610 | # Commented pending actually doing something with possibly new type DELEGATE | 
|---|
| 4611 | #my $tmprev = $host; | 
|---|
| 4612 | #$tmprev =~ s/^\d+\.//; | 
|---|
| 4613 | #($code,$tmprev) = _zone2cidr($tmprev); | 
|---|
| 4614 | #push @{$suboct{"$tmprev"}{cname}}, $val; | 
|---|
| 4615 | # Silently skip CNAMEs in revzones. | 
|---|
| 4616 | next; | 
|---|
| 4617 | } else { | 
|---|
| 4618 | $val = $rr->cname; | 
|---|
| 4619 | } | 
|---|
| 4620 | } elsif ($type eq 'SOA') { | 
|---|
| 4621 | next if $args{rwsoa}; | 
|---|
| 4622 | $host = $rr->rname.":".$rr->mname; | 
|---|
| 4623 | $val = $rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum; | 
|---|
| 4624 | $soaflag = 1; | 
|---|
| 4625 | } elsif ($type eq 'PTR') { | 
|---|
| 4626 | ($host,$val) = _revswap($host,$rr->ptrdname); | 
|---|
| 4627 | $logfrag = "Added record '$val $type $host', TTL $ttl"; | 
|---|
| 4628 | # hmm.  PTR records should not be in forward zones. | 
|---|
| 4629 | } elsif ($type eq 'MX') { | 
|---|
| 4630 | $val = $rr->exchange; | 
|---|
| 4631 | $distance = $rr->preference; | 
|---|
| 4632 | } elsif ($type eq 'TXT') { | 
|---|
| 4633 | ##fixme:  Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(), | 
|---|
| 4634 | ## but don't really seem enthusiastic about it. | 
|---|
| 4635 | #print "should use rdatastr:\n\t".$rr->rdatastr."\n  or char_str_list:\n\t".join(' ',$rr->char_str_list())."\n"; | 
|---|
| 4636 | # rdatastr returns a BIND-targetted logical string, including opening and closing quotes | 
|---|
| 4637 | # char_str_list returns a list of the individual string fragments in the record | 
|---|
| 4638 | # txtdata returns the more useful all-in-one form (since we want to push such protocol | 
|---|
| 4639 | # details as far down the stack as we can) | 
|---|
| 4640 | # NB:  this may turn out to be more troublesome if we ever have need of >512-byte TXT records. | 
|---|
| 4641 | if ($rev eq 'y') { | 
|---|
| 4642 | ($host,$val) = _revswap($host,$rr->txtdata); | 
|---|
| 4643 | $logfrag = "Added record '$val $type $host', TTL $ttl"; | 
|---|
| 4644 | } else { | 
|---|
| 4645 | $val = $rr->txtdata; | 
|---|
| 4646 | } | 
|---|
| 4647 | } elsif ($type eq 'SPF') { | 
|---|
| 4648 | ##fixme: and the same caveat here, since it is apparently a clone of ::TXT | 
|---|
| 4649 | $val = $rr->txtdata; | 
|---|
| 4650 | } elsif ($type eq 'AAAA') { | 
|---|
| 4651 | $val = $rr->address; | 
|---|
| 4652 | } elsif ($type eq 'SRV') { | 
|---|
| 4653 | $val = $rr->target; | 
|---|
| 4654 | $distance = $rr->priority; | 
|---|
| 4655 | $weight = $rr->weight; | 
|---|
| 4656 | $port = $rr->port; | 
|---|
| 4657 | } elsif ($type eq 'KEY') { | 
|---|
| 4658 | # we don't actually know what to do with these... | 
|---|
| 4659 | $val = $rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname; | 
|---|
| 4660 | } else { | 
|---|
| 4661 | $val = $rr->rdatastr; | 
|---|
| 4662 | # Finding a different record type is not fatal.... just problematic. | 
|---|
| 4663 | # We may not be able to export it correctly. | 
|---|
| 4664 | $warnmsg .= "Unusual record ".$rr->name." ($type) found\n"; | 
|---|
| 4665 | } | 
|---|
| 4666 |  | 
|---|
| 4667 | my $logentry = "[AXFR ".($rev eq 'n' ? $zone : $cidr)."] "; | 
|---|
| 4668 |  | 
|---|
| 4669 | if ($args{merge}) { | 
|---|
| 4670 | if ($rev eq 'n') { | 
|---|
| 4671 | # importing a domain;  we have A and AAAA records that could be merged with matching PTR records | 
|---|
| 4672 | my $etype; | 
|---|
| 4673 | my ($erdns,$erid,$ettl) = $dbh->selectrow_array("SELECT rdns_id,record_id,ttl FROM records ". | 
|---|
| 4674 | "WHERE host=? AND val=? AND type=12", | 
|---|
| 4675 | undef, ($host, $val) ); | 
|---|
| 4676 | if ($erid) { | 
|---|
| 4677 | if ($type eq 'A') { # PTR -> A+PTR | 
|---|
| 4678 | $etype = 65280; | 
|---|
| 4679 | $logentry .= "Merged A record with existing PTR record '$host A+PTR $val', TTL $ettl"; | 
|---|
| 4680 | } | 
|---|
| 4681 | if ($type eq 'AAAA') {      # PTR -> AAAA+PTR | 
|---|
| 4682 | $etype = 65281; | 
|---|
| 4683 | $logentry .= "Merged AAAA record with existing PTR record '$host AAAA+PTR $val', TTL $ettl"; | 
|---|
| 4684 | } | 
|---|
| 4685 | $ettl = ($ettl < $ttl ? $ettl : $ttl);    # use lower TTL | 
|---|
| 4686 | $dbh->do("UPDATE records SET domain_id=?,ttl=?,type=? WHERE record_id=?", undef, | 
|---|
| 4687 | ($domain_id, $ettl, $etype, $erid)); | 
|---|
| 4688 | $nrecs++; | 
|---|
| 4689 | $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $erdns, entry => $logentry); | 
|---|
| 4690 | next;       # while axfr_next | 
|---|
| 4691 | } | 
|---|
| 4692 | } # $rev eq 'n' | 
|---|
| 4693 | else { | 
|---|
| 4694 | # importing a revzone, we have PTR records that could be merged with matching A/AAAA records | 
|---|
| 4695 | my ($domid,$erid,$ettl,$etype) = $dbh->selectrow_array("SELECT domain_id,record_id,ttl,type FROM records ". | 
|---|
| 4696 | "WHERE host=? AND val=? AND (type=1 OR type=28)", | 
|---|
| 4697 | undef, ($host, $val) ); | 
|---|
| 4698 | if ($erid) { | 
|---|
| 4699 | if ($etype == 1) {  # A -> A+PTR | 
|---|
| 4700 | $etype = 65280; | 
|---|
| 4701 | $logentry .= "Merged PTR record with existing matching A record '$host A+PTR $val', TTL $ettl"; | 
|---|
| 4702 | } | 
|---|
| 4703 | if ($etype == 28) { # AAAA -> AAAA+PTR | 
|---|
| 4704 | $etype = 65281; | 
|---|
| 4705 | $logentry .= "Merged PTR record with existing matching AAAA record '$host AAAA+PTR $val', TTL $ettl"; | 
|---|
| 4706 | } | 
|---|
| 4707 | $ettl = ($ettl < $ttl ? $ettl : $ttl);    # use lower TTL | 
|---|
| 4708 | $dbh->do("UPDATE records SET rdns_id=?,ttl=?,type=? WHERE record_id=?", undef, | 
|---|
| 4709 | ($rdns_id, $ettl, $etype, $erid)); | 
|---|
| 4710 | $nrecs++; | 
|---|
| 4711 | $self->_log(group_id => $group, domain_id => $domid, rdns_id => $rdns_id, entry => $logentry); | 
|---|
| 4712 | next;       # while axfr_next | 
|---|
| 4713 | } | 
|---|
| 4714 | } # $rev eq 'y' | 
|---|
| 4715 | } # if $args{merge} | 
|---|
| 4716 |  | 
|---|
| 4717 | # Insert the new record | 
|---|
| 4718 | $sth->execute($domain_id, $rdns_id, $host, $reverse_typemap{$type}, $val, | 
|---|
| 4719 | $distance, $weight, $port, $ttl); | 
|---|
| 4720 |  | 
|---|
| 4721 | $nrecs++; | 
|---|
| 4722 |  | 
|---|
| 4723 | if ($type eq 'SOA') { | 
|---|
| 4724 | # also !$args{rwsoa}, but if that's set, it should be impossible to get here. | 
|---|
| 4725 | my @tmp1 = split /:/, $host; | 
|---|
| 4726 | my @tmp2 = split /:/, $val; | 
|---|
| 4727 | $logentry .= "Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ". | 
|---|
| 4728 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"; | 
|---|
| 4729 | } elsif ($logfrag) { | 
|---|
| 4730 | # special case for log entries we need to meddle with a little. | 
|---|
| 4731 | $logentry .= $logfrag; | 
|---|
| 4732 | } else { | 
|---|
| 4733 | $logentry .= "Added record '$host $type"; | 
|---|
| 4734 | $logentry .= " [distance $distance]" if $type eq 'MX'; | 
|---|
| 4735 | $logentry .= " [priority $distance] [weight $weight] [port $port]" if $type eq 'SRV'; | 
|---|
| 4736 | $logentry .= " $val', TTL $ttl"; | 
|---|
| 4737 | } | 
|---|
| 4738 | $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $rdns_id, entry => $logentry); | 
|---|
| 4739 |  | 
|---|
| 4740 | } # while axfr_next | 
|---|
| 4741 |  | 
|---|
| 4742 | # Detect and handle delegated subzones | 
|---|
| 4743 | # Placeholder for when we decide what to actually do with this, see previous comments in NS and CNAME handling. | 
|---|
| 4744 | #foreach (keys %suboct) { | 
|---|
| 4745 | #  print "found ".($suboct{$_}{ns} ? @{$suboct{$_}{ns}} : '0')." NS records and ". | 
|---|
| 4746 | #       ($suboct{$_}{cname} ? @{$suboct{$_}{cname}} : '0')." CNAMEs for $_\n"; | 
|---|
| 4747 | #} | 
|---|
| 4748 |  | 
|---|
| 4749 | # Overwrite SOA record | 
|---|
| 4750 | if ($args{rwsoa}) { | 
|---|
| 4751 | $soaflag = 1; | 
|---|
| 4752 | my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?"); | 
|---|
| 4753 | my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)"); | 
|---|
| 4754 | $sthgetsoa->execute($group,$reverse_typemap{SOA}); | 
|---|
| 4755 | while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) { | 
|---|
| 4756 | $host =~ s/DOMAIN/$zone/g; | 
|---|
| 4757 | $val =~ s/DOMAIN/$zone/g; | 
|---|
| 4758 | $sthputsoa->execute($zone_id,$host,$reverse_typemap{SOA},$val,$ttl); | 
|---|
| 4759 | } | 
|---|
| 4760 | } | 
|---|
| 4761 |  | 
|---|
| 4762 | # Overwrite NS records | 
|---|
| 4763 | if ($args{rwns}) { | 
|---|
| 4764 | $nsflag = 1; | 
|---|
| 4765 | my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?"); | 
|---|
| 4766 | my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)"); | 
|---|
| 4767 | $sthgetns->execute($group,$reverse_typemap{NS}); | 
|---|
| 4768 | while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) { | 
|---|
| 4769 | $host =~ s/DOMAIN/$zone/g; | 
|---|
| 4770 | $val =~ s/DOMAIN/$zone/g; | 
|---|
| 4771 | $sthputns->execute($zone_id,$host,$reverse_typemap{NS},$val,$ttl); | 
|---|
| 4772 | } | 
|---|
| 4773 | } | 
|---|
| 4774 |  | 
|---|
| 4775 | die "No records found;  either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs; | 
|---|
| 4776 | die "Bad zone:  No SOA record!\n" if !$soaflag; | 
|---|
| 4777 | die "Bad zone:  No NS records!\n" if !$nsflag; | 
|---|
| 4778 |  | 
|---|
| 4779 | $dbh->commit; | 
|---|
| 4780 |  | 
|---|
| 4781 | }; | 
|---|
| 4782 |  | 
|---|
| 4783 | if ($@) { | 
|---|
| 4784 | my $msg = $@; | 
|---|
| 4785 | eval { $dbh->rollback; }; | 
|---|
| 4786 | return ('FAIL',$msg." $warnmsg"); | 
|---|
| 4787 | } else { | 
|---|
| 4788 | return ('WARN', $warnmsg) if $warnmsg; | 
|---|
| 4789 | return ('OK',"Imported OK"); | 
|---|
| 4790 | } | 
|---|
| 4791 |  | 
|---|
| 4792 | # it should be impossible to get here. | 
|---|
| 4793 | return ('WARN',"OOOK!"); | 
|---|
| 4794 | } # end importAXFR() | 
|---|
| 4795 |  | 
|---|
| 4796 |  | 
|---|
| 4797 | ## DNSDB::importBIND() | 
|---|
| 4798 | sub importBIND { | 
|---|
| 4799 | } # end importBIND() | 
|---|
| 4800 |  | 
|---|
| 4801 |  | 
|---|
| 4802 | ## DNSDB::import_tinydns() | 
|---|
| 4803 | sub import_tinydns { | 
|---|
| 4804 | } # end import_tinydns() | 
|---|
| 4805 |  | 
|---|
| 4806 |  | 
|---|
| 4807 | ## DNSDB::export() | 
|---|
| 4808 | # Export the DNS database, or a part of it | 
|---|
| 4809 | # Takes a string indicating the export type, plus optional arguments depending on type | 
|---|
| 4810 | # Writes zone data to targets as appropriate for type | 
|---|
| 4811 | sub export { | 
|---|
| 4812 | my $self = shift; | 
|---|
| 4813 | my $target = shift; | 
|---|
| 4814 |  | 
|---|
| 4815 | if ($target eq 'tiny') { | 
|---|
| 4816 | $self->__export_tiny(@_); | 
|---|
| 4817 | } | 
|---|
| 4818 | # elsif ($target eq 'foo') { | 
|---|
| 4819 | #   __export_foo(@_); | 
|---|
| 4820 | #} | 
|---|
| 4821 | # etc | 
|---|
| 4822 |  | 
|---|
| 4823 | } # end export() | 
|---|
| 4824 |  | 
|---|
| 4825 |  | 
|---|
| 4826 | ## DNSDB::__export_tiny | 
|---|
| 4827 | # Internal sub to implement tinyDNS (compatible) export | 
|---|
| 4828 | # Takes filehandle to write export to, optional argument(s) | 
|---|
| 4829 | # to determine which data gets exported | 
|---|
| 4830 | sub __export_tiny { | 
|---|
| 4831 | my $self = shift; | 
|---|
| 4832 | my $dbh = $self->{dbh}; | 
|---|
| 4833 | my $datafile = shift; | 
|---|
| 4834 |  | 
|---|
| 4835 | ##fixme: slurp up further options to specify particular zone(s) to export | 
|---|
| 4836 |  | 
|---|
| 4837 | ##fixme: fail if $datafile isn't an open, writable file | 
|---|
| 4838 |  | 
|---|
| 4839 | # easy case - export all evarything | 
|---|
| 4840 | # not-so-easy case - export item(s) specified | 
|---|
| 4841 | # todo:  figure out what kind of list we use to export items | 
|---|
| 4842 |  | 
|---|
| 4843 | # raw packet in unknown format:  first byte indicates length | 
|---|
| 4844 | # of remaining data, allows up to 255 raw bytes | 
|---|
| 4845 |  | 
|---|
| 4846 | # Locations/views - worth including in the caching setup? | 
|---|
| 4847 | my $lochash = $dbh->selectall_hashref("SELECT location,iplist FROM locations", 'location'); | 
|---|
| 4848 | foreach my $location (keys %$lochash) { | 
|---|
| 4849 | foreach my $ipprefix (split /[,\s]+/, $lochash->{$location}{iplist}) { | 
|---|
| 4850 | $ipprefix =~ s/\s+//g; | 
|---|
| 4851 | $ipprefix = new NetAddr::IP $ipprefix; | 
|---|
| 4852 | ##fixme:  how to handle IPv6? | 
|---|
| 4853 | next if $ipprefix->{isv6}; | 
|---|
| 4854 | # have to account for /nn CIDR entries.  tinydns only speaks octet-sliced prefix. | 
|---|
| 4855 | if ($ipprefix->masklen <= 8) { | 
|---|
| 4856 | foreach ($ipprefix->split(8)) { | 
|---|
| 4857 | my $tmp = $_->addr; | 
|---|
| 4858 | $tmp =~ s/\.\d+\.\d+\.\d+$//; | 
|---|
| 4859 | print $datafile "%$location:$tmp\n"; | 
|---|
| 4860 | } | 
|---|
| 4861 | } elsif ($ipprefix->masklen <= 16) { | 
|---|
| 4862 | foreach ($ipprefix->split(16)) { | 
|---|
| 4863 | my $tmp = $_->addr; | 
|---|
| 4864 | $tmp =~ s/\.\d+\.\d+$//; | 
|---|
| 4865 | print $datafile "%$location:$tmp\n"; | 
|---|
| 4866 | } | 
|---|
| 4867 | } elsif ($ipprefix->masklen <= 24) { | 
|---|
| 4868 | foreach ($ipprefix->split(24)) { | 
|---|
| 4869 | my $tmp = $_->addr; | 
|---|
| 4870 | $tmp =~ s/\.\d+$//; | 
|---|
| 4871 | print $datafile "%$location:$tmp\n"; | 
|---|
| 4872 | } | 
|---|
| 4873 | } else { | 
|---|
| 4874 | foreach ($ipprefix->split(32)) { | 
|---|
| 4875 | print $datafile "%$location:".$_->addr."\n"; | 
|---|
| 4876 | } | 
|---|
| 4877 | } | 
|---|
| 4878 | } | 
|---|
| 4879 | print $datafile "%$location\n" if !$lochash->{$location}{iplist}; | 
|---|
| 4880 | } | 
|---|
| 4881 |  | 
|---|
| 4882 | # tracking hash so we don't double-export A+PTR or AAAA+PTR records. | 
|---|
| 4883 | my %recflags; | 
|---|
| 4884 |  | 
|---|
| 4885 | my $domsth = $dbh->prepare("SELECT domain_id,domain,status,changed FROM domains WHERE status=1"); | 
|---|
| 4886 | my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ". | 
|---|
| 4887 | "FROM records WHERE domain_id=? AND type < 65280");     # Just exclude all types relating to rDNS | 
|---|
| 4888 | my $zonesth = $dbh->prepare("UPDATE domains SET changed='n' WHERE domain_id=?"); | 
|---|
| 4889 | $domsth->execute(); | 
|---|
| 4890 | while (my ($domid,$dom,$domstat,$changed) = $domsth->fetchrow_array) { | 
|---|
| 4891 | ##fixme: need to find a way to block opening symlinked files without introducing a race. | 
|---|
| 4892 | #       O_NOFOLLOW | 
|---|
| 4893 | #              If  pathname  is a symbolic link, then the open fails.  This is a FreeBSD extension, which was | 
|---|
| 4894 | #              added to Linux in version 2.1.126.  Symbolic links in earlier components of the pathname  will | 
|---|
| 4895 | #              still be followed. | 
|---|
| 4896 | # but that doesn't help other platforms.  :/ | 
|---|
| 4897 | sysopen(ZONECACHE, "$self->{exportcache}/$dom", O_RDWR|O_CREAT); | 
|---|
| 4898 | flock(ZONECACHE, LOCK_EX); | 
|---|
| 4899 | if ($changed || -s "$self->{exportcache}/$dom" == 0) { | 
|---|
| 4900 | $recsth->execute($domid); | 
|---|
| 4901 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc) = $recsth->fetchrow_array) { | 
|---|
| 4902 | next if $recflags{$recid}; | 
|---|
| 4903 |  | 
|---|
| 4904 | $loc = '' if !$loc;     # de-nullify - just in case | 
|---|
| 4905 | ##fixme:  handle case of record-with-location-that-doesn't-exist better. | 
|---|
| 4906 | # note this currently fails safe (tested) - records with a location that | 
|---|
| 4907 | # doesn't exist will not be sent to any client | 
|---|
| 4908 | #       $loc = '' if !$lochash->{$loc}; | 
|---|
| 4909 |  | 
|---|
| 4910 | ##fixme:  record validity timestamp. tinydns supports fiddling with timestamps. | 
|---|
| 4911 | # note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps. | 
|---|
| 4912 | # timestamps are TAI64 | 
|---|
| 4913 | # ~~ 2^62 + time() | 
|---|
| 4914 | my $stamp = ''; | 
|---|
| 4915 |  | 
|---|
| 4916 | # support tinydns' auto-TTL | 
|---|
| 4917 | $ttl = '' if $ttl == -1; | 
|---|
| 4918 |  | 
|---|
| 4919 | # Spaces are evil. | 
|---|
| 4920 | $host =~ s/^\s+//; | 
|---|
| 4921 | $host =~ s/\s+$//; | 
|---|
| 4922 | if ($typemap{$type} ne 'TXT') { | 
|---|
| 4923 | # Leading or trailng spaces could be legit in TXT records. | 
|---|
| 4924 | $val =~ s/^\s+//; | 
|---|
| 4925 | $val =~ s/\s+$//; | 
|---|
| 4926 | } | 
|---|
| 4927 |  | 
|---|
| 4928 | _printrec_tiny(*ZONECACHE, 'n', \%recflags, | 
|---|
| 4929 | $dom, $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp) | 
|---|
| 4930 | if *ZONECACHE; | 
|---|
| 4931 |  | 
|---|
| 4932 | # in case the zone shrunk, get rid of garbage at the end of the file. | 
|---|
| 4933 | truncate(ZONECACHE, tell(ZONECACHE)); | 
|---|
| 4934 |  | 
|---|
| 4935 | $recflags{$recid} = 1; | 
|---|
| 4936 | } # while ($recsth) | 
|---|
| 4937 | } | 
|---|
| 4938 | # stream from cache, whether freshly created or existing | 
|---|
| 4939 | print $datafile $_ while <ZONECACHE>; | 
|---|
| 4940 | close ZONECACHE; | 
|---|
| 4941 | # mark domain as unmodified | 
|---|
| 4942 | $zonesth->execute($domid); | 
|---|
| 4943 | } # while ($domsth) | 
|---|
| 4944 |  | 
|---|
| 4945 | my $revsth = $dbh->prepare("SELECT rdns_id,revnet,status,changed FROM revzones WHERE status=1 ". | 
|---|
| 4946 | "ORDER BY masklen(revnet) DESC"); | 
|---|
| 4947 |  | 
|---|
| 4948 | # For reasons unknown, we can't sanely UNION these statements.  Feh. | 
|---|
| 4949 | # Supposedly it should work though (note last 3 lines): | 
|---|
| 4950 | ## PG manual | 
|---|
| 4951 | #UNION Clause | 
|---|
| 4952 | # | 
|---|
| 4953 | #The UNION clause has this general form: | 
|---|
| 4954 | # | 
|---|
| 4955 | #    select_statement UNION [ ALL ] select_statement | 
|---|
| 4956 | # | 
|---|
| 4957 | #select_statement is any SELECT statement without an ORDER BY, LIMIT, FOR UPDATE, or FOR SHARE clause. (ORDER BY | 
|---|
| 4958 | #and LIMIT can be attached to a subexpression if it is enclosed in parentheses. Without parentheses, these | 
|---|
| 4959 | #clauses will be taken to apply to the result of the UNION, not to its right-hand input expression.) | 
|---|
| 4960 | my $soasth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ". | 
|---|
| 4961 | "FROM records WHERE rdns_id=? AND type=6"); | 
|---|
| 4962 | $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ". | 
|---|
| 4963 | "FROM records WHERE rdns_id=? AND not type=6 ". | 
|---|
| 4964 | "ORDER BY masklen(CAST(val AS inet)) DESC, CAST(val AS inet)"); | 
|---|
| 4965 | $zonesth = $dbh->prepare("UPDATE revzones SET changed='n' WHERE rdns_id=?"); | 
|---|
| 4966 | $revsth->execute(); | 
|---|
| 4967 | while (my ($revid,$revzone,$revstat,$changed) = $revsth->fetchrow_array) { | 
|---|
| 4968 | ##fixme: need to find a way to block opening symlinked files without introducing a race. | 
|---|
| 4969 | #       O_NOFOLLOW | 
|---|
| 4970 | #              If  pathname  is a symbolic link, then the open fails.  This is a FreeBSD extension, which was | 
|---|
| 4971 | #              added to Linux in version 2.1.126.  Symbolic links in earlier components of the pathname  will | 
|---|
| 4972 | #              still be followed. | 
|---|
| 4973 | # but that doesn't help other platforms.  :/ | 
|---|
| 4974 | my $tmpzone = NetAddr::IP->new($revzone); | 
|---|
| 4975 | sysopen(ZONECACHE, "$self->{exportcache}/".$tmpzone->network->addr, O_RDWR|O_CREAT); | 
|---|
| 4976 | flock(ZONECACHE, LOCK_EX); | 
|---|
| 4977 | if ($changed || -s "$self->{exportcache}/".$tmpzone->network->addr == 0) { | 
|---|
| 4978 | # need to fetch this separately since the rest of the records all (should) have real IPs in val | 
|---|
| 4979 | $soasth->execute($revid); | 
|---|
| 4980 | my (@zsoa) = $soasth->fetchrow_array(); | 
|---|
| 4981 | _printrec_tiny(*ZONECACHE,'y',\%recflags,$revzone, | 
|---|
| 4982 | $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],''); | 
|---|
| 4983 |  | 
|---|
| 4984 | $recsth->execute($revid); | 
|---|
| 4985 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc) = $recsth->fetchrow_array) { | 
|---|
| 4986 | next if $recflags{$recid}; | 
|---|
| 4987 |  | 
|---|
| 4988 | $loc = '' if !$loc;     # de-nullify - just in case | 
|---|
| 4989 | ##fixme:  handle case of record-with-location-that-doesn't-exist better. | 
|---|
| 4990 | # note this currently fails safe (tested) - records with a location that | 
|---|
| 4991 | # doesn't exist will not be sent to any client | 
|---|
| 4992 | #       $loc = '' if !$lochash->{$loc}; | 
|---|
| 4993 |  | 
|---|
| 4994 | ##fixme:  record validity timestamp. tinydns supports fiddling with timestamps. | 
|---|
| 4995 | # note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps. | 
|---|
| 4996 | # timestamps are TAI64 | 
|---|
| 4997 | # ~~ 2^62 + time() | 
|---|
| 4998 | my $stamp = ''; | 
|---|
| 4999 |  | 
|---|
| 5000 | # support tinydns' auto-TTL | 
|---|
| 5001 | $ttl = '' if $ttl == -1; | 
|---|
| 5002 |  | 
|---|
| 5003 | _printrec_tiny(*ZONECACHE, 'y', \%recflags, $revzone, | 
|---|
| 5004 | $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp) | 
|---|
| 5005 | if *ZONECACHE; | 
|---|
| 5006 |  | 
|---|
| 5007 | # in case the zone shrunk, get rid of garbage at the end of the file. | 
|---|
| 5008 | truncate(ZONECACHE, tell(ZONECACHE)); | 
|---|
| 5009 |  | 
|---|
| 5010 | $recflags{$recid} = 1; | 
|---|
| 5011 | } # while ($recsth) | 
|---|
| 5012 | } | 
|---|
| 5013 | # stream from cache, whether freshly created or existing | 
|---|
| 5014 | print $datafile $_ while <ZONECACHE>; | 
|---|
| 5015 | close ZONECACHE; | 
|---|
| 5016 | # mark zone as unmodified | 
|---|
| 5017 | $zonesth->execute($revid); | 
|---|
| 5018 | } # while ($domsth) | 
|---|
| 5019 |  | 
|---|
| 5020 | } # end __export_tiny() | 
|---|
| 5021 |  | 
|---|
| 5022 |  | 
|---|
| 5023 | # Utility sub for __export_tiny above | 
|---|
| 5024 | sub _printrec_tiny { | 
|---|
| 5025 | my ($datafile,$revrec,$recflags,$zone,$host,$type,$val,$dist,$weight,$port,$ttl,$loc,$stamp) = @_; | 
|---|
| 5026 |  | 
|---|
| 5027 | ## Convert a bare number into an octal-coded pair of octets. | 
|---|
| 5028 | # Take optional arg to indicate a decimal or hex input.  Defaults to hex. | 
|---|
| 5029 | sub octalize { | 
|---|
| 5030 | my $tmp = shift; | 
|---|
| 5031 | my $srctype = shift || 'h'; # default assumes hex string | 
|---|
| 5032 | $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h';       # 0-pad hex to 4 digits | 
|---|
| 5033 | $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd';    # 0-pad decimal to 4 hex digits | 
|---|
| 5034 | my @o = ($tmp =~ /^(..)(..)$/);     # split into octets | 
|---|
| 5035 | return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);; | 
|---|
| 5036 | } | 
|---|
| 5037 |  | 
|---|
| 5038 | ## WARNING:  This works to export even the whole Internet's worth of IP space... | 
|---|
| 5039 | ##  if you have the disk/RAM to handle the dataset, and you call this sub based on /16-sized chunks | 
|---|
| 5040 | ##  A /16 took ~3 seconds with a handful of separate records;  adding a /8 pushed export time out to ~13m:40s | 
|---|
| 5041 | ##  0/0 is estimated to take ~54 hours and ~256G of disk | 
|---|
| 5042 | ##  RAM usage depends on how many non-template entries you have in the set. | 
|---|
| 5043 | ##  This should probably be done on record addition rather than export;  large blocks may need to be done in a | 
|---|
| 5044 | ##  forked process | 
|---|
| 5045 | sub __publish_subnet { | 
|---|
| 5046 | my $sub = shift; | 
|---|
| 5047 | my $recflags = shift; | 
|---|
| 5048 | my $hpat = shift; | 
|---|
| 5049 | my $fh = shift; | 
|---|
| 5050 | my $ttl = shift; | 
|---|
| 5051 | my $stamp = shift; | 
|---|
| 5052 | my $loc = shift; | 
|---|
| 5053 | my $ptronly = shift || 0; | 
|---|
| 5054 |  | 
|---|
| 5055 | my $iplist = $sub->splitref(32); | 
|---|
| 5056 | foreach (@$iplist) { | 
|---|
| 5057 | my $ip = $_->addr; | 
|---|
| 5058 | # make as if we split the non-octet-aligned block into octet-aligned blocks as with SOA | 
|---|
| 5059 | next if $ip =~ /\.(0|255)$/; | 
|---|
| 5060 | next if $$recflags{$ip}; | 
|---|
| 5061 | $$recflags{$ip}++; | 
|---|
| 5062 | next if $hpat eq '%blank%';       # Allows blanking a subnet so no records are published. | 
|---|
| 5063 | my $rec = $hpat;  # start fresh with the template for each IP | 
|---|
| 5064 | _template4_expand(\$rec, $ip); | 
|---|
| 5065 | print $fh ($ptronly ? "^"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$rec" : "=$rec:$ip"). | 
|---|
| 5066 | ":$ttl:$stamp:$loc\n"; | 
|---|
| 5067 | } | 
|---|
| 5068 | } | 
|---|
| 5069 |  | 
|---|
| 5070 | ##fixme?  append . to all host/val hostnames | 
|---|
| 5071 | if ($typemap{$type} eq 'SOA') { | 
|---|
| 5072 |  | 
|---|
| 5073 | # host contains pri-ns:responsible | 
|---|
| 5074 | # val is abused to contain refresh:retry:expire:minttl | 
|---|
| 5075 | ##fixme:  "manual" serial vs tinydns-autoserial | 
|---|
| 5076 | # let's be explicit about abusing $host and $val | 
|---|
| 5077 | my ($email, $primary) = (split /:/, $host)[0,1]; | 
|---|
| 5078 | my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3]; | 
|---|
| 5079 | if ($revrec eq 'y') { | 
|---|
| 5080 | ##fixme:  have to publish SOA records for each v4 /24 in sub-/16, and each /16 in sub-/8 | 
|---|
| 5081 | # what about v6? | 
|---|
| 5082 | # -> only need SOA for local chunks offset from reverse delegation boundaries, so v6 is fine | 
|---|
| 5083 | $zone = NetAddr::IP->new($zone); | 
|---|
| 5084 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones | 
|---|
| 5085 | if (!$zone->{isv6} && ($zone->masklen < 24) && ($zone->masklen % 8 != 0)) { | 
|---|
| 5086 | foreach my $szone ($zone->split($zone->masklen + (8 - $zone->masklen % 8))) { | 
|---|
| 5087 | $szone = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.'); | 
|---|
| 5088 | print $datafile "Z$szone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n"; | 
|---|
| 5089 | } | 
|---|
| 5090 | return; # skips "default" bits just below | 
|---|
| 5091 | } | 
|---|
| 5092 | $zone = _ZONE($zone, 'ZONE', 'r', '.').($zone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa'); | 
|---|
| 5093 | } | 
|---|
| 5094 | print $datafile "Z$zone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n"; | 
|---|
| 5095 |  | 
|---|
| 5096 | } elsif ($typemap{$type} eq 'A') { | 
|---|
| 5097 |  | 
|---|
| 5098 | print $datafile "+$host:$val:$ttl:$stamp:$loc\n"; | 
|---|
| 5099 |  | 
|---|
| 5100 | } elsif ($typemap{$type} eq 'NS') { | 
|---|
| 5101 |  | 
|---|
| 5102 | if ($revrec eq 'y') { | 
|---|
| 5103 | $val = NetAddr::IP->new($val); | 
|---|
| 5104 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones | 
|---|
| 5105 | if (!$val->{isv6} && ($val->masklen < 24) && ($val->masklen % 8 != 0)) { | 
|---|
| 5106 | foreach my $szone ($val->split($val->masklen + (8 - $val->masklen % 8))) { | 
|---|
| 5107 | my $szone2 = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.'); | 
|---|
| 5108 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen; | 
|---|
| 5109 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n"; | 
|---|
| 5110 | $$recflags{$szone2} = $val->masklen; | 
|---|
| 5111 | } | 
|---|
| 5112 | } elsif ($val->{isv6} && ($val->masklen < 64) && ($val->masklen % 4 !=0)) { | 
|---|
| 5113 | foreach my $szone ($val->split($val->masklen + (4 - $val->masklen % 4))) { | 
|---|
| 5114 | my $szone2 = _ZONE($szone, 'ZONE.ip6.arpa', 'r', '.'); | 
|---|
| 5115 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen; | 
|---|
| 5116 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n"; | 
|---|
| 5117 | $$recflags{$szone2} = $val->masklen; | 
|---|
| 5118 | } | 
|---|
| 5119 | } else { | 
|---|
| 5120 | my $val2 = _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa'); | 
|---|
| 5121 | print $datafile "\&$val2"."::$host:$ttl:$stamp:$loc\n"; | 
|---|
| 5122 | $$recflags{$val2} = $val->masklen; | 
|---|
| 5123 | } | 
|---|
| 5124 | } else { | 
|---|
| 5125 | print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n"; | 
|---|
| 5126 | } | 
|---|
| 5127 |  | 
|---|
| 5128 | } elsif ($typemap{$type} eq 'AAAA') { | 
|---|
| 5129 |  | 
|---|
| 5130 | print $datafile ":$host:28:"; | 
|---|
| 5131 | my $altgrp = 0; | 
|---|
| 5132 | my @altconv; | 
|---|
| 5133 | # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing) | 
|---|
| 5134 | foreach (split /:/, $val) { | 
|---|
| 5135 | if (/^$/) { | 
|---|
| 5136 | # flag blank entry;  this is a series of 0's of (currently) unknown length | 
|---|
| 5137 | $altconv[$altgrp++] = 's'; | 
|---|
| 5138 | } else { | 
|---|
| 5139 | # call sub to convert 1-4 hex digits to 2 string-rep octal bytes | 
|---|
| 5140 | $altconv[$altgrp++] = octalize($_) | 
|---|
| 5141 | } | 
|---|
| 5142 | } | 
|---|
| 5143 | foreach my $octet (@altconv) { | 
|---|
| 5144 | # if not 's', output | 
|---|
| 5145 | print $datafile $octet unless $octet =~ /^s$/; | 
|---|
| 5146 | # if 's', output (9-array length)x literal '\000\000' | 
|---|
| 5147 | print $datafile '\000\000'x(9-$altgrp) if $octet =~ /^s$/; | 
|---|
| 5148 | } | 
|---|
| 5149 | print $datafile ":$ttl:$stamp:$loc\n"; | 
|---|
| 5150 |  | 
|---|
| 5151 | } elsif ($typemap{$type} eq 'MX') { | 
|---|
| 5152 |  | 
|---|
| 5153 | print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n"; | 
|---|
| 5154 |  | 
|---|
| 5155 | } elsif ($typemap{$type} eq 'TXT') { | 
|---|
| 5156 |  | 
|---|
| 5157 | ##fixme:  split v-e-r-y long TXT strings?  will need to do so for BIND export, at least | 
|---|
| 5158 | if ($revrec eq 'n') { | 
|---|
| 5159 | $val =~ s/:/\\072/g;  # may need to replace other symbols | 
|---|
| 5160 | print $datafile "'$host:$val:$ttl:$stamp:$loc\n"; | 
|---|
| 5161 | } else { | 
|---|
| 5162 | $host =~ s/:/\\072/g; # may need to replace other symbols | 
|---|
| 5163 | my $val2 = NetAddr::IP->new($val); | 
|---|
| 5164 | print $datafile "'"._ZONE($val2, 'ZONE', 'r', '.').($val2->{isv6} ? '.ip6.arpa' : '.in-addr.arpa'). | 
|---|
| 5165 | ":$host:$ttl:$stamp:$loc\n"; | 
|---|
| 5166 | } | 
|---|
| 5167 |  | 
|---|
| 5168 | # by-hand TXT | 
|---|
| 5169 | #:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600 | 
|---|
| 5170 | #@       IN      TXT     "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all" | 
|---|
| 5171 | #'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600 | 
|---|
| 5172 |  | 
|---|
| 5173 | #txttest IN      TXT     "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?" | 
|---|
| 5174 | #: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 | 
|---|
| 5175 |  | 
|---|
| 5176 | # very long TXT record as brought in by axfr-get | 
|---|
| 5177 | # note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that | 
|---|
| 5178 | # also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either.  :/ | 
|---|
| 5179 | #:longtxt.deepnet.cx:16: | 
|---|
| 5180 | #\170this is a very long txt record.  it is really long.  long. very long.  really very long. this is a very long txt record. | 
|---|
| 5181 | #\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. | 
|---|
| 5182 | #\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. | 
|---|
| 5183 | #:3600 | 
|---|
| 5184 |  | 
|---|
| 5185 | } elsif ($typemap{$type} eq 'CNAME') { | 
|---|
| 5186 |  | 
|---|
| 5187 | if ($revrec eq 'n') { | 
|---|
| 5188 | print $datafile "C$host:$val:$ttl:$stamp:$loc\n"; | 
|---|
| 5189 | } else { | 
|---|
| 5190 | my $val2 = NetAddr::IP->new($val); | 
|---|
| 5191 | print $datafile "C"._ZONE($val2, 'ZONE', 'r', '.').($val2->{isv6} ? '.ip6.arpa' : '.in-addr.arpa'). | 
|---|
| 5192 | ":$host:$ttl:$stamp:$loc\n"; | 
|---|
| 5193 | } | 
|---|
| 5194 |  | 
|---|
| 5195 | } elsif ($typemap{$type} eq 'SRV') { | 
|---|
| 5196 |  | 
|---|
| 5197 | # data is two-byte values for priority, weight, port, in that order, | 
|---|
| 5198 | # followed by length/string data | 
|---|
| 5199 |  | 
|---|
| 5200 | print $datafile ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d'); | 
|---|
| 5201 |  | 
|---|
| 5202 | $val .= '.' if $val !~ /\.$/; | 
|---|
| 5203 | foreach (split /\./, $val) { | 
|---|
| 5204 | printf $datafile "\\%0.3o%s", length($_), $_; | 
|---|
| 5205 | } | 
|---|
| 5206 | print $datafile "\\000:$ttl:$stamp:$loc\n"; | 
|---|
| 5207 |  | 
|---|
| 5208 | } elsif ($typemap{$type} eq 'RP') { | 
|---|
| 5209 |  | 
|---|
| 5210 | # RP consists of two mostly free-form strings. | 
|---|
| 5211 | # The first is supposed to be an email address with @ replaced by . (as with the SOA contact) | 
|---|
| 5212 | # The second is the "hostname" of a TXT record with more info. | 
|---|
| 5213 | print $datafile ":$host:17:"; | 
|---|
| 5214 | my ($who,$what) = split /\s/, $val; | 
|---|
| 5215 | foreach (split /\./, $who) { | 
|---|
| 5216 | printf $datafile "\\%0.3o%s", length($_), $_; | 
|---|
| 5217 | } | 
|---|
| 5218 | print $datafile '\000'; | 
|---|
| 5219 | foreach (split /\./, $what) { | 
|---|
| 5220 | printf $datafile "\\%0.3o%s", length($_), $_; | 
|---|
| 5221 | } | 
|---|
| 5222 | print $datafile "\\000:$ttl:$stamp:$loc\n"; | 
|---|
| 5223 |  | 
|---|
| 5224 | } elsif ($typemap{$type} eq 'PTR') { | 
|---|
| 5225 |  | 
|---|
| 5226 | $zone = NetAddr::IP->new($zone); | 
|---|
| 5227 | $$recflags{$val}++; | 
|---|
| 5228 | if (!$zone->{isv6} && $zone->masklen > 24) { | 
|---|
| 5229 | ($val) = ($val =~ /\.(\d+)$/); | 
|---|
| 5230 | print $datafile "^$val."._ZONE($zone, 'ZONE', 'r', '.').'.in-addr.arpa'. | 
|---|
| 5231 | ":$host:ttl:$stamp:$loc\n"; | 
|---|
| 5232 | } else { | 
|---|
| 5233 | $val = NetAddr::IP->new($val); | 
|---|
| 5234 | print $datafile "^". | 
|---|
| 5235 | _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa'). | 
|---|
| 5236 | ":$host:$ttl:$stamp:$loc\n"; | 
|---|
| 5237 | } | 
|---|
| 5238 |  | 
|---|
| 5239 | } elsif ($type == 65280) { # A+PTR | 
|---|
| 5240 |  | 
|---|
| 5241 | $$recflags{$val}++; | 
|---|
| 5242 | print $datafile "=$host:$val:$ttl:$stamp:$loc\n"; | 
|---|
| 5243 |  | 
|---|
| 5244 | } elsif ($type == 65281) { # AAAA+PTR | 
|---|
| 5245 |  | 
|---|
| 5246 | #$$recflags{$val}++; | 
|---|
| 5247 | # treat these as two separate records.  since tinydns doesn't have | 
|---|
| 5248 | # a native combined type, we have to create them separately anyway. | 
|---|
| 5249 | if ($revrec eq 'n') { | 
|---|
| 5250 | $type = 28; | 
|---|
| 5251 | } else { | 
|---|
| 5252 | $type = 12; | 
|---|
| 5253 | } | 
|---|
| 5254 | _printrec_tiny($datafile,$revrec,$recflags,$zone,$host,$type,$val,$dist,$weight,$port,$ttl,$loc,$stamp); | 
|---|
| 5255 | ##fixme: add a config flag to indicate use of the patch from http://www.fefe.de/dns/ | 
|---|
| 5256 | # type 6 is for AAAA+PTR, type 3 is for AAAA | 
|---|
| 5257 |  | 
|---|
| 5258 | } elsif ($type == 65282) { # PTR template | 
|---|
| 5259 |  | 
|---|
| 5260 | # only useful for v4 with standard DNS software, since this expands all | 
|---|
| 5261 | # IPs in $zone (or possibly $val?) with autogenerated records | 
|---|
| 5262 | $val = NetAddr::IP->new($val); | 
|---|
| 5263 | return if $val->{isv6}; | 
|---|
| 5264 |  | 
|---|
| 5265 | if ($val->masklen <= 16) { | 
|---|
| 5266 | foreach my $sub ($val->split(16)) { | 
|---|
| 5267 | __publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, 1); | 
|---|
| 5268 | } | 
|---|
| 5269 | } else { | 
|---|
| 5270 | __publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, 1); | 
|---|
| 5271 | } | 
|---|
| 5272 |  | 
|---|
| 5273 | } elsif ($type == 65283) { # A+PTR template | 
|---|
| 5274 |  | 
|---|
| 5275 | $val = NetAddr::IP->new($val); | 
|---|
| 5276 | # Just In Case.  An A+PTR should be impossible to add to a v6 revzone via API. | 
|---|
| 5277 | return if $val->{isv6}; | 
|---|
| 5278 |  | 
|---|
| 5279 | if ($val->masklen <= 16) { | 
|---|
| 5280 | foreach my $sub ($val->split(16)) { | 
|---|
| 5281 | __publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, 0); | 
|---|
| 5282 | } | 
|---|
| 5283 | } else { | 
|---|
| 5284 | __publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, 0); | 
|---|
| 5285 | } | 
|---|
| 5286 |  | 
|---|
| 5287 | } elsif ($type == 65284) { # AAAA+PTR template | 
|---|
| 5288 | # Stub for completeness.  Could be exported to DNS software that supports | 
|---|
| 5289 | # some degree of internal automagic in generic-record-creation | 
|---|
| 5290 | # (eg http://search.cpan.org/dist/AllKnowingDNS/ ) | 
|---|
| 5291 |  | 
|---|
| 5292 | } elsif ($type == 65285) { # Delegation | 
|---|
| 5293 | # This is intended for reverse zones, but may prove useful in forward zones. | 
|---|
| 5294 |  | 
|---|
| 5295 | # All delegations need to create one or more NS records.  The NS record handler knows what to do. | 
|---|
| 5296 | _printrec_tiny($datafile,$revrec,$recflags,$zone,$host,$reverse_typemap{'NS'}, | 
|---|
| 5297 | $val,$dist,$weight,$port,$ttl,$loc,$stamp); | 
|---|
| 5298 | if ($revrec eq 'y') { | 
|---|
| 5299 | # In the case of a sub-/24 v4 reverse delegation, we need to generate CNAMEs | 
|---|
| 5300 | # to redirect all of the individual IP lookups as well. | 
|---|
| 5301 | # Not sure how this would actually resolve if a /24 or larger was delegated | 
|---|
| 5302 | # one way, and a sub-/24 in that >=/24 was delegated elsewhere... | 
|---|
| 5303 | my $dblock = NetAddr::IP->new($val); | 
|---|
| 5304 | if (!$dblock->{isv6} && $dblock->masklen > 24) { | 
|---|
| 5305 | my @subs = $dblock->split; | 
|---|
| 5306 | foreach (@subs) { | 
|---|
| 5307 | next if $$recflags{"$_"}; | 
|---|
| 5308 | my ($oct) = ($_->addr =~ /(\d+)$/); | 
|---|
| 5309 | print $datafile "C"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$oct.". | 
|---|
| 5310 | _ZONE($dblock, 'ZONE.in-addr.arpa', 'r', '.').":$ttl:$stamp:$loc\n"; | 
|---|
| 5311 | $$recflags{"$_"}++; | 
|---|
| 5312 | } | 
|---|
| 5313 | } | 
|---|
| 5314 | } | 
|---|
| 5315 |  | 
|---|
| 5316 | ## | 
|---|
| 5317 | ## Uncommon types.  These will need better UI support Any Day Sometime Maybe(TM). | 
|---|
| 5318 | ## | 
|---|
| 5319 |  | 
|---|
| 5320 | } elsif ($type == 44) { # SSHFP | 
|---|
| 5321 | my ($algo,$fpt,$fp) = split /\s+/, $val; | 
|---|
| 5322 |  | 
|---|
| 5323 | my $rec = sprintf ":$host:44:\\%0.3o\\%0.3o", $algo, $fpt; | 
|---|
| 5324 | while (my ($byte) = ($fp =~ /^(..)/) ) { | 
|---|
| 5325 | $rec .= sprintf "\\%0.3o", hex($byte); | 
|---|
| 5326 | $fp =~ s/^..//; | 
|---|
| 5327 | } | 
|---|
| 5328 | print $datafile "$rec:$ttl:$stamp:$loc\n"; | 
|---|
| 5329 |  | 
|---|
| 5330 | } else { | 
|---|
| 5331 | # raw record.  we don't know what's in here, so we ASS-U-ME the user has | 
|---|
| 5332 | # put it in correctly, since either the user is messing directly with the | 
|---|
| 5333 | # database, or the record was imported via AXFR | 
|---|
| 5334 | # <split by char> | 
|---|
| 5335 | # convert anything not a-zA-Z0-9.- to octal coding | 
|---|
| 5336 |  | 
|---|
| 5337 | ##fixme: add flag to export "unknown" record types - note we'll probably end up | 
|---|
| 5338 | # mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr. | 
|---|
| 5339 | #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n"; | 
|---|
| 5340 |  | 
|---|
| 5341 | } # record type if-else | 
|---|
| 5342 |  | 
|---|
| 5343 | } # end _printrec_tiny() | 
|---|
| 5344 |  | 
|---|
| 5345 |  | 
|---|
| 5346 | ## DNSDB::mailNotify() | 
|---|
| 5347 | # Sends notification mail to recipients regarding a DNSDB operation | 
|---|
| 5348 | sub mailNotify { | 
|---|
| 5349 | my $self = shift; | 
|---|
| 5350 | my $dbh = $self->{dbh}; | 
|---|
| 5351 | my ($subj,$message) = @_; | 
|---|
| 5352 |  | 
|---|
| 5353 | return if $self->{mailhost} eq 'smtp.example.com';   # do nothing if still using default SMTP host. | 
|---|
| 5354 |  | 
|---|
| 5355 | my $mailer = Net::SMTP->new($self->{mailhost}, Hello => "dnsadmin.$self->{domain}"); | 
|---|
| 5356 |  | 
|---|
| 5357 | my $mailsender = ($self->{mailsender} ? $self->{mailsender} : $self->{mailnotify}); | 
|---|
| 5358 |  | 
|---|
| 5359 | $mailer->mail($mailsender); | 
|---|
| 5360 | $mailer->to($self->{mailnotify}); | 
|---|
| 5361 | $mailer->data("From: \"$self->{mailname}\" <$mailsender>\n", | 
|---|
| 5362 | "To: <$self->{mailnotify}>\n", | 
|---|
| 5363 | "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n", | 
|---|
| 5364 | "Subject: $subj\n", | 
|---|
| 5365 | "X-Mailer: DNSAdmin Notify v".sprintf("%.1d",$DNSDB::VERSION)."\n", | 
|---|
| 5366 | "Organization: $self->{orgname}\n", | 
|---|
| 5367 | "\n$message\n"); | 
|---|
| 5368 | $mailer->quit; | 
|---|
| 5369 | } | 
|---|
| 5370 |  | 
|---|
| 5371 | # shut Perl up | 
|---|
| 5372 | 1; | 
|---|