| 1 | # dns/trunk/DNSDB.pm | 
|---|
| 2 | # Abstraction functions for DNS administration | 
|---|
| 3 | ## | 
|---|
| 4 | # $Id: DNSDB.pm 685 2015-07-27 21:32:49Z 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 Digest::MD5 qw(md5_hex); | 
|---|
| 30 | use Net::SMTP; | 
|---|
| 31 | use NetAddr::IP 4.027 qw(:lower); | 
|---|
| 32 | use POSIX; | 
|---|
| 33 | use Fcntl qw(:flock); | 
|---|
| 34 | use Time::TAI64 qw(:tai64); | 
|---|
| 35 |  | 
|---|
| 36 | use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS); | 
|---|
| 37 |  | 
|---|
| 38 | $VERSION        = 1.3;  ##VERSION## | 
|---|
| 39 | @ISA            = qw(Exporter); | 
|---|
| 40 | @EXPORT_OK      = qw( | 
|---|
| 41 | &initGlobals &login &initActionLog | 
|---|
| 42 | &getPermissions &changePermissions &comparePermissions | 
|---|
| 43 | &changeGroup | 
|---|
| 44 | &connectDB &finish | 
|---|
| 45 | &addDomain &delZone &domainName &revName &domainID &revID &addRDNS | 
|---|
| 46 | &getZoneCount &getZoneList &getZoneLocation | 
|---|
| 47 | &addGroup &delGroup &getChildren &groupName | 
|---|
| 48 | &getGroupCount &getGroupList | 
|---|
| 49 | &addUser &updateUser &delUser &userFullName &userStatus &getUserData | 
|---|
| 50 | &getUserCount &getUserList &getUserDropdown | 
|---|
| 51 | &addLoc &updateLoc &delLoc &getLoc | 
|---|
| 52 | &getLocCount &getLocList &getLocDropdown | 
|---|
| 53 | &getSOA &updateSOA &getRecLine &getRecList &getRecCount | 
|---|
| 54 | &addRec &updateRec &delRec | 
|---|
| 55 | &getLogCount &getLogEntries | 
|---|
| 56 | &getRevPattern | 
|---|
| 57 | &getTypelist | 
|---|
| 58 | &parentID | 
|---|
| 59 | &isParent | 
|---|
| 60 | &zoneStatus &getZonesByCIDR &importAXFR | 
|---|
| 61 | &export | 
|---|
| 62 | &mailNotify | 
|---|
| 63 | %typemap %reverse_typemap | 
|---|
| 64 | @permtypes $permlist %permchains | 
|---|
| 65 | ); | 
|---|
| 66 |  | 
|---|
| 67 | @EXPORT         = qw(%typemap %reverse_typemap @permtypes $permlist %permchains); | 
|---|
| 68 | %EXPORT_TAGS    = ( ALL => [qw( | 
|---|
| 69 | &initGlobals &login &initActionLog | 
|---|
| 70 | &getPermissions &changePermissions &comparePermissions | 
|---|
| 71 | &changeGroup | 
|---|
| 72 | &connectDB &finish | 
|---|
| 73 | &addDomain &delZone &domainName &revName &domainID &revID &addRDNS | 
|---|
| 74 | &getZoneCount &getZoneList &getZoneLocation | 
|---|
| 75 | &addGroup &delGroup &getChildren &groupName | 
|---|
| 76 | &getGroupCount &getGroupList | 
|---|
| 77 | &addUser &updateUser &delUser &userFullName &userStatus &getUserData | 
|---|
| 78 | &getUserCount &getUserList &getUserDropdown | 
|---|
| 79 | &addLoc &updateLoc &delLoc &getLoc | 
|---|
| 80 | &getLocCount &getLocList &getLocDropdown | 
|---|
| 81 | &getSOA &updateSOA &getRecLine &getRecList &getRecCount | 
|---|
| 82 | &addRec &updateRec &delRec | 
|---|
| 83 | &getLogCount &getLogEntries | 
|---|
| 84 | &getRevPattern | 
|---|
| 85 | &getTypelist | 
|---|
| 86 | &parentID | 
|---|
| 87 | &isParent | 
|---|
| 88 | &zoneStatus &getZonesByCIDR &importAXFR | 
|---|
| 89 | &export | 
|---|
| 90 | &mailNotify | 
|---|
| 91 | %typemap %reverse_typemap | 
|---|
| 92 | @permtypes $permlist %permchains | 
|---|
| 93 | )] | 
|---|
| 94 | ); | 
|---|
| 95 |  | 
|---|
| 96 | our $errstr = ''; | 
|---|
| 97 | our $resultstr = ''; | 
|---|
| 98 |  | 
|---|
| 99 | # Arguably defined wholly in the db, but little reason to change without supporting code changes | 
|---|
| 100 | # group_view, user_view permissions? separate rDNS permission(s)? | 
|---|
| 101 | our @permtypes = qw ( | 
|---|
| 102 | group_edit      group_create    group_delete | 
|---|
| 103 | user_edit       user_create     user_delete | 
|---|
| 104 | domain_edit     domain_create   domain_delete | 
|---|
| 105 | record_edit     record_create   record_delete   record_locchg | 
|---|
| 106 | location_edit   location_create location_delete location_view | 
|---|
| 107 | self_edit       admin | 
|---|
| 108 | ); | 
|---|
| 109 | our $permlist = join(',',@permtypes); | 
|---|
| 110 |  | 
|---|
| 111 | # Some permissions more or less require certain others. | 
|---|
| 112 | our %permchains = ( | 
|---|
| 113 | user_edit       => 'self_edit', | 
|---|
| 114 | location_edit   => 'location_view', | 
|---|
| 115 | location_create => 'location_view', | 
|---|
| 116 | location_delete => 'location_view', | 
|---|
| 117 | record_locchg   => 'location_view', | 
|---|
| 118 | ); | 
|---|
| 119 |  | 
|---|
| 120 | # DNS record type map and reverse map. | 
|---|
| 121 | # loaded from the database, from http://www.iana.org/assignments/dns-parameters | 
|---|
| 122 | our %typemap; | 
|---|
| 123 | our %reverse_typemap; | 
|---|
| 124 |  | 
|---|
| 125 | ## (Semi)private variables | 
|---|
| 126 |  | 
|---|
| 127 | # Hash of functions for validating record types.  Filled in initGlobals() since | 
|---|
| 128 | # it relies on visibility flags from the rectypes table in the DB | 
|---|
| 129 | my %validators; | 
|---|
| 130 |  | 
|---|
| 131 | # Entity-relationship reference hashes. | 
|---|
| 132 | my %par_tbl = ( | 
|---|
| 133 | group   => 'groups', | 
|---|
| 134 | user    => 'users', | 
|---|
| 135 | defrec  => 'default_records', | 
|---|
| 136 | defrevrec       => 'default_rev_records', | 
|---|
| 137 | domain  => 'domains', | 
|---|
| 138 | revzone => 'revzones', | 
|---|
| 139 | record  => 'records' | 
|---|
| 140 | ); | 
|---|
| 141 | my %id_col = ( | 
|---|
| 142 | group   => 'group_id', | 
|---|
| 143 | user    => 'user_id', | 
|---|
| 144 | defrec  => 'record_id', | 
|---|
| 145 | defrevrec       => 'record_id', | 
|---|
| 146 | domain  => 'domain_id', | 
|---|
| 147 | revzone => 'rdns_id', | 
|---|
| 148 | record  => 'record_id' | 
|---|
| 149 | ); | 
|---|
| 150 | my %par_col = ( | 
|---|
| 151 | group   => 'parent_group_id', | 
|---|
| 152 | user    => 'group_id', | 
|---|
| 153 | defrec  => 'group_id', | 
|---|
| 154 | defrevrec       => 'group_id', | 
|---|
| 155 | domain  => 'group_id', | 
|---|
| 156 | revzone => 'group_id', | 
|---|
| 157 | record  => 'domain_id' | 
|---|
| 158 | ); | 
|---|
| 159 | my %par_type = ( | 
|---|
| 160 | group   => 'group', | 
|---|
| 161 | user    => 'group', | 
|---|
| 162 | defrec  => 'group', | 
|---|
| 163 | defrevrec       => 'group', | 
|---|
| 164 | domain  => 'group', | 
|---|
| 165 | revzone => 'group', | 
|---|
| 166 | record  => 'domain' | 
|---|
| 167 | ); | 
|---|
| 168 |  | 
|---|
| 169 | ## | 
|---|
| 170 | ## Constructor and destructor | 
|---|
| 171 | ## | 
|---|
| 172 |  | 
|---|
| 173 | sub new { | 
|---|
| 174 | my $this = shift; | 
|---|
| 175 | my $class = ref($this) || $this; | 
|---|
| 176 | my %args = @_; | 
|---|
| 177 |  | 
|---|
| 178 | # Prepopulate a basic config.  Note some of these *will* cause errors if left unset. | 
|---|
| 179 | # note:  add appropriate stanzas in __cfgload() to parse these | 
|---|
| 180 | my %defconfig = ( | 
|---|
| 181 | # The only configuration options not loadable from a config file. | 
|---|
| 182 | configfile => "/etc/dnsdb/dnsdb.conf",  ##CFG_LEAF## | 
|---|
| 183 |  | 
|---|
| 184 | # Database connection info | 
|---|
| 185 | dbname  => 'dnsdb', | 
|---|
| 186 | dbuser  => 'dnsdb', | 
|---|
| 187 | dbpass  => 'secret', | 
|---|
| 188 | dbhost  => '', | 
|---|
| 189 |  | 
|---|
| 190 | # Email notice settings | 
|---|
| 191 | mailhost        => 'smtp.example.com', | 
|---|
| 192 | mailnotify      => 'dnsdb@example.com', # to | 
|---|
| 193 | mailsender      => 'dnsdb@example.com', # from | 
|---|
| 194 | mailname        => 'DNS Administration', | 
|---|
| 195 | orgname         => 'Example Corp', | 
|---|
| 196 | domain          => 'example.com', | 
|---|
| 197 |  | 
|---|
| 198 | # Template directory | 
|---|
| 199 | templatedir     => 'templates/', | 
|---|
| 200 | # fmeh.  this is a real web path, not a logical internal one.  hm.. | 
|---|
| 201 | #               cssdir  => 'templates/', | 
|---|
| 202 | sessiondir      => 'session/', | 
|---|
| 203 | exportcache     => 'cache/', | 
|---|
| 204 | usecache        => 1,   # do we bother using the cache above? | 
|---|
| 205 |  | 
|---|
| 206 | # Session params | 
|---|
| 207 | timeout         => '1h',        # passed as-is to CGI::Session | 
|---|
| 208 |  | 
|---|
| 209 | # Other miscellanea | 
|---|
| 210 | log_failures    => 1,   # log all evarthing by default | 
|---|
| 211 | perpage         => 15, | 
|---|
| 212 | maxfcgi         => 10,  # reasonable default? | 
|---|
| 213 | force_refresh   => 1, | 
|---|
| 214 | lowercase       => 0,   # mangle as little as possible by default | 
|---|
| 215 | # show IPs and CIDR blocks as-is for reverse zones.  valid values are | 
|---|
| 216 | # 'none' (default, show natural IP or CIDR) | 
|---|
| 217 | # 'zone' (zone name, wherever used) | 
|---|
| 218 | # 'record' (IP or CIDR values in reverse record lists) | 
|---|
| 219 | # 'all' (all IP values in any reverse zone view) | 
|---|
| 220 | showrev_arpa    => 'none', | 
|---|
| 221 | # Two options for template record expansion: | 
|---|
| 222 | template_skip_0 => 0,   # publish .0 by default | 
|---|
| 223 | template_skip_255       => 0,   # publish .255 by default | 
|---|
| 224 | ); | 
|---|
| 225 |  | 
|---|
| 226 | # Config file parse calls. | 
|---|
| 227 | # If we are passed a blank argument for $args{configfile}, | 
|---|
| 228 | #   we should NOT parse the default config file - we will | 
|---|
| 229 | #   rely on hardcoded defaults OR caller-specified values. | 
|---|
| 230 | # If we are passed a non-blank argument, parse that file. | 
|---|
| 231 | # If no config file is specified, parse the default one. | 
|---|
| 232 | my %siteconfig; | 
|---|
| 233 | if (defined($args{configfile})) { | 
|---|
| 234 | if ($args{configfile}) { | 
|---|
| 235 | return if !__cfgload($args{configfile}, \%siteconfig); | 
|---|
| 236 | } | 
|---|
| 237 | } else { | 
|---|
| 238 | return if !__cfgload($defconfig{configfile}, \%siteconfig); | 
|---|
| 239 | } | 
|---|
| 240 |  | 
|---|
| 241 | # Assemble the object.  Apply configuration hashes in order of precedence. | 
|---|
| 242 | my $self = { | 
|---|
| 243 | # Hardcoded defaults | 
|---|
| 244 | %defconfig, | 
|---|
| 245 | # Default config file OR caller-specified one, loaded above | 
|---|
| 246 | %siteconfig, | 
|---|
| 247 | # Caller-specified arguments | 
|---|
| 248 | %args | 
|---|
| 249 | }; | 
|---|
| 250 | bless $self, $class; | 
|---|
| 251 |  | 
|---|
| 252 | # Several settings are booleans.  Handle multiple possible ways of setting them. | 
|---|
| 253 | for my $boolopt ('log_failures', 'force_refresh', 'lowercase', 'usecache', | 
|---|
| 254 | 'template_skip_0', 'template_skip_255') { | 
|---|
| 255 | if ($self->{$boolopt} ne '1' && $self->{$boolopt} ne '0') { | 
|---|
| 256 | # true/false, on/off, yes/no all valid. | 
|---|
| 257 | if ($self->{$boolopt} =~ /^(?:true|false|t|f|on|off|yes|no)$/) { | 
|---|
| 258 | if ($self->{$boolopt} =~ /(?:true|t|on|yes)/) { | 
|---|
| 259 | $self->{$boolopt} = 1; | 
|---|
| 260 | } else { | 
|---|
| 261 | $self->{$boolopt} = 0; | 
|---|
| 262 | } | 
|---|
| 263 | } else { | 
|---|
| 264 | warn "Bad $boolopt setting $self->{$boolopt}, using default\n"; | 
|---|
| 265 | $self->{$boolopt} = $defconfig{$boolopt}; | 
|---|
| 266 | } | 
|---|
| 267 | } | 
|---|
| 268 | } | 
|---|
| 269 |  | 
|---|
| 270 | # Enum-ish option(s) | 
|---|
| 271 | if (!grep /$self->{showrev_arpa}/, ('none','zone','record','all')) { | 
|---|
| 272 | warn "Bad showrev_arpa setting $self->{showrev_arpa}, using default\n"; | 
|---|
| 273 | $self->{showrev_arpa} = 'none'; | 
|---|
| 274 | } | 
|---|
| 275 |  | 
|---|
| 276 | # Try to connect to the DB, and initialize a number of handy globals. | 
|---|
| 277 | $self->{dbh} = connectDB($self->{dbname}, $self->{dbuser}, $self->{dbpass}, $self->{dbhost}) or return; | 
|---|
| 278 | $self->initGlobals(); | 
|---|
| 279 |  | 
|---|
| 280 | return $self; | 
|---|
| 281 | } | 
|---|
| 282 |  | 
|---|
| 283 | sub DESTROY { | 
|---|
| 284 | my $self = shift; | 
|---|
| 285 | $self->{dbh}->disconnect if $self->{dbh}; | 
|---|
| 286 | } | 
|---|
| 287 |  | 
|---|
| 288 | sub errstr { $DNSDB::errstr; } | 
|---|
| 289 |  | 
|---|
| 290 | ## | 
|---|
| 291 | ## utility functions | 
|---|
| 292 | ## | 
|---|
| 293 |  | 
|---|
| 294 | ## DNSDB::_rectable() | 
|---|
| 295 | # Takes default+rdns flags, returns appropriate table name | 
|---|
| 296 | sub _rectable { | 
|---|
| 297 | my $def = shift; | 
|---|
| 298 | my $rev = shift; | 
|---|
| 299 |  | 
|---|
| 300 | return 'records' if $def ne 'y'; | 
|---|
| 301 | return 'default_records' if $rev ne 'y'; | 
|---|
| 302 | return 'default_rev_records'; | 
|---|
| 303 | } # end _rectable() | 
|---|
| 304 |  | 
|---|
| 305 | ## DNSDB::_recparent() | 
|---|
| 306 | # Takes default+rdns flags, returns appropriate parent-id column name | 
|---|
| 307 | sub _recparent { | 
|---|
| 308 | my $def = shift; | 
|---|
| 309 | my $rev = shift; | 
|---|
| 310 |  | 
|---|
| 311 | return 'group_id' if $def eq 'y'; | 
|---|
| 312 | return 'rdns_id' if $rev eq 'y'; | 
|---|
| 313 | return 'domain_id'; | 
|---|
| 314 | } # end _recparent() | 
|---|
| 315 |  | 
|---|
| 316 | ## DNSDB::_ipparent() | 
|---|
| 317 | # Check an IP to be added in a reverse zone to see if it's really in the requested parent. | 
|---|
| 318 | # Takes default and reverse flags, IP (fragment) to check, parent zone ID, | 
|---|
| 319 | # and a reference to a NetAddr::IP object (also used to pass back a fully-reconstructed IP for | 
|---|
| 320 | # database insertion) | 
|---|
| 321 | sub _ipparent { | 
|---|
| 322 | my $self = shift; | 
|---|
| 323 | my $dbh = $self->{dbh}; | 
|---|
| 324 | my $defrec = shift; | 
|---|
| 325 | my $revrec = shift; | 
|---|
| 326 | my $val = shift; | 
|---|
| 327 | my $id = shift; | 
|---|
| 328 | my $addr = shift; | 
|---|
| 329 |  | 
|---|
| 330 | return if $revrec ne 'y';     # this sub not useful in forward zones | 
|---|
| 331 |  | 
|---|
| 332 | $$addr = NetAddr::IP->new($$val);      #necessary? | 
|---|
| 333 |  | 
|---|
| 334 | # subsub to split, reverse, and overlay an IP fragment on a netblock | 
|---|
| 335 | sub __rev_overlay { | 
|---|
| 336 | my $splitme = shift;        # ':' or '.', m'lud? | 
|---|
| 337 | my $parnet = shift; | 
|---|
| 338 | my $val = shift; | 
|---|
| 339 | my $addr = shift; | 
|---|
| 340 |  | 
|---|
| 341 | my $joinme = $splitme; | 
|---|
| 342 | $splitme = '\.' if $splitme eq '.'; | 
|---|
| 343 | my @working = reverse(split($splitme, $parnet->addr)); | 
|---|
| 344 | my @parts = reverse(split($splitme, $$val)); | 
|---|
| 345 | for (my $i = 0; $i <= $#parts; $i++) { | 
|---|
| 346 | $working[$i] = $parts[$i]; | 
|---|
| 347 | } | 
|---|
| 348 | my $checkme = NetAddr::IP->new(join($joinme, reverse(@working))) or return 0; | 
|---|
| 349 | return 0 unless $checkme->within($parnet); | 
|---|
| 350 | $$addr = $checkme;  # force "correct" IP to be recorded. | 
|---|
| 351 | return 1; | 
|---|
| 352 | } | 
|---|
| 353 |  | 
|---|
| 354 | my ($parstr) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id = ?", undef, ($id)); | 
|---|
| 355 | my $parnet = NetAddr::IP->new($parstr); | 
|---|
| 356 |  | 
|---|
| 357 | # Fail early on v6-in-v4 or v4-in-v6.  We're not accepting these ATM. | 
|---|
| 358 | return 0 if $parnet->addr =~ /\./ && $$val =~ /:/; | 
|---|
| 359 | return 0 if $parnet->addr =~ /:/ && $$val =~ /\./; | 
|---|
| 360 |  | 
|---|
| 361 | if ($$addr && ($$val =~ /^[\da-fA-F][\da-fA-F:]+[\da-fA-F]$/ || $$val =~ m|/\d+$|)) { | 
|---|
| 362 | # the only case where NetAddr::IP's acceptance of legitimate IPs is "correct" is for a proper IPv6 address, | 
|---|
| 363 | # or a netblock (only expected on templates) | 
|---|
| 364 | # the rest we have to restructure before fiddling.  *sigh* | 
|---|
| 365 | return 1 if $$addr->within($parnet); | 
|---|
| 366 | } else { | 
|---|
| 367 | # We don't have a complete IP in $$val (yet)... unless we have a netblock | 
|---|
| 368 | if ($parnet->addr =~ /:/) { | 
|---|
| 369 | $$val =~ s/^:+//;  # gotta strip'em all... | 
|---|
| 370 | return __rev_overlay(':', $parnet, $val, $addr); | 
|---|
| 371 | } | 
|---|
| 372 | if ($parnet->addr =~ /\./) { | 
|---|
| 373 | $$val =~ s/^\.+//; | 
|---|
| 374 | return __rev_overlay('.', $parnet, $val, $addr); | 
|---|
| 375 | } | 
|---|
| 376 | # should be impossible to get here... | 
|---|
| 377 | } | 
|---|
| 378 | # ... and here. | 
|---|
| 379 | # can't do nuttin' in forward zones | 
|---|
| 380 | } # end _ipparent() | 
|---|
| 381 |  | 
|---|
| 382 | ## DNSDB::_maybeip() | 
|---|
| 383 | # Wrapper for quick "does this look like an IP address?" regex, so we don't make dumb copy-paste mistakes | 
|---|
| 384 | sub _maybeip { | 
|---|
| 385 | my $izzit = shift;  # reference | 
|---|
| 386 | return 1 if $$izzit =~ m,^(?:[\d\./]+|[0-9a-fA-F:/]+)$,; | 
|---|
| 387 | } | 
|---|
| 388 |  | 
|---|
| 389 | ## DNSDB::_inrev() | 
|---|
| 390 | # Check if a given "hostname" is within a given reverse zone | 
|---|
| 391 | # Takes a reference to the "hostname" and the reverse zone CIDR as a NetAddr::IP | 
|---|
| 392 | # Returns true/false.  Sets $errstr on errors. | 
|---|
| 393 | sub _inrev { | 
|---|
| 394 | my $self = shift; | 
|---|
| 395 | my $dbh = $self->{dbh}; | 
|---|
| 396 | # References, since we might munge them | 
|---|
| 397 | my $fq = shift; | 
|---|
| 398 | my $zone = shift; | 
|---|
| 399 |  | 
|---|
| 400 | # set default error | 
|---|
| 401 | $errstr = "$$fq not within $zone"; | 
|---|
| 402 |  | 
|---|
| 403 | # Unlike forward zones, we will not coerce the data into the reverse zone - an A record | 
|---|
| 404 | # in a reverse zone is already silly enough without appending a mess of 1.2.3.in-addr.arpa | 
|---|
| 405 | # (or worse, 1.2.3.4.5.6.7.8.ip6.arpa) on the end of the nominal "hostname". | 
|---|
| 406 | # We're also going to allow the "hostname" to be stored as .arpa or IP, because of | 
|---|
| 407 | # non-IP FQDNs in .arpa | 
|---|
| 408 | if ($$fq =~ /\.arpa$/) { | 
|---|
| 409 | # "FQDN" could be any syntactically legitimate string, but it must be within the formal | 
|---|
| 410 | # .arpa zone.  Note we're not validating these for correct reverse-IP values. | 
|---|
| 411 | # yes, we really need the v6 branch on the end here. | 
|---|
| 412 | $zone = _ZONE($zone, 'ZONE', 'r', '.').($zone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa'); | 
|---|
| 413 | return unless $$fq =~ /$zone$/; | 
|---|
| 414 | } else { | 
|---|
| 415 | # in most cases we should be getting a real IP as the "FQDN" to test | 
|---|
| 416 | my $addr = new NetAddr::IP $$fq if _maybeip($fq); | 
|---|
| 417 |  | 
|---|
| 418 | # "FQDN" should be a valid IP address.  Normalize formatting if so. | 
|---|
| 419 | if (!$addr) { | 
|---|
| 420 | $errstr = "$$fq is not a valid IP address"; | 
|---|
| 421 | return; | 
|---|
| 422 | } | 
|---|
| 423 | return if !$zone->contains($addr); | 
|---|
| 424 | ($$fq = $addr) =~ s{/(?:32|128)$}{}; | 
|---|
| 425 | } | 
|---|
| 426 | return 1; | 
|---|
| 427 | } # end _inrev() | 
|---|
| 428 |  | 
|---|
| 429 | ## DNSDB::_hostparent() | 
|---|
| 430 | # A little different than _ipparent above;  this tries to *find* the parent zone of a hostname | 
|---|
| 431 | # Takes a hostname. | 
|---|
| 432 | # Returns the domain ID of the parent domain if one was found. | 
|---|
| 433 | sub _hostparent { | 
|---|
| 434 | my $self = shift; | 
|---|
| 435 | my $dbh = $self->{dbh}; | 
|---|
| 436 | my $hname = shift; | 
|---|
| 437 |  | 
|---|
| 438 | $hname =~ s/^\*\.//;  # this should be impossible to find in the domains table. | 
|---|
| 439 | my @hostbits = split /\./, $hname; | 
|---|
| 440 | my $sth = $dbh->prepare("SELECT count(*),domain_id FROM domains WHERE lower(domain) = lower(?) GROUP BY domain_id"); | 
|---|
| 441 | foreach (@hostbits) { | 
|---|
| 442 | $sth->execute($hname); | 
|---|
| 443 | my ($found, $parid) = $sth->fetchrow_array; | 
|---|
| 444 | if ($found) { | 
|---|
| 445 | return $parid; | 
|---|
| 446 | } | 
|---|
| 447 | $hname =~ s/^$_\.//; | 
|---|
| 448 | } | 
|---|
| 449 | } # end _hostparent() | 
|---|
| 450 |  | 
|---|
| 451 | ## DNSDB::_log() | 
|---|
| 452 | # Log an action | 
|---|
| 453 | # Takes a log entry hash containing at least: | 
|---|
| 454 | #  group_id, log entry | 
|---|
| 455 | # and optionally one or more of: | 
|---|
| 456 | #  domain_id, rdns_id | 
|---|
| 457 | # The %userdata hash provides the user ID, username, and fullname | 
|---|
| 458 | sub _log { | 
|---|
| 459 | my $self = shift; | 
|---|
| 460 | my $dbh = $self->{dbh}; | 
|---|
| 461 |  | 
|---|
| 462 | my %args = @_; | 
|---|
| 463 |  | 
|---|
| 464 | $args{rdns_id} = 0 if !$args{rdns_id}; | 
|---|
| 465 | $args{domain_id} = 0 if !$args{domain_id}; | 
|---|
| 466 |  | 
|---|
| 467 | ##fixme:  farm out the actual logging to different subs for file, syslog, internal, etc based on config | 
|---|
| 468 | #  if ($self->{log_channel} eq 'sql') { | 
|---|
| 469 | $dbh->do("INSERT INTO log (domain_id,rdns_id,group_id,entry,user_id,email,name) VALUES (?,?,?,?,?,?,?)", | 
|---|
| 470 | undef, | 
|---|
| 471 | ($args{domain_id}, $args{rdns_id}, $args{group_id}, $args{entry}, | 
|---|
| 472 | $self->{loguserid}, $self->{logusername}, $self->{logfullname}) ); | 
|---|
| 473 | #  } elsif ($self->{log_channel} eq 'file') { | 
|---|
| 474 | #  } elsif ($self->{log_channel} eq 'syslog') { | 
|---|
| 475 | #  } | 
|---|
| 476 | } # end _log | 
|---|
| 477 |  | 
|---|
| 478 |  | 
|---|
| 479 | ## | 
|---|
| 480 | ## Record validation subs. | 
|---|
| 481 | ## | 
|---|
| 482 |  | 
|---|
| 483 | ## All of these subs take substantially the same arguments: | 
|---|
| 484 | # a hash containing at least the following keys: | 
|---|
| 485 | #  - defrec (default/live flag) | 
|---|
| 486 | #  - revrec (forward/reverse flag) | 
|---|
| 487 | #  - id (parent entity ID) | 
|---|
| 488 | #  - host (hostname) | 
|---|
| 489 | #  - rectype | 
|---|
| 490 | #  - val (IP, hostname [CNAME/MX/SRV] or text) | 
|---|
| 491 | #  - addr (NetAddr::IP object from val.  May be undef.) | 
|---|
| 492 | # MX and SRV record validation also expect distance, and SRV records expect weight and port as well. | 
|---|
| 493 | # host, rectype, and addr should be references as these may be modified in validation | 
|---|
| 494 |  | 
|---|
| 495 | # A record | 
|---|
| 496 | sub _validate_1 { | 
|---|
| 497 | my $self = shift; | 
|---|
| 498 | my $dbh = $self->{dbh}; | 
|---|
| 499 |  | 
|---|
| 500 | my %args = @_; | 
|---|
| 501 |  | 
|---|
| 502 | # only for strict type restrictions | 
|---|
| 503 | #  return ('FAIL', 'Reverse zones cannot contain A records') if $args{revrec} eq 'y'; | 
|---|
| 504 |  | 
|---|
| 505 | if ($args{revrec} eq 'y') { | 
|---|
| 506 | # Get the revzone, so we can see if ${$args{val}} is in that zone | 
|---|
| 507 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y'); | 
|---|
| 508 |  | 
|---|
| 509 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone); | 
|---|
| 510 |  | 
|---|
| 511 | # ${$args{val}} is either a valid IP or a string ending with the .arpa zone name; | 
|---|
| 512 | # now check if it's a well-formed FQDN | 
|---|
| 513 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) && | 
|---|
| 514 | ${$args{val}} =~ /\.arpa$/; | 
|---|
| 515 |  | 
|---|
| 516 | # Check IP is well-formed, and that it's a v4 address | 
|---|
| 517 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable. | 
|---|
| 518 | return ('FAIL',"A record must be a valid IPv4 address") | 
|---|
| 519 | unless ${$args{host}} =~ m{^\d+\.\d+\.\d+\.\d+(/\d+)?$}; | 
|---|
| 520 | $args{addr} = new NetAddr::IP ${$args{host}}; | 
|---|
| 521 | return ('FAIL',"A record must be a valid IPv4 address") | 
|---|
| 522 | unless $args{addr} && !$args{addr}->{isv6}; | 
|---|
| 523 | # coerce IP/value to normalized form for storage | 
|---|
| 524 | ${$args{host}} = $args{addr}->addr; | 
|---|
| 525 |  | 
|---|
| 526 | # I'm just going to ignore the utterly barmy idea of an A record in the *default* | 
|---|
| 527 | # records for a reverse zone;  it's bad enough to find one in funky legacy data. | 
|---|
| 528 |  | 
|---|
| 529 | } else { | 
|---|
| 530 | # revrec ne 'y' | 
|---|
| 531 |  | 
|---|
| 532 | # Coerce all hostnames to end in ".DOMAIN" for group/default records, | 
|---|
| 533 | # or the intended parent domain for live records. | 
|---|
| 534 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id})); | 
|---|
| 535 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i); | 
|---|
| 536 |  | 
|---|
| 537 | # Check if it's a proper formal .arpa name for an IP, and renormalize it to the IP | 
|---|
| 538 | # value if so.  Done mainly for symmetry with PTR/A+PTR, and saves a conversion on export. | 
|---|
| 539 | if (${$args{val}} =~ /\.arpa$/) { | 
|---|
| 540 | my ($code,$tmp) = _zone2cidr(${$args{val}}); | 
|---|
| 541 | if ($code ne 'FAIL') { | 
|---|
| 542 | ${$args{val}} = $tmp->addr; | 
|---|
| 543 | $args{addr} = $tmp; | 
|---|
| 544 | } | 
|---|
| 545 | } | 
|---|
| 546 | # Check IP is well-formed, and that it's a v4 address | 
|---|
| 547 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable. | 
|---|
| 548 | return ('FAIL',"A record must be a valid IPv4 address") | 
|---|
| 549 | unless ${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/; | 
|---|
| 550 | $args{addr} = new NetAddr::IP ${$args{val}}; | 
|---|
| 551 | return ('FAIL',"A record must be a valid IPv4 address") | 
|---|
| 552 | unless $args{addr} && !$args{addr}->{isv6}; | 
|---|
| 553 | # coerce IP/value to normalized form for storage | 
|---|
| 554 | ${$args{val}} = $args{addr}->addr; | 
|---|
| 555 | } | 
|---|
| 556 |  | 
|---|
| 557 | return ('OK','OK'); | 
|---|
| 558 | } # done A record | 
|---|
| 559 |  | 
|---|
| 560 | # NS record | 
|---|
| 561 | sub _validate_2 { | 
|---|
| 562 | my $self = shift; | 
|---|
| 563 | my $dbh = $self->{dbh}; | 
|---|
| 564 |  | 
|---|
| 565 | my %args = @_; | 
|---|
| 566 |  | 
|---|
| 567 | # NS target check - IP addresses not allowed.  Must be a more or less well-formed hostname. | 
|---|
| 568 | if ($args{revrec} eq 'y') { | 
|---|
| 569 | return ('FAIL', "NS records cannot point directly to an IP address") | 
|---|
| 570 | if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/; | 
|---|
| 571 | ##enhance:  Look up the passed value to see if it exists.  Ooo, fancy. | 
|---|
| 572 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec}); | 
|---|
| 573 | } else { | 
|---|
| 574 | return ('FAIL', "NS records cannot point directly to an IP address") | 
|---|
| 575 | if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/; | 
|---|
| 576 | ##enhance:  Look up the passed value to see if it exists.  Ooo, fancy. | 
|---|
| 577 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}); | 
|---|
| 578 | } | 
|---|
| 579 |  | 
|---|
| 580 | # Check that the target of the record is within the parent. | 
|---|
| 581 | if ($args{defrec} eq 'n') { | 
|---|
| 582 | # Check if IP/address/zone/"subzone" is within the parent | 
|---|
| 583 | if ($args{revrec} eq 'y') { | 
|---|
| 584 | # Get the revzone, so we can see if ${$args{val}} is in that zone | 
|---|
| 585 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y'); | 
|---|
| 586 |  | 
|---|
| 587 | # Note the NS record may or may not be for the zone itself, it may be a pointer for a subzone | 
|---|
| 588 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone); | 
|---|
| 589 |  | 
|---|
| 590 | # ${$args{val}} is either a valid IP or a string ending with the .arpa zone name; | 
|---|
| 591 | # now check if it's a well-formed FQDN | 
|---|
| 592 | ##enhance or ##fixme | 
|---|
| 593 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design | 
|---|
| 594 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) && | 
|---|
| 595 | ${$args{val}} =~ /\.arpa$/; | 
|---|
| 596 | } else { | 
|---|
| 597 | # Forcibly append the domain name if the hostname being added does not end with the current domain name | 
|---|
| 598 | my $pname = $self->domainName($args{id}); | 
|---|
| 599 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i); | 
|---|
| 600 | } | 
|---|
| 601 | } else { | 
|---|
| 602 | # Default reverse NS records should always refer to the implied parent. | 
|---|
| 603 | if ($args{revrec} eq 'y') { | 
|---|
| 604 | ${$args{val}} = 'ZONE'; | 
|---|
| 605 | } else { | 
|---|
| 606 | ${$args{host}} = 'DOMAIN'; | 
|---|
| 607 | } | 
|---|
| 608 | } | 
|---|
| 609 |  | 
|---|
| 610 | return ('OK','OK'); | 
|---|
| 611 | } # done NS record | 
|---|
| 612 |  | 
|---|
| 613 | # CNAME record | 
|---|
| 614 | sub _validate_5 { | 
|---|
| 615 | my $self = shift; | 
|---|
| 616 | my $dbh = $self->{dbh}; | 
|---|
| 617 |  | 
|---|
| 618 | my %args = @_; | 
|---|
| 619 |  | 
|---|
| 620 | # CNAMEs in reverse zones shouldn't be handled manually, they should be generated on | 
|---|
| 621 | # export by use of the "delegation" type.  For the masochistic, and those importing | 
|---|
| 622 | # legacy data from $deity-knows-where, we'll support them. | 
|---|
| 623 |  | 
|---|
| 624 | if ($args{revrec} eq 'y') { | 
|---|
| 625 | # CNAME target check - IP addresses not allowed.  Must be a more or less well-formed hostname. | 
|---|
| 626 | return ('FAIL', "CNAME records cannot point directly to an IP address") | 
|---|
| 627 | if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/; | 
|---|
| 628 |  | 
|---|
| 629 | if ($args{defrec} eq 'n') { | 
|---|
| 630 | # Get the revzone, so we can see if ${$args{val}} is in that zone | 
|---|
| 631 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y'); | 
|---|
| 632 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone); | 
|---|
| 633 | # CNAMEs can not be used for parent nodes;  just leaf nodes with no other record types | 
|---|
| 634 | # note that this WILL probably miss some edge cases. | 
|---|
| 635 | if (${$args{val}} =~ /^[\d.\/]+$/) { | 
|---|
| 636 | # convert IP "hostname" to .arpa | 
|---|
| 637 | my $tmphn = _ZONE(NetAddr::IP->new(${$args{val}}), 'ZONE', 'r', '.'); | 
|---|
| 638 | my $tmpz = _ZONE($revzone, 'ZONE', 'r', '.'); | 
|---|
| 639 | return ('FAIL', "The bare zone may not be a CNAME") if $tmphn eq $tmpz; | 
|---|
| 640 | ##enhance: look up the target name and publish that instead on export | 
|---|
| 641 | } | 
|---|
| 642 | } | 
|---|
| 643 |  | 
|---|
| 644 | ##enhance or ##fixme | 
|---|
| 645 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design | 
|---|
| 646 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) && | 
|---|
| 647 | ${$args{val}} =~ /\.arpa$/; | 
|---|
| 648 |  | 
|---|
| 649 | ##enhance:  Look up the passed value to see if it exists.  Ooo, fancy. | 
|---|
| 650 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec}); | 
|---|
| 651 | } else { | 
|---|
| 652 | # CNAME target check - IP addresses not allowed.  Must be a more or less well-formed hostname. | 
|---|
| 653 | return ('FAIL', "CNAME records cannot point directly to an IP address") | 
|---|
| 654 | if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/; | 
|---|
| 655 |  | 
|---|
| 656 | # Make sure target is a well-formed hostname | 
|---|
| 657 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}); | 
|---|
| 658 |  | 
|---|
| 659 | # Forcibly append the domain name if the hostname being added does not end with the current domain name | 
|---|
| 660 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id})); | 
|---|
| 661 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/i; | 
|---|
| 662 |  | 
|---|
| 663 | # CNAMEs can not be used for parent nodes;  just leaf nodes with no other record types | 
|---|
| 664 | # Enforce this for the zone name | 
|---|
| 665 | return ('FAIL', "The bare zone name may not be a CNAME") if ${$args{host}} eq $pname || ${$args{host}} =~ /^\@/; | 
|---|
| 666 |  | 
|---|
| 667 | ##enhance:  Look up the passed value to see if it exists.  Ooo, fancy. | 
|---|
| 668 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}); | 
|---|
| 669 | } | 
|---|
| 670 |  | 
|---|
| 671 | return ('OK','OK'); | 
|---|
| 672 | } # done CNAME record | 
|---|
| 673 |  | 
|---|
| 674 | # SOA record | 
|---|
| 675 | sub _validate_6 { | 
|---|
| 676 | # Smart monkeys won't stick their fingers in here;  we have | 
|---|
| 677 | # separate dedicated routines to deal with SOA records. | 
|---|
| 678 | return ('OK','OK'); | 
|---|
| 679 | } # done SOA record | 
|---|
| 680 |  | 
|---|
| 681 | # PTR record | 
|---|
| 682 | sub _validate_12 { | 
|---|
| 683 | my $self = shift; | 
|---|
| 684 | my $dbh = $self->{dbh}; | 
|---|
| 685 |  | 
|---|
| 686 | my %args = @_; | 
|---|
| 687 | my $warnflag = ''; | 
|---|
| 688 |  | 
|---|
| 689 | if ($args{defrec} eq 'y') { | 
|---|
| 690 | if ($args{revrec} eq 'y') { | 
|---|
| 691 | if (${$args{val}} =~ /^[\d.]+$/) { | 
|---|
| 692 | # v4 or bare number | 
|---|
| 693 | if (${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/) { | 
|---|
| 694 | # probable full IP.  pointless but harmless.  validate/normalize. | 
|---|
| 695 | my $tmp = NetAddr::IP->new(${$args{val}})->addr | 
|---|
| 696 | or return ('FAIL', "${$args{val}} is not a valid IP address"); | 
|---|
| 697 | ${$args{val}} = $tmp; | 
|---|
| 698 | $warnflag = "${$args{val}} will only be added to a small number of zones\n"; | 
|---|
| 699 | } elsif (${$args{val}} =~ /^\d+$/) { | 
|---|
| 700 | # bare number.  This can be expanded to either a v4 or v6 zone | 
|---|
| 701 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/; | 
|---|
| 702 | } else { | 
|---|
| 703 | # $deity-only-knows what kind of gibberish we've been given.  Only usable as a formal .arpa name. | 
|---|
| 704 | # Append ARPAZONE to be replaced with the formal .arpa zone name when converted to a live record. | 
|---|
| 705 | ${$args{val}} =~ s/\.*$/.ARPAZONE/ unless ${$args{val}} =~ /ARPAZONE$/; | 
|---|
| 706 | } | 
|---|
| 707 | } elsif (${$args{val}} =~ /^[a-fA-F0-9:]+$/) { | 
|---|
| 708 | # v6 or fragment;  pray it's not complete gibberish | 
|---|
| 709 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/; | 
|---|
| 710 | } else { | 
|---|
| 711 | # $deity-only-knows what kind of gibberish we've been given.  Only usable as a formal .arpa name. | 
|---|
| 712 | # Append ARPAZONE to be replaced with the formal .arpa zone name when converted to a live record. | 
|---|
| 713 | ${$args{val}} .= ".ARPAZONE" unless ${$args{val}} =~ /ARPAZONE$/; | 
|---|
| 714 | } | 
|---|
| 715 | } else { | 
|---|
| 716 | return ('FAIL', "PTR records are not supported in default record sets for forward zones (domains)"); | 
|---|
| 717 | } | 
|---|
| 718 | } else { | 
|---|
| 719 | if ($args{revrec} eq 'y') { | 
|---|
| 720 | # Get the revzone, so we can see if ${$args{val}} is in that zone | 
|---|
| 721 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y'); | 
|---|
| 722 |  | 
|---|
| 723 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone); | 
|---|
| 724 |  | 
|---|
| 725 | if (${$args{val}} =~ /\.arpa$/) { | 
|---|
| 726 | # Check that it's well-formed | 
|---|
| 727 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}); | 
|---|
| 728 |  | 
|---|
| 729 | # Check if it's a proper formal .arpa name for an IP, and renormalize it to the IP | 
|---|
| 730 | # value if so.  I can't see why someone would voluntarily work with those instead of | 
|---|
| 731 | # the natural IP values but what the hey. | 
|---|
| 732 | my ($code,$tmp) = _zone2cidr(${$args{val}}); | 
|---|
| 733 | ${$args{val}} = $tmp->addr if $code ne 'FAIL'; | 
|---|
| 734 | } else { | 
|---|
| 735 | # not a formal .arpa name, so it should be an IP value.  Validate... | 
|---|
| 736 | return ('FAIL', "${$args{val}} is not a valid IP value") | 
|---|
| 737 | unless ${$args{val}} =~ /^(?:\d+\.\d+\.\d+\.\d+|[a-fA-F0-9:]+)$/; | 
|---|
| 738 | $args{addr} = NetAddr::IP->new(${$args{val}}) | 
|---|
| 739 | or return ('FAIL', "IP/value looks like an IP address but isn't valid"); | 
|---|
| 740 | # ... and normalize. | 
|---|
| 741 | ${$args{val}} = $args{addr}->addr; | 
|---|
| 742 | } | 
|---|
| 743 | # Validate PTR target for form. | 
|---|
| 744 | # %blank% skips the IP when expanding a template record | 
|---|
| 745 | return ('FAIL', $errstr) | 
|---|
| 746 | unless _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) || | 
|---|
| 747 | lc(${$args{host}}) eq '%blank%'; | 
|---|
| 748 | } else { # revrec ne 'y' | 
|---|
| 749 | # Fetch the domain and append if the passed hostname isn't within it. | 
|---|
| 750 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id})); | 
|---|
| 751 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i); | 
|---|
| 752 | # Validate hostname and target for form | 
|---|
| 753 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec}); | 
|---|
| 754 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}); | 
|---|
| 755 | } | 
|---|
| 756 | } | 
|---|
| 757 |  | 
|---|
| 758 | # Multiple PTR records do NOT generally do what most people believe they do, | 
|---|
| 759 | # and tend to fail in the most awkward way possible.  Check and warn. | 
|---|
| 760 |  | 
|---|
| 761 | my $chkbase = ${$args{val}};; | 
|---|
| 762 | my $hostcol = 'val';  # Reverse zone hostnames are stored "backwards" | 
|---|
| 763 | if ($args{revrec} eq 'n') {   # PTRs in forward zones should be rare. | 
|---|
| 764 | $chkbase = ${$args{host}}; | 
|---|
| 765 | $hostcol = 'host'; | 
|---|
| 766 | } | 
|---|
| 767 | my @checkvals = ($chkbase); | 
|---|
| 768 | if ($chkbase =~ /,/) { | 
|---|
| 769 | # push . and :: variants into checkvals if $chkbase has , | 
|---|
| 770 | my $tmp; | 
|---|
| 771 | ($tmp = $chkbase) =~ s/,/./; | 
|---|
| 772 | push @checkvals, $tmp; | 
|---|
| 773 | ($tmp = $chkbase) =~ s/,/::/; | 
|---|
| 774 | push @checkvals, $tmp; | 
|---|
| 775 | } | 
|---|
| 776 |  | 
|---|
| 777 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE $hostcol = ?"); | 
|---|
| 778 | foreach my $checkme (@checkvals) { | 
|---|
| 779 | if ($args{update}) { | 
|---|
| 780 | # $args{update} contains the ID of the record being updated.  If the list of records that matches | 
|---|
| 781 | # the new hostname specification doesn't include this, the change effectively adds a new PTR that's | 
|---|
| 782 | # the same as one or more existing ones. | 
|---|
| 783 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}). | 
|---|
| 784 | " WHERE val = ?", undef, ($checkme)) }; | 
|---|
| 785 | $warnflag .= "PTR record for $checkme already exists;  adding another will probably not do what you want" | 
|---|
| 786 | if @ptrs && (!grep /^$args{update}$/, @ptrs); | 
|---|
| 787 | } else { | 
|---|
| 788 | # New record.  Always warn if a PTR exists | 
|---|
| 789 | # Don't warn when a matching A record exists tho | 
|---|
| 790 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}). | 
|---|
| 791 | " WHERE $hostcol = ? AND (type=12 OR type=65280 OR type=65281)", undef, ($checkme)); | 
|---|
| 792 | $warnflag .= "PTR record for $checkme already exists;  adding another will probably not do what you want" | 
|---|
| 793 | if $ptrcount; | 
|---|
| 794 | } | 
|---|
| 795 | } | 
|---|
| 796 |  | 
|---|
| 797 | return ('WARN',$warnflag) if $warnflag; | 
|---|
| 798 |  | 
|---|
| 799 | return ('OK','OK'); | 
|---|
| 800 | } # done PTR record | 
|---|
| 801 |  | 
|---|
| 802 | # MX record | 
|---|
| 803 | sub _validate_15 { | 
|---|
| 804 | my $self = shift; | 
|---|
| 805 | my $dbh = $self->{dbh}; | 
|---|
| 806 |  | 
|---|
| 807 | my %args = @_; | 
|---|
| 808 |  | 
|---|
| 809 | # only for strict type restrictions | 
|---|
| 810 | #  return ('FAIL', 'Reverse zones cannot contain MX records') if $args{revrec} eq 'y'; | 
|---|
| 811 |  | 
|---|
| 812 | return ('FAIL', "Distance is required for MX records") unless defined(${$args{dist}}); | 
|---|
| 813 | ${$args{dist}} =~ s/\s*//g; | 
|---|
| 814 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/; | 
|---|
| 815 |  | 
|---|
| 816 | ${$args{fields}} = "distance,"; | 
|---|
| 817 | push @{$args{vallist}}, ${$args{dist}}; | 
|---|
| 818 |  | 
|---|
| 819 | if ($args{revrec} eq 'n') { | 
|---|
| 820 | # MX target check - IP addresses not allowed.  Must be a more or less well-formed hostname. | 
|---|
| 821 | return ('FAIL', "MX records cannot point directly to an IP address") | 
|---|
| 822 | if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/; | 
|---|
| 823 |  | 
|---|
| 824 | # Coerce all hostnames to end in ".DOMAIN" for group/default records, | 
|---|
| 825 | # or the intended parent domain for live records. | 
|---|
| 826 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id})); | 
|---|
| 827 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i); | 
|---|
| 828 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec}); | 
|---|
| 829 | } else { | 
|---|
| 830 | # MX target check - IP addresses not allowed.  Must be a more or less well-formed hostname. | 
|---|
| 831 | return ('FAIL', "MX records cannot point directly to an IP address") | 
|---|
| 832 | if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/; | 
|---|
| 833 |  | 
|---|
| 834 | # MX records in reverse zones get stricter treatment.  The UI bars adding them in | 
|---|
| 835 | # reverse record sets, but we "need" to allow editing existing ones.  And we'll allow | 
|---|
| 836 | # editing them if some loon manually munges one into a default reverse record set. | 
|---|
| 837 | if ($args{defrec} eq 'n') { | 
|---|
| 838 | # Get the revzone, so we can see if ${$args{val}} is in that zone | 
|---|
| 839 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y'); | 
|---|
| 840 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone); | 
|---|
| 841 | } | 
|---|
| 842 |  | 
|---|
| 843 | ##enhance or ##fixme | 
|---|
| 844 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design | 
|---|
| 845 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) && | 
|---|
| 846 | ${$args{val}} =~ /\.arpa$/; | 
|---|
| 847 |  | 
|---|
| 848 | ##enhance:  Look up the passed value to see if it exists.  Ooo, fancy. | 
|---|
| 849 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec}); | 
|---|
| 850 |  | 
|---|
| 851 | } | 
|---|
| 852 |  | 
|---|
| 853 | return ('OK','OK'); | 
|---|
| 854 | } # done MX record | 
|---|
| 855 |  | 
|---|
| 856 | # TXT record | 
|---|
| 857 | sub _validate_16 { | 
|---|
| 858 | my $self = shift; | 
|---|
| 859 |  | 
|---|
| 860 | my %args = @_; | 
|---|
| 861 |  | 
|---|
| 862 | if ($args{revrec} eq 'n') { | 
|---|
| 863 | # Coerce all hostnames to end in ".DOMAIN" for group/default records, | 
|---|
| 864 | # or the intended parent domain for live records. | 
|---|
| 865 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id})); | 
|---|
| 866 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i); | 
|---|
| 867 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec}); | 
|---|
| 868 | } else { | 
|---|
| 869 | # We don't coerce reverse "hostnames" into the zone, mainly because we store most sane | 
|---|
| 870 | # records as IP values, not .arpa names. | 
|---|
| 871 | if ($args{defrec} eq 'n') { | 
|---|
| 872 | # Get the revzone, so we can see if ${$args{val}} is in that zone | 
|---|
| 873 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y'); | 
|---|
| 874 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone); | 
|---|
| 875 | } | 
|---|
| 876 |  | 
|---|
| 877 | ##enhance or ##fixme | 
|---|
| 878 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design | 
|---|
| 879 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) && | 
|---|
| 880 | ${$args{val}} =~ /\.arpa$/; | 
|---|
| 881 | } | 
|---|
| 882 |  | 
|---|
| 883 | # Could arguably put a WARN return here on very long (>512) records | 
|---|
| 884 | return ('OK','OK'); | 
|---|
| 885 | } # done TXT record | 
|---|
| 886 |  | 
|---|
| 887 | # RP record | 
|---|
| 888 | sub _validate_17 { | 
|---|
| 889 | # Probably have to validate these separately some day.  Call _validate_16() above since | 
|---|
| 890 | # they're otherwise very similar | 
|---|
| 891 | return _validate_16(@_); | 
|---|
| 892 | } # done RP record | 
|---|
| 893 |  | 
|---|
| 894 | # AAAA record | 
|---|
| 895 | # Almost but not quite an exact duplicate of A record | 
|---|
| 896 | sub _validate_28 { | 
|---|
| 897 | my $self = shift; | 
|---|
| 898 | my $dbh = $self->{dbh}; | 
|---|
| 899 |  | 
|---|
| 900 | my %args = @_; | 
|---|
| 901 |  | 
|---|
| 902 | # only for strict type restrictions | 
|---|
| 903 | #  return ('FAIL', 'Reverse zones cannot contain AAAA records') if $args{revrec} eq 'y'; | 
|---|
| 904 |  | 
|---|
| 905 | if ($args{revrec} eq 'y') { | 
|---|
| 906 | # Get the revzone, so we can see if ${$args{val}} is in that zone | 
|---|
| 907 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y'); | 
|---|
| 908 |  | 
|---|
| 909 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone); | 
|---|
| 910 |  | 
|---|
| 911 | # ${$args{val}} is either a valid IP or a string ending with the .arpa zone name; | 
|---|
| 912 | # now check if it's a well-formed FQDN | 
|---|
| 913 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) && | 
|---|
| 914 | ${$args{val}} =~ /\.arpa$/; | 
|---|
| 915 |  | 
|---|
| 916 | # Check IP is well-formed, and that it's a v4 address | 
|---|
| 917 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable. | 
|---|
| 918 | return ('FAIL',"AAAA record must be a valid IPv6 address") | 
|---|
| 919 | unless ${$args{host}} =~ /^[a-fA-F0-9:]+$/; | 
|---|
| 920 | $args{addr} = new NetAddr::IP ${$args{host}}; | 
|---|
| 921 | return ('FAIL',"AAAA record must be a valid IPv6 address") | 
|---|
| 922 | unless $args{addr} && $args{addr}->{isv6}; | 
|---|
| 923 | # coerce IP/value to normalized form for storage | 
|---|
| 924 | ${$args{host}} = $args{addr}->addr; | 
|---|
| 925 |  | 
|---|
| 926 | # I'm just going to ignore the utterly barmy idea of an AAAA record in the *default* | 
|---|
| 927 | # records for a reverse zone;  it's bad enough to find one in funky legacy data. | 
|---|
| 928 |  | 
|---|
| 929 | } else { | 
|---|
| 930 | # revrec ne 'y' | 
|---|
| 931 |  | 
|---|
| 932 | # Coerce all hostnames to end in ".DOMAIN" for group/default records, | 
|---|
| 933 | # or the intended parent domain for live records. | 
|---|
| 934 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id})); | 
|---|
| 935 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i); | 
|---|
| 936 |  | 
|---|
| 937 | # Check if it's a proper formal .arpa name for an IP, and renormalize it to the IP | 
|---|
| 938 | # value if so.  Done mainly for symmetry with PTR/AAAA+PTR, and saves a conversion on export. | 
|---|
| 939 | if (${$args{val}} =~ /\.arpa$/) { | 
|---|
| 940 | my ($code,$tmp) = _zone2cidr(${$args{val}}); | 
|---|
| 941 | if ($code ne 'FAIL') { | 
|---|
| 942 | ${$args{val}} = $tmp->addr; | 
|---|
| 943 | $args{addr} = $tmp; | 
|---|
| 944 | } | 
|---|
| 945 | } | 
|---|
| 946 | # Check IP is well-formed, and that it's a v6 address | 
|---|
| 947 | return ('FAIL',"AAAA record must be a valid IPv6 address") | 
|---|
| 948 | unless ${$args{val}} =~ /^[a-fA-F0-9:]+$/; | 
|---|
| 949 | $args{addr} = new NetAddr::IP ${$args{val}}; | 
|---|
| 950 | return ('FAIL',"AAAA record must be a valid IPv6 address") | 
|---|
| 951 | unless $args{addr} && $args{addr}->{isv6}; | 
|---|
| 952 | # coerce IP/value to normalized form for storage | 
|---|
| 953 | ${$args{val}} = $args{addr}->addr; | 
|---|
| 954 | } | 
|---|
| 955 |  | 
|---|
| 956 | return ('OK','OK'); | 
|---|
| 957 | } # done AAAA record | 
|---|
| 958 |  | 
|---|
| 959 | # SRV record | 
|---|
| 960 | sub _validate_33 { | 
|---|
| 961 | my $self = shift; | 
|---|
| 962 | my $dbh = $self->{dbh}; | 
|---|
| 963 |  | 
|---|
| 964 | my %args = @_; | 
|---|
| 965 |  | 
|---|
| 966 | # Not absolutely true but WTF use is an SRV record for a reverse zone? | 
|---|
| 967 | #  return ('FAIL', 'Reverse zones cannot contain SRV records') if $args{revrec} eq 'y'; | 
|---|
| 968 |  | 
|---|
| 969 | # Key additional record parts.  Always required. | 
|---|
| 970 | return ('FAIL',"Distance, port and weight are required for SRV records") | 
|---|
| 971 | unless defined(${$args{weight}}) && defined(${$args{port}}) && defined(${$args{dist}}); | 
|---|
| 972 | ${$args{dist}} =~ s/\s*//g; | 
|---|
| 973 | ${$args{weight}} =~ s/\s*//g; | 
|---|
| 974 | ${$args{port}} =~ s/\s*//g; | 
|---|
| 975 | return ('FAIL',"Distance, port and weight are required, and must be numeric") | 
|---|
| 976 | unless ${$args{weight}} =~ /^\d+$/ && ${$args{port}} =~ /^\d+$/; | 
|---|
| 977 |  | 
|---|
| 978 | ${$args{fields}} = "distance,weight,port,"; | 
|---|
| 979 | push @{$args{vallist}}, (${$args{dist}}, ${$args{weight}}, ${$args{port}}); | 
|---|
| 980 |  | 
|---|
| 981 | if ($args{revrec} eq 'n') { | 
|---|
| 982 | # Coerce all hostnames to end in ".DOMAIN" for group/default records, | 
|---|
| 983 | # or the intended parent domain for live records. | 
|---|
| 984 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id})); | 
|---|
| 985 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/i; | 
|---|
| 986 |  | 
|---|
| 987 | ##enhance:  Rejig so that we can pass back a WARN red flag, instead of | 
|---|
| 988 | # hard-failing, since it seems that purely from the DNS record perspective, | 
|---|
| 989 | # SRV records without underscores are syntactically valid | 
|---|
| 990 | # Not strictly true, but SRV records not following this convention won't be found. | 
|---|
| 991 | return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]") | 
|---|
| 992 | unless ${$args{host}} =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/; | 
|---|
| 993 |  | 
|---|
| 994 | # SRV target check - IP addresses not allowed.  Must be a more or less well-formed hostname. | 
|---|
| 995 | return ('FAIL', "SRV records cannot point directly to an IP address") | 
|---|
| 996 | if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/; | 
|---|
| 997 | } else { | 
|---|
| 998 | # hm.  we can't do anything sane with IP values here;  part of the record data is in | 
|---|
| 999 | # fact encoded in the "hostname".  enforce .arpa names?  OTOH, SRV records in a reverse | 
|---|
| 1000 | # zone are pretty silly. | 
|---|
| 1001 |  | 
|---|
| 1002 | ##enhance:  Rejig so that we can pass back a WARN red flag, instead of | 
|---|
| 1003 | # hard-failing, since it seems that purely from the DNS record perspective, | 
|---|
| 1004 | # SRV records without underscores are syntactically valid | 
|---|
| 1005 | # Not strictly true, but SRV records not following this convention won't be found. | 
|---|
| 1006 | return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]") | 
|---|
| 1007 | unless ${$args{val}} =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/; | 
|---|
| 1008 |  | 
|---|
| 1009 | # SRV target check - IP addresses not allowed.  Must be a more or less well-formed hostname. | 
|---|
| 1010 | return ('FAIL', "SRV records cannot point directly to an IP address") | 
|---|
| 1011 | if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/; | 
|---|
| 1012 |  | 
|---|
| 1013 | # SRV records in reverse zones get stricter treatment.  The UI bars adding them in | 
|---|
| 1014 | # reverse record sets, but we "need" to allow editing existing ones.  And we'll allow | 
|---|
| 1015 | # editing them if some loon manually munges one into a default reverse record set. | 
|---|
| 1016 | if ($args{defrec} eq 'n') { | 
|---|
| 1017 | # Get the revzone, so we can see if ${$args{val}} is in that zone | 
|---|
| 1018 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y'); | 
|---|
| 1019 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone); | 
|---|
| 1020 | } | 
|---|
| 1021 |  | 
|---|
| 1022 | ##enhance or ##fixme | 
|---|
| 1023 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design | 
|---|
| 1024 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) && | 
|---|
| 1025 | ${$args{val}} =~ /\.arpa$/; | 
|---|
| 1026 |  | 
|---|
| 1027 | ##enhance:  Look up the passed value to see if it exists.  Ooo, fancy. | 
|---|
| 1028 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec}); | 
|---|
| 1029 |  | 
|---|
| 1030 | } | 
|---|
| 1031 |  | 
|---|
| 1032 | return ('OK','OK'); | 
|---|
| 1033 | } # done SRV record | 
|---|
| 1034 |  | 
|---|
| 1035 | # Now the custom types | 
|---|
| 1036 |  | 
|---|
| 1037 | # A+PTR record.  With a very little bit of magic we can also use this sub to validate AAAA+PTR.  Whee! | 
|---|
| 1038 | sub _validate_65280 { | 
|---|
| 1039 | my $self = shift; | 
|---|
| 1040 | my $dbh = $self->{dbh}; | 
|---|
| 1041 |  | 
|---|
| 1042 | my %args = @_; | 
|---|
| 1043 |  | 
|---|
| 1044 | my $code = 'OK'; | 
|---|
| 1045 | my $msg = 'OK'; | 
|---|
| 1046 |  | 
|---|
| 1047 | if ($args{defrec} eq 'n') { | 
|---|
| 1048 | # live record;  revrec determines whether we validate the PTR or A component first. | 
|---|
| 1049 |  | 
|---|
| 1050 | # Fail early on non-IP gibberish in ${$args{val}}.  Arguably .arpa names might be acceptable | 
|---|
| 1051 | # but that gets stupid in forward zones, since these records are shared. | 
|---|
| 1052 | return ('FAIL', "$typemap{${$args{rectype}}} record must be a valid IPv4 address") | 
|---|
| 1053 | if ${$args{rectype}} == 65280 && ${$args{val}} !~ m{^\d+\.\d+\.\d+\.\d+(?:/\d+)?$}; | 
|---|
| 1054 | return ('FAIL', "$typemap{${$args{rectype}}} record must be a valid IPv6 address") | 
|---|
| 1055 | if ${$args{rectype}} == 65281 && ${$args{val}} !~ m{^[a-fA-F0-9:]+(?:/\d+)?$}; | 
|---|
| 1056 | # If things are not OK, this should prevent Stupid in the error log. | 
|---|
| 1057 | $args{addr} = new NetAddr::IP ${$args{val}} | 
|---|
| 1058 | or return ('FAIL', "$typemap{${$args{rectype}}} record must be a valid IPv". | 
|---|
| 1059 | (${$args{rectype}} == 65280 ? '4' : '6')." address"); | 
|---|
| 1060 | ${$args{val}} = $args{addr}->addr; | 
|---|
| 1061 |  | 
|---|
| 1062 | if ($args{revrec} eq 'y') { | 
|---|
| 1063 | ($code,$msg) = $self->_validate_12(%args); | 
|---|
| 1064 | return ($code,$msg) if $code eq 'FAIL'; | 
|---|
| 1065 |  | 
|---|
| 1066 | # check A+PTR is really v4 | 
|---|
| 1067 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address") | 
|---|
| 1068 | if ${$args{rectype}} == 65280 && $args{addr}->{isv6}; | 
|---|
| 1069 | # check AAAA+PTR is really v6 | 
|---|
| 1070 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address") | 
|---|
| 1071 | if ${$args{rectype}} == 65281 && !$args{addr}->{isv6}; | 
|---|
| 1072 |  | 
|---|
| 1073 | # Check if the reqested domain exists.  If not, coerce the type down to PTR and warn. | 
|---|
| 1074 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) { | 
|---|
| 1075 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added'). | 
|---|
| 1076 | " as PTR instead of $typemap{${$args{rectype}}};  domain not found for ${$args{host}}"; | 
|---|
| 1077 | $msg .= "\n$addmsg" if $code eq 'WARN'; | 
|---|
| 1078 | $msg = $addmsg if $code eq 'OK'; | 
|---|
| 1079 | ${$args{rectype}} = $reverse_typemap{PTR}; | 
|---|
| 1080 | return ('WARN', $msg); | 
|---|
| 1081 | } | 
|---|
| 1082 |  | 
|---|
| 1083 | # Add domain ID to field list and values | 
|---|
| 1084 | ${$args{fields}} .= "domain_id,"; | 
|---|
| 1085 | push @{$args{vallist}}, ${$args{domid}}; | 
|---|
| 1086 |  | 
|---|
| 1087 | } else { | 
|---|
| 1088 | ($code,$msg) = $self->_validate_1(%args) if ${$args{rectype}} == 65280; | 
|---|
| 1089 | ($code,$msg) = $self->_validate_28(%args) if ${$args{rectype}} == 65281; | 
|---|
| 1090 | return ($code,$msg) if $code eq 'FAIL'; | 
|---|
| 1091 |  | 
|---|
| 1092 | # Check if the requested reverse zone exists - note, an IP fragment won't | 
|---|
| 1093 | # work here since we don't *know* which parent to put it in. | 
|---|
| 1094 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls. | 
|---|
| 1095 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?". | 
|---|
| 1096 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}})); | 
|---|
| 1097 | if (!$revid) { | 
|---|
| 1098 | $msg = "Record ".($args{update} ? 'updated' : 'added')." as ".(${$args{rectype}} == 65280 ? 'A' : 'AAAA'). | 
|---|
| 1099 | " instead of $typemap{${$args{rectype}}};  reverse zone not found for ${$args{val}}"; | 
|---|
| 1100 | ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA}); | 
|---|
| 1101 | return ('WARN', $msg); | 
|---|
| 1102 | } | 
|---|
| 1103 |  | 
|---|
| 1104 | # Check for duplicate PTRs.  Note we don't have to play games with $code and $msg, because | 
|---|
| 1105 | # by definition there can't be duplicate PTRs if the reverse zone isn't managed here. | 
|---|
| 1106 | if ($args{update}) { | 
|---|
| 1107 | # Record update.  There should usually be an existing PTR (the record being updated) | 
|---|
| 1108 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}). | 
|---|
| 1109 | " WHERE val = ?", undef, (${$args{val}})) }; | 
|---|
| 1110 | if (@ptrs && (!grep /^$args{update}$/, @ptrs)) { | 
|---|
| 1111 | $msg = "PTR record for ${$args{val}} already exists;  adding another will probably not do what you want"; | 
|---|
| 1112 | $code = 'WARN'; | 
|---|
| 1113 | } | 
|---|
| 1114 | } else { | 
|---|
| 1115 | # New record.  Always warn if a PTR exists | 
|---|
| 1116 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}). | 
|---|
| 1117 | " WHERE val = ?", undef, (${$args{val}})); | 
|---|
| 1118 | $msg = "PTR record for ${$args{val}} already exists;  adding another will probably not do what you want" | 
|---|
| 1119 | if $ptrcount; | 
|---|
| 1120 | $code = 'WARN' if $ptrcount; | 
|---|
| 1121 | } | 
|---|
| 1122 |  | 
|---|
| 1123 | # Add the reverse zone ID to the fieldlist | 
|---|
| 1124 | ${$args{fields}} .= "rdns_id,"; | 
|---|
| 1125 | push @{$args{vallist}}, $revid; | 
|---|
| 1126 |  | 
|---|
| 1127 | # Coerce the hostname back to the domain;  this is so it displays and manipulates | 
|---|
| 1128 | # sanely in the reverse zone. | 
|---|
| 1129 | if (${$args{host}} eq '@') { | 
|---|
| 1130 | ${$args{host}} = $self->domainName($args{id});  # errors?  What errors? | 
|---|
| 1131 | } | 
|---|
| 1132 | } # revrec ne 'y' | 
|---|
| 1133 |  | 
|---|
| 1134 | } else {      # defrec eq 'y' | 
|---|
| 1135 |  | 
|---|
| 1136 | if ($args{revrec} eq 'y') { | 
|---|
| 1137 | ($code,$msg) = $self->_validate_12(%args); | 
|---|
| 1138 | return ($code,$msg) if $code eq 'FAIL'; | 
|---|
| 1139 | if (${$args{rectype}} == 65280) { | 
|---|
| 1140 | return ('FAIL',"A+PTR record must be a valid IPv4 address or fragment") | 
|---|
| 1141 | if ${$args{val}} =~ /:/; | 
|---|
| 1142 | ${$args{val}} =~ s/^ZONE,/ZONE./;       # Clean up after uncertain IP-fragment-type from _validate_12 | 
|---|
| 1143 | } elsif (${$args{rectype}} == 65281) { | 
|---|
| 1144 | return ('FAIL',"AAAA+PTR record must be a valid IPv6 address or fragment") | 
|---|
| 1145 | if ${$args{val}} =~ /\./; | 
|---|
| 1146 | ${$args{val}} =~ s/^ZONE,/ZONE::/;      # Clean up after uncertain IP-fragment-type from _validate_12 | 
|---|
| 1147 | } | 
|---|
| 1148 | } else { | 
|---|
| 1149 | # This is easy.  I also can't see a real use-case for A/AAAA+PTR in *all* forward | 
|---|
| 1150 | # domains, since you wouldn't be able to substitute both domain and reverse zone | 
|---|
| 1151 | # sanely, and you'd end up with guaranteed over-replicated PTR records that would | 
|---|
| 1152 | # confuse the hell out of pretty much anything that uses them. | 
|---|
| 1153 | ##fixme: make this a config flag? | 
|---|
| 1154 | return ('FAIL', "$typemap{${$args{rectype}}} records not allowed in default domains"); | 
|---|
| 1155 | } | 
|---|
| 1156 | } | 
|---|
| 1157 |  | 
|---|
| 1158 | return ($code, $msg); | 
|---|
| 1159 | } # done A+PTR record | 
|---|
| 1160 |  | 
|---|
| 1161 | # AAAA+PTR record | 
|---|
| 1162 | # A+PTR above has been magicked to handle AAAA+PTR as well. | 
|---|
| 1163 | sub _validate_65281 { | 
|---|
| 1164 | return _validate_65280(@_); | 
|---|
| 1165 | } # done AAAA+PTR record | 
|---|
| 1166 |  | 
|---|
| 1167 | # PTR template record | 
|---|
| 1168 | sub _validate_65282 { | 
|---|
| 1169 | my $self = shift; | 
|---|
| 1170 | my $dbh = $self->{dbh}; | 
|---|
| 1171 |  | 
|---|
| 1172 | my %args = @_; | 
|---|
| 1173 |  | 
|---|
| 1174 | # we're *this* >.< close to being able to just call _validate_12... unfortunately we can't, quite. | 
|---|
| 1175 | if ($args{revrec} eq 'y') { | 
|---|
| 1176 | if ($args{defrec} eq 'n') { | 
|---|
| 1177 | return ('FAIL', "Template block ${$args{val}} is not within ".$self->revName($args{id})) | 
|---|
| 1178 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr}); | 
|---|
| 1179 | ##fixme:  warn if $args{val} is not /31 or larger block? | 
|---|
| 1180 | ${$args{val}} = "$args{addr}"; | 
|---|
| 1181 | } else { | 
|---|
| 1182 | if (${$args{val}} =~ /\./) { | 
|---|
| 1183 | # looks like a v4 or fragment | 
|---|
| 1184 | if (${$args{val}} =~ m|^\d+\.\d+\.\d+\.\d+(?:/\d+)?$|) { | 
|---|
| 1185 | # woo!  a complete IP!  validate it and normalize, or fail. | 
|---|
| 1186 | $args{addr} = NetAddr::IP->new(${$args{val}}) | 
|---|
| 1187 | or return ('FAIL', "IP/value looks like IPv4 but isn't valid"); | 
|---|
| 1188 | ${$args{val}} = "$args{addr}"; | 
|---|
| 1189 | } else { | 
|---|
| 1190 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/; | 
|---|
| 1191 | } | 
|---|
| 1192 | } elsif (${$args{val}} =~ /[a-f:]/) { | 
|---|
| 1193 | # looks like a v6 or fragment | 
|---|
| 1194 | ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/; | 
|---|
| 1195 | if ($args{addr}) { | 
|---|
| 1196 | if ($args{addr}->addr =~ /^0/) { | 
|---|
| 1197 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/; | 
|---|
| 1198 | } else { | 
|---|
| 1199 | ${$args{val}} = "$args{addr}"; | 
|---|
| 1200 | } | 
|---|
| 1201 | } | 
|---|
| 1202 | } else { | 
|---|
| 1203 | # bare number (probably).  These could be v4 or v6, so we'll | 
|---|
| 1204 | # expand on these on creation of a reverse zone. | 
|---|
| 1205 | ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/; | 
|---|
| 1206 | } | 
|---|
| 1207 | } | 
|---|
| 1208 | ##fixme:  validate %-patterns? | 
|---|
| 1209 |  | 
|---|
| 1210 | # Unlike single PTR records, there is absolutely no way to sanely support multiple | 
|---|
| 1211 | # PTR templates for the same block, since they expect to expand to all the individual | 
|---|
| 1212 | # IPs on export.  Nested templates should be supported though. | 
|---|
| 1213 |  | 
|---|
| 1214 | my @checkvals = (${$args{val}}); | 
|---|
| 1215 | if (${$args{val}} =~ /,/) { | 
|---|
| 1216 | # push . and :: variants into checkvals if val has , | 
|---|
| 1217 | my $tmp; | 
|---|
| 1218 | ($tmp = ${$args{val}}) =~ s/,/./; | 
|---|
| 1219 | push @checkvals, $tmp; | 
|---|
| 1220 | ($tmp = ${$args{val}}) =~ s/,/::/; | 
|---|
| 1221 | push @checkvals, $tmp; | 
|---|
| 1222 | } | 
|---|
| 1223 | ##fixme:  this feels wrong still - need to restrict template pseudorecords to One Of Each | 
|---|
| 1224 | # Per Netblock such that they don't conflict on export | 
|---|
| 1225 | my $typeck; | 
|---|
| 1226 | # type 65282 -> ptr template -> look for any of 65282, 65283, 65284 | 
|---|
| 1227 | $typeck = 'type=65283 OR type=65284' if ${$args{rectype}} == 65282; | 
|---|
| 1228 | # type 65283 -> a+ptr template -> v4 -> look for 65282 or 65283 | 
|---|
| 1229 | $typeck = 'type=65283' if ${$args{rectype}} == 65282; | 
|---|
| 1230 | # type 65284 -> aaaa+ptr template -> v6 -> look for 65282 or 65284 | 
|---|
| 1231 | $typeck = 'type=65284' if ${$args{rectype}} == 65282; | 
|---|
| 1232 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ? ". | 
|---|
| 1233 | "AND (type=65282 OR $typeck)"); | 
|---|
| 1234 | foreach my $checkme (@checkvals) { | 
|---|
| 1235 | $pcsth->execute($checkme); | 
|---|
| 1236 | my ($rc) = $pcsth->fetchrow_array; | 
|---|
| 1237 | return ('FAIL', "Only one template pseudorecord may exist for a given IP block") if $rc > 1; | 
|---|
| 1238 | } | 
|---|
| 1239 |  | 
|---|
| 1240 | } else { | 
|---|
| 1241 | return ('FAIL', "Forward zones cannot contain PTR records"); | 
|---|
| 1242 | } | 
|---|
| 1243 |  | 
|---|
| 1244 | return ('OK','OK'); | 
|---|
| 1245 | } # done PTR template record | 
|---|
| 1246 |  | 
|---|
| 1247 | # A+PTR template record | 
|---|
| 1248 | sub _validate_65283 { | 
|---|
| 1249 | my $self = shift; | 
|---|
| 1250 | my $dbh = $self->{dbh}; | 
|---|
| 1251 |  | 
|---|
| 1252 | my %args = @_; | 
|---|
| 1253 |  | 
|---|
| 1254 | my ($code,$msg) = ('OK','OK'); | 
|---|
| 1255 |  | 
|---|
| 1256 | ##fixme:  need to fiddle things since A+PTR templates are acceptable in live | 
|---|
| 1257 | # forward zones but not default records | 
|---|
| 1258 | if ($args{defrec} eq 'n') { | 
|---|
| 1259 | if ($args{revrec} eq 'n') { | 
|---|
| 1260 |  | 
|---|
| 1261 | # Coerce all hostnames to end in ".DOMAIN" for group/default records, | 
|---|
| 1262 | # or the intended parent domain for live records. | 
|---|
| 1263 | my $pname = $self->domainName($args{id}); | 
|---|
| 1264 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/i; | 
|---|
| 1265 |  | 
|---|
| 1266 | # check for form;  note this checks both normal and "other" hostnames. | 
|---|
| 1267 | return ('FAIL', $errstr) | 
|---|
| 1268 | if !_check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec}); | 
|---|
| 1269 |  | 
|---|
| 1270 | # Check if the requested reverse zone exists - note, an IP fragment won't | 
|---|
| 1271 | # work here since we don't *know* which parent to put it in. | 
|---|
| 1272 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls. | 
|---|
| 1273 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?". | 
|---|
| 1274 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}})); | 
|---|
| 1275 | # Fail if no match;  we can't coerce a PTR-template type down to not include the PTR bit currently. | 
|---|
| 1276 | if (!$revid) { | 
|---|
| 1277 | $msg = "Can't ".($args{update} ? 'update' : 'add')." ${$args{host}}/${$args{val}} as ". | 
|---|
| 1278 | "$typemap{${$args{rectype}}}:  reverse zone not found for ${$args{val}}"; | 
|---|
| 1279 | ##fixme:  add A template, AAAA template types? | 
|---|
| 1280 | #       ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA}); | 
|---|
| 1281 | return ('FAIL', $msg); | 
|---|
| 1282 | } | 
|---|
| 1283 |  | 
|---|
| 1284 | # Add reverse zone ID to field list and values | 
|---|
| 1285 | ${$args{fields}} .= "rdns_id,"; | 
|---|
| 1286 | push @{$args{vallist}}, $revid; | 
|---|
| 1287 |  | 
|---|
| 1288 | } else { | 
|---|
| 1289 | return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".$self->revName($args{id})) | 
|---|
| 1290 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr}); | 
|---|
| 1291 | ${$args{val}} = "$args{addr}"; | 
|---|
| 1292 |  | 
|---|
| 1293 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) { | 
|---|
| 1294 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added'). | 
|---|
| 1295 | " as PTR template instead of $typemap{${$args{rectype}}};  domain not found for ${$args{host}}"; | 
|---|
| 1296 | $msg .= "\n$addmsg" if $code eq 'WARN'; | 
|---|
| 1297 | $msg = $addmsg if $code eq 'OK'; | 
|---|
| 1298 | ${$args{rectype}} = 65282; | 
|---|
| 1299 | return ('WARN', $msg); | 
|---|
| 1300 | } | 
|---|
| 1301 |  | 
|---|
| 1302 | # Add domain ID to field list and values | 
|---|
| 1303 | ${$args{fields}} .= "domain_id,"; | 
|---|
| 1304 | push @{$args{vallist}}, ${$args{domid}}; | 
|---|
| 1305 | } | 
|---|
| 1306 |  | 
|---|
| 1307 | } else { | 
|---|
| 1308 | my ($code,$msg) = $self->_validate_65282(%args); | 
|---|
| 1309 | return ($code, $msg) if $code eq 'FAIL'; | 
|---|
| 1310 | # get domain, check against ${$args{name}} | 
|---|
| 1311 | } | 
|---|
| 1312 |  | 
|---|
| 1313 | return ('OK','OK'); | 
|---|
| 1314 | } # done A+PTR template record | 
|---|
| 1315 |  | 
|---|
| 1316 | # AAAA+PTR template record | 
|---|
| 1317 | # Not sure this can be handled sanely due to the size of IPv6 address space | 
|---|
| 1318 | # _validate_65283 above should handle v6 template records fine.  It's on export we've got trouble. | 
|---|
| 1319 | sub _validate_65284 { | 
|---|
| 1320 | my $self = shift; | 
|---|
| 1321 | my %args = @_; | 
|---|
| 1322 |  | 
|---|
| 1323 | # do a quick check on the form of the hostname part;  this is effectively a | 
|---|
| 1324 | # "*.0.0.f.ip6.arpa" hostname, not an actual expandable IP template pattern | 
|---|
| 1325 | # like with 65283. | 
|---|
| 1326 | return ('FAIL', $errstr) | 
|---|
| 1327 | if !_check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec}); | 
|---|
| 1328 | return $self->_validate_65283(%args); | 
|---|
| 1329 | } # done AAAA+PTR template record | 
|---|
| 1330 |  | 
|---|
| 1331 | # Delegation record | 
|---|
| 1332 | # This is essentially a specialized clone of the NS record, primarily useful | 
|---|
| 1333 | # for delegating IPv4 sub-/24 reverse blocks | 
|---|
| 1334 | sub _validate_65285 { | 
|---|
| 1335 | my $self = shift; | 
|---|
| 1336 | my $dbh = $self->{dbh}; | 
|---|
| 1337 |  | 
|---|
| 1338 | my %args = @_; | 
|---|
| 1339 |  | 
|---|
| 1340 | # Almost, but not quite, identical to NS record validation. | 
|---|
| 1341 |  | 
|---|
| 1342 | # Check that the target of the record is within the parent. | 
|---|
| 1343 | # Yes, host<->val are mixed up here;  can't see a way to avoid it.  :( | 
|---|
| 1344 | if ($args{defrec} eq 'n') { | 
|---|
| 1345 | # Check if IP/address/zone/"subzone" is within the parent | 
|---|
| 1346 | if ($args{revrec} eq 'y') { | 
|---|
| 1347 | my $tmpip = NetAddr::IP->new(${$args{val}}); | 
|---|
| 1348 | my $pname = $self->revName($args{id}); | 
|---|
| 1349 | return ('FAIL',"${$args{val}} not within $pname") | 
|---|
| 1350 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$tmpip); | 
|---|
| 1351 | # Normalize | 
|---|
| 1352 | ${$args{val}} = "$tmpip"; | 
|---|
| 1353 | } else { | 
|---|
| 1354 | my $pname = $self->domainName($args{id}); | 
|---|
| 1355 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/i; | 
|---|
| 1356 | } | 
|---|
| 1357 | } else { | 
|---|
| 1358 | return ('FAIL',"Delegation records are not permitted in default record sets"); | 
|---|
| 1359 | } | 
|---|
| 1360 | return ('OK','OK'); | 
|---|
| 1361 | } | 
|---|
| 1362 |  | 
|---|
| 1363 | # Subs not specific to a particular record type | 
|---|
| 1364 |  | 
|---|
| 1365 | # Convert $$host and/or $$val to lowercase as appropriate. | 
|---|
| 1366 | # Should only be called if $self->{lowercase} is true. | 
|---|
| 1367 | # $rectype is also a reference for caller convenience | 
|---|
| 1368 | sub _caseclean { | 
|---|
| 1369 | my ($rectype, $host, $val, $defrec, $revrec) = @_; | 
|---|
| 1370 |  | 
|---|
| 1371 | # Can't case-squash default records, due to DOMAIN, ZONE, and ADMINDOMAIN templating | 
|---|
| 1372 | return if $defrec eq 'y'; | 
|---|
| 1373 |  | 
|---|
| 1374 | if ($typemap{$$rectype} eq 'TXT' || $typemap{$$rectype} eq 'SPF') { | 
|---|
| 1375 | # TXT records should preserve user entry in the string. | 
|---|
| 1376 | # SPF records are a duplicate of TXT with a new record type value (99) | 
|---|
| 1377 | $$host = lc($$host) if $revrec eq 'n';      # only lowercase $$host on live forward TXT;  preserve TXT content | 
|---|
| 1378 | $$val = lc($$val) if $revrec eq 'y';        # only lowercase $$val on live reverse TXT;  preserve TXT content | 
|---|
| 1379 | } else { | 
|---|
| 1380 | # Non-TXT, live records, are fully case-insensitive | 
|---|
| 1381 | $$host = lc($$host); | 
|---|
| 1382 | $$val = lc($$val); | 
|---|
| 1383 | } # $typemap{$$rectype} else | 
|---|
| 1384 |  | 
|---|
| 1385 | } # _caseclean() | 
|---|
| 1386 |  | 
|---|
| 1387 |  | 
|---|
| 1388 | ## | 
|---|
| 1389 | ## Record data substitution subs | 
|---|
| 1390 | ## | 
|---|
| 1391 |  | 
|---|
| 1392 | # Replace ZONE in hostname, or create (most of) the actual proper zone name | 
|---|
| 1393 | sub _ZONE { | 
|---|
| 1394 | my $zone = shift; | 
|---|
| 1395 | my $string = shift; | 
|---|
| 1396 | my $fr = shift || 'f';        # flag for forward/reverse order?  nb: ignored for IP | 
|---|
| 1397 | my $sep = shift || '-';       # Separator character - unlikely we'll ever need more than . or - | 
|---|
| 1398 |  | 
|---|
| 1399 | my $prefix; | 
|---|
| 1400 |  | 
|---|
| 1401 | $string =~ s/,/./ if !$zone->{isv6}; | 
|---|
| 1402 | $string =~ s/,/::/ if $zone->{isv6}; | 
|---|
| 1403 |  | 
|---|
| 1404 | # Subbing ZONE in the host.  We need to properly ID the netblock range | 
|---|
| 1405 | # The subbed text should have "network IP with trailing zeros stripped" for | 
|---|
| 1406 | # blocks lined up on octet (for v4) or hex-quad (for v6) boundaries | 
|---|
| 1407 | # For blocks that do NOT line up on these boundaries, we take the most | 
|---|
| 1408 | # significant octet or 16-bit chunk of the "broadcast" IP and append it | 
|---|
| 1409 | # after a double-dash | 
|---|
| 1410 | # ie: | 
|---|
| 1411 | # 8.0.0.0/6 -> 8.0.0.0 -> 11.255.255.255;  sub should be 8--11 | 
|---|
| 1412 | # 10.0.0.0/12 -> 10.0.0.0 -> 10.0.0.0 -> 10.15.255.255;  sub should be 10-0--15 | 
|---|
| 1413 | # 192.168.4.0/22 -> 192.168.4.0 -> 192.168.7.255;  sub should be 192-168-4--7 | 
|---|
| 1414 | # 192.168.0.8/29 -> 192.168.0.8 -> 192.168.0.15;  sub should be 192-168-0-8--15 | 
|---|
| 1415 | # Similar for v6 | 
|---|
| 1416 |  | 
|---|
| 1417 | if (!$zone->{isv6}) { # IPv4 | 
|---|
| 1418 |  | 
|---|
| 1419 | $prefix = $zone->network->addr;     # Just In Case someone managed to slip in | 
|---|
| 1420 | # a funky subnet that had host bits set. | 
|---|
| 1421 | my $bc = $zone->broadcast->addr; | 
|---|
| 1422 |  | 
|---|
| 1423 | if ($zone->masklen > 24) { | 
|---|
| 1424 | $bc =~ s/^\d+\.\d+\.\d+\.//; | 
|---|
| 1425 | } elsif ($zone->masklen > 16) { | 
|---|
| 1426 | $prefix =~ s/\.0$//; | 
|---|
| 1427 | $bc =~ s/^\d+\.\d+\.//; | 
|---|
| 1428 | } elsif ($zone->masklen > 8) { | 
|---|
| 1429 | $bc =~ s/^\d+\.//; | 
|---|
| 1430 | $prefix =~ s/\.0\.0$//; | 
|---|
| 1431 | } else { | 
|---|
| 1432 | $prefix =~ s/\.0\.0\.0$//; | 
|---|
| 1433 | } | 
|---|
| 1434 | if ($zone->masklen % 8) { | 
|---|
| 1435 | $bc =~ s/(\.255)+$//; | 
|---|
| 1436 | $prefix .= "--$bc";       #"--".zone->masklen;    # use range or mask length? | 
|---|
| 1437 | } | 
|---|
| 1438 | if ($fr eq 'f') { | 
|---|
| 1439 | $prefix =~ s/\.+/$sep/g; | 
|---|
| 1440 | } else { | 
|---|
| 1441 | $prefix = join($sep, reverse(split(/\./, $prefix))); | 
|---|
| 1442 | } | 
|---|
| 1443 |  | 
|---|
| 1444 | } else { # IPv6 | 
|---|
| 1445 |  | 
|---|
| 1446 | if ($fr eq 'f') { | 
|---|
| 1447 |  | 
|---|
| 1448 | $prefix = $zone->network->addr;   # Just In Case someone managed to slip in | 
|---|
| 1449 | # a funky subnet that had host bits set. | 
|---|
| 1450 | my $bc = $zone->broadcast->addr; | 
|---|
| 1451 | if (($zone->masklen % 16) != 0) { | 
|---|
| 1452 | # Strip trailing :0 off $prefix, and :ffff off the broadcast IP | 
|---|
| 1453 | for (my $i=0; $i<(7-int($zone->masklen / 16)); $i++) { | 
|---|
| 1454 | $prefix =~ s/:0$//; | 
|---|
| 1455 | $bc =~ s/:ffff$//; | 
|---|
| 1456 | } | 
|---|
| 1457 | # Strip the leading 16-bit chunks off the front of the broadcast IP | 
|---|
| 1458 | $bc =~ s/^([a-f0-9]+:)+//; | 
|---|
| 1459 | # Append the remaining 16-bit chunk to the prefix after "--" | 
|---|
| 1460 | $prefix .= "--$bc"; | 
|---|
| 1461 | } else { | 
|---|
| 1462 | # Strip off :0 from the end until we reach the netblock length. | 
|---|
| 1463 | for (my $i=0; $i<(8-$zone->masklen / 16); $i++) { | 
|---|
| 1464 | $prefix =~ s/:0$//; | 
|---|
| 1465 | } | 
|---|
| 1466 | } | 
|---|
| 1467 | # Actually deal with the separator | 
|---|
| 1468 | $prefix =~ s/:/$sep/g; | 
|---|
| 1469 |  | 
|---|
| 1470 | } else {    # $fr eq 'f' | 
|---|
| 1471 |  | 
|---|
| 1472 | $prefix = $zone->network->full;   # Just In Case someone managed to slip in | 
|---|
| 1473 | # a funky subnet that had host bits set. | 
|---|
| 1474 | my $bc = $zone->broadcast->full; | 
|---|
| 1475 | $prefix =~ s/://g;        # clean these out since they're not spaced right for this case | 
|---|
| 1476 | $bc =~ s/://g; | 
|---|
| 1477 | # Strip trailing 0 off $prefix, and f off the broadcast IP, to match the mask length | 
|---|
| 1478 | for (my $i=0; $i<(31-int($zone->masklen / 4)); $i++) { | 
|---|
| 1479 | $prefix =~ s/0$//; | 
|---|
| 1480 | $bc =~ s/f$//; | 
|---|
| 1481 | } | 
|---|
| 1482 | # Split and reverse the order of the nibbles in the network/broadcast IPs | 
|---|
| 1483 | # trim another 0 for nibble-aligned blocks first, but only if we really have a block, not an IP | 
|---|
| 1484 | $prefix =~ s/0$// if $zone->masklen % 4 == 0 && $zone->masklen != 128; | 
|---|
| 1485 | my @nbits = reverse split //, $prefix; | 
|---|
| 1486 | my @bbits = reverse split //, $bc; | 
|---|
| 1487 | # Handle the sub-nibble case.  Eww.  I feel dirty supporting this... | 
|---|
| 1488 | $nbits[0] = "$nbits[0]-$bbits[0]" if ($zone->masklen % 4) != 0; | 
|---|
| 1489 | # Glue it back together | 
|---|
| 1490 | $prefix = join($sep, @nbits); | 
|---|
| 1491 |  | 
|---|
| 1492 | }   # $fr ne 'f' | 
|---|
| 1493 |  | 
|---|
| 1494 | } # $zone->{isv6} | 
|---|
| 1495 |  | 
|---|
| 1496 | # Do the substitution, finally | 
|---|
| 1497 | $string =~ s/ZONE/$prefix/; | 
|---|
| 1498 | $string =~ s/--/-/ if $sep ne '-';    # - as separator needs extra help for sub-octet v4 netblocks | 
|---|
| 1499 | return $string; | 
|---|
| 1500 | } # done _ZONE() | 
|---|
| 1501 |  | 
|---|
| 1502 | # Not quite a substitution sub, but placed here as it's basically the inverse of above; | 
|---|
| 1503 | # given the .arpa zone name, return the CIDR netblock the zone is for. | 
|---|
| 1504 | # Supports v4 non-octet/non-classful netblocks as per the method outlined in the Grasshopper Book (2nd Ed p217-218) | 
|---|
| 1505 | # Does NOT support non-quad v6 netblocks via the same scheme;  it shouldn't ever be necessary. | 
|---|
| 1506 | # Takes a nominal .arpa zone name, returns a success code and NetAddr::IP, or a fail code and message | 
|---|
| 1507 | sub _zone2cidr { | 
|---|
| 1508 | my $zone = shift; | 
|---|
| 1509 |  | 
|---|
| 1510 | my $cidr; | 
|---|
| 1511 | my $tmpcidr; | 
|---|
| 1512 | my $warnmsg = ''; | 
|---|
| 1513 |  | 
|---|
| 1514 | if ($zone =~ /\.in-addr\.arpa\.?$/) { | 
|---|
| 1515 | # v4 revzone, formal zone name type | 
|---|
| 1516 | my $tmpzone = $zone; | 
|---|
| 1517 | return ('FAIL', "Non-numerics in apparent IPv4 reverse zone name [$tmpzone]") | 
|---|
| 1518 | if $tmpzone !~ m{^(?:\d+[/-])?[\d\.]+\.in-addr\.arpa\.?$}; | 
|---|
| 1519 | $tmpzone =~ s/\.in-addr\.arpa\.?//; | 
|---|
| 1520 |  | 
|---|
| 1521 | # Snag the octet pieces | 
|---|
| 1522 | my @octs = split /\./, $tmpzone; | 
|---|
| 1523 |  | 
|---|
| 1524 | # Map result of a range manipulation to a mask length change.  Cheaper than finding the 2-root of $octets[0]+1. | 
|---|
| 1525 | # Note we will not support /31 blocks, mostly due to issues telling "24-31" -> .24/29 apart from | 
|---|
| 1526 | # "24-31" -> .24/31", with a litte bit of "/31 is icky". | 
|---|
| 1527 | my %maskmap = (  3 => 2,  7 => 3, 15 => 4, 31 => 5, 63 => 6, 127 => 7, | 
|---|
| 1528 | 30 => 2, 29 => 3, 28 => 4, 27 => 5, 26 => 6,  25 => 7 | 
|---|
| 1529 | ); | 
|---|
| 1530 |  | 
|---|
| 1531 | # Handle "range" blocks, eg, 80-83.168.192.in-addr.arpa (192.168.80.0/22) | 
|---|
| 1532 | # Need to take the size of the range to offset the basic octet-based mask length, | 
|---|
| 1533 | # and make sure the first number in the range gets used as the network address for the block | 
|---|
| 1534 | # Alternate form:  The second number is actually the real netmask, not the end of the range. | 
|---|
| 1535 | my $masklen = 0; | 
|---|
| 1536 | if ($octs[0] =~ m{^((\d+)[/-](\d+))$}) {    # take the range... | 
|---|
| 1537 | if (24 < $3 && $3 < 31) { | 
|---|
| 1538 | # we have a real netmask | 
|---|
| 1539 | $masklen = -$maskmap{$3}; | 
|---|
| 1540 | } else { | 
|---|
| 1541 | # we have a range.  NB:  only real CIDR ranges are supported | 
|---|
| 1542 | $masklen -= $maskmap{-(eval $1)};       # find the mask base... | 
|---|
| 1543 | } | 
|---|
| 1544 | $octs[0] = $2;    # set the base octet of the range... | 
|---|
| 1545 | } | 
|---|
| 1546 | @octs = reverse @octs;      # We can reverse the octet pieces now that we've extracted and munged any ranges | 
|---|
| 1547 |  | 
|---|
| 1548 | # arguably we should only allow sub-octet range/mask in-addr.arpa | 
|---|
| 1549 | # specifications in the least significant octet, but the code is | 
|---|
| 1550 | # simpler if we deal with sub-octet delegations at any level. | 
|---|
| 1551 |  | 
|---|
| 1552 | # Now we find the "true" mask with the aid of the "base" calculated above | 
|---|
| 1553 | if ($#octs == 0) { | 
|---|
| 1554 | $masklen += 8; | 
|---|
| 1555 | $tmpcidr = "$octs[0].0.0.0/$masklen";     # really hope we don't see one of these very often. | 
|---|
| 1556 | } elsif ($#octs == 1) { | 
|---|
| 1557 | $masklen += 16; | 
|---|
| 1558 | $tmpcidr = "$octs[0].$octs[1].0.0/$masklen"; | 
|---|
| 1559 | } elsif ($#octs == 2) { | 
|---|
| 1560 | $masklen += 24; | 
|---|
| 1561 | $tmpcidr = "$octs[0].$octs[1].$octs[2].0/$masklen"; | 
|---|
| 1562 | } else { | 
|---|
| 1563 | $masklen += 32; | 
|---|
| 1564 | $tmpcidr = "$octs[0].$octs[1].$octs[2].$octs[3]/$masklen"; | 
|---|
| 1565 | } | 
|---|
| 1566 |  | 
|---|
| 1567 | } elsif ($zone =~ /\.ip6\.arpa\.?$/) { | 
|---|
| 1568 | # v6 revzone, formal zone name type | 
|---|
| 1569 | my $tmpzone = $zone; | 
|---|
| 1570 | ##fixme:  if-n-when we decide we can support sub-nibble v6 zone names, we'll need to change this segment | 
|---|
| 1571 | return ('FAIL', "Non-hexadecimals in apparent IPv6 reverse zone name [$tmpzone]") | 
|---|
| 1572 | if $tmpzone !~ /^[a-fA-F\d\.]+\.ip6\.arpa\.?$/; | 
|---|
| 1573 | $tmpzone =~ s/\.ip6\.arpa\.?//; | 
|---|
| 1574 | my @quads = reverse(split(/\./, $tmpzone)); | 
|---|
| 1575 | $warnmsg .= "Apparent sub-/64 IPv6 reverse zone\n" if $#quads > 15; | 
|---|
| 1576 | my $nc; | 
|---|
| 1577 | foreach (@quads) { | 
|---|
| 1578 | $tmpcidr .= $_; | 
|---|
| 1579 | $tmpcidr .= ":" if ++$nc % 4 == 0 && $nc < $#quads; | 
|---|
| 1580 | } | 
|---|
| 1581 | my $nq = 1 if $nc % 4 != 0; | 
|---|
| 1582 | my $mask = $nc * 4; # need to do this here because we probably increment it below | 
|---|
| 1583 | while ($nc++ % 4 != 0) { | 
|---|
| 1584 | $tmpcidr .= "0"; | 
|---|
| 1585 | } | 
|---|
| 1586 | # polish it off with trailing ::/mask if this is a CIDR block instead of an IP | 
|---|
| 1587 | $tmpcidr .= "::/$mask" if $mask != 128; | 
|---|
| 1588 | } | 
|---|
| 1589 |  | 
|---|
| 1590 | # Just to be sure, use NetAddr::IP to validate.  Saves a lot of nasty regex watching for valid octet values. | 
|---|
| 1591 | return ('FAIL', "Invalid zone $zone (apparent netblock $tmpcidr)") | 
|---|
| 1592 | unless $cidr = NetAddr::IP->new($tmpcidr); | 
|---|
| 1593 |  | 
|---|
| 1594 | if ($warnmsg) { | 
|---|
| 1595 | $errstr = $warnmsg; | 
|---|
| 1596 | return ('WARN', $cidr); | 
|---|
| 1597 | } | 
|---|
| 1598 | return ('OK', $cidr); | 
|---|
| 1599 | ##fixme:  use wantarray() to decide what to return? | 
|---|
| 1600 | } # done _zone2cidr() | 
|---|
| 1601 |  | 
|---|
| 1602 | # Record template %-parameter expansion, IPv4.  Note that IPv6 doesn't | 
|---|
| 1603 | # really have a sane way to handle this type of expansion at the moment | 
|---|
| 1604 | # due to the size of the address space. | 
|---|
| 1605 | # Takes a reference to a template string to be expanded, an IP to use in the replacement, | 
|---|
| 1606 | # an optional netblock for the %ngb (net, gw, bcast) expansion, and an optional index | 
|---|
| 1607 | # number for %c "n'th usable IP in block/range" patterns. | 
|---|
| 1608 | # Alters the template string referred. | 
|---|
| 1609 | sub _template4_expand { | 
|---|
| 1610 | # ugh pthui | 
|---|
| 1611 | my $self; | 
|---|
| 1612 | $self = shift if ref($_[0]) eq 'DNSDB'; | 
|---|
| 1613 |  | 
|---|
| 1614 | my $tmpl = shift; | 
|---|
| 1615 | my $ip = shift; | 
|---|
| 1616 | my $subnet = shift;   # for %ngb and %c | 
|---|
| 1617 | my $ipindex = shift;  # for %c | 
|---|
| 1618 |  | 
|---|
| 1619 | # blank $tmpl on config template_skip_0 or template_skip_255, unless we have a %ngb | 
|---|
| 1620 | if ($$tmpl !~ /\%-?n-?g-?b\%/) { | 
|---|
| 1621 | if ( ($ip =~ /\.0$/ && $self->{template_skip_0}) || | 
|---|
| 1622 | ($ip =~ /\.255$/ && $self->{template_skip_255}) ) { | 
|---|
| 1623 | $$tmpl = ''; | 
|---|
| 1624 | return; | 
|---|
| 1625 | } | 
|---|
| 1626 | } | 
|---|
| 1627 |  | 
|---|
| 1628 | my @ipparts = split /\./, $ip; | 
|---|
| 1629 | my @iphex; | 
|---|
| 1630 | my @ippad; | 
|---|
| 1631 | for (@ipparts) { | 
|---|
| 1632 | push @iphex, sprintf("%x", $_); | 
|---|
| 1633 | push @ippad, sprintf("%0.3u", $_); | 
|---|
| 1634 | } | 
|---|
| 1635 |  | 
|---|
| 1636 | # Two or three consecutive separator characters (_ or -) should be rare - users that use them | 
|---|
| 1637 | # anywhere other than punycoded internationalized domains get to keep the pieces when it breaks. | 
|---|
| 1638 | # We clean up the ones that we may inadvertently generate after replacing %c and %ngb% | 
|---|
| 1639 | my ($thrsep) = ($$tmpl =~ /[_-]{3}/); | 
|---|
| 1640 | my ($twosep) = ($$tmpl =~ /[_-]{2}/); | 
|---|
| 1641 |  | 
|---|
| 1642 | # Take the simplest path to pattern substitution;  replace only exactly the %c or %ngb% | 
|---|
| 1643 | # patterns as-is.  Then check after to see if we've caused doubled separator characters (- or _) | 
|---|
| 1644 | # and eliminate them, but only if the original template didn't have them already.  Also | 
|---|
| 1645 | # unconditionally drop separator characters immediately before a dot;  these do not always | 
|---|
| 1646 | # strictly make the label invalid but almost always, and any exceptions should never show up | 
|---|
| 1647 | # in a template record that expands to "many" real records anyway. | 
|---|
| 1648 |  | 
|---|
| 1649 | # %ngb and %c require a netblock | 
|---|
| 1650 | if ($subnet) { | 
|---|
| 1651 | # extract the fragments | 
|---|
| 1652 | my ($ngb,$n,$g,$b) = ($$tmpl =~ /(\%(-?n)(-?g)(-?b)\%)/); | 
|---|
| 1653 | my ($c) = ($$tmpl =~ /(\%-?c)/);  my $nld = '';  my $cld = ''; | 
|---|
| 1654 | $c = '' if !$c; | 
|---|
| 1655 | my $skipgw = ($c =~ /\%-c/ ? 0 : 1); | 
|---|
| 1656 | my $ipkill = 0; | 
|---|
| 1657 |  | 
|---|
| 1658 | ##fixme: still have one edge case not handled well: | 
|---|
| 1659 | # %c%n-gb% | 
|---|
| 1660 | # do we drop the record as per -g, or publish the record with an index of 1 as per %c? | 
|---|
| 1661 | # arguably this is a "that's a STUPID question!" case | 
|---|
| 1662 |  | 
|---|
| 1663 | if ($c) { | 
|---|
| 1664 | # "n'th usable IP in the block" pattern.  We need the caller to provide an index | 
|---|
| 1665 | # number otherwise we see exponential time growth because we have to iterate over | 
|---|
| 1666 | # the whole block to map the IP back to an index.  :/ | 
|---|
| 1667 | # NetAddr::IP does not have a method for asking "what index is IP <foo> at?" | 
|---|
| 1668 |  | 
|---|
| 1669 | # no index, or index == 0, (AKA network address), or IP == broadcast, blank the index fragment | 
|---|
| 1670 | if (!$ipindex || ($$subnet->broadcast->addr eq $ip)) { | 
|---|
| 1671 | $$tmpl =~ s/$c//; | 
|---|
| 1672 | } else { | 
|---|
| 1673 | # if we have %c, AKA "skip the gateway", and we're on the nominal gateway IP, blank the index fragment | 
|---|
| 1674 | if ($skipgw && $$subnet->first->addr eq $ip) { | 
|---|
| 1675 | $$tmpl =~ s/$c//; | 
|---|
| 1676 | } | 
|---|
| 1677 | # else replace the index fragment with the passed index minus $skipgw, so that we can start the | 
|---|
| 1678 | # resulting index at 1 on net+2 | 
|---|
| 1679 | else { | 
|---|
| 1680 | $$tmpl =~ s/$c/($ipindex-$skipgw)/e; | 
|---|
| 1681 | } | 
|---|
| 1682 | } | 
|---|
| 1683 | } # if ($c) | 
|---|
| 1684 |  | 
|---|
| 1685 | if ($ngb) { | 
|---|
| 1686 | # individually check the network, standard gateway (net+1) IP, and broadcast IP | 
|---|
| 1687 | # blank $$tmpl if n, g, or b was prefixed with - (this allows "hiding" net/gw/bcast entries) | 
|---|
| 1688 |  | 
|---|
| 1689 | if ($$subnet->network->addr eq $ip) { | 
|---|
| 1690 | if ($n eq '-n') { | 
|---|
| 1691 | $$tmpl = ''; | 
|---|
| 1692 | } else { | 
|---|
| 1693 | $$tmpl =~ s/$ngb/net/; | 
|---|
| 1694 | $ipkill = 1; | 
|---|
| 1695 | } | 
|---|
| 1696 | } elsif ($$subnet->first->addr eq $ip) { | 
|---|
| 1697 | if ($g eq '-g') { | 
|---|
| 1698 | $$tmpl = ''; | 
|---|
| 1699 | } else { | 
|---|
| 1700 | $$tmpl =~ s/$ngb/gw/; | 
|---|
| 1701 | $ipkill = 1; | 
|---|
| 1702 | } | 
|---|
| 1703 | } elsif ($$subnet->broadcast->addr eq $ip) { | 
|---|
| 1704 | if ($b eq '-b') { | 
|---|
| 1705 | $$tmpl = ''; | 
|---|
| 1706 | } else { | 
|---|
| 1707 | $$tmpl =~ s/$ngb/bcast/; | 
|---|
| 1708 | $ipkill = 1; | 
|---|
| 1709 | } | 
|---|
| 1710 | } else { | 
|---|
| 1711 | $$tmpl =~ s/$ngb//; | 
|---|
| 1712 | } | 
|---|
| 1713 | } | 
|---|
| 1714 |  | 
|---|
| 1715 | # We don't (usually) want to expand the IP-related patterns on the -net, -gw, or -bcast IPs. | 
|---|
| 1716 | # Arguably this is another place for another config knob, or possibly further extension of | 
|---|
| 1717 | # the template pattern to control it on a per-subnet basis. | 
|---|
| 1718 | if ($ipkill) { | 
|---|
| 1719 | # kill common IP patterns | 
|---|
| 1720 | $$tmpl =~ s/\%[_.-]?[irdh]//; | 
|---|
| 1721 | # kill IP octet patterns | 
|---|
| 1722 | $$tmpl =~ s/\%[1234][dh0](?:[_.-]\%[1234][dh0]){0,3}//; | 
|---|
| 1723 | } | 
|---|
| 1724 |  | 
|---|
| 1725 | # and now clean up to make sure we leave a valid DNS label... mostly.  Should arguably | 
|---|
| 1726 | # split on /\./ and process each label separately. | 
|---|
| 1727 | $$tmpl =~ s/([_-]){3}/$1/ if !$thrsep; | 
|---|
| 1728 | $$tmpl =~ s/([_-]){2}/$1/ if !$twosep; | 
|---|
| 1729 | $$tmpl =~ s/[_-]\././; | 
|---|
| 1730 |  | 
|---|
| 1731 | } # if ($subnet) | 
|---|
| 1732 |  | 
|---|
| 1733 | # IP substitutions in template records: | 
|---|
| 1734 | #major patterns: | 
|---|
| 1735 | #dashed IP, forward and reverse | 
|---|
| 1736 | #underscoreed IP, forward and reverse | 
|---|
| 1737 | #dotted IP, forward and reverse (even if forward is... dumb) | 
|---|
| 1738 | # -> %r for reverse, %i for forward, leading -, _, or . to indicate separator, defaults to - | 
|---|
| 1739 | # %r or %-r   => %4d-%3d-%2d-%1d | 
|---|
| 1740 | # %_r         => %4d_%3d_%2d_%1d | 
|---|
| 1741 | # %.r         => %4d.%3d.%2d.%1d | 
|---|
| 1742 | # %i or %-i   => %1d-%2d-%3d-%4d | 
|---|
| 1743 | # %_i         => %1d_%2d_%3d_%4d | 
|---|
| 1744 | # %.i         => %1d.%2d.%3d.%4d | 
|---|
| 1745 | $$tmpl =~ s/\%r/\%4d-\%3d-\%2d-\%1d/g; | 
|---|
| 1746 | $$tmpl =~ s/\%([-._])r/\%4d$1\%3d$1\%2d$1\%1d/g; | 
|---|
| 1747 | $$tmpl =~ s/\%i/\%1d-\%2d-\%3d-\%4d/g; | 
|---|
| 1748 | $$tmpl =~ s/\%([-._])i/\%1d$1\%2d$1\%3d$1\%4d/g; | 
|---|
| 1749 |  | 
|---|
| 1750 | #hex-coded IP | 
|---|
| 1751 | # %h | 
|---|
| 1752 | $$tmpl =~ s/\%h/$iphex[0]$iphex[1]$iphex[2]$iphex[3]/g; | 
|---|
| 1753 |  | 
|---|
| 1754 | #IP as decimal-coded 32-bit value | 
|---|
| 1755 | # %d | 
|---|
| 1756 | my $iptmp = $ipparts[0]*256*256*256 + $ipparts[1]*256*256 + $ipparts[2]*256 + $ipparts[3]; | 
|---|
| 1757 | $$tmpl =~ s/\%d/$iptmp/g; | 
|---|
| 1758 |  | 
|---|
| 1759 | #minor patterns (per-octet) | 
|---|
| 1760 | # %[1234][dh0] | 
|---|
| 1761 | #octet | 
|---|
| 1762 | #hex-coded octet | 
|---|
| 1763 | #0-padded octet | 
|---|
| 1764 | $$tmpl =~ s/\%([1234])d/$ipparts[$1-1]/g; | 
|---|
| 1765 | $$tmpl =~ s/\%([1234])h/$iphex[$1-1]/g; | 
|---|
| 1766 | $$tmpl =~ s/\%([1234])0/$ippad[$1-1]/g; | 
|---|
| 1767 |  | 
|---|
| 1768 | } # _template4_expand() | 
|---|
| 1769 |  | 
|---|
| 1770 | # Broad syntactic check on the hostname.  Checks for valid characters, correctly-expandable template patterns. | 
|---|
| 1771 | # Takes the hostname, type, and live/default and forward/reverse flags | 
|---|
| 1772 | # Returns true/false, sets errstr on failures | 
|---|
| 1773 | sub _check_hostname_form { | 
|---|
| 1774 | my ($hname,$rectype,$defrec,$revrec) = @_; | 
|---|
| 1775 |  | 
|---|
| 1776 | if ($hname =~ /\%/ && ($rectype == 65282 || $rectype == 65283) ) { | 
|---|
| 1777 | my $tmphost = $hname; | 
|---|
| 1778 | # we don't actually need to test with the real IP passed;  that saves a bit of fiddling. | 
|---|
| 1779 | DNSDB::_template4_expand(\$tmphost, '10.10.10.10'); | 
|---|
| 1780 | if ($tmphost =~ /\%/ || lc($tmphost) !~ /^(?:\*\.)?(?:[0-9a-z_.-]+)$/) { | 
|---|
| 1781 | $errstr = "Invalid template $hname"; | 
|---|
| 1782 | return; | 
|---|
| 1783 | } | 
|---|
| 1784 | } elsif ($rectype == $reverse_typemap{CNAME} && $revrec eq 'y') { | 
|---|
| 1785 | # Allow / in reverse CNAME hostnames for sub-/24 delegation | 
|---|
| 1786 | if (lc($hname) !~ m|^[0-9a-z_./-]+$|) { | 
|---|
| 1787 | # error message is deliberately restrictive;  special cases are SPECIAL and not for general use | 
|---|
| 1788 | $errstr = "Hostnames may not contain anything other than (0-9 a-z . _)"; | 
|---|
| 1789 | return; | 
|---|
| 1790 | } | 
|---|
| 1791 | } elsif ($revrec eq 'y') { | 
|---|
| 1792 | # Reverse zones don't support @ in hostnames | 
|---|
| 1793 | if (lc($hname) !~ /^(?:\*\.)?[0-9a-z_.-]+$/) { | 
|---|
| 1794 | # error message is deliberately restrictive;  special cases are SPECIAL and not for general use | 
|---|
| 1795 | $errstr = "Hostnames may not contain anything other than (0-9 a-z . _)"; | 
|---|
| 1796 | return; | 
|---|
| 1797 | } | 
|---|
| 1798 | } else { | 
|---|
| 1799 | if (lc($hname) !~ /^(?:\*\.)?(?:[0-9a-z_.-]+|@)$/) { | 
|---|
| 1800 | # Don't mention @, because it would be far too wordy to explain the nuance of @ | 
|---|
| 1801 | $errstr = "Hostnames may not contain anything other than (0-9 a-z . _)"; | 
|---|
| 1802 | return; | 
|---|
| 1803 | } | 
|---|
| 1804 | } | 
|---|
| 1805 | return 1; | 
|---|
| 1806 | } # _check_hostname_form() | 
|---|
| 1807 |  | 
|---|
| 1808 |  | 
|---|
| 1809 | ## | 
|---|
| 1810 | ## Initialization and cleanup subs | 
|---|
| 1811 | ## | 
|---|
| 1812 |  | 
|---|
| 1813 | ## DNSDB::__cfgload() | 
|---|
| 1814 | # Private sub to parse a config file and load it into %config | 
|---|
| 1815 | # Takes a filename and a hashref to put the parsed entries in | 
|---|
| 1816 | sub __cfgload { | 
|---|
| 1817 | $errstr = ''; | 
|---|
| 1818 | my $cfgfile = shift; | 
|---|
| 1819 | my $cfg = shift; | 
|---|
| 1820 |  | 
|---|
| 1821 | if (open CFG, "<$cfgfile") { | 
|---|
| 1822 | while (<CFG>) { | 
|---|
| 1823 | chomp; | 
|---|
| 1824 | s/^\s*//; | 
|---|
| 1825 | next if /^#/; | 
|---|
| 1826 | next if /^$/; | 
|---|
| 1827 | # hmm.  more complex bits in this file might require [heading] headers, maybe? | 
|---|
| 1828 | #    $mode = $1 if /^\[(a-z)+]/; | 
|---|
| 1829 | # DB connect info | 
|---|
| 1830 | $cfg->{dbname}    = $1 if /^dbname\s*=\s*([a-z0-9_.-]+)/i; | 
|---|
| 1831 | $cfg->{dbuser}    = $1 if /^dbuser\s*=\s*([a-z0-9_.-]+)/i; | 
|---|
| 1832 | $cfg->{dbpass}    = $1 if /^dbpass\s*=\s*([a-z0-9_.-]+)/i; | 
|---|
| 1833 | $cfg->{dbhost}    = $1 if /^dbhost\s*=\s*([a-z0-9_.-]+)/i; | 
|---|
| 1834 | # Mail settings | 
|---|
| 1835 | $cfg->{mailhost}          = $1 if /^mailhost\s*=\s*([a-z0-9_.-]+)/i; | 
|---|
| 1836 | $cfg->{mailnotify}        = $1 if /^mailnotify\s*=\s*([a-z0-9_.\@-]+)/i; | 
|---|
| 1837 | $cfg->{mailsender}        = $1 if /^mailsender\s*=\s*([a-z0-9_.\@-]+)/i; | 
|---|
| 1838 | $cfg->{mailname}          = $1 if /^mailname\s*=\s*([a-z0-9\s_.-]+)/i; | 
|---|
| 1839 | $cfg->{orgname}           = $1 if /^orgname\s*=\s*([a-z0-9\s_.,'-]+)/i; | 
|---|
| 1840 | $cfg->{domain}            = $1 if /^domain\s*=\s*([a-z0-9_.-]+)/i; | 
|---|
| 1841 | # session - note this is fed directly to CGI::Session | 
|---|
| 1842 | $cfg->{timeout}           = $1 if /^[tT][iI][mM][eE][oO][uU][tT]\s*=\s*(\d+[smhdwMy]?)/; | 
|---|
| 1843 | $cfg->{sessiondir}        = $1 if m{^sessiondir\s*=\s*([a-z0-9/_.-]+)}i; | 
|---|
| 1844 | # misc | 
|---|
| 1845 | $cfg->{log_failures}      = $1 if /^log_failures\s*=\s*([a-z01]+)/i; | 
|---|
| 1846 | $cfg->{perpage}           = $1 if /^perpage\s*=\s*(\d+)/i; | 
|---|
| 1847 | $cfg->{exportcache}       = $1 if m{^exportcache\s*=\s*([a-z0-9/_.-]+)}i; | 
|---|
| 1848 | $cfg->{usecache}          = $1 if m{^usecache\s*=\s*([a-z01]+)}i; | 
|---|
| 1849 | $cfg->{force_refresh}     = $1 if /^force_refresh\s*=\s*([a-z01]+)/i; | 
|---|
| 1850 | $cfg->{lowercase}         = $1 if /^lowercase\s*=\s*([a-z01]+)/i; | 
|---|
| 1851 | $cfg->{showrev_arpa}      = $1 if /^showrev_arpa\s*=\s*([a-z]+)/i; | 
|---|
| 1852 | $cfg->{template_skip_0}   = $1 if /^template_skip_0\s*=\s*([a-z01]+)/i; | 
|---|
| 1853 | $cfg->{template_skip_255} = $1 if /^template_skip_255\s*=\s*([a-z01]+)/i; | 
|---|
| 1854 | # not supported in dns.cgi yet | 
|---|
| 1855 | #      $cfg->{templatedir}      = $1 if m{^templatedir\s*=\s*([a-z0-9/_.-]+)}i; | 
|---|
| 1856 | #      $cfg->{templateoverride} = $1 if m{^templateoverride\s*=\s*([a-z0-9/_.-]+)}i; | 
|---|
| 1857 | # RPC options | 
|---|
| 1858 | $cfg->{rpcmode}           = $1 if /^rpc_mode\s*=\s*(socket|HTTP|XMLRPC)\s*$/i; | 
|---|
| 1859 | $cfg->{maxfcgi}           = $1 if /^max_fcgi_requests\s*=\s*(\d+)\s*$/i; | 
|---|
| 1860 | if (my ($tmp) = /^rpc_iplist\s*=\s*(.+)/i) { | 
|---|
| 1861 | my @ips = split /[,\s]+/, $tmp; | 
|---|
| 1862 | my $rpcsys = shift @ips; | 
|---|
| 1863 | push @{$cfg->{rpcacl}{$rpcsys}}, @ips; | 
|---|
| 1864 | } | 
|---|
| 1865 | } | 
|---|
| 1866 | close CFG; | 
|---|
| 1867 | } else { | 
|---|
| 1868 | $errstr = "Couldn't load configuration file $cfgfile: $!"; | 
|---|
| 1869 | return; | 
|---|
| 1870 | } | 
|---|
| 1871 | return 1; | 
|---|
| 1872 | } # end __cfgload() | 
|---|
| 1873 |  | 
|---|
| 1874 |  | 
|---|
| 1875 | ## DNSDB::connectDB() | 
|---|
| 1876 | # Creates connection to DNS database. | 
|---|
| 1877 | # Requires the database name, username, and password. | 
|---|
| 1878 | # Returns a handle to the db or undef on failure. | 
|---|
| 1879 | # Set up for a PostgreSQL db;  could be any transactional DBMS with the | 
|---|
| 1880 | # right changes. | 
|---|
| 1881 | # Called by new();  not intended to be called publicly. | 
|---|
| 1882 | sub connectDB { | 
|---|
| 1883 | $errstr = ''; | 
|---|
| 1884 | my $dbname = shift; | 
|---|
| 1885 | my $user = shift; | 
|---|
| 1886 | my $pass = shift; | 
|---|
| 1887 | my $dbh; | 
|---|
| 1888 | my $DSN = "DBI:Pg:dbname=$dbname"; | 
|---|
| 1889 |  | 
|---|
| 1890 | my $host = shift; | 
|---|
| 1891 | $DSN .= ";host=$host" if $host; | 
|---|
| 1892 |  | 
|---|
| 1893 | # Note that we want to autocommit by default, and we will turn it off locally as necessary. | 
|---|
| 1894 | # We may not want to print gobbledygook errors;  YMMV.  Have to ponder that further. | 
|---|
| 1895 | $dbh = DBI->connect($DSN, $user, $pass, { | 
|---|
| 1896 | AutoCommit => 1, | 
|---|
| 1897 | PrintError => 0 | 
|---|
| 1898 | }); | 
|---|
| 1899 | if (!$dbh) { | 
|---|
| 1900 | $errstr = $DBI::errstr; | 
|---|
| 1901 | return; | 
|---|
| 1902 | } | 
|---|
| 1903 | #) if(!$dbh); | 
|---|
| 1904 |  | 
|---|
| 1905 | local $dbh->{RaiseError} = 1; | 
|---|
| 1906 |  | 
|---|
| 1907 | eval { | 
|---|
| 1908 | ##fixme:  initialize the DB if we can't find the table (since, by definition, there's | 
|---|
| 1909 | # nothing there if we can't select from it...) | 
|---|
| 1910 | my $tblsth = $dbh->prepare("SELECT count(*) FROM pg_catalog.pg_class WHERE relkind='r' AND relname=?"); | 
|---|
| 1911 | my ($tblcount) = $dbh->selectrow_array($tblsth, undef, ('misc')); | 
|---|
| 1912 | #  return (undef,$DBI::errstr) if $dbh->err; | 
|---|
| 1913 |  | 
|---|
| 1914 | #if ($tblcount == 0) { | 
|---|
| 1915 | #  # create tables one at a time, checking for each. | 
|---|
| 1916 | #  return (undef, "check table misc missing"); | 
|---|
| 1917 | #} | 
|---|
| 1918 |  | 
|---|
| 1919 | # Return here if we can't select. | 
|---|
| 1920 | # This should retrieve the dbversion key. | 
|---|
| 1921 | my $sth = $dbh->prepare("SELECT key,value FROM misc WHERE misc_id=1"); | 
|---|
| 1922 | $sth->execute(); | 
|---|
| 1923 | #  return (undef,$DBI::errstr) if ($sth->err); | 
|---|
| 1924 |  | 
|---|
| 1925 | ##fixme:  do stuff to the DB on version mismatch | 
|---|
| 1926 | # x.y series should upgrade on $DNSDB::VERSION > misc(key=>version) | 
|---|
| 1927 | # DB should be downward-compatible;  column defaults should give sane (if possibly | 
|---|
| 1928 | # useless-and-needs-help) values in columns an older software stack doesn't know about. | 
|---|
| 1929 |  | 
|---|
| 1930 | # See if the select returned anything (or null data).  This should | 
|---|
| 1931 | # succeed if the select executed, but... | 
|---|
| 1932 | $sth->fetchrow(); | 
|---|
| 1933 | #  return (undef,$DBI::errstr)  if ($sth->err); | 
|---|
| 1934 |  | 
|---|
| 1935 | $sth->finish; | 
|---|
| 1936 |  | 
|---|
| 1937 | }; # wrapped DB checks | 
|---|
| 1938 | if ($@) { | 
|---|
| 1939 | $errstr = $@; | 
|---|
| 1940 | return; | 
|---|
| 1941 | } | 
|---|
| 1942 |  | 
|---|
| 1943 | # If we get here, we should be OK. | 
|---|
| 1944 | return $dbh; | 
|---|
| 1945 | } # end connectDB | 
|---|
| 1946 |  | 
|---|
| 1947 |  | 
|---|
| 1948 | ## DNSDB::finish() | 
|---|
| 1949 | # Cleans up after database handles and so on. | 
|---|
| 1950 | # Requires a database handle | 
|---|
| 1951 | sub finish { | 
|---|
| 1952 | my $self = shift; | 
|---|
| 1953 | $self->{dbh}->disconnect; | 
|---|
| 1954 | } # end finish | 
|---|
| 1955 |  | 
|---|
| 1956 |  | 
|---|
| 1957 | ## DNSDB::initGlobals() | 
|---|
| 1958 | # Initialize global variables | 
|---|
| 1959 | # NB: this does NOT include web-specific session variables! | 
|---|
| 1960 | sub initGlobals { | 
|---|
| 1961 | my $self = shift; | 
|---|
| 1962 | my $dbh = $self->{dbh}; | 
|---|
| 1963 |  | 
|---|
| 1964 | # load record types from database | 
|---|
| 1965 | my $sth = $dbh->prepare("SELECT val,name,stdflag FROM rectypes"); | 
|---|
| 1966 | $sth->execute; | 
|---|
| 1967 | while (my ($recval,$recname,$stdflag) = $sth->fetchrow_array()) { | 
|---|
| 1968 | $typemap{$recval} = $recname; | 
|---|
| 1969 | $reverse_typemap{$recname} = $recval; | 
|---|
| 1970 | # now we fill the record validation function hash | 
|---|
| 1971 | if ($stdflag < 5) { | 
|---|
| 1972 | my $fn = "_validate_$recval"; | 
|---|
| 1973 | $validators{$recval} = \&$fn; | 
|---|
| 1974 | } else { | 
|---|
| 1975 | my $fn = "sub { return ('FAIL','Type $recval ($recname) not supported'); }"; | 
|---|
| 1976 | $validators{$recval} = eval $fn; | 
|---|
| 1977 | } | 
|---|
| 1978 | } | 
|---|
| 1979 | } # end initGlobals | 
|---|
| 1980 |  | 
|---|
| 1981 |  | 
|---|
| 1982 | ## DNSDB::initRPC() | 
|---|
| 1983 | # Takes a remote username and remote fullname. | 
|---|
| 1984 | # Sets up the RPC logging-pseudouser if needed. | 
|---|
| 1985 | # Sets the %userdata hash for logging. | 
|---|
| 1986 | # Returns undef on failure | 
|---|
| 1987 | sub initRPC { | 
|---|
| 1988 | my $self = shift; | 
|---|
| 1989 | my $dbh = $self->{dbh}; | 
|---|
| 1990 | my %args  = @_; | 
|---|
| 1991 |  | 
|---|
| 1992 | return if !$args{username}; | 
|---|
| 1993 | return if !$args{fullname}; | 
|---|
| 1994 |  | 
|---|
| 1995 | $args{username} = "$args{username}/$args{rpcsys}"; | 
|---|
| 1996 |  | 
|---|
| 1997 | my $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status". | 
|---|
| 1998 | " FROM users WHERE username=?", undef, ($args{username}) ); | 
|---|
| 1999 | if (!$tmpuser) { | 
|---|
| 2000 | $dbh->do("INSERT INTO users (username,password,firstname,type) VALUES (?,'RPC',?,'R')", undef, | 
|---|
| 2001 | ($args{username}, $args{fullname}) ); | 
|---|
| 2002 | $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status". | 
|---|
| 2003 | " FROM users WHERE username=?", undef, ($args{username}) ); | 
|---|
| 2004 | } | 
|---|
| 2005 | $tmpuser->{lastname} = '' if !$tmpuser->{lastname}; | 
|---|
| 2006 | $self->{loguserid} = $tmpuser->{userid}; | 
|---|
| 2007 | $self->{logusername} = $tmpuser->{username}; | 
|---|
| 2008 | $self->{logfullname} = "$tmpuser->{firstname} $tmpuser->{lastname} ($args{rpcsys})"; | 
|---|
| 2009 | return 1 if $tmpuser; | 
|---|
| 2010 | } # end initRPC() | 
|---|
| 2011 |  | 
|---|
| 2012 |  | 
|---|
| 2013 | ## DNSDB::login() | 
|---|
| 2014 | # Takes a database handle, username and password | 
|---|
| 2015 | # Returns a userdata hash (UID, GID, username, fullname parts) if username exists, | 
|---|
| 2016 | # password matches the one on file, and account is not disabled | 
|---|
| 2017 | # Returns undef otherwise | 
|---|
| 2018 | sub login { | 
|---|
| 2019 | my $self = shift; | 
|---|
| 2020 | my $dbh = $self->{dbh}; | 
|---|
| 2021 | my $user = shift; | 
|---|
| 2022 | my $pass = shift; | 
|---|
| 2023 |  | 
|---|
| 2024 | my $userinfo = $dbh->selectrow_hashref("SELECT user_id,group_id,password,firstname,lastname,status". | 
|---|
| 2025 | " FROM users WHERE username=?", | 
|---|
| 2026 | undef, ($user) ); | 
|---|
| 2027 | return if !$userinfo; | 
|---|
| 2028 | return if !$userinfo->{status}; | 
|---|
| 2029 |  | 
|---|
| 2030 | if ($userinfo->{password} =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) { | 
|---|
| 2031 | # native passwords (crypt-md5) | 
|---|
| 2032 | return if $userinfo->{password} ne unix_md5_crypt($pass,$1); | 
|---|
| 2033 | } elsif ($userinfo->{password} =~ /^[0-9a-f]{32}$/) { | 
|---|
| 2034 | # VegaDNS import (hex-coded MD5) | 
|---|
| 2035 | return if $userinfo->{password} ne md5_hex($pass); | 
|---|
| 2036 | } else { | 
|---|
| 2037 | # plaintext (convenient now and then) | 
|---|
| 2038 | return if $userinfo->{password} ne $pass; | 
|---|
| 2039 | } | 
|---|
| 2040 |  | 
|---|
| 2041 | return $userinfo; | 
|---|
| 2042 | } # end login() | 
|---|
| 2043 |  | 
|---|
| 2044 |  | 
|---|
| 2045 | ## DNSDB::initActionLog() | 
|---|
| 2046 | # Set up action logging.  Takes a database handle and user ID | 
|---|
| 2047 | # Sets some internal globals and Does The Right Thing to set up a logging channel. | 
|---|
| 2048 | # This sets up _log() to spew out log entries to the defined channel without worrying | 
|---|
| 2049 | # about having to open a file or a syslog channel | 
|---|
| 2050 | ##fixme Need to call _initActionLog_blah() for various logging channels, configured | 
|---|
| 2051 | # via dnsdb.conf, in $self->{log_channel} or something | 
|---|
| 2052 | # See https://secure.deepnet.cx/trac/dnsadmin/ticket/21 | 
|---|
| 2053 | sub initActionLog { | 
|---|
| 2054 | my $self = shift; | 
|---|
| 2055 | my $dbh = $self->{dbh}; | 
|---|
| 2056 | my $uid = shift; | 
|---|
| 2057 |  | 
|---|
| 2058 | return if !$uid; | 
|---|
| 2059 |  | 
|---|
| 2060 | # snag user info for logging.  there's got to be a way to not have to pass this back | 
|---|
| 2061 | # and forth from a caller, but web usage means no persistence we can rely on from | 
|---|
| 2062 | # the server side. | 
|---|
| 2063 | my ($username,$fullname) = $dbh->selectrow_array("SELECT username, firstname || ' ' || lastname". | 
|---|
| 2064 | " FROM users WHERE user_id=?", undef, ($uid)); | 
|---|
| 2065 | ##fixme: errors are unpossible! | 
|---|
| 2066 |  | 
|---|
| 2067 | $self->{logusername} = $username; | 
|---|
| 2068 | $self->{loguserid} = $uid; | 
|---|
| 2069 | $self->{logfullname} = $fullname; | 
|---|
| 2070 |  | 
|---|
| 2071 | # convert to real check once we have other logging channels | 
|---|
| 2072 | # if ($self->{log_channel} eq 'sql') { | 
|---|
| 2073 | #   Open Log, Sez Me! | 
|---|
| 2074 | # } | 
|---|
| 2075 |  | 
|---|
| 2076 | } # end initActionLog | 
|---|
| 2077 |  | 
|---|
| 2078 |  | 
|---|
| 2079 | ## DNSDB::getPermissions() | 
|---|
| 2080 | # Get permissions from DB | 
|---|
| 2081 | # Requires DB handle, group or user flag, ID, and hashref. | 
|---|
| 2082 | sub getPermissions { | 
|---|
| 2083 | my $self = shift; | 
|---|
| 2084 | my $dbh = $self->{dbh}; | 
|---|
| 2085 |  | 
|---|
| 2086 | my $type = shift; | 
|---|
| 2087 | my $id = shift; | 
|---|
| 2088 | my $hash = shift; | 
|---|
| 2089 |  | 
|---|
| 2090 | my $sql = qq( | 
|---|
| 2091 | SELECT | 
|---|
| 2092 | p.admin,p.self_edit, | 
|---|
| 2093 | p.group_create,p.group_edit,p.group_delete, | 
|---|
| 2094 | p.user_create,p.user_edit,p.user_delete, | 
|---|
| 2095 | p.domain_create,p.domain_edit,p.domain_delete, | 
|---|
| 2096 | p.record_create,p.record_edit,p.record_delete,p.record_locchg, | 
|---|
| 2097 | p.location_create,p.location_edit,p.location_delete,p.location_view | 
|---|
| 2098 | FROM permissions p | 
|---|
| 2099 | ); | 
|---|
| 2100 | if ($type eq 'group') { | 
|---|
| 2101 | $sql .= qq( | 
|---|
| 2102 | JOIN groups g ON g.permission_id=p.permission_id | 
|---|
| 2103 | WHERE g.group_id=? | 
|---|
| 2104 | ); | 
|---|
| 2105 | } else { | 
|---|
| 2106 | $sql .= qq( | 
|---|
| 2107 | JOIN users u ON u.permission_id=p.permission_id | 
|---|
| 2108 | WHERE u.user_id=? | 
|---|
| 2109 | ); | 
|---|
| 2110 | } | 
|---|
| 2111 |  | 
|---|
| 2112 | my $sth = $dbh->prepare($sql); | 
|---|
| 2113 |  | 
|---|
| 2114 | ##fixme?  we don't trap other plain SELECT errors | 
|---|
| 2115 | $sth->execute($id); | 
|---|
| 2116 |  | 
|---|
| 2117 | #  my $permref = $sth->fetchrow_hashref; | 
|---|
| 2118 | #  return $permref; | 
|---|
| 2119 | #  $hash = $permref; | 
|---|
| 2120 | # Eww.  Need to learn how to forcibly drop a hashref onto an existing hash. | 
|---|
| 2121 | ($hash->{admin},$hash->{self_edit}, | 
|---|
| 2122 | $hash->{group_create},$hash->{group_edit},$hash->{group_delete}, | 
|---|
| 2123 | $hash->{user_create},$hash->{user_edit},$hash->{user_delete}, | 
|---|
| 2124 | $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete}, | 
|---|
| 2125 | $hash->{record_create},$hash->{record_edit},$hash->{record_delete},$hash->{record_locchg}, | 
|---|
| 2126 | $hash->{location_create},$hash->{location_edit},$hash->{location_delete},$hash->{location_view} | 
|---|
| 2127 | ) = $sth->fetchrow_array; | 
|---|
| 2128 |  | 
|---|
| 2129 | } # end getPermissions() | 
|---|
| 2130 |  | 
|---|
| 2131 |  | 
|---|
| 2132 | ## DNSDB::changePermissions() | 
|---|
| 2133 | # Update an ACL entry | 
|---|
| 2134 | # Takes a db handle, type, owner-id, and hashref for the changed permissions. | 
|---|
| 2135 | sub changePermissions { | 
|---|
| 2136 | my $self = shift; | 
|---|
| 2137 | my $dbh = $self->{dbh}; | 
|---|
| 2138 | my $type = shift; | 
|---|
| 2139 | my $id = shift; | 
|---|
| 2140 | my $newperms = shift; | 
|---|
| 2141 | my $inherit = shift || 0; | 
|---|
| 2142 |  | 
|---|
| 2143 | my $resultmsg = ''; | 
|---|
| 2144 |  | 
|---|
| 2145 | # see if we're switching from inherited to custom.  for bonus points, | 
|---|
| 2146 | # snag the permid and parent permid anyway, since we'll need the permid | 
|---|
| 2147 | # to set/alter custom perms, and both if we're switching from custom to | 
|---|
| 2148 | # inherited. | 
|---|
| 2149 | my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id,". | 
|---|
| 2150 | ($type eq 'user' ? 'u.group_id,u.username' : 'u.parent_group_id,u.group_name'). | 
|---|
| 2151 | " FROM ".($type eq 'user' ? 'users' : 'groups')." u ". | 
|---|
| 2152 | " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ". | 
|---|
| 2153 | " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?"); | 
|---|
| 2154 | $sth->execute($id); | 
|---|
| 2155 |  | 
|---|
| 2156 | my ($wasinherited,$permid,$parpermid,$parid,$name) = $sth->fetchrow_array; | 
|---|
| 2157 |  | 
|---|
| 2158 | # hack phtoui | 
|---|
| 2159 | # group id 1 is "special" in that it's it's own parent (err...  possibly.) | 
|---|
| 2160 | # may make its parent id 0 which doesn't exist, and as a bonus is Perl-false. | 
|---|
| 2161 | $wasinherited = 0 if ($type eq 'group' && $id == 1); | 
|---|
| 2162 |  | 
|---|
| 2163 | local $dbh->{AutoCommit} = 0; | 
|---|
| 2164 | local $dbh->{RaiseError} = 1; | 
|---|
| 2165 |  | 
|---|
| 2166 | # Wrap all the SQL in a transaction | 
|---|
| 2167 | eval { | 
|---|
| 2168 | if ($inherit) { | 
|---|
| 2169 |  | 
|---|
| 2170 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ". | 
|---|
| 2171 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) ); | 
|---|
| 2172 | $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) ); | 
|---|
| 2173 |  | 
|---|
| 2174 | } else { | 
|---|
| 2175 |  | 
|---|
| 2176 | if ($wasinherited) {      # munge new permission entry in if we're switching from inherited perms | 
|---|
| 2177 | ##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users | 
|---|
| 2178 | # ... if'n'when we have groups with fully inherited permissions. | 
|---|
| 2179 | # SQL is coo | 
|---|
| 2180 | $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ". | 
|---|
| 2181 | "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) ); | 
|---|
| 2182 | ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ". | 
|---|
| 2183 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) ); | 
|---|
| 2184 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ". | 
|---|
| 2185 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) ); | 
|---|
| 2186 | } | 
|---|
| 2187 |  | 
|---|
| 2188 | # and now set the permissions we were passed | 
|---|
| 2189 | foreach (@permtypes) { | 
|---|
| 2190 | if (defined ($newperms->{$_})) { | 
|---|
| 2191 | $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) ); | 
|---|
| 2192 | } | 
|---|
| 2193 | } | 
|---|
| 2194 |  | 
|---|
| 2195 | } # (inherited->)? custom | 
|---|
| 2196 |  | 
|---|
| 2197 | if ($type eq 'user') { | 
|---|
| 2198 | $resultmsg = "Updated permissions for user $name"; | 
|---|
| 2199 | } else { | 
|---|
| 2200 | $resultmsg = "Updated default permissions for group $name"; | 
|---|
| 2201 | } | 
|---|
| 2202 | $self->_log(group_id => ($type eq 'user' ? $parid : $id), entry => $resultmsg); | 
|---|
| 2203 | $dbh->commit; | 
|---|
| 2204 | }; # end eval | 
|---|
| 2205 | if ($@) { | 
|---|
| 2206 | my $msg = $@; | 
|---|
| 2207 | eval { $dbh->rollback; }; | 
|---|
| 2208 | return ('FAIL',"Error changing permissions: $msg"); | 
|---|
| 2209 | } | 
|---|
| 2210 |  | 
|---|
| 2211 | return ('OK',$resultmsg); | 
|---|
| 2212 | } # end changePermissions() | 
|---|
| 2213 |  | 
|---|
| 2214 |  | 
|---|
| 2215 | ## DNSDB::comparePermissions() | 
|---|
| 2216 | # Compare two permission hashes | 
|---|
| 2217 | # Returns '>', '<', '=', '!' | 
|---|
| 2218 | sub comparePermissions { | 
|---|
| 2219 | my $self = shift; | 
|---|
| 2220 | my $p1 = shift; | 
|---|
| 2221 | my $p2 = shift; | 
|---|
| 2222 |  | 
|---|
| 2223 | my $retval = '=';     # assume equality until proven otherwise | 
|---|
| 2224 |  | 
|---|
| 2225 | no warnings "uninitialized"; | 
|---|
| 2226 |  | 
|---|
| 2227 | foreach (@permtypes) { | 
|---|
| 2228 | next if $p1->{$_} == $p2->{$_};     # equal is good | 
|---|
| 2229 | if ($p1->{$_} && !$p2->{$_}) { | 
|---|
| 2230 | if ($retval eq '<') {     # if we've already found an unequal pair where | 
|---|
| 2231 | $retval = '!';          # $p2 has more access, and we now find a pair | 
|---|
| 2232 | last;                   # where $p1 has more access, the overall access | 
|---|
| 2233 | }                         # is neither greater or lesser, it's unequal. | 
|---|
| 2234 | $retval = '>'; | 
|---|
| 2235 | } | 
|---|
| 2236 | if (!$p1->{$_} && $p2->{$_}) { | 
|---|
| 2237 | if ($retval eq '>') {     # if we've already found an unequal pair where | 
|---|
| 2238 | $retval = '!';          # $p1 has more access, and we now find a pair | 
|---|
| 2239 | last;                   # where $p2 has more access, the overall access | 
|---|
| 2240 | }                         # is neither greater or lesser, it's unequal. | 
|---|
| 2241 | $retval = '<'; | 
|---|
| 2242 | } | 
|---|
| 2243 | } | 
|---|
| 2244 | return $retval; | 
|---|
| 2245 | } # end comparePermissions() | 
|---|
| 2246 |  | 
|---|
| 2247 |  | 
|---|
| 2248 | ## DNSDB::changeGroup() | 
|---|
| 2249 | # Change group ID of an entity | 
|---|
| 2250 | # Takes a database handle, entity type, entity ID, and new group ID | 
|---|
| 2251 | sub changeGroup { | 
|---|
| 2252 | my $self = shift; | 
|---|
| 2253 | my $dbh = $self->{dbh}; | 
|---|
| 2254 | my $type = shift; | 
|---|
| 2255 | my $id = shift; | 
|---|
| 2256 | my $newgrp = shift; | 
|---|
| 2257 |  | 
|---|
| 2258 | ##fixme:  fail on not enough args | 
|---|
| 2259 | #return ('FAIL', "Missing | 
|---|
| 2260 |  | 
|---|
| 2261 | return ('FAIL', "Can't change the group of a $type") | 
|---|
| 2262 | unless grep /^$type$/, ('domain','revzone','user','group');     # could be extended for defrecs? | 
|---|
| 2263 |  | 
|---|
| 2264 | # Collect some names for logging and messages | 
|---|
| 2265 | my $entname; | 
|---|
| 2266 | if ($type eq 'domain') { | 
|---|
| 2267 | $entname = $self->domainName($id); | 
|---|
| 2268 | } elsif ($type eq 'revzone') { | 
|---|
| 2269 | $entname = $self->revName($id); | 
|---|
| 2270 | } elsif ($type eq 'user') { | 
|---|
| 2271 | $entname = $self->userFullName($id, '%u'); | 
|---|
| 2272 | } elsif ($type eq 'group') { | 
|---|
| 2273 | $entname = $self->groupName($id); | 
|---|
| 2274 | } | 
|---|
| 2275 |  | 
|---|
| 2276 | my ($oldgid) = $dbh->selectrow_array("SELECT group_id FROM $par_tbl{$type} WHERE $id_col{$type}=?", | 
|---|
| 2277 | undef, ($id)); | 
|---|
| 2278 | my $oldgname = $self->groupName($oldgid); | 
|---|
| 2279 | my $newgname = $self->groupName($newgrp); | 
|---|
| 2280 |  | 
|---|
| 2281 | return ('FAIL', "Can't move things into a group that doesn't exist") if !$newgname; | 
|---|
| 2282 |  | 
|---|
| 2283 | return ('WARN', "Nothing to do, new group is the same as the old group") if $oldgid == $newgrp; | 
|---|
| 2284 |  | 
|---|
| 2285 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 2286 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 2287 | local $dbh->{AutoCommit} = 0; | 
|---|
| 2288 | local $dbh->{RaiseError} = 1; | 
|---|
| 2289 |  | 
|---|
| 2290 | eval { | 
|---|
| 2291 | $dbh->do("UPDATE $par_tbl{$type} SET group_id=? WHERE $id_col{$type}=?", undef, ($newgrp, $id)); | 
|---|
| 2292 | # Log the change in both the old and new groups | 
|---|
| 2293 | $self->_log(group_id => $oldgid, entry => "Moved $type $entname from $oldgname to $newgname"); | 
|---|
| 2294 | $self->_log(group_id => $newgrp, entry => "Moved $type $entname from $oldgname to $newgname"); | 
|---|
| 2295 | $dbh->commit; | 
|---|
| 2296 | }; | 
|---|
| 2297 | if ($@) { | 
|---|
| 2298 | my $msg = $@; | 
|---|
| 2299 | eval { $dbh->rollback; }; | 
|---|
| 2300 | if ($self->{log_failures}) { | 
|---|
| 2301 | $self->_log(group_id => $oldgid, entry => "Error moving $type $entname to $newgname: $msg"); | 
|---|
| 2302 | $dbh->commit;     # since we enabled transactions earlier | 
|---|
| 2303 | } | 
|---|
| 2304 | return ('FAIL',"Error moving $type $entname to $newgname: $msg"); | 
|---|
| 2305 | } | 
|---|
| 2306 |  | 
|---|
| 2307 | return ('OK',"Moved $type $entname from $oldgname to $newgname"); | 
|---|
| 2308 | } # end changeGroup() | 
|---|
| 2309 |  | 
|---|
| 2310 |  | 
|---|
| 2311 | ## | 
|---|
| 2312 | ## Processing subs | 
|---|
| 2313 | ## | 
|---|
| 2314 |  | 
|---|
| 2315 | ## DNSDB::addDomain() | 
|---|
| 2316 | # Add a domain | 
|---|
| 2317 | # Takes a database handle, domain name, numeric group, boolean(ish) state (active/inactive), | 
|---|
| 2318 | # and user info hash (for logging). | 
|---|
| 2319 | # Returns a status code and message | 
|---|
| 2320 | sub addDomain { | 
|---|
| 2321 | $errstr = ''; | 
|---|
| 2322 | my $self = shift; | 
|---|
| 2323 | my $dbh = $self->{dbh}; | 
|---|
| 2324 | my $domain = shift; | 
|---|
| 2325 | return ('FAIL',"Domain must not be blank\n") if !$domain; | 
|---|
| 2326 | my $group = shift; | 
|---|
| 2327 | return ('FAIL',"Group must be specified\n") if !defined($group); | 
|---|
| 2328 | my $state = shift; | 
|---|
| 2329 | return ('FAIL',"Domain status must be specified\n") if !defined($state); | 
|---|
| 2330 | my $defloc = shift || ''; | 
|---|
| 2331 |  | 
|---|
| 2332 | $state = 1 if $state =~ /^active$/; | 
|---|
| 2333 | $state = 1 if $state =~ /^on$/; | 
|---|
| 2334 | $state = 0 if $state =~ /^inactive$/; | 
|---|
| 2335 | $state = 0 if $state =~ /^off$/; | 
|---|
| 2336 |  | 
|---|
| 2337 | return ('FAIL',"Invalid domain status") if $state !~ /^\d+$/; | 
|---|
| 2338 |  | 
|---|
| 2339 | $domain = lc($domain) if $self->{lowercase}; | 
|---|
| 2340 |  | 
|---|
| 2341 | return ('FAIL', "Invalid characters in domain") if $domain !~ /^[a-zA-Z0-9_.-]+$/; | 
|---|
| 2342 |  | 
|---|
| 2343 | my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)"); | 
|---|
| 2344 | my $dom_id; | 
|---|
| 2345 |  | 
|---|
| 2346 | # quick check to start to see if we've already got one | 
|---|
| 2347 | $sth->execute($domain); | 
|---|
| 2348 | ($dom_id) = $sth->fetchrow_array; | 
|---|
| 2349 |  | 
|---|
| 2350 | return ('FAIL', "Domain already exists") if $dom_id; | 
|---|
| 2351 |  | 
|---|
| 2352 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 2353 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 2354 | local $dbh->{AutoCommit} = 0; | 
|---|
| 2355 | local $dbh->{RaiseError} = 1; | 
|---|
| 2356 |  | 
|---|
| 2357 | # Wrap all the SQL in a transaction | 
|---|
| 2358 | eval { | 
|---|
| 2359 | # insert the domain... | 
|---|
| 2360 | $dbh->do("INSERT INTO domains (domain,group_id,status,default_location) VALUES (?,?,?,?)", undef, | 
|---|
| 2361 | ($domain, $group, $state, $defloc)); | 
|---|
| 2362 |  | 
|---|
| 2363 | # get the ID... | 
|---|
| 2364 | ($dom_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)", | 
|---|
| 2365 | undef, ($domain)); | 
|---|
| 2366 |  | 
|---|
| 2367 | $self->_log(domain_id => $dom_id, group_id => $group, | 
|---|
| 2368 | entry => "Added ".($state ? 'active' : 'inactive')." domain $domain"); | 
|---|
| 2369 |  | 
|---|
| 2370 | # ... and now we construct the standard records from the default set.  NB:  group should be variable. | 
|---|
| 2371 | my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?"); | 
|---|
| 2372 | my $sth_in = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,distance,weight,port,ttl,location)". | 
|---|
| 2373 | " VALUES ($dom_id,?,?,?,?,?,?,?,?)"); | 
|---|
| 2374 | $sth->execute($group); | 
|---|
| 2375 | while (my ($host, $type, $val, $dist, $weight, $port, $ttl) = $sth->fetchrow_array()) { | 
|---|
| 2376 | $host =~ s/DOMAIN/$domain/g; | 
|---|
| 2377 | $val =~ s/DOMAIN/$domain/g; | 
|---|
| 2378 | _caseclean(\$type, \$host, \$val, 'n', 'n') if $self->{lowercase}; | 
|---|
| 2379 | $sth_in->execute($host, $type, $val, $dist, $weight, $port, $ttl, $defloc); | 
|---|
| 2380 | if ($typemap{$type} eq 'SOA') { | 
|---|
| 2381 | my @tmp1 = split /:/, $host; | 
|---|
| 2382 | my @tmp2 = split /:/, $val; | 
|---|
| 2383 | $self->_log(domain_id => $dom_id, group_id => $group, | 
|---|
| 2384 | entry => "[new $domain] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ". | 
|---|
| 2385 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"); | 
|---|
| 2386 | } else { | 
|---|
| 2387 | my $logentry = "[new $domain] Added record '$host $typemap{$type}"; | 
|---|
| 2388 | $logentry .= " [distance $dist]" if $typemap{$type} eq 'MX'; | 
|---|
| 2389 | $logentry .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$type} eq 'SRV'; | 
|---|
| 2390 | $self->_log(domain_id => $dom_id, group_id => $group, | 
|---|
| 2391 | entry => $logentry." $val', TTL $ttl"); | 
|---|
| 2392 | } | 
|---|
| 2393 | } | 
|---|
| 2394 |  | 
|---|
| 2395 | # once we get here, we should have suceeded. | 
|---|
| 2396 | $dbh->commit; | 
|---|
| 2397 | }; # end eval | 
|---|
| 2398 |  | 
|---|
| 2399 | if ($@) { | 
|---|
| 2400 | my $msg = $@; | 
|---|
| 2401 | eval { $dbh->rollback; }; | 
|---|
| 2402 | $self->_log(group_id => $group, entry => "Failed adding domain $domain ($msg)") | 
|---|
| 2403 | if $self->{log_failures}; | 
|---|
| 2404 | $dbh->commit;       # since we enabled transactions earlier | 
|---|
| 2405 | return ('FAIL',$msg); | 
|---|
| 2406 | } else { | 
|---|
| 2407 | return ('OK',$dom_id); | 
|---|
| 2408 | } | 
|---|
| 2409 | } # end addDomain | 
|---|
| 2410 |  | 
|---|
| 2411 |  | 
|---|
| 2412 | ## DNSDB::delZone() | 
|---|
| 2413 | # Delete a forward or reverse zone. | 
|---|
| 2414 | # Takes a database handle, zone ID, and forward/reverse flag. | 
|---|
| 2415 | # for now, just delete the records, then the domain. | 
|---|
| 2416 | # later we may want to archive it in some way instead (status code 2, for example?) | 
|---|
| 2417 | sub delZone { | 
|---|
| 2418 | my $self = shift; | 
|---|
| 2419 | my $dbh = $self->{dbh}; | 
|---|
| 2420 | my $zoneid = shift; | 
|---|
| 2421 | my $revrec = shift; | 
|---|
| 2422 |  | 
|---|
| 2423 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 2424 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 2425 | local $dbh->{AutoCommit} = 0; | 
|---|
| 2426 | local $dbh->{RaiseError} = 1; | 
|---|
| 2427 |  | 
|---|
| 2428 | my $msg = ''; | 
|---|
| 2429 | my $failmsg = ''; | 
|---|
| 2430 | my $zone = ($revrec eq 'n' ? $self->domainName($zoneid) : $self->revName($zoneid)); | 
|---|
| 2431 |  | 
|---|
| 2432 | return ('FAIL', ($revrec eq 'n' ? 'Domain' : 'Reverse zone')." ID $zoneid doesn't exist") if !$zone; | 
|---|
| 2433 |  | 
|---|
| 2434 | # Set this up here since we may use if if $self->{log_failures} is enabled | 
|---|
| 2435 | my %loghash; | 
|---|
| 2436 | $loghash{domain_id} = $zoneid if $revrec eq 'n'; | 
|---|
| 2437 | $loghash{rdns_id} = $zoneid if $revrec eq 'y'; | 
|---|
| 2438 | $loghash{group_id} = $self->parentID( | 
|---|
| 2439 | id => $zoneid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec); | 
|---|
| 2440 |  | 
|---|
| 2441 | # Wrap all the SQL in a transaction | 
|---|
| 2442 | eval { | 
|---|
| 2443 | # Disentangle custom record types before removing the | 
|---|
| 2444 | # ones that are only in the zone to be deleted | 
|---|
| 2445 | if ($revrec eq 'n') { | 
|---|
| 2446 | my $sth = $dbh->prepare("UPDATE records SET type=?,domain_id=0 WHERE domain_id=? AND type=?"); | 
|---|
| 2447 | $failmsg = "Failure converting multizone types to single-zone"; | 
|---|
| 2448 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65280); | 
|---|
| 2449 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65281); | 
|---|
| 2450 | $sth->execute(65282, $zoneid, 65283); | 
|---|
| 2451 | $sth->execute(65282, $zoneid, 65284); | 
|---|
| 2452 | $failmsg = "Failure removing domain records"; | 
|---|
| 2453 | $dbh->do("DELETE FROM records WHERE domain_id=?", undef, ($zoneid)); | 
|---|
| 2454 | $failmsg = "Failure removing domain"; | 
|---|
| 2455 | $dbh->do("DELETE FROM domains WHERE domain_id=?", undef, ($zoneid)); | 
|---|
| 2456 | } else { | 
|---|
| 2457 | my $sth = $dbh->prepare("UPDATE records SET type=?,rdns_id=0 WHERE rdns_id=? AND type=?"); | 
|---|
| 2458 | $failmsg = "Failure converting multizone types to single-zone"; | 
|---|
| 2459 | $sth->execute($reverse_typemap{A}, $zoneid, 65280); | 
|---|
| 2460 | $sth->execute($reverse_typemap{AAAA}, $zoneid, 65281); | 
|---|
| 2461 | # We don't have an "A template" or "AAAA template" type, although it might be useful for symmetry. | 
|---|
| 2462 | #      $sth->execute(65286?, $zoneid, 65283); | 
|---|
| 2463 | #      $sth->execute(65286?, $zoneid, 65284); | 
|---|
| 2464 | $failmsg = "Failure removing reverse records"; | 
|---|
| 2465 | $dbh->do("DELETE FROM records WHERE rdns_id=?", undef, ($zoneid)); | 
|---|
| 2466 | $failmsg = "Failure removing reverse zone"; | 
|---|
| 2467 | $dbh->do("DELETE FROM revzones WHERE rdns_id=?", undef, ($zoneid)); | 
|---|
| 2468 | } | 
|---|
| 2469 |  | 
|---|
| 2470 | $msg = "Deleted ".($revrec eq 'n' ? 'domain' : 'reverse zone')." $zone"; | 
|---|
| 2471 | $loghash{entry} = $msg; | 
|---|
| 2472 | $self->_log(%loghash); | 
|---|
| 2473 |  | 
|---|
| 2474 | # once we get here, we should have suceeded. | 
|---|
| 2475 | $dbh->commit; | 
|---|
| 2476 | }; # end eval | 
|---|
| 2477 |  | 
|---|
| 2478 | if ($@) { | 
|---|
| 2479 | $msg = $@; | 
|---|
| 2480 | eval { $dbh->rollback; }; | 
|---|
| 2481 | $loghash{entry} = "Error deleting $zone: $msg ($failmsg)"; | 
|---|
| 2482 | if ($self->{log_failures}) { | 
|---|
| 2483 | $self->_log(%loghash); | 
|---|
| 2484 | $dbh->commit;     # since we enabled transactions earlier | 
|---|
| 2485 | } | 
|---|
| 2486 | return ('FAIL', $loghash{entry}); | 
|---|
| 2487 | } else { | 
|---|
| 2488 | return ('OK', $msg); | 
|---|
| 2489 | } | 
|---|
| 2490 |  | 
|---|
| 2491 | } # end delZone() | 
|---|
| 2492 |  | 
|---|
| 2493 |  | 
|---|
| 2494 | ## DNSDB::domainName() | 
|---|
| 2495 | # Return the domain name based on a domain ID | 
|---|
| 2496 | # Takes a database handle and the domain ID | 
|---|
| 2497 | # Returns the domain name or undef on failure | 
|---|
| 2498 | sub domainName { | 
|---|
| 2499 | $errstr = ''; | 
|---|
| 2500 | my $self = shift; | 
|---|
| 2501 | my $dbh = $self->{dbh}; | 
|---|
| 2502 | my $domid = shift; | 
|---|
| 2503 | my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) ); | 
|---|
| 2504 | $errstr = $DBI::errstr if !$domname; | 
|---|
| 2505 | return $domname if $domname; | 
|---|
| 2506 | } # end domainName() | 
|---|
| 2507 |  | 
|---|
| 2508 |  | 
|---|
| 2509 | ## DNSDB::revName() | 
|---|
| 2510 | # Return the reverse zone name based on an rDNS ID | 
|---|
| 2511 | # Takes a database handle and the rDNS ID, and an optional flag to force return of the CIDR zone | 
|---|
| 2512 | # instead of the formal .arpa zone name | 
|---|
| 2513 | # Returns the reverse zone name or undef on failure | 
|---|
| 2514 | sub revName { | 
|---|
| 2515 | $errstr = ''; | 
|---|
| 2516 | my $self = shift; | 
|---|
| 2517 | my $dbh = $self->{dbh}; | 
|---|
| 2518 | my $revid = shift; | 
|---|
| 2519 | my $cidrflag = shift || 'n'; | 
|---|
| 2520 | my ($revname) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id=?", undef, ($revid) ); | 
|---|
| 2521 | $errstr = $DBI::errstr if !$revname; | 
|---|
| 2522 | my $tmp = new NetAddr::IP $revname; | 
|---|
| 2523 | $revname = _ZONE($tmp, 'ZONE', 'r', '.').($tmp->{isv6} ? '.ip6.arpa' : '.in-addr.arpa') | 
|---|
| 2524 | if ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all') && $cidrflag eq 'n'; | 
|---|
| 2525 | return $revname if $revname; | 
|---|
| 2526 | } # end revName() | 
|---|
| 2527 |  | 
|---|
| 2528 |  | 
|---|
| 2529 | ## DNSDB::domainID() | 
|---|
| 2530 | # Takes a database handle and domain name | 
|---|
| 2531 | # Returns the domain ID number | 
|---|
| 2532 | sub domainID { | 
|---|
| 2533 | $errstr = ''; | 
|---|
| 2534 | my $self = shift; | 
|---|
| 2535 | my $dbh = $self->{dbh}; | 
|---|
| 2536 | my $domain = shift; | 
|---|
| 2537 | my ($domid) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)", | 
|---|
| 2538 | undef, ($domain) ); | 
|---|
| 2539 | if (!$domid) { | 
|---|
| 2540 | if ($dbh->err) { | 
|---|
| 2541 | $errstr = $DBI::errstr; | 
|---|
| 2542 | } else { | 
|---|
| 2543 | $errstr = "Domain $domain not present"; | 
|---|
| 2544 | } | 
|---|
| 2545 | } | 
|---|
| 2546 | return $domid if $domid; | 
|---|
| 2547 | } # end domainID() | 
|---|
| 2548 |  | 
|---|
| 2549 |  | 
|---|
| 2550 | ## DNSDB::revID() | 
|---|
| 2551 | # Takes a database handle and reverse zone name | 
|---|
| 2552 | # Returns the rDNS ID number | 
|---|
| 2553 | sub revID { | 
|---|
| 2554 | $errstr = ''; | 
|---|
| 2555 | my $self = shift; | 
|---|
| 2556 | my $dbh = $self->{dbh}; | 
|---|
| 2557 | my $revzone = shift; | 
|---|
| 2558 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ($revzone) ); | 
|---|
| 2559 | if (!$revid) { | 
|---|
| 2560 | if ($dbh->err) { | 
|---|
| 2561 | $errstr = $DBI::errstr; | 
|---|
| 2562 | } else { | 
|---|
| 2563 | $errstr = "Reverse zone $revzone not present"; | 
|---|
| 2564 | } | 
|---|
| 2565 | } | 
|---|
| 2566 | return $revid if $revid; | 
|---|
| 2567 | } # end revID() | 
|---|
| 2568 |  | 
|---|
| 2569 |  | 
|---|
| 2570 | ## DNSDB::addRDNS | 
|---|
| 2571 | # Adds a reverse DNS zone | 
|---|
| 2572 | # Takes a database handle, CIDR block, reverse DNS pattern, numeric group, | 
|---|
| 2573 | # and boolean(ish) state (active/inactive) | 
|---|
| 2574 | # Returns a status code and message | 
|---|
| 2575 | sub addRDNS { | 
|---|
| 2576 | my $self = shift; | 
|---|
| 2577 | my $dbh = $self->{dbh}; | 
|---|
| 2578 | my $zone = shift; | 
|---|
| 2579 |  | 
|---|
| 2580 | # Autodetect formal .arpa zones | 
|---|
| 2581 | if ($zone =~ /\.arpa\.?$/) { | 
|---|
| 2582 | my $code; | 
|---|
| 2583 | ($code,$zone) = _zone2cidr($zone); | 
|---|
| 2584 | return ('FAIL', $zone) if $code eq 'FAIL'; | 
|---|
| 2585 | } | 
|---|
| 2586 | $zone = NetAddr::IP->new($zone); | 
|---|
| 2587 |  | 
|---|
| 2588 | return ('FAIL',"Zone name must be a valid CIDR netblock") unless ($zone && $zone->addr !~ /^0/); | 
|---|
| 2589 | my $revpatt = shift;  # construct a custom (A/AAAA+)? PTR template record | 
|---|
| 2590 | my $group = shift; | 
|---|
| 2591 | my $state = shift; | 
|---|
| 2592 | my $defloc = shift || ''; | 
|---|
| 2593 |  | 
|---|
| 2594 | $state = 1 if $state =~ /^active$/; | 
|---|
| 2595 | $state = 1 if $state =~ /^on$/; | 
|---|
| 2596 | $state = 0 if $state =~ /^inactive$/; | 
|---|
| 2597 | $state = 0 if $state =~ /^off$/; | 
|---|
| 2598 |  | 
|---|
| 2599 | return ('FAIL',"Invalid zone status") if $state !~ /^\d+$/; | 
|---|
| 2600 |  | 
|---|
| 2601 | # quick check to start to see if we've already got one | 
|---|
| 2602 | my ($rdns_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ("$zone")); | 
|---|
| 2603 |  | 
|---|
| 2604 | return ('FAIL', "Zone already exists") if $rdns_id; | 
|---|
| 2605 |  | 
|---|
| 2606 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 2607 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 2608 | local $dbh->{AutoCommit} = 0; | 
|---|
| 2609 | local $dbh->{RaiseError} = 1; | 
|---|
| 2610 |  | 
|---|
| 2611 | my $warnstr = ''; | 
|---|
| 2612 | my $defttl = 3600;    # 1 hour should be reasonable.  And unless things have gone horribly | 
|---|
| 2613 | # wrong, we should have a value to override this anyway. | 
|---|
| 2614 |  | 
|---|
| 2615 | # Wrap all the SQL in a transaction | 
|---|
| 2616 | eval { | 
|---|
| 2617 | # insert the zone... | 
|---|
| 2618 | $dbh->do("INSERT INTO revzones (revnet,group_id,status,default_location) VALUES (?,?,?,?)", undef, | 
|---|
| 2619 | ($zone, $group, $state, $defloc) ); | 
|---|
| 2620 |  | 
|---|
| 2621 | # get the ID... | 
|---|
| 2622 | ($rdns_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')"); | 
|---|
| 2623 |  | 
|---|
| 2624 | $self->_log(rdns_id => $rdns_id, group_id => $group, | 
|---|
| 2625 | entry => "Added ".($state ? 'active' : 'inactive')." reverse zone $zone"); | 
|---|
| 2626 |  | 
|---|
| 2627 | # ... and now we construct the standard records from the default set.  NB:  group should be variable. | 
|---|
| 2628 | my $sth = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?"); | 
|---|
| 2629 | my $sth_in = $dbh->prepare("INSERT INTO records (rdns_id,domain_id,host,type,val,ttl,location)". | 
|---|
| 2630 | " VALUES ($rdns_id,?,?,?,?,?,?)"); | 
|---|
| 2631 | $sth->execute($group); | 
|---|
| 2632 | while (my ($host,$type,$val,$ttl) = $sth->fetchrow_array()) { | 
|---|
| 2633 | # Silently skip v4/v6 mismatches.  This is not an error, this is expected. | 
|---|
| 2634 | if ($zone->{isv6}) { | 
|---|
| 2635 | next if ($type == 65280 || $type == 65283); | 
|---|
| 2636 | } else { | 
|---|
| 2637 | next if ($type == 65281 || $type == 65284); | 
|---|
| 2638 | } | 
|---|
| 2639 |  | 
|---|
| 2640 | $host =~ s/ADMINDOMAIN/$self->{domain}/g; | 
|---|
| 2641 |  | 
|---|
| 2642 | # Check to make sure the IP stubs will fit in the zone.  Under most usage failures here should be rare. | 
|---|
| 2643 | # On failure, tack a note on to a warning string and continue without adding this record. | 
|---|
| 2644 | # While we're at it, we substitute $zone for ZONE in the value. | 
|---|
| 2645 | if ($val eq 'ZONE') { | 
|---|
| 2646 | # If we've got a pattern, we skip the default record version on (A+)PTR-template types | 
|---|
| 2647 | next if $revpatt && ($type == 65282 || $type == 65283); | 
|---|
| 2648 | ##fixme?  do we care if we have multiple whole-zone templates? | 
|---|
| 2649 | $val = $zone->network; | 
|---|
| 2650 | } elsif ($val =~ /ZONE/) { | 
|---|
| 2651 | my $tmpval = $val; | 
|---|
| 2652 | $tmpval =~ s/ZONE//; | 
|---|
| 2653 | # Bend the rules and allow single-trailing-number PTR or PTR template records to be inserted | 
|---|
| 2654 | # as either v4 or v6.  May make this an off-by-default config flag | 
|---|
| 2655 | # Note that the origin records that may trigger this **SHOULD** already have ZONE,\d | 
|---|
| 2656 | if ($type == 12 || $type == 65282) { | 
|---|
| 2657 | $tmpval =~ s/[,.]/::/ if ($tmpval =~ /^[,.]\d+$/ && $zone->{isv6}); | 
|---|
| 2658 | $tmpval =~ s/[,:]+/./ if ($tmpval =~ /^(?:,|::)\d+$/ && !$zone->{isv6}); | 
|---|
| 2659 | } | 
|---|
| 2660 | my $addr; | 
|---|
| 2661 | if ($self->_ipparent('n', 'y', \$tmpval, $rdns_id, \$addr)) { | 
|---|
| 2662 | $val = $addr->addr; | 
|---|
| 2663 | } else { | 
|---|
| 2664 | $warnstr .= "\nDefault record '$val $typemap{$type} $host' doesn't fit in $zone, skipping"; | 
|---|
| 2665 | next; | 
|---|
| 2666 | } | 
|---|
| 2667 | } | 
|---|
| 2668 |  | 
|---|
| 2669 | # Substitute $zone for ZONE in the hostname, but only for non-NS records. | 
|---|
| 2670 | # NS records get this substitution on the value instead. | 
|---|
| 2671 | $host = _ZONE($zone, $host) if $type != 2; | 
|---|
| 2672 |  | 
|---|
| 2673 | # Fill in the forward domain ID if we can find it, otherwise: | 
|---|
| 2674 | # Coerce type down to PTR or PTR template if we can't | 
|---|
| 2675 | my $domid = 0; | 
|---|
| 2676 | if ($type >= 65280) { | 
|---|
| 2677 | if (!($domid = $self->_hostparent($host))) { | 
|---|
| 2678 | $warnstr .= "\nRecord added as PTR instead of $typemap{$type};  domain not found for $host"; | 
|---|
| 2679 | $type = $reverse_typemap{PTR}; | 
|---|
| 2680 | $domid = 0;   # just to be explicit. | 
|---|
| 2681 | } | 
|---|
| 2682 | } | 
|---|
| 2683 |  | 
|---|
| 2684 | _caseclean(\$type, \$host, \$val, 'n', 'y') if $self->{lowercase}; | 
|---|
| 2685 |  | 
|---|
| 2686 | $sth_in->execute($domid,$host,$type,$val,$ttl,$defloc); | 
|---|
| 2687 |  | 
|---|
| 2688 | if ($typemap{$type} eq 'SOA') { | 
|---|
| 2689 | my @tmp1 = split /:/, $host; | 
|---|
| 2690 | my @tmp2 = split /:/, $val; | 
|---|
| 2691 | $self->_log(rdns_id => $rdns_id, group_id => $group, | 
|---|
| 2692 | entry => "[new $zone] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ". | 
|---|
| 2693 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"); | 
|---|
| 2694 | $defttl = $tmp2[3]; | 
|---|
| 2695 | } else { | 
|---|
| 2696 | my $logentry = "[new $zone] Added record '$host $typemap{$type} $val', TTL $ttl"; | 
|---|
| 2697 | $logentry .= ", default location ".$self->getLoc($defloc)->{description} if $defloc; | 
|---|
| 2698 | $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group, entry => $logentry); | 
|---|
| 2699 | } | 
|---|
| 2700 | } | 
|---|
| 2701 |  | 
|---|
| 2702 | # Generate record based on provided pattern. | 
|---|
| 2703 | if ($revpatt) { | 
|---|
| 2704 | my $host; | 
|---|
| 2705 | my $type = ($zone->{isv6} ? 65284 : 65283); | 
|---|
| 2706 | my $val = $zone->network; | 
|---|
| 2707 |  | 
|---|
| 2708 | # Substitute $zone for ZONE in the hostname. | 
|---|
| 2709 | $host = _ZONE($zone, $revpatt); | 
|---|
| 2710 |  | 
|---|
| 2711 | my $domid = 0; | 
|---|
| 2712 | if (!($domid = $self->_hostparent($host))) { | 
|---|
| 2713 | $warnstr .= "\nDefault pattern added as PTR template instead of $typemap{$type};  domain not found for $host"; | 
|---|
| 2714 | $type = 65282; | 
|---|
| 2715 | $domid = 0;     # just to be explicit. | 
|---|
| 2716 | } | 
|---|
| 2717 |  | 
|---|
| 2718 | $sth_in->execute($domid,$host,$type,$val,$defttl,$defloc); | 
|---|
| 2719 | my $logentry = "[new $zone] Added record '$host $typemap{$type}"; | 
|---|
| 2720 | $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group, | 
|---|
| 2721 | entry => $logentry." $val', TTL $defttl from pattern"); | 
|---|
| 2722 | } | 
|---|
| 2723 |  | 
|---|
| 2724 | # If there are warnings (presumably about default records skipped for cause) log them | 
|---|
| 2725 | $self->_log(rdns_id => $rdns_id, group_id => $group, entry => "Warning(s) adding $zone:$warnstr") | 
|---|
| 2726 | if $warnstr; | 
|---|
| 2727 |  | 
|---|
| 2728 | # once we get here, we should have suceeded. | 
|---|
| 2729 | $dbh->commit; | 
|---|
| 2730 | }; # end eval | 
|---|
| 2731 |  | 
|---|
| 2732 | if ($@) { | 
|---|
| 2733 | my $msg = $@; | 
|---|
| 2734 | eval { $dbh->rollback; }; | 
|---|
| 2735 | $self->_log(group_id => $group, entry => "Failed adding reverse zone $zone ($msg)") | 
|---|
| 2736 | if $self->{log_failures}; | 
|---|
| 2737 | $dbh->commit;       # since we enabled transactions earlier | 
|---|
| 2738 | return ('FAIL',$msg); | 
|---|
| 2739 | } else { | 
|---|
| 2740 | my $retcode = 'OK'; | 
|---|
| 2741 | if ($warnstr) { | 
|---|
| 2742 | $resultstr = $warnstr; | 
|---|
| 2743 | $retcode = 'WARN'; | 
|---|
| 2744 | } | 
|---|
| 2745 | return ($retcode, $rdns_id); | 
|---|
| 2746 | } | 
|---|
| 2747 |  | 
|---|
| 2748 | } # end addRDNS() | 
|---|
| 2749 |  | 
|---|
| 2750 |  | 
|---|
| 2751 | ## DNSDB::getZoneCount | 
|---|
| 2752 | # Get count of zones in group or groups | 
|---|
| 2753 | # Takes a database handle and hash containing: | 
|---|
| 2754 | #  - the "current" group | 
|---|
| 2755 | #  - an array of "acceptable" groups | 
|---|
| 2756 | #  - a flag for forward/reverse zones | 
|---|
| 2757 | #  - Optionally accept a "starts with" and/or "contains" filter argument | 
|---|
| 2758 | # Returns an integer count of the resulting zone list. | 
|---|
| 2759 | sub getZoneCount { | 
|---|
| 2760 | my $self = shift; | 
|---|
| 2761 | my $dbh = $self->{dbh}; | 
|---|
| 2762 |  | 
|---|
| 2763 | my %args = @_; | 
|---|
| 2764 |  | 
|---|
| 2765 | # Fail on bad curgroup argument.  There's no sane fallback on this one. | 
|---|
| 2766 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) { | 
|---|
| 2767 | $errstr = "Bad or missing curgroup argument"; | 
|---|
| 2768 | return; | 
|---|
| 2769 | } | 
|---|
| 2770 | # Fail on bad childlist argument.  This could be sanely ignored if bad, maybe. | 
|---|
| 2771 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) { | 
|---|
| 2772 | $errstr = "Bad childlist argument"; | 
|---|
| 2773 | return; | 
|---|
| 2774 | } | 
|---|
| 2775 |  | 
|---|
| 2776 | my @filterargs; | 
|---|
| 2777 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/; | 
|---|
| 2778 | push @filterargs, "^$args{startwith}" if $args{startwith}; | 
|---|
| 2779 | $args{filter} =~ s/\./\[\.\]/g if $args{filter};      # only match literal dots, usually in reverse zones | 
|---|
| 2780 | push @filterargs, $args{filter} if $args{filter}; | 
|---|
| 2781 |  | 
|---|
| 2782 | my $sql; | 
|---|
| 2783 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read | 
|---|
| 2784 | if ($args{revrec} eq 'n') { | 
|---|
| 2785 | $sql = "SELECT count(*) FROM domains". | 
|---|
| 2786 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")". | 
|---|
| 2787 | ($args{startwith} ? " AND domain ~* ?" : ''). | 
|---|
| 2788 | ($args{filter} ? " AND domain ~* ?" : ''); | 
|---|
| 2789 | } else { | 
|---|
| 2790 | $sql = "SELECT count(*) FROM revzones". | 
|---|
| 2791 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")". | 
|---|
| 2792 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : ''); | 
|---|
| 2793 | #    if ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all') { | 
|---|
| 2794 | # Just In Case the UI is using formal .arpa notation, and someone enters something reversed, | 
|---|
| 2795 | # we want to match both the formal and natural zone name | 
|---|
| 2796 | $sql .= ($args{filter} ? " AND (CAST(revnet AS VARCHAR) ~* ? OR CAST(revnet AS VARCHAR) ~* ?)" : ''); | 
|---|
| 2797 | push @filterargs, join('[.]',reverse(split(/\[\.\]/,$args{filter}))) if $args{filter}; | 
|---|
| 2798 | #    } else { | 
|---|
| 2799 | #      $sql .= ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : ''); | 
|---|
| 2800 | #    } | 
|---|
| 2801 | } | 
|---|
| 2802 | my ($count) = $dbh->selectrow_array($sql, undef, @filterargs); | 
|---|
| 2803 | return $count; | 
|---|
| 2804 | } # end getZoneCount() | 
|---|
| 2805 |  | 
|---|
| 2806 |  | 
|---|
| 2807 | ## DNSDB::getZoneList() | 
|---|
| 2808 | # Get a list of zones in the specified group(s) | 
|---|
| 2809 | # Takes the same arguments as getZoneCount() above | 
|---|
| 2810 | # Returns a reference to an array of hashrefs suitable for feeding to HTML::Template | 
|---|
| 2811 | sub getZoneList { | 
|---|
| 2812 | my $self = shift; | 
|---|
| 2813 | my $dbh = $self->{dbh}; | 
|---|
| 2814 |  | 
|---|
| 2815 | my %args = @_; | 
|---|
| 2816 |  | 
|---|
| 2817 | my @zonelist; | 
|---|
| 2818 |  | 
|---|
| 2819 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC'); | 
|---|
| 2820 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/; | 
|---|
| 2821 |  | 
|---|
| 2822 | # Fail on bad curgroup argument.  There's no sane fallback on this one. | 
|---|
| 2823 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) { | 
|---|
| 2824 | $errstr = "Bad or missing curgroup argument"; | 
|---|
| 2825 | return; | 
|---|
| 2826 | } | 
|---|
| 2827 | # Fail on bad childlist argument.  This could be sanely ignored if bad, maybe. | 
|---|
| 2828 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) { | 
|---|
| 2829 | $errstr = "Bad childlist argument"; | 
|---|
| 2830 | return; | 
|---|
| 2831 | } | 
|---|
| 2832 |  | 
|---|
| 2833 | my @filterargs; | 
|---|
| 2834 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/; | 
|---|
| 2835 | push @filterargs, "^$args{startwith}" if $args{startwith}; | 
|---|
| 2836 | $args{filter} =~ s/\./\[\.\]/g if $args{filter};      # only match literal dots, usually in reverse zones | 
|---|
| 2837 | push @filterargs, $args{filter} if $args{filter}; | 
|---|
| 2838 |  | 
|---|
| 2839 | my $sql; | 
|---|
| 2840 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read | 
|---|
| 2841 | if ($args{revrec} eq 'n') { | 
|---|
| 2842 | $args{sortby} = 'domain' if !$args{sortby} || !grep /^$args{sortby}$/, ('domain','group','status'); | 
|---|
| 2843 | $sql = "SELECT domain_id AS zoneid,domain AS zone,status,groups.group_name AS group FROM domains". | 
|---|
| 2844 | " INNER JOIN groups ON domains.group_id=groups.group_id". | 
|---|
| 2845 | " WHERE domains.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")". | 
|---|
| 2846 | ($args{startwith} ? " AND domain ~* ?" : ''). | 
|---|
| 2847 | ($args{filter} ? " AND domain ~* ?" : ''); | 
|---|
| 2848 | } else { | 
|---|
| 2849 | ##fixme:  arguably startwith here is irrelevant.  depends on the UI though. | 
|---|
| 2850 | $args{sortby} = 'revnet' if !$args{sortby} || !grep /^$args{sortby}$/, ('revnet','group','status'); | 
|---|
| 2851 | $sql = "SELECT rdns_id AS zoneid,revnet AS zone,status,groups.group_name AS group FROM revzones". | 
|---|
| 2852 | " INNER JOIN groups ON revzones.group_id=groups.group_id". | 
|---|
| 2853 | " WHERE revzones.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")". | 
|---|
| 2854 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : ''); | 
|---|
| 2855 | #    if ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all') { | 
|---|
| 2856 | # Just In Case the UI is using formal .arpa notation, and someone enters something reversed, | 
|---|
| 2857 | # we want to match both the formal and natural zone name | 
|---|
| 2858 | $sql .= ($args{filter} ? " AND (CAST(revnet AS VARCHAR) ~* ? OR CAST(revnet AS VARCHAR) ~* ?)" : ''); | 
|---|
| 2859 | push @filterargs, join('[.]',reverse(split(/\[\.\]/,$args{filter}))) if $args{filter}; | 
|---|
| 2860 | #    } else { | 
|---|
| 2861 | #      $sql .= ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : ''); | 
|---|
| 2862 | #    } | 
|---|
| 2863 | } | 
|---|
| 2864 | # A common tail. | 
|---|
| 2865 | $sql .= " ORDER BY ".($args{sortby} eq 'group' ? 'groups.group_name' : $args{sortby})." $args{sortorder} ". | 
|---|
| 2866 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage}". | 
|---|
| 2867 | " OFFSET ".$args{offset}*$self->{perpage}); | 
|---|
| 2868 |  | 
|---|
| 2869 | my @working; | 
|---|
| 2870 | my $zsth = $dbh->prepare($sql); | 
|---|
| 2871 | $zsth->execute(@filterargs); | 
|---|
| 2872 | while (my $zone = $zsth->fetchrow_hashref) { | 
|---|
| 2873 | if ($args{revrec} eq 'y' && ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all')) { | 
|---|
| 2874 | my $tmp = new NetAddr::IP $zone->{zone}; | 
|---|
| 2875 | $zone->{zone} = DNSDB::_ZONE($tmp, 'ZONE', 'r', '.').($tmp->{isv6} ? '.ip6.arpa' : '.in-addr.arpa'); | 
|---|
| 2876 | } | 
|---|
| 2877 | push @working, $zone; | 
|---|
| 2878 | } | 
|---|
| 2879 | return \@working; | 
|---|
| 2880 | } # end getZoneList() | 
|---|
| 2881 |  | 
|---|
| 2882 |  | 
|---|
| 2883 | ## DNSDB::getZoneLocation() | 
|---|
| 2884 | # Retrieve the default location for a zone. | 
|---|
| 2885 | # Takes a database handle, forward/reverse flag, and zone ID | 
|---|
| 2886 | sub getZoneLocation { | 
|---|
| 2887 | my $self = shift; | 
|---|
| 2888 | my $dbh = $self->{dbh}; | 
|---|
| 2889 | my $revrec = shift; | 
|---|
| 2890 | my $zoneid = shift; | 
|---|
| 2891 |  | 
|---|
| 2892 | my ($loc) = $dbh->selectrow_array("SELECT default_location FROM ". | 
|---|
| 2893 | ($revrec eq 'n' ? 'domains WHERE domain_id = ?' : 'revzones WHERE rdns_id = ?'), | 
|---|
| 2894 | undef, ($zoneid)); | 
|---|
| 2895 | return $loc; | 
|---|
| 2896 | } # end getZoneLocation() | 
|---|
| 2897 |  | 
|---|
| 2898 |  | 
|---|
| 2899 | ## DNSDB::addGroup() | 
|---|
| 2900 | # Add a group | 
|---|
| 2901 | # Takes a database handle, group name, parent group, hashref for permissions, | 
|---|
| 2902 | # and optional template-vs-cloneme flag for the default records | 
|---|
| 2903 | # Returns a status code and message | 
|---|
| 2904 | sub addGroup { | 
|---|
| 2905 | $errstr = ''; | 
|---|
| 2906 | my $self = shift; | 
|---|
| 2907 | my $dbh = $self->{dbh}; | 
|---|
| 2908 | my $groupname = shift; | 
|---|
| 2909 | my $pargroup = shift; | 
|---|
| 2910 | my $permissions = shift; | 
|---|
| 2911 |  | 
|---|
| 2912 | # 0 indicates "custom", hardcoded. | 
|---|
| 2913 | # Any other value clones that group's default records, if it exists. | 
|---|
| 2914 | my $inherit = shift || 0; | 
|---|
| 2915 | ##fixme:  need a flag to indicate clone records or <?> ? | 
|---|
| 2916 |  | 
|---|
| 2917 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 2918 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 2919 | local $dbh->{AutoCommit} = 0; | 
|---|
| 2920 | local $dbh->{RaiseError} = 1; | 
|---|
| 2921 |  | 
|---|
| 2922 | my ($group_id) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($groupname)); | 
|---|
| 2923 |  | 
|---|
| 2924 | return ('FAIL', "Group already exists") if $group_id; | 
|---|
| 2925 |  | 
|---|
| 2926 | # Wrap all the SQL in a transaction | 
|---|
| 2927 | eval { | 
|---|
| 2928 | $dbh->do("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)", undef, ($pargroup, $groupname) ); | 
|---|
| 2929 |  | 
|---|
| 2930 | my ($groupid) = $dbh->selectrow_array("SELECT currval('groups_group_id_seq')"); | 
|---|
| 2931 |  | 
|---|
| 2932 | # We work through the whole set of permissions instead of specifying them so | 
|---|
| 2933 | # that when we add a new permission, we don't have to change the code anywhere | 
|---|
| 2934 | # that doesn't explicitly deal with that specific permission. | 
|---|
| 2935 | my @permvals; | 
|---|
| 2936 | foreach (@permtypes) { | 
|---|
| 2937 | if (!defined ($permissions->{$_})) { | 
|---|
| 2938 | push @permvals, 0; | 
|---|
| 2939 | } else { | 
|---|
| 2940 | push @permvals, $permissions->{$_}; | 
|---|
| 2941 | } | 
|---|
| 2942 | } | 
|---|
| 2943 | $dbh->do("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")", | 
|---|
| 2944 | undef, ($groupid, @permvals) ); | 
|---|
| 2945 | my ($permid) = $dbh->selectrow_array("SELECT currval('permissions_permission_id_seq')"); | 
|---|
| 2946 | $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid"); | 
|---|
| 2947 |  | 
|---|
| 2948 | # Default records | 
|---|
| 2949 | my $sthf = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ". | 
|---|
| 2950 | "VALUES ($groupid,?,?,?,?,?,?,?)"); | 
|---|
| 2951 | my $sthr = $dbh->prepare("INSERT INTO default_rev_records (group_id,host,type,val,ttl) ". | 
|---|
| 2952 | "VALUES ($groupid,?,?,?,?)"); | 
|---|
| 2953 | if ($inherit) { | 
|---|
| 2954 | # Duplicate records from parent.  Actually relying on inherited records feels | 
|---|
| 2955 | # very fragile, and it would be problematic to roll over at a later time. | 
|---|
| 2956 | my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?"); | 
|---|
| 2957 | $sth2->execute($pargroup); | 
|---|
| 2958 | while (my @clonedata = $sth2->fetchrow_array) { | 
|---|
| 2959 | $sthf->execute(@clonedata); | 
|---|
| 2960 | } | 
|---|
| 2961 | # And now the reverse records | 
|---|
| 2962 | $sth2 = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?"); | 
|---|
| 2963 | $sth2->execute($pargroup); | 
|---|
| 2964 | while (my @clonedata = $sth2->fetchrow_array) { | 
|---|
| 2965 | $sthr->execute(@clonedata); | 
|---|
| 2966 | } | 
|---|
| 2967 | } else { | 
|---|
| 2968 | ##fixme: Hardcoding is Bad, mmmmkaaaay? | 
|---|
| 2969 | # reasonable basic defaults for SOA, MX, NS, and minimal hosting | 
|---|
| 2970 | # could load from a config file, but somewhere along the line we need hardcoded bits. | 
|---|
| 2971 | $sthf->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400); | 
|---|
| 2972 | $sthf->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200); | 
|---|
| 2973 | $sthf->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200); | 
|---|
| 2974 | $sthf->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200); | 
|---|
| 2975 | $sthf->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200); | 
|---|
| 2976 | $sthf->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200); | 
|---|
| 2977 | # reasonable basic defaults for generic reverse zone.  Same as initial SQL tabledef. | 
|---|
| 2978 | $sthr->execute('hostmaster.ADMINDOMAIN:ns1.ADMINDOMAIN', 6, '10800:3600:604800:10800', 86400); | 
|---|
| 2979 | $sthr->execute('unused-%r.ADMINDOMAIN', 65283, 'ZONE', 3600); | 
|---|
| 2980 | } | 
|---|
| 2981 |  | 
|---|
| 2982 | $self->_log(group_id => $pargroup, entry => "Added group $groupname"); | 
|---|
| 2983 |  | 
|---|
| 2984 | # once we get here, we should have suceeded. | 
|---|
| 2985 | $dbh->commit; | 
|---|
| 2986 | }; # end eval | 
|---|
| 2987 |  | 
|---|
| 2988 | if ($@) { | 
|---|
| 2989 | my $msg = $@; | 
|---|
| 2990 | eval { $dbh->rollback; }; | 
|---|
| 2991 | if ($self->{log_failures}) { | 
|---|
| 2992 | $self->_log(group_id => $pargroup, entry => "Failed to add group $groupname: $msg"); | 
|---|
| 2993 | $dbh->commit; | 
|---|
| 2994 | } | 
|---|
| 2995 | return ('FAIL',$msg); | 
|---|
| 2996 | } | 
|---|
| 2997 |  | 
|---|
| 2998 | return ('OK','OK'); | 
|---|
| 2999 | } # end addGroup() | 
|---|
| 3000 |  | 
|---|
| 3001 |  | 
|---|
| 3002 | ## DNSDB::delGroup() | 
|---|
| 3003 | # Delete a group. | 
|---|
| 3004 | # Takes a group ID | 
|---|
| 3005 | # Returns a status code and message | 
|---|
| 3006 | sub delGroup { | 
|---|
| 3007 | my $self = shift; | 
|---|
| 3008 | my $dbh = $self->{dbh}; | 
|---|
| 3009 | my $groupid = shift; | 
|---|
| 3010 |  | 
|---|
| 3011 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 3012 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 3013 | local $dbh->{AutoCommit} = 0; | 
|---|
| 3014 | local $dbh->{RaiseError} = 1; | 
|---|
| 3015 |  | 
|---|
| 3016 | ##fixme:  locate "knowable" error conditions and deal with them before the eval | 
|---|
| 3017 | # ... or inside, whatever. | 
|---|
| 3018 | # -> domains still exist in group | 
|---|
| 3019 | # -> ... | 
|---|
| 3020 | my $failmsg = ''; | 
|---|
| 3021 | my $resultmsg = ''; | 
|---|
| 3022 |  | 
|---|
| 3023 | # collect some pieces for logging and error messages | 
|---|
| 3024 | my $groupname = $self->groupName($groupid); | 
|---|
| 3025 | my $parid = $self->parentID(id => $groupid, type => 'group'); | 
|---|
| 3026 |  | 
|---|
| 3027 | # Wrap all the SQL in a transaction | 
|---|
| 3028 | eval { | 
|---|
| 3029 | # Check for Things in the group | 
|---|
| 3030 | $failmsg = "Can't remove group $groupname"; | 
|---|
| 3031 | my ($grpcnt) = $dbh->selectrow_array("SELECT count(*) FROM groups WHERE parent_group_id=?", undef, ($groupid)); | 
|---|
| 3032 | die "$grpcnt groups still in group\n" if $grpcnt; | 
|---|
| 3033 | my ($domcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($groupid)); | 
|---|
| 3034 | die "$domcnt domains still in group\n" if $domcnt; | 
|---|
| 3035 | my ($revcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($groupid)); | 
|---|
| 3036 | die "$revcnt reverse zones still in group\n" if $revcnt; | 
|---|
| 3037 | my ($usercnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($groupid)); | 
|---|
| 3038 | die "$usercnt users still in group\n" if $usercnt; | 
|---|
| 3039 |  | 
|---|
| 3040 | $failmsg = "Failed to delete default records for $groupname"; | 
|---|
| 3041 | $dbh->do("DELETE from default_records WHERE group_id=?", undef, ($groupid)); | 
|---|
| 3042 | $failmsg = "Failed to delete default reverse records for $groupname"; | 
|---|
| 3043 | $dbh->do("DELETE from default_rev_records WHERE group_id=?", undef, ($groupid)); | 
|---|
| 3044 | $failmsg = "Failed to remove group $groupname"; | 
|---|
| 3045 | $dbh->do("DELETE from groups WHERE group_id=?", undef, ($groupid)); | 
|---|
| 3046 |  | 
|---|
| 3047 | $self->_log(group_id => $parid, entry => "Deleted group $groupname"); | 
|---|
| 3048 | $resultmsg = "Deleted group $groupname"; | 
|---|
| 3049 |  | 
|---|
| 3050 | # once we get here, we should have suceeded. | 
|---|
| 3051 | $dbh->commit; | 
|---|
| 3052 | }; # end eval | 
|---|
| 3053 |  | 
|---|
| 3054 | if ($@) { | 
|---|
| 3055 | my $msg = $@; | 
|---|
| 3056 | eval { $dbh->rollback; }; | 
|---|
| 3057 | if ($self->{log_failures}) { | 
|---|
| 3058 | $self->_log(group_id => $parid, entry => "$failmsg: $msg"); | 
|---|
| 3059 | $dbh->commit;     # since we enabled transactions earlier | 
|---|
| 3060 | } | 
|---|
| 3061 | return ('FAIL',"$failmsg: $msg"); | 
|---|
| 3062 | } | 
|---|
| 3063 |  | 
|---|
| 3064 | return ('OK',$resultmsg); | 
|---|
| 3065 | } # end delGroup() | 
|---|
| 3066 |  | 
|---|
| 3067 |  | 
|---|
| 3068 | ## DNSDB::getChildren() | 
|---|
| 3069 | # Get a list of all groups whose parent^n is group <n> | 
|---|
| 3070 | # Takes a database handle, group ID, reference to an array to put the group IDs in, | 
|---|
| 3071 | # and an optional flag to return only immediate children or all children-of-children | 
|---|
| 3072 | # default to returning all children | 
|---|
| 3073 | # Calls itself | 
|---|
| 3074 | sub getChildren { | 
|---|
| 3075 | $errstr = ''; | 
|---|
| 3076 | my $self = shift; | 
|---|
| 3077 | my $dbh = $self->{dbh}; | 
|---|
| 3078 | my $rootgroup = shift; | 
|---|
| 3079 | my $groupdest = shift; | 
|---|
| 3080 | my $immed = shift || 'all'; | 
|---|
| 3081 |  | 
|---|
| 3082 | # special break for default group;  otherwise we get stuck. | 
|---|
| 3083 | if ($rootgroup == 1) { | 
|---|
| 3084 | # by definition, group 1 is the Root Of All Groups | 
|---|
| 3085 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)". | 
|---|
| 3086 | ($immed ne 'all' ? " AND parent_group_id=1" : '')." ORDER BY group_name"); | 
|---|
| 3087 | $sth->execute; | 
|---|
| 3088 | while (my @this = $sth->fetchrow_array) { | 
|---|
| 3089 | push @$groupdest, @this; | 
|---|
| 3090 | } | 
|---|
| 3091 | } else { | 
|---|
| 3092 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=? ORDER BY group_name"); | 
|---|
| 3093 | $sth->execute($rootgroup); | 
|---|
| 3094 | return if $sth->rows == 0; | 
|---|
| 3095 | my @grouplist; | 
|---|
| 3096 | while (my ($group) = $sth->fetchrow_array) { | 
|---|
| 3097 | push @$groupdest, $group; | 
|---|
| 3098 | $self->getChildren($group, $groupdest) if $immed eq 'all'; | 
|---|
| 3099 | } | 
|---|
| 3100 | } | 
|---|
| 3101 | } # end getChildren() | 
|---|
| 3102 |  | 
|---|
| 3103 |  | 
|---|
| 3104 | ## DNSDB::groupName() | 
|---|
| 3105 | # Return the group name based on a group ID | 
|---|
| 3106 | # Takes a database handle and the group ID | 
|---|
| 3107 | # Returns the group name or undef on failure | 
|---|
| 3108 | sub groupName { | 
|---|
| 3109 | $errstr = ''; | 
|---|
| 3110 | my $self = shift; | 
|---|
| 3111 | my $dbh = $self->{dbh}; | 
|---|
| 3112 | my $groupid = shift; | 
|---|
| 3113 | my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?"); | 
|---|
| 3114 | $sth->execute($groupid); | 
|---|
| 3115 | my ($groupname) = $sth->fetchrow_array(); | 
|---|
| 3116 | $errstr = $DBI::errstr if !$groupname; | 
|---|
| 3117 | return $groupname if $groupname; | 
|---|
| 3118 | } # end groupName | 
|---|
| 3119 |  | 
|---|
| 3120 |  | 
|---|
| 3121 | ## DNSDB::getGroupCount() | 
|---|
| 3122 | # Get count of subgroups in group or groups | 
|---|
| 3123 | # Takes a database handle and hash containing: | 
|---|
| 3124 | #  - the "current" group | 
|---|
| 3125 | #  - an array of "acceptable" groups | 
|---|
| 3126 | #  - Optionally accept a "starts with" and/or "contains" filter argument | 
|---|
| 3127 | # Returns an integer count of the resulting group list. | 
|---|
| 3128 | sub getGroupCount { | 
|---|
| 3129 | my $self = shift; | 
|---|
| 3130 | my $dbh = $self->{dbh}; | 
|---|
| 3131 |  | 
|---|
| 3132 | my %args = @_; | 
|---|
| 3133 |  | 
|---|
| 3134 | # Fail on bad curgroup argument.  There's no sane fallback on this one. | 
|---|
| 3135 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) { | 
|---|
| 3136 | $errstr = "Bad or missing curgroup argument"; | 
|---|
| 3137 | return; | 
|---|
| 3138 | } | 
|---|
| 3139 | # Fail on bad childlist argument.  This could be sanely ignored if bad, maybe. | 
|---|
| 3140 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) { | 
|---|
| 3141 | $errstr = "Bad childlist argument"; | 
|---|
| 3142 | return; | 
|---|
| 3143 | } | 
|---|
| 3144 |  | 
|---|
| 3145 | my @filterargs; | 
|---|
| 3146 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/; | 
|---|
| 3147 | push @filterargs, "^$args{startwith}" if $args{startwith}; | 
|---|
| 3148 | push @filterargs, $args{filter} if $args{filter}; | 
|---|
| 3149 |  | 
|---|
| 3150 | my $sql = "SELECT count(*) FROM groups ". | 
|---|
| 3151 | "WHERE parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")". | 
|---|
| 3152 | ($args{startwith} ? " AND group_name ~* ?" : ''). | 
|---|
| 3153 | ($args{filter} ? " AND group_name ~* ?" : ''); | 
|---|
| 3154 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) ); | 
|---|
| 3155 | $errstr = $dbh->errstr if !$count; | 
|---|
| 3156 | return $count; | 
|---|
| 3157 | } # end getGroupCount | 
|---|
| 3158 |  | 
|---|
| 3159 |  | 
|---|
| 3160 | ## DNSDB::getGroupList() | 
|---|
| 3161 | # Get a list of sub^n-groups in the specified group(s) | 
|---|
| 3162 | # Takes the same arguments as getGroupCount() above | 
|---|
| 3163 | # Returns an arrayref containing hashrefs suitable for feeding straight to HTML::Template | 
|---|
| 3164 | sub getGroupList { | 
|---|
| 3165 | my $self = shift; | 
|---|
| 3166 | my $dbh = $self->{dbh}; | 
|---|
| 3167 |  | 
|---|
| 3168 | my %args = @_; | 
|---|
| 3169 |  | 
|---|
| 3170 | # Fail on bad curgroup argument.  There's no sane fallback on this one. | 
|---|
| 3171 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) { | 
|---|
| 3172 | $errstr = "Bad or missing curgroup argument"; | 
|---|
| 3173 | return; | 
|---|
| 3174 | } | 
|---|
| 3175 | # Fail on bad childlist argument.  This could be sanely ignored if bad, maybe. | 
|---|
| 3176 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) { | 
|---|
| 3177 | $errstr = "Bad childlist argument"; | 
|---|
| 3178 | return; | 
|---|
| 3179 | } | 
|---|
| 3180 |  | 
|---|
| 3181 | my @filterargs; | 
|---|
| 3182 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/; | 
|---|
| 3183 | push @filterargs, "^$args{startwith}" if $args{startwith}; | 
|---|
| 3184 | push @filterargs, $args{filter} if $args{filter}; | 
|---|
| 3185 |  | 
|---|
| 3186 | # protection against bad or missing arguments | 
|---|
| 3187 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC'); | 
|---|
| 3188 | $args{sortby} = 'group' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/; | 
|---|
| 3189 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/; | 
|---|
| 3190 |  | 
|---|
| 3191 | # munge sortby for columns in database | 
|---|
| 3192 | $args{sortby} = 'g.group_name' if $args{sortby} eq 'group'; | 
|---|
| 3193 | $args{sortby} = 'g2.group_name' if $args{sortby} eq 'parent'; | 
|---|
| 3194 |  | 
|---|
| 3195 | my $sql = q(SELECT g.group_id AS groupid, g.group_name AS groupname, g2.group_name AS pgroup | 
|---|
| 3196 | FROM groups g | 
|---|
| 3197 | INNER JOIN groups g2 ON g2.group_id=g.parent_group_id | 
|---|
| 3198 | ). | 
|---|
| 3199 | " WHERE g.parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")". | 
|---|
| 3200 | ($args{startwith} ? " AND g.group_name ~* ?" : ''). | 
|---|
| 3201 | ($args{filter} ? " AND g.group_name ~* ?" : ''). | 
|---|
| 3202 | " GROUP BY g.group_id, g.group_name, g2.group_name ". | 
|---|
| 3203 | " ORDER BY $args{sortby} $args{sortorder} ". | 
|---|
| 3204 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage}); | 
|---|
| 3205 | my $glist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) ); | 
|---|
| 3206 | $errstr = $dbh->errstr if !$glist; | 
|---|
| 3207 |  | 
|---|
| 3208 | # LEFT JOINs make the result set balloon beyond sanity just to include counts; | 
|---|
| 3209 | # this means there's lots of crunching needed to trim the result set back down. | 
|---|
| 3210 | # So instead we track the order of the groups, and push the counts into the | 
|---|
| 3211 | # arrayref result separately. | 
|---|
| 3212 | ##fixme:  put this whole sub in a transaction?  might be | 
|---|
| 3213 | # needed for accurate results on very busy systems. | 
|---|
| 3214 | ##fixme:  large group lists need prepared statements? | 
|---|
| 3215 | #my $ucsth = $dbh->prepare("SELECT count(*) FROM users WHERE group_id=?"); | 
|---|
| 3216 | #my $dcsth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?"); | 
|---|
| 3217 | #my $rcsth = $dbh->prepare("SELECT count(*) FROM revzones WHERE group_id=?"); | 
|---|
| 3218 | foreach (@{$glist}) { | 
|---|
| 3219 | my ($ucnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($$_{groupid})); | 
|---|
| 3220 | $$_{nusers} = $ucnt; | 
|---|
| 3221 | my ($dcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($$_{groupid})); | 
|---|
| 3222 | $$_{ndomains} = $dcnt; | 
|---|
| 3223 | my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($$_{groupid})); | 
|---|
| 3224 | $$_{nrevzones} = $rcnt; | 
|---|
| 3225 | } | 
|---|
| 3226 |  | 
|---|
| 3227 | return $glist; | 
|---|
| 3228 | } # end getGroupList | 
|---|
| 3229 |  | 
|---|
| 3230 |  | 
|---|
| 3231 | ## DNSDB::groupID() | 
|---|
| 3232 | # Return the group ID based on the group name | 
|---|
| 3233 | # Takes a database handle and the group name | 
|---|
| 3234 | # Returns the group ID or undef on failure | 
|---|
| 3235 | sub groupID { | 
|---|
| 3236 | $errstr = ''; | 
|---|
| 3237 | my $self = shift; | 
|---|
| 3238 | my $dbh = $self->{dbh}; | 
|---|
| 3239 | my $group = shift; | 
|---|
| 3240 | my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($group) ); | 
|---|
| 3241 | $errstr = $DBI::errstr if !$grpid; | 
|---|
| 3242 | return $grpid if $grpid; | 
|---|
| 3243 | } # end groupID() | 
|---|
| 3244 |  | 
|---|
| 3245 |  | 
|---|
| 3246 | ## DNSDB::addUser() | 
|---|
| 3247 | # Add a user. | 
|---|
| 3248 | # Takes a DB handle, username, group ID, password, state (active/inactive). | 
|---|
| 3249 | # Optionally accepts: | 
|---|
| 3250 | #   user type (user/admin)      - defaults to user | 
|---|
| 3251 | #   permissions string          - defaults to inherit from group | 
|---|
| 3252 | #      three valid forms: | 
|---|
| 3253 | #       i                    - Inherit permissions | 
|---|
| 3254 | #       c:<user_id>          - Clone permissions from <user_id> | 
|---|
| 3255 | #       C:<permission list>  - Set these specific permissions | 
|---|
| 3256 | #   first name                  - defaults to username | 
|---|
| 3257 | #   last name                   - defaults to blank | 
|---|
| 3258 | #   phone                       - defaults to blank (could put other data within column def) | 
|---|
| 3259 | # Returns (OK,<uid>) on success, (FAIL,<message>) on failure | 
|---|
| 3260 | sub addUser { | 
|---|
| 3261 | $errstr = ''; | 
|---|
| 3262 | my $self = shift; | 
|---|
| 3263 | my $dbh = $self->{dbh}; | 
|---|
| 3264 | my $username = shift; | 
|---|
| 3265 | my $group = shift; | 
|---|
| 3266 | my $pass = shift; | 
|---|
| 3267 | my $state = shift; | 
|---|
| 3268 |  | 
|---|
| 3269 | return ('FAIL', "Missing one or more required entries") if !defined($state); | 
|---|
| 3270 | return ('FAIL', "Username must not be blank") if !$username; | 
|---|
| 3271 |  | 
|---|
| 3272 | # Munge in some alternate state values | 
|---|
| 3273 | $state = 1 if $state =~ /^active$/; | 
|---|
| 3274 | $state = 1 if $state =~ /^on$/; | 
|---|
| 3275 | $state = 0 if $state =~ /^inactive$/; | 
|---|
| 3276 | $state = 0 if $state =~ /^off$/; | 
|---|
| 3277 |  | 
|---|
| 3278 | my $type = shift || 'u';      # create limited users by default - fwiw, not sure yet how this will interact with ACLs | 
|---|
| 3279 |  | 
|---|
| 3280 | my $permstring = shift || 'i';        # default is to inhert permissions from group | 
|---|
| 3281 |  | 
|---|
| 3282 | my $fname = shift || $username; | 
|---|
| 3283 | my $lname = shift || ''; | 
|---|
| 3284 | my $phone = shift || '';      # not going format-check | 
|---|
| 3285 |  | 
|---|
| 3286 | my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?"); | 
|---|
| 3287 | my $user_id; | 
|---|
| 3288 |  | 
|---|
| 3289 | # quick check to start to see if we've already got one | 
|---|
| 3290 | $sth->execute($username); | 
|---|
| 3291 | ($user_id) = $sth->fetchrow_array; | 
|---|
| 3292 |  | 
|---|
| 3293 | return ('FAIL', "User already exists") if $user_id; | 
|---|
| 3294 |  | 
|---|
| 3295 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 3296 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 3297 | local $dbh->{AutoCommit} = 0; | 
|---|
| 3298 | local $dbh->{RaiseError} = 1; | 
|---|
| 3299 |  | 
|---|
| 3300 | # Wrap all the SQL in a transaction | 
|---|
| 3301 | eval { | 
|---|
| 3302 | # insert the user...  note we set inherited perms by default since | 
|---|
| 3303 | # it's simple and cleans up some other bits of state | 
|---|
| 3304 | ##fixme:  need better handling of case of inherited or missing (!!) permissions entries | 
|---|
| 3305 | my $sth = $dbh->prepare("INSERT INTO users ". | 
|---|
| 3306 | "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ". | 
|---|
| 3307 | "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')"); | 
|---|
| 3308 | $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group); | 
|---|
| 3309 |  | 
|---|
| 3310 | # get the ID... | 
|---|
| 3311 | ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')"); | 
|---|
| 3312 |  | 
|---|
| 3313 | # Permissions!  Gotta set'em all! | 
|---|
| 3314 | die "Invalid permission string $permstring\n" | 
|---|
| 3315 | if $permstring !~ /^(?: | 
|---|
| 3316 | i       # inherit | 
|---|
| 3317 | |c:\d+  # clone | 
|---|
| 3318 | # custom.  no, the leading , is not a typo | 
|---|
| 3319 | |C:(?:,(?:group|user|domain|record|location|self)_(?:edit|create|delete|locchg|view))* | 
|---|
| 3320 | )$/x; | 
|---|
| 3321 | # bleh.  I'd call another function to do my dirty work, but we're in the middle of a transaction already. | 
|---|
| 3322 | if ($permstring ne 'i') { | 
|---|
| 3323 | # for cloned or custom permissions, we have to create a new permissions entry. | 
|---|
| 3324 | my $clonesrc = $group; | 
|---|
| 3325 | if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; } | 
|---|
| 3326 | $dbh->do("INSERT INTO permissions ($permlist,user_id) ". | 
|---|
| 3327 | "SELECT $permlist,? FROM permissions WHERE permission_id=". | 
|---|
| 3328 | "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)", | 
|---|
| 3329 | undef, ($user_id,$clonesrc) ); | 
|---|
| 3330 | $dbh->do("UPDATE users SET permission_id=". | 
|---|
| 3331 | "(SELECT permission_id FROM permissions WHERE user_id=?) ". | 
|---|
| 3332 | "WHERE user_id=?", undef, ($user_id, $user_id) ); | 
|---|
| 3333 | } | 
|---|
| 3334 | if ($permstring =~ /^C:/) { | 
|---|
| 3335 | # finally for custom permissions, we set the passed-in permissions (and unset | 
|---|
| 3336 | # any that might have been brought in by the clone operation above) | 
|---|
| 3337 | my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?", | 
|---|
| 3338 | undef, ($user_id) ); | 
|---|
| 3339 | foreach (@permtypes) { | 
|---|
| 3340 | if ($permstring =~ /,$_/) { | 
|---|
| 3341 | $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) ); | 
|---|
| 3342 | } else { | 
|---|
| 3343 | $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) ); | 
|---|
| 3344 | } | 
|---|
| 3345 | } | 
|---|
| 3346 | } | 
|---|
| 3347 |  | 
|---|
| 3348 | $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) ); | 
|---|
| 3349 |  | 
|---|
| 3350 | ##fixme: add another table to hold name/email for log table? | 
|---|
| 3351 |  | 
|---|
| 3352 | $self->_log(group_id => $group, entry => "Added user $username ($fname $lname)"); | 
|---|
| 3353 | # once we get here, we should have suceeded. | 
|---|
| 3354 | $dbh->commit; | 
|---|
| 3355 | }; # end eval | 
|---|
| 3356 |  | 
|---|
| 3357 | if ($@) { | 
|---|
| 3358 | my $msg = $@; | 
|---|
| 3359 | eval { $dbh->rollback; }; | 
|---|
| 3360 | if ($self->{log_failures}) { | 
|---|
| 3361 | $self->_log(group_id => $group, entry => "Error adding user $username: $msg"); | 
|---|
| 3362 | $dbh->commit;     # since we enabled transactions earlier | 
|---|
| 3363 | } | 
|---|
| 3364 | return ('FAIL',"Error adding user $username: $msg"); | 
|---|
| 3365 | } | 
|---|
| 3366 |  | 
|---|
| 3367 | return ('OK',"User $username ($fname $lname) added"); | 
|---|
| 3368 | } # end addUser | 
|---|
| 3369 |  | 
|---|
| 3370 |  | 
|---|
| 3371 | ## DNSDB::getUserCount() | 
|---|
| 3372 | # Get count of users in group | 
|---|
| 3373 | # Takes a database handle and hash containing at least the current group, and optionally: | 
|---|
| 3374 | # - a reference list of secondary groups | 
|---|
| 3375 | # - a filter string | 
|---|
| 3376 | # - a "Starts with" string | 
|---|
| 3377 | sub getUserCount { | 
|---|
| 3378 | my $self = shift; | 
|---|
| 3379 | my $dbh = $self->{dbh}; | 
|---|
| 3380 |  | 
|---|
| 3381 | my %args = @_; | 
|---|
| 3382 |  | 
|---|
| 3383 | # Fail on bad curgroup argument.  There's no sane fallback on this one. | 
|---|
| 3384 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) { | 
|---|
| 3385 | $errstr = "Bad or missing curgroup argument"; | 
|---|
| 3386 | return; | 
|---|
| 3387 | } | 
|---|
| 3388 | # Fail on bad childlist argument.  This could be sanely ignored if bad, maybe. | 
|---|
| 3389 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) { | 
|---|
| 3390 | $errstr = "Bad childlist argument"; | 
|---|
| 3391 | return; | 
|---|
| 3392 | } | 
|---|
| 3393 |  | 
|---|
| 3394 | my @filterargs; | 
|---|
| 3395 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/; | 
|---|
| 3396 | push @filterargs, "^$args{startwith}" if $args{startwith}; | 
|---|
| 3397 | push @filterargs, $args{filter} if $args{filter}; | 
|---|
| 3398 |  | 
|---|
| 3399 | my $sql = "SELECT count(*) FROM users ". | 
|---|
| 3400 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")". | 
|---|
| 3401 | ($args{startwith} ? " AND username ~* ?" : ''). | 
|---|
| 3402 | ($args{filter} ? " AND username ~* ?" : ''); | 
|---|
| 3403 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) ); | 
|---|
| 3404 | $errstr = $dbh->errstr if !$count; | 
|---|
| 3405 | return $count; | 
|---|
| 3406 | } # end getUserCount() | 
|---|
| 3407 |  | 
|---|
| 3408 |  | 
|---|
| 3409 | ## DNSDB::getUserList() | 
|---|
| 3410 | # Get list of users | 
|---|
| 3411 | # Takes the same arguments as getUserCount() above, plus optional: | 
|---|
| 3412 | # - sort field | 
|---|
| 3413 | # - sort order | 
|---|
| 3414 | # - offset/return-all-everything flag (defaults to $perpage records) | 
|---|
| 3415 | sub getUserList { | 
|---|
| 3416 | my $self = shift; | 
|---|
| 3417 | my $dbh = $self->{dbh}; | 
|---|
| 3418 |  | 
|---|
| 3419 | my %args = @_; | 
|---|
| 3420 |  | 
|---|
| 3421 | # Fail on bad curgroup argument.  There's no sane fallback on this one. | 
|---|
| 3422 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) { | 
|---|
| 3423 | $errstr = "Bad or missing curgroup argument"; | 
|---|
| 3424 | return; | 
|---|
| 3425 | } | 
|---|
| 3426 | # Fail on bad childlist argument.  This could be sanely ignored if bad, maybe. | 
|---|
| 3427 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) { | 
|---|
| 3428 | $errstr = "Bad childlist argument"; | 
|---|
| 3429 | return; | 
|---|
| 3430 | } | 
|---|
| 3431 |  | 
|---|
| 3432 | my @filterargs; | 
|---|
| 3433 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/; | 
|---|
| 3434 | push @filterargs, "^$args{startwith}" if $args{startwith}; | 
|---|
| 3435 | push @filterargs, $args{filter} if $args{filter}; | 
|---|
| 3436 |  | 
|---|
| 3437 | # better to request sorts on "simple" names, but it means we need to map it to real columns | 
|---|
| 3438 | my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status', | 
|---|
| 3439 | fname => 'fname'); | 
|---|
| 3440 | $args{sortby} = $sortmap{$args{sortby}}; | 
|---|
| 3441 |  | 
|---|
| 3442 | # protection against bad or missing arguments | 
|---|
| 3443 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC'); | 
|---|
| 3444 | $args{sortby} = 'u.username' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/; | 
|---|
| 3445 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/; | 
|---|
| 3446 |  | 
|---|
| 3447 | my $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ". | 
|---|
| 3448 | "FROM users u ". | 
|---|
| 3449 | "INNER JOIN groups g ON u.group_id=g.group_id ". | 
|---|
| 3450 | "WHERE u.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")". | 
|---|
| 3451 | ($args{startwith} ? " AND u.username ~* ?" : ''). | 
|---|
| 3452 | ($args{filter} ? " AND u.username ~* ?" : ''). | 
|---|
| 3453 | " AND NOT u.type = 'R' ". | 
|---|
| 3454 | " ORDER BY $args{sortby} $args{sortorder} ". | 
|---|
| 3455 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage}); | 
|---|
| 3456 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) ); | 
|---|
| 3457 | $errstr = $dbh->errstr if !$ulist; | 
|---|
| 3458 | return $ulist; | 
|---|
| 3459 | } # end getUserList() | 
|---|
| 3460 |  | 
|---|
| 3461 |  | 
|---|
| 3462 | ## DNSDB::getUserDropdown() | 
|---|
| 3463 | # Get a list of usernames for use in a dropdown menu. | 
|---|
| 3464 | # Takes a database handle, current group, and optional "tag this as selected" flag. | 
|---|
| 3465 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template | 
|---|
| 3466 | sub getUserDropdown { | 
|---|
| 3467 | my $self = shift; | 
|---|
| 3468 | my $dbh = $self->{dbh}; | 
|---|
| 3469 | my $grp = shift; | 
|---|
| 3470 | my $sel = shift || 0; | 
|---|
| 3471 |  | 
|---|
| 3472 | my $sth = $dbh->prepare("SELECT username,user_id FROM users WHERE group_id=?"); | 
|---|
| 3473 | $sth->execute($grp); | 
|---|
| 3474 |  | 
|---|
| 3475 | my @userlist; | 
|---|
| 3476 | while (my ($username,$uid) = $sth->fetchrow_array) { | 
|---|
| 3477 | my %row = ( | 
|---|
| 3478 | username => $username, | 
|---|
| 3479 | uid => $uid, | 
|---|
| 3480 | selected => ($sel == $uid ? 1 : 0) | 
|---|
| 3481 | ); | 
|---|
| 3482 | push @userlist, \%row; | 
|---|
| 3483 | } | 
|---|
| 3484 | return \@userlist; | 
|---|
| 3485 | } # end getUserDropdown() | 
|---|
| 3486 |  | 
|---|
| 3487 |  | 
|---|
| 3488 | ## DNSDB:: updateUser() | 
|---|
| 3489 | # Update general data about user | 
|---|
| 3490 | sub updateUser { | 
|---|
| 3491 | my $self = shift; | 
|---|
| 3492 | my $dbh = $self->{dbh}; | 
|---|
| 3493 |  | 
|---|
| 3494 | ##fixme:  tweak calling convention so that we can update any given bit of data | 
|---|
| 3495 | my $uid = shift; | 
|---|
| 3496 | my $username = shift; | 
|---|
| 3497 | my $group = shift; | 
|---|
| 3498 | my $pass = shift; | 
|---|
| 3499 | my $state = shift; | 
|---|
| 3500 | my $type = shift || 'u'; | 
|---|
| 3501 | my $fname = shift || $username; | 
|---|
| 3502 | my $lname = shift || ''; | 
|---|
| 3503 | my $phone = shift || '';      # not going format-check | 
|---|
| 3504 |  | 
|---|
| 3505 | my $resultmsg = ''; | 
|---|
| 3506 |  | 
|---|
| 3507 | # Munge in some alternate state values | 
|---|
| 3508 | $state = 1 if $state =~ /^active$/; | 
|---|
| 3509 | $state = 1 if $state =~ /^on$/; | 
|---|
| 3510 | $state = 0 if $state =~ /^inactive$/; | 
|---|
| 3511 | $state = 0 if $state =~ /^off$/; | 
|---|
| 3512 |  | 
|---|
| 3513 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 3514 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 3515 | local $dbh->{AutoCommit} = 0; | 
|---|
| 3516 | local $dbh->{RaiseError} = 1; | 
|---|
| 3517 |  | 
|---|
| 3518 | my $sth; | 
|---|
| 3519 |  | 
|---|
| 3520 | # Password can be left blank;  if so we assume there's one on file. | 
|---|
| 3521 | # Actual blank passwords are bad, mm'kay? | 
|---|
| 3522 | if (!$pass) { | 
|---|
| 3523 | ($pass) = $dbh->selectrow_array("SELECT password FROM users WHERE user_id=?", undef, ($uid)); | 
|---|
| 3524 | } else { | 
|---|
| 3525 | $pass = unix_md5_crypt($pass); | 
|---|
| 3526 | } | 
|---|
| 3527 |  | 
|---|
| 3528 | eval { | 
|---|
| 3529 | $dbh->do("UPDATE users SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?". | 
|---|
| 3530 | " WHERE user_id=?", undef, ($username, $pass, $fname, $lname, $phone, $type, $state, $uid)); | 
|---|
| 3531 | $resultmsg = "Updated user info for $username ($fname $lname)"; | 
|---|
| 3532 | $self->_log(group_id => $group, entry => $resultmsg); | 
|---|
| 3533 | $dbh->commit; | 
|---|
| 3534 | }; | 
|---|
| 3535 | if ($@) { | 
|---|
| 3536 | my $msg = $@; | 
|---|
| 3537 | eval { $dbh->rollback; }; | 
|---|
| 3538 | if ($self->{log_failures}) { | 
|---|
| 3539 | $self->_log(group_id => $group, entry => "Error updating user $username: $msg"); | 
|---|
| 3540 | $dbh->commit;     # since we enabled transactions earlier | 
|---|
| 3541 | } | 
|---|
| 3542 | return ('FAIL',"Error updating user $username: $msg"); | 
|---|
| 3543 | } | 
|---|
| 3544 |  | 
|---|
| 3545 | return ('OK',$resultmsg); | 
|---|
| 3546 | } # end updateUser() | 
|---|
| 3547 |  | 
|---|
| 3548 |  | 
|---|
| 3549 | ## DNSDB::delUser() | 
|---|
| 3550 | # Delete a user. | 
|---|
| 3551 | # Takes a database handle and user ID | 
|---|
| 3552 | # Returns a success/failure code and matching message | 
|---|
| 3553 | sub delUser { | 
|---|
| 3554 | my $self = shift; | 
|---|
| 3555 | my $dbh = $self->{dbh}; | 
|---|
| 3556 | my $userid = shift; | 
|---|
| 3557 |  | 
|---|
| 3558 | return ('FAIL',"Bad userid") if !defined($userid); | 
|---|
| 3559 |  | 
|---|
| 3560 | my $userdata = $self->getUserData($userid); | 
|---|
| 3561 |  | 
|---|
| 3562 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 3563 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 3564 | local $dbh->{AutoCommit} = 0; | 
|---|
| 3565 | local $dbh->{RaiseError} = 1; | 
|---|
| 3566 |  | 
|---|
| 3567 | eval { | 
|---|
| 3568 | $dbh->do("DELETE FROM users WHERE user_id=?", undef, ($userid)); | 
|---|
| 3569 | $self->_log(group_id => $userdata->{group_id}, | 
|---|
| 3570 | entry => "Deleted user ID $userid/".$userdata->{username}. | 
|---|
| 3571 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")"); | 
|---|
| 3572 | $dbh->commit; | 
|---|
| 3573 | }; | 
|---|
| 3574 | if ($@) { | 
|---|
| 3575 | my $msg = $@; | 
|---|
| 3576 | eval { $dbh->rollback; }; | 
|---|
| 3577 | if ($self->{log_failures}) { | 
|---|
| 3578 | $self->_log(group_id => $userdata->{group_id}, entry => "Error deleting user ID ". | 
|---|
| 3579 | "$userid/".$userdata->{username}.": $msg"); | 
|---|
| 3580 | $dbh->commit; | 
|---|
| 3581 | } | 
|---|
| 3582 | return ('FAIL',"Error deleting user $userid/".$userdata->{username}.": $msg"); | 
|---|
| 3583 | } | 
|---|
| 3584 |  | 
|---|
| 3585 | return ('OK',"Deleted user ".$userdata->{username}." (".$userdata->{firstname}." ".$userdata->{lastname}.")"); | 
|---|
| 3586 | } # end delUser | 
|---|
| 3587 |  | 
|---|
| 3588 |  | 
|---|
| 3589 | ## DNSDB::userFullName() | 
|---|
| 3590 | # Return a pretty string! | 
|---|
| 3591 | # Takes a user_id and optional printf-ish string to indicate which pieces where: | 
|---|
| 3592 | # %u for the username | 
|---|
| 3593 | # %f for the first name | 
|---|
| 3594 | # %l for the last name | 
|---|
| 3595 | # All other text in the passed string will be left as-is. | 
|---|
| 3596 | ##fixme:  need a "smart" option too, so that missing/null/blank first/last names don't give funky output | 
|---|
| 3597 | sub userFullName { | 
|---|
| 3598 | $errstr = ''; | 
|---|
| 3599 | my $self = shift; | 
|---|
| 3600 | my $dbh = $self->{dbh}; | 
|---|
| 3601 | my $userid = shift; | 
|---|
| 3602 | my $fullformat = shift || '%f %l (%u)'; | 
|---|
| 3603 | my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?"); | 
|---|
| 3604 | $sth->execute($userid); | 
|---|
| 3605 | my ($uname,$fname,$lname) = $sth->fetchrow_array(); | 
|---|
| 3606 | $errstr = $DBI::errstr if !$uname; | 
|---|
| 3607 |  | 
|---|
| 3608 | $fullformat =~ s/\%u/$uname/g; | 
|---|
| 3609 | $fullformat =~ s/\%f/$fname/g; | 
|---|
| 3610 | $fullformat =~ s/\%l/$lname/g; | 
|---|
| 3611 |  | 
|---|
| 3612 | return $fullformat; | 
|---|
| 3613 | } # end userFullName | 
|---|
| 3614 |  | 
|---|
| 3615 |  | 
|---|
| 3616 | ## DNSDB::userStatus() | 
|---|
| 3617 | # Sets and/or returns a user's status | 
|---|
| 3618 | # Takes a database handle, user ID and optionally a status argument | 
|---|
| 3619 | # Returns undef on errors. | 
|---|
| 3620 | sub userStatus { | 
|---|
| 3621 | my $self = shift; | 
|---|
| 3622 | my $dbh = $self->{dbh}; | 
|---|
| 3623 | my $id = shift; | 
|---|
| 3624 | my $newstatus = shift || 'mu'; | 
|---|
| 3625 |  | 
|---|
| 3626 | return undef if $id !~ /^\d+$/; | 
|---|
| 3627 |  | 
|---|
| 3628 | my $userdata = $self->getUserData($id); | 
|---|
| 3629 |  | 
|---|
| 3630 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 3631 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 3632 | local $dbh->{AutoCommit} = 0; | 
|---|
| 3633 | local $dbh->{RaiseError} = 1; | 
|---|
| 3634 |  | 
|---|
| 3635 | if ($newstatus ne 'mu') { | 
|---|
| 3636 | # ooo, fun!  let's see what we were passed for status | 
|---|
| 3637 | eval { | 
|---|
| 3638 | $newstatus = 0 if $newstatus eq 'useroff'; | 
|---|
| 3639 | $newstatus = 1 if $newstatus eq 'useron'; | 
|---|
| 3640 | $dbh->do("UPDATE users SET status=? WHERE user_id=?", undef, ($newstatus, $id)); | 
|---|
| 3641 |  | 
|---|
| 3642 | $resultstr = ($newstatus ? 'Enabled' : 'Disabled')." user ".$userdata->{username}. | 
|---|
| 3643 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")"; | 
|---|
| 3644 |  | 
|---|
| 3645 | my %loghash; | 
|---|
| 3646 | $loghash{group_id} = $self->parentID(id => $id, type => 'user'); | 
|---|
| 3647 | $loghash{entry} = $resultstr; | 
|---|
| 3648 | $self->_log(%loghash); | 
|---|
| 3649 |  | 
|---|
| 3650 | $dbh->commit; | 
|---|
| 3651 | }; | 
|---|
| 3652 | if ($@) { | 
|---|
| 3653 | my $msg = $@; | 
|---|
| 3654 | eval { $dbh->rollback; }; | 
|---|
| 3655 | $resultstr = ''; | 
|---|
| 3656 | $errstr = $msg; | 
|---|
| 3657 | ##fixme: failure logging? | 
|---|
| 3658 | return; | 
|---|
| 3659 | } | 
|---|
| 3660 | } | 
|---|
| 3661 |  | 
|---|
| 3662 | my ($status) = $dbh->selectrow_array("SELECT status FROM users WHERE user_id=?", undef, ($id)); | 
|---|
| 3663 | return $status; | 
|---|
| 3664 | } # end userStatus() | 
|---|
| 3665 |  | 
|---|
| 3666 |  | 
|---|
| 3667 | ## DNSDB::getUserData() | 
|---|
| 3668 | # Get misc user data for display | 
|---|
| 3669 | sub getUserData { | 
|---|
| 3670 | my $self = shift; | 
|---|
| 3671 | my $dbh = $self->{dbh}; | 
|---|
| 3672 | my $uid = shift; | 
|---|
| 3673 |  | 
|---|
| 3674 | my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ". | 
|---|
| 3675 | "FROM users WHERE user_id=?"); | 
|---|
| 3676 | $sth->execute($uid); | 
|---|
| 3677 | return $sth->fetchrow_hashref(); | 
|---|
| 3678 | } # end getUserData() | 
|---|
| 3679 |  | 
|---|
| 3680 |  | 
|---|
| 3681 | ## DNSDB::addLoc() | 
|---|
| 3682 | # Add a new location. | 
|---|
| 3683 | # Takes a database handle, group ID, short and long description, and a comma-separated | 
|---|
| 3684 | # list of IP addresses. | 
|---|
| 3685 | # Returns ('OK',<location>) on success, ('FAIL',<failmsg>) on failure | 
|---|
| 3686 | sub addLoc { | 
|---|
| 3687 | my $self = shift; | 
|---|
| 3688 | my $dbh = $self->{dbh}; | 
|---|
| 3689 | my $grp = shift; | 
|---|
| 3690 | my $shdesc = shift; | 
|---|
| 3691 | my $comments = shift; | 
|---|
| 3692 | my $iplist = shift; | 
|---|
| 3693 |  | 
|---|
| 3694 | # $shdesc gets set to the generated location ID if possible, but these can be de-undefined here. | 
|---|
| 3695 | $comments = '' if !$comments; | 
|---|
| 3696 | $iplist = '' if !$iplist; | 
|---|
| 3697 |  | 
|---|
| 3698 | my $loc; | 
|---|
| 3699 |  | 
|---|
| 3700 | # Generate a location ID.  This is, by spec, a two-character widget.  We'll use [a-z][a-z] | 
|---|
| 3701 | # for now;  676 locations should satisfy all but the largest of the huge networks. | 
|---|
| 3702 | # Not sure whether these are case-sensitive, or what other rules might apply - in any case | 
|---|
| 3703 | # the absolute maximum is 16K (256*256) since it's parsed by tinydns as a two-character field. | 
|---|
| 3704 |  | 
|---|
| 3705 | # add just after "my $origloc = $loc;": | 
|---|
| 3706 | #    # These expand the possible space from 26^2 to 52^2 [* note in testing only 2052 were achieved], | 
|---|
| 3707 | #    # and wrap it around. | 
|---|
| 3708 | #    # Yes, they skip a couple of possibles.  No, I don't care. | 
|---|
| 3709 | #    $loc = 'aA' if $loc eq 'zz'; | 
|---|
| 3710 | #    $loc = 'Aa' if $loc eq 'zZ'; | 
|---|
| 3711 | #    $loc = 'ZA' if $loc eq 'Zz'; | 
|---|
| 3712 | #    $loc = 'aa' if $loc eq 'ZZ'; | 
|---|
| 3713 |  | 
|---|
| 3714 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 3715 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 3716 | local $dbh->{AutoCommit} = 0; | 
|---|
| 3717 | local $dbh->{RaiseError} = 1; | 
|---|
| 3718 |  | 
|---|
| 3719 | ##fixme:  There is probably a far better way to do this.  Sequential increments | 
|---|
| 3720 | # are marginally less stupid that pure random generation though, and the existence | 
|---|
| 3721 | # check makes sure we don't stomp on an imported one. | 
|---|
| 3722 |  | 
|---|
| 3723 | eval { | 
|---|
| 3724 | # Get the "last" location.  Note this is the only use for loc_id, because selecting on location Does Funky Things | 
|---|
| 3725 | ($loc) = $dbh->selectrow_array("SELECT location FROM locations ORDER BY loc_id DESC LIMIT 1"); | 
|---|
| 3726 | ($loc) = ($loc =~ /^(..)/) if $loc; | 
|---|
| 3727 | my $origloc = $loc; | 
|---|
| 3728 | $loc = 'aa' if !$loc; | 
|---|
| 3729 | # Make a change... | 
|---|
| 3730 | $loc++; | 
|---|
| 3731 | # ... and keep changing if it exists | 
|---|
| 3732 | while ($dbh->selectrow_array("SELECT count(*) FROM locations WHERE location LIKE ?", undef, ($loc.'%'))) { | 
|---|
| 3733 | $loc++; | 
|---|
| 3734 | ($loc) = ($loc =~ /^(..)/); | 
|---|
| 3735 | die "too many locations in use, can't add another one\n" if $loc eq $origloc; | 
|---|
| 3736 | ##fixme: really need to handle this case faster somehow | 
|---|
| 3737 | #if $loc eq $origloc die "<thwap> bad admin:  all locations used, your network is too fragmented"; | 
|---|
| 3738 | } | 
|---|
| 3739 | # And now we should have a unique location.  tinydns fundamentally limits the | 
|---|
| 3740 | # number of these but there's no doc on what characters are valid. | 
|---|
| 3741 | $shdesc = $loc if !$shdesc; | 
|---|
| 3742 | $dbh->do("INSERT INTO locations (location, group_id, iplist, description, comments) VALUES (?,?,?,?,?)", | 
|---|
| 3743 | undef, ($loc, $grp, $iplist, $shdesc, $comments) ); | 
|---|
| 3744 | $self->_log(entry => "Added location ($shdesc, '$iplist')"); | 
|---|
| 3745 | $dbh->commit; | 
|---|
| 3746 | }; | 
|---|
| 3747 | if ($@) { | 
|---|
| 3748 | my $msg = $@; | 
|---|
| 3749 | eval { $dbh->rollback; }; | 
|---|
| 3750 | if ($self->{log_failures}) { | 
|---|
| 3751 | $shdesc = $loc if !$shdesc; | 
|---|
| 3752 | $self->_log(entry => "Failed adding location ($shdesc, '$iplist'): $msg"); | 
|---|
| 3753 | $dbh->commit; | 
|---|
| 3754 | } | 
|---|
| 3755 | return ('FAIL',$msg); | 
|---|
| 3756 | } | 
|---|
| 3757 |  | 
|---|
| 3758 | return ('OK',$loc); | 
|---|
| 3759 | } # end addLoc() | 
|---|
| 3760 |  | 
|---|
| 3761 |  | 
|---|
| 3762 | ## DNSDB::updateLoc() | 
|---|
| 3763 | # Update details of a location. | 
|---|
| 3764 | # Takes a database handle, location ID, group ID, short description, | 
|---|
| 3765 | # long comments/notes, and comma/space-separated IP list | 
|---|
| 3766 | # Returns a result code and message | 
|---|
| 3767 | sub updateLoc { | 
|---|
| 3768 | my $self = shift; | 
|---|
| 3769 | my $dbh = $self->{dbh}; | 
|---|
| 3770 | my $loc = shift; | 
|---|
| 3771 | my $grp = shift; | 
|---|
| 3772 | my $shdesc = shift; | 
|---|
| 3773 | my $comments = shift; | 
|---|
| 3774 | my $iplist = shift; | 
|---|
| 3775 |  | 
|---|
| 3776 | $shdesc = '' if !$shdesc; | 
|---|
| 3777 | $comments = '' if !$comments; | 
|---|
| 3778 | $iplist = '' if !$iplist; | 
|---|
| 3779 |  | 
|---|
| 3780 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 3781 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 3782 | local $dbh->{AutoCommit} = 0; | 
|---|
| 3783 | local $dbh->{RaiseError} = 1; | 
|---|
| 3784 |  | 
|---|
| 3785 | my $oldloc = $self->getLoc($loc); | 
|---|
| 3786 | my $okmsg = "Updated location (".$oldloc->{description}.", '".$oldloc->{iplist}."') to ($shdesc, '$iplist')"; | 
|---|
| 3787 |  | 
|---|
| 3788 | eval { | 
|---|
| 3789 | $dbh->do("UPDATE locations SET group_id=?,iplist=?,description=?,comments=? WHERE location=?", | 
|---|
| 3790 | undef, ($grp, $iplist, $shdesc, $comments, $loc) ); | 
|---|
| 3791 | $self->_log(entry => $okmsg); | 
|---|
| 3792 | $dbh->commit; | 
|---|
| 3793 | }; | 
|---|
| 3794 | if ($@) { | 
|---|
| 3795 | my $msg = $@; | 
|---|
| 3796 | eval { $dbh->rollback; }; | 
|---|
| 3797 | if ($self->{log_failures}) { | 
|---|
| 3798 | $shdesc = $loc if !$shdesc; | 
|---|
| 3799 | $self->_log(entry => "Failed updating location ($shdesc, '$iplist'): $msg"); | 
|---|
| 3800 | $dbh->commit; | 
|---|
| 3801 | } | 
|---|
| 3802 | return ('FAIL',$msg); | 
|---|
| 3803 | } | 
|---|
| 3804 |  | 
|---|
| 3805 | return ('OK',$okmsg); | 
|---|
| 3806 | } # end updateLoc() | 
|---|
| 3807 |  | 
|---|
| 3808 |  | 
|---|
| 3809 | ## DNSDB::delLoc() | 
|---|
| 3810 | sub delLoc { | 
|---|
| 3811 | my $self = shift; | 
|---|
| 3812 | my $dbh = $self->{dbh}; | 
|---|
| 3813 | my $loc = shift; | 
|---|
| 3814 |  | 
|---|
| 3815 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 3816 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 3817 | local $dbh->{AutoCommit} = 0; | 
|---|
| 3818 | local $dbh->{RaiseError} = 1; | 
|---|
| 3819 |  | 
|---|
| 3820 | my $oldloc = $self->getLoc($loc); | 
|---|
| 3821 | my $olddesc = ($oldloc->{description} ? $oldloc->{description} : $loc); | 
|---|
| 3822 | my $okmsg = "Deleted location ($olddesc, '".$oldloc->{iplist}."')"; | 
|---|
| 3823 |  | 
|---|
| 3824 | eval { | 
|---|
| 3825 | # Check for records with this location first.  Deleting a location without deleting records | 
|---|
| 3826 | # tagged for that location will render them unpublished without other warning. | 
|---|
| 3827 | my ($r) = $dbh->selectrow_array("SELECT record_id FROM records WHERE location=? LIMIT 1", undef, ($loc) ); | 
|---|
| 3828 | die "Records still exist in location $olddesc\n" if $r; | 
|---|
| 3829 | $dbh->do("DELETE FROM locations WHERE location=?", undef, ($loc) ); | 
|---|
| 3830 | $self->_log(entry => $okmsg); | 
|---|
| 3831 | $dbh->commit; | 
|---|
| 3832 | }; | 
|---|
| 3833 | if ($@) { | 
|---|
| 3834 | my $msg = $@; | 
|---|
| 3835 | eval { $dbh->rollback; }; | 
|---|
| 3836 | if ($self->{log_failures}) { | 
|---|
| 3837 | $self->_log(entry => "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg"); | 
|---|
| 3838 | $dbh->commit; | 
|---|
| 3839 | } | 
|---|
| 3840 | return ('FAIL', "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg"); | 
|---|
| 3841 | } | 
|---|
| 3842 |  | 
|---|
| 3843 | return ('OK',$okmsg); | 
|---|
| 3844 | } # end delLoc() | 
|---|
| 3845 |  | 
|---|
| 3846 |  | 
|---|
| 3847 | ## DNSDB::getLoc() | 
|---|
| 3848 | # Get details about a location/view | 
|---|
| 3849 | # Takes a database handle and location ID. | 
|---|
| 3850 | # Returns a reference to a hash containing the group ID, IP list, description, and comments/notes | 
|---|
| 3851 | sub getLoc { | 
|---|
| 3852 | my $self = shift; | 
|---|
| 3853 | my $dbh = $self->{dbh}; | 
|---|
| 3854 | my $loc = shift; | 
|---|
| 3855 |  | 
|---|
| 3856 | my $sth = $dbh->prepare("SELECT group_id,iplist,description,comments FROM locations WHERE location=?"); | 
|---|
| 3857 | $sth->execute($loc); | 
|---|
| 3858 | return $sth->fetchrow_hashref(); | 
|---|
| 3859 | } # end getLoc() | 
|---|
| 3860 |  | 
|---|
| 3861 |  | 
|---|
| 3862 | ## DNSDB::getLocCount() | 
|---|
| 3863 | # Get count of locations/views | 
|---|
| 3864 | # Takes a database handle and hash containing at least the current group, and optionally: | 
|---|
| 3865 | # - a reference list of secondary groups | 
|---|
| 3866 | # - a filter string | 
|---|
| 3867 | # - a "Starts with" string | 
|---|
| 3868 | sub getLocCount { | 
|---|
| 3869 | my $self = shift; | 
|---|
| 3870 | my $dbh = $self->{dbh}; | 
|---|
| 3871 |  | 
|---|
| 3872 | my %args = @_; | 
|---|
| 3873 |  | 
|---|
| 3874 | # Fail on bad curgroup argument.  There's no sane fallback on this one. | 
|---|
| 3875 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) { | 
|---|
| 3876 | $errstr = "Bad or missing curgroup argument"; | 
|---|
| 3877 | return; | 
|---|
| 3878 | } | 
|---|
| 3879 | # Fail on bad childlist argument.  This could be sanely ignored if bad, maybe. | 
|---|
| 3880 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) { | 
|---|
| 3881 | $errstr = "Bad childlist argument"; | 
|---|
| 3882 | return; | 
|---|
| 3883 | } | 
|---|
| 3884 |  | 
|---|
| 3885 | my @filterargs; | 
|---|
| 3886 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/; | 
|---|
| 3887 | push @filterargs, "^$args{startwith}" if $args{startwith}; | 
|---|
| 3888 | push @filterargs, $args{filter} if $args{filter}; | 
|---|
| 3889 |  | 
|---|
| 3890 | my $sql = "SELECT count(*) FROM locations ". | 
|---|
| 3891 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")". | 
|---|
| 3892 | ($args{startwith} ? " AND description ~* ?" : ''). | 
|---|
| 3893 | ($args{filter} ? " AND description ~* ?" : ''); | 
|---|
| 3894 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) ); | 
|---|
| 3895 | $errstr = $dbh->errstr if !$count; | 
|---|
| 3896 | return $count; | 
|---|
| 3897 | } # end getLocCount() | 
|---|
| 3898 |  | 
|---|
| 3899 |  | 
|---|
| 3900 | ## DNSDB::getLocList() | 
|---|
| 3901 | sub getLocList { | 
|---|
| 3902 | my $self = shift; | 
|---|
| 3903 | my $dbh = $self->{dbh}; | 
|---|
| 3904 |  | 
|---|
| 3905 | my %args = @_; | 
|---|
| 3906 |  | 
|---|
| 3907 | # Fail on bad curgroup argument.  There's no sane fallback on this one. | 
|---|
| 3908 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) { | 
|---|
| 3909 | $errstr = "Bad or missing curgroup argument"; | 
|---|
| 3910 | return; | 
|---|
| 3911 | } | 
|---|
| 3912 | # Fail on bad childlist argument.  This could be sanely ignored if bad, maybe. | 
|---|
| 3913 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) { | 
|---|
| 3914 | $errstr = "Bad childlist argument"; | 
|---|
| 3915 | return; | 
|---|
| 3916 | } | 
|---|
| 3917 |  | 
|---|
| 3918 | my @filterargs; | 
|---|
| 3919 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/; | 
|---|
| 3920 | push @filterargs, "^$args{startwith}" if $args{startwith}; | 
|---|
| 3921 | push @filterargs, $args{filter} if $args{filter}; | 
|---|
| 3922 |  | 
|---|
| 3923 | # better to request sorts on "simple" names, but it means we need to map it to real columns | 
|---|
| 3924 | #  my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status', | 
|---|
| 3925 | #       fname => 'fname'); | 
|---|
| 3926 | #  $args{sortby} = $sortmap{$args{sortby}}; | 
|---|
| 3927 |  | 
|---|
| 3928 | # protection against bad or missing arguments | 
|---|
| 3929 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC'); | 
|---|
| 3930 | $args{sortby} = 'l.description' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/; | 
|---|
| 3931 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/; | 
|---|
| 3932 |  | 
|---|
| 3933 | my $sql = "SELECT l.location, l.description, l.iplist, g.group_name ". | 
|---|
| 3934 | "FROM locations l ". | 
|---|
| 3935 | "INNER JOIN groups g ON l.group_id=g.group_id ". | 
|---|
| 3936 | "WHERE l.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")". | 
|---|
| 3937 | ($args{startwith} ? " AND l.description ~* ?" : ''). | 
|---|
| 3938 | ($args{filter} ? " AND l.description ~* ?" : ''). | 
|---|
| 3939 | " ORDER BY $args{sortby} $args{sortorder} ". | 
|---|
| 3940 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage}); | 
|---|
| 3941 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) ); | 
|---|
| 3942 | $errstr = $dbh->errstr if !$ulist; | 
|---|
| 3943 | return $ulist; | 
|---|
| 3944 | } # end getLocList() | 
|---|
| 3945 |  | 
|---|
| 3946 |  | 
|---|
| 3947 | ## DNSDB::getLocDropdown() | 
|---|
| 3948 | # Get a list of location names for use in a dropdown menu. | 
|---|
| 3949 | # Takes a database handle, current group, and optional "tag this as selected" flag. | 
|---|
| 3950 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template | 
|---|
| 3951 | sub getLocDropdown { | 
|---|
| 3952 | my $self = shift; | 
|---|
| 3953 | my $dbh = $self->{dbh}; | 
|---|
| 3954 | my $grp = shift; | 
|---|
| 3955 | my $sel = shift || ''; | 
|---|
| 3956 |  | 
|---|
| 3957 | my $sth = $dbh->prepare(qq( | 
|---|
| 3958 | SELECT description,location FROM locations | 
|---|
| 3959 | WHERE group_id=? | 
|---|
| 3960 | ORDER BY description | 
|---|
| 3961 | ) ); | 
|---|
| 3962 | $sth->execute($grp); | 
|---|
| 3963 |  | 
|---|
| 3964 | my @loclist; | 
|---|
| 3965 | push @loclist, { locname => "(Default/All)", loc => '', selected => ($sel ? 0 : ($sel eq '' ? 1 : 0)) }; | 
|---|
| 3966 | while (my ($locname, $loc) = $sth->fetchrow_array) { | 
|---|
| 3967 | my %row = ( | 
|---|
| 3968 | locname => $locname, | 
|---|
| 3969 | loc => $loc, | 
|---|
| 3970 | selected => ($sel eq $loc ? 1 : 0) | 
|---|
| 3971 | ); | 
|---|
| 3972 | push @loclist, \%row; | 
|---|
| 3973 | } | 
|---|
| 3974 | return \@loclist; | 
|---|
| 3975 | } # end getLocDropdown() | 
|---|
| 3976 |  | 
|---|
| 3977 |  | 
|---|
| 3978 | ## DNSDB::getSOA() | 
|---|
| 3979 | # Return all suitable fields from an SOA record in separate elements of a hash | 
|---|
| 3980 | # Takes a database handle, default/live flag, domain/reverse flag, and parent ID | 
|---|
| 3981 | sub getSOA { | 
|---|
| 3982 | $errstr = ''; | 
|---|
| 3983 | my $self = shift; | 
|---|
| 3984 | my $dbh = $self->{dbh}; | 
|---|
| 3985 | my $def = shift; | 
|---|
| 3986 | my $rev = shift; | 
|---|
| 3987 | my $id = shift; | 
|---|
| 3988 |  | 
|---|
| 3989 | # (ab)use distance and weight columns to store SOA data?  can't for default_rev_records... | 
|---|
| 3990 | # - should really attach serial to the zone parent somewhere | 
|---|
| 3991 |  | 
|---|
| 3992 | my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev). | 
|---|
| 3993 | " WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}"; | 
|---|
| 3994 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) ); | 
|---|
| 3995 | return if !$ret; | 
|---|
| 3996 | ##fixme:  stick a flag somewhere if the record doesn't exist.  by the API, this is an impossible case, but... | 
|---|
| 3997 |  | 
|---|
| 3998 | ($ret->{contact},$ret->{prins}) = split /:/, $ret->{host}; | 
|---|
| 3999 | delete $ret->{host}; | 
|---|
| 4000 | ($ret->{refresh},$ret->{retry},$ret->{expire},$ret->{minttl}) = split /:/, $ret->{val}; | 
|---|
| 4001 | delete $ret->{val}; | 
|---|
| 4002 |  | 
|---|
| 4003 | return $ret; | 
|---|
| 4004 | } # end getSOA() | 
|---|
| 4005 |  | 
|---|
| 4006 |  | 
|---|
| 4007 | ## DNSDB::updateSOA() | 
|---|
| 4008 | # Update the specified SOA record | 
|---|
| 4009 | # Takes a database handle, default/live flag, forward/reverse flag, and SOA data hash | 
|---|
| 4010 | # Returns a two-element list with a result code and message | 
|---|
| 4011 | sub updateSOA { | 
|---|
| 4012 | my $self = shift; | 
|---|
| 4013 | my $dbh = $self->{dbh}; | 
|---|
| 4014 | my $defrec = shift; | 
|---|
| 4015 | my $revrec = shift; | 
|---|
| 4016 |  | 
|---|
| 4017 | my %soa = @_; | 
|---|
| 4018 |  | 
|---|
| 4019 | my $oldsoa = $self->getSOA($defrec, $revrec, $soa{id}); | 
|---|
| 4020 |  | 
|---|
| 4021 | my $msg; | 
|---|
| 4022 | my %logdata; | 
|---|
| 4023 | if ($defrec eq 'n') { | 
|---|
| 4024 | $logdata{domain_id} = $soa{id} if $revrec eq 'n'; | 
|---|
| 4025 | $logdata{rdns_id} = $soa{id} if $revrec eq 'y'; | 
|---|
| 4026 | $logdata{group_id} = $self->parentID(id => $soa{id}, revrec => $revrec, | 
|---|
| 4027 | type => ($revrec eq 'n' ? 'domain' : 'revzone') ); | 
|---|
| 4028 | } else { | 
|---|
| 4029 | $logdata{group_id} = $soa{id}; | 
|---|
| 4030 | } | 
|---|
| 4031 | my $parname = ($defrec eq 'y' ? $self->groupName($soa{id}) : | 
|---|
| 4032 | ($revrec eq 'n' ? $self->domainName($soa{id}) : $self->revName($soa{id})) ); | 
|---|
| 4033 |  | 
|---|
| 4034 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 4035 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 4036 | local $dbh->{AutoCommit} = 0; | 
|---|
| 4037 | local $dbh->{RaiseError} = 1; | 
|---|
| 4038 |  | 
|---|
| 4039 | eval { | 
|---|
| 4040 | if (!$oldsoa) { | 
|---|
| 4041 | # old SOA record is missing for some reason.  create a new one. | 
|---|
| 4042 | my $sql = "INSERT INTO "._rectable($defrec, $revrec)." ("._recparent($defrec, $revrec). | 
|---|
| 4043 | ", host, type, val, ttl) VALUES (?,?,6,?,?)"; | 
|---|
| 4044 | $dbh->do($sql, undef, ($soa{id}, "$soa{contact}:$soa{prins}", | 
|---|
| 4045 | "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}", $soa{ttl}) ); | 
|---|
| 4046 | $msg = ($defrec eq 'y' ? ($revrec eq 'y' ? 'Default reverse ' : 'Default ') : ''). | 
|---|
| 4047 | "SOA missing for $parname;  added (ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},". | 
|---|
| 4048 | " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})"; | 
|---|
| 4049 | } else { | 
|---|
| 4050 | my $sql = "UPDATE "._rectable($defrec, $revrec)." SET host=?, val=?, ttl=? WHERE record_id=? AND type=6"; | 
|---|
| 4051 | $dbh->do($sql, undef, ("$soa{contact}:$soa{prins}", "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}", | 
|---|
| 4052 | $soa{ttl}, $oldsoa->{record_id}) ); | 
|---|
| 4053 | $msg = "Updated ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse ' : 'default ') : ''). | 
|---|
| 4054 | "SOA for $parname: ". | 
|---|
| 4055 | "(ns $oldsoa->{prins}, contact $oldsoa->{contact}, refresh $oldsoa->{refresh},". | 
|---|
| 4056 | " retry $oldsoa->{retry}, expire $oldsoa->{expire}, minTTL $oldsoa->{minttl}, TTL $oldsoa->{ttl}) to ". | 
|---|
| 4057 | "(ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},". | 
|---|
| 4058 | " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})"; | 
|---|
| 4059 | } | 
|---|
| 4060 | $logdata{entry} = $msg; | 
|---|
| 4061 | $self->_log(%logdata); | 
|---|
| 4062 |  | 
|---|
| 4063 | $dbh->commit; | 
|---|
| 4064 | }; | 
|---|
| 4065 | if ($@) { | 
|---|
| 4066 | $msg = $@; | 
|---|
| 4067 | eval { $dbh->rollback; }; | 
|---|
| 4068 | $logdata{entry} = "Error updating ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse zone ' : 'default ') : ''). | 
|---|
| 4069 | "SOA record for $parname: $msg"; | 
|---|
| 4070 | if ($self->{log_failures}) { | 
|---|
| 4071 | $self->_log(%logdata); | 
|---|
| 4072 | $dbh->commit; | 
|---|
| 4073 | } | 
|---|
| 4074 | return ('FAIL', $logdata{entry}); | 
|---|
| 4075 | } else { | 
|---|
| 4076 | return ('OK', $msg); | 
|---|
| 4077 | } | 
|---|
| 4078 | } # end updateSOA() | 
|---|
| 4079 |  | 
|---|
| 4080 |  | 
|---|
| 4081 | ## DNSDB::getRecLine() | 
|---|
| 4082 | # Return all data fields for a zone record in separate elements of a hash | 
|---|
| 4083 | # Takes a database handle, default/live flag, forward/reverse flag, and record ID | 
|---|
| 4084 | sub getRecLine { | 
|---|
| 4085 | $errstr = ''; | 
|---|
| 4086 | my $self = shift; | 
|---|
| 4087 | my $dbh = $self->{dbh}; | 
|---|
| 4088 | my $defrec = shift; | 
|---|
| 4089 | my $revrec = shift; | 
|---|
| 4090 | my $id = shift; | 
|---|
| 4091 |  | 
|---|
| 4092 | ##fixme: do we need a knob to twist to switch between unix epoch and postgres time string? | 
|---|
| 4093 | my $sql = "SELECT record_id,host,type,val,ttl". | 
|---|
| 4094 | ($defrec eq 'n' ? ',location' : ''). | 
|---|
| 4095 | ($revrec eq 'n' ? ',distance,weight,port' : ''). | 
|---|
| 4096 | (($defrec eq 'y') ? ',group_id FROM ' : ',domain_id,rdns_id,stamp,stamp < now() AS ispast,expires,stampactive FROM '). | 
|---|
| 4097 | _rectable($defrec,$revrec)." WHERE record_id=?"; | 
|---|
| 4098 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) ); | 
|---|
| 4099 |  | 
|---|
| 4100 | if ($dbh->err) { | 
|---|
| 4101 | $errstr = $DBI::errstr; | 
|---|
| 4102 | return undef; | 
|---|
| 4103 | } | 
|---|
| 4104 |  | 
|---|
| 4105 | if (!$ret) { | 
|---|
| 4106 | $errstr = "No such record"; | 
|---|
| 4107 | return undef; | 
|---|
| 4108 | } | 
|---|
| 4109 |  | 
|---|
| 4110 | # explicitly set a parent id | 
|---|
| 4111 | if ($defrec eq 'y') { | 
|---|
| 4112 | $ret->{parid} = $ret->{group_id}; | 
|---|
| 4113 | } else { | 
|---|
| 4114 | $ret->{parid} = (($revrec eq 'n') ? $ret->{domain_id} : $ret->{rdns_id}); | 
|---|
| 4115 | # and a secondary if we have a custom type that lives in both a forward and reverse zone | 
|---|
| 4116 | $ret->{secid} = (($revrec eq 'y') ? $ret->{domain_id} : $ret->{rdns_id}) if $ret->{type} > 65279; | 
|---|
| 4117 | } | 
|---|
| 4118 | $ret->{address} = $ret->{val};        # because. | 
|---|
| 4119 |  | 
|---|
| 4120 | return $ret; | 
|---|
| 4121 | } | 
|---|
| 4122 |  | 
|---|
| 4123 |  | 
|---|
| 4124 | ##fixme: should use above (getRecLine()) to get lines for below? | 
|---|
| 4125 | ## DNSDB::getRecList() | 
|---|
| 4126 | # Return records for a group or zone | 
|---|
| 4127 | # Takes a default/live flag, group or zone ID, start, | 
|---|
| 4128 | # number of records, sort field, and sort order | 
|---|
| 4129 | # Returns a reference to an array of hashes | 
|---|
| 4130 | sub getRecList { | 
|---|
| 4131 | $errstr = ''; | 
|---|
| 4132 | my $self = shift; | 
|---|
| 4133 | my $dbh = $self->{dbh}; | 
|---|
| 4134 |  | 
|---|
| 4135 | my %args = @_; | 
|---|
| 4136 |  | 
|---|
| 4137 | $args{revrec} = 'n' if !$args{revrec}; | 
|---|
| 4138 | $args{defrec} = 'n' if !$args{defrec}; | 
|---|
| 4139 |  | 
|---|
| 4140 | # protection against bad or missing arguments | 
|---|
| 4141 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC'); | 
|---|
| 4142 | my $defsort; | 
|---|
| 4143 | $defsort = 'host' if $args{revrec} eq 'n';     # default sort by host on domain record list | 
|---|
| 4144 | $defsort = 'val' if $args{revrec} eq 'y';      # default sort by IP on revzone record list | 
|---|
| 4145 | $args{sortby} = '' if !$args{sortby}; | 
|---|
| 4146 | $args{sortby} = $defsort if !$args{revrec}; | 
|---|
| 4147 | $args{sortby} = $defsort if $args{sortby} !~ /^[\w_,.]+$/; | 
|---|
| 4148 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/; | 
|---|
| 4149 | my $perpage = ($args{nrecs} ? $args{nrecs} : $self->{perpage}); | 
|---|
| 4150 |  | 
|---|
| 4151 |  | 
|---|
| 4152 | ##fixme:  do we need a knob to twist to switch from unix epoch to postgres time string? | 
|---|
| 4153 | my @bindvars; | 
|---|
| 4154 | my $sql = "SELECT r.record_id,"; | 
|---|
| 4155 | # only include the parent info if we don't already know which parent we're in | 
|---|
| 4156 | $sql .= "r.domain_id,r.rdns_id," unless $args{id}; | 
|---|
| 4157 | $sql .= "r.host,r.type,r.val,r.ttl"; | 
|---|
| 4158 | $sql .= ",l.description AS locname,stamp,r.stamp < now() AS ispast,r.expires,r.stampactive" | 
|---|
| 4159 | if $args{defrec} eq 'n'; | 
|---|
| 4160 | $sql .= ",r.distance,r.weight,r.port" if $args{revrec} eq 'n'; | 
|---|
| 4161 | $sql .= " FROM "._rectable($args{defrec},$args{revrec})." r "; | 
|---|
| 4162 | $sql .= "INNER JOIN rectypes t ON r.type=t.val ";     # for sorting by type alphabetically | 
|---|
| 4163 | $sql .= "LEFT JOIN locations l ON r.location=l.location " if $args{defrec} eq 'n'; | 
|---|
| 4164 | $sql .= "WHERE NOT r.type=$reverse_typemap{SOA}"; | 
|---|
| 4165 |  | 
|---|
| 4166 | # "normal" record list | 
|---|
| 4167 | if ($args{id}) { | 
|---|
| 4168 | $sql .= " AND "._recparent($args{defrec},$args{revrec})." = ?"; | 
|---|
| 4169 | push @bindvars, $args{id}; | 
|---|
| 4170 | } | 
|---|
| 4171 |  | 
|---|
| 4172 | # Filtering on host/val (mainly normal record list) | 
|---|
| 4173 | if ($args{filter}) { | 
|---|
| 4174 | $sql .= " AND (r.host ~* ? OR r.val ~* ? OR r.host ~* ? OR r.val ~* ?)"; | 
|---|
| 4175 | my $tmp = join('.',reverse(split(/\./,$args{filter}))); | 
|---|
| 4176 | push @bindvars, ($args{filter},$args{filter}); | 
|---|
| 4177 | push @bindvars, ($tmp, $tmp); | 
|---|
| 4178 | } | 
|---|
| 4179 |  | 
|---|
| 4180 | # Filtering on other fields | 
|---|
| 4181 | foreach (qw(type distance weight port ttl description)) { | 
|---|
| 4182 | if ($args{$_}) { | 
|---|
| 4183 | $sql .= " AND $_ ~* ?"; | 
|---|
| 4184 | push @bindvars, $args{$_}; | 
|---|
| 4185 | } | 
|---|
| 4186 | } | 
|---|
| 4187 |  | 
|---|
| 4188 | # whee!  multisort means just passing comma-separated fields in sortby! | 
|---|
| 4189 | my $newsort = ''; | 
|---|
| 4190 | foreach my $sf (split /,/, $args{sortby}) { | 
|---|
| 4191 | $sf = "r.$sf"; | 
|---|
| 4192 | # sort on IP, correctly | 
|---|
| 4193 | $sf =~ s/r\.val/inetlazy(r.val)/; | 
|---|
| 4194 | # hmm.  do we really need to limit this? | 
|---|
| 4195 | #       if $args{revrec} eq 'y' && $args{defrec} eq 'n'; | 
|---|
| 4196 | $sf =~ s/r\.type/t.alphaorder/;  # subtly different from sorting on rectypes.name | 
|---|
| 4197 | $newsort .= ",$sf"; | 
|---|
| 4198 | } | 
|---|
| 4199 | $newsort =~ s/^,//; | 
|---|
| 4200 | ##enhance: pass in ascending/descending sort per-field | 
|---|
| 4201 | $sql .= " ORDER BY $newsort $args{sortorder}"; | 
|---|
| 4202 | # ensure consistent ordering by sorting on record_id too | 
|---|
| 4203 | $sql .= ", record_id $args{sortorder}"; | 
|---|
| 4204 |  | 
|---|
| 4205 | # Offset/pagination | 
|---|
| 4206 | $sql .= ($args{offset} eq 'all' ? '' : " LIMIT $perpage OFFSET ".$args{offset}*$perpage); | 
|---|
| 4207 |  | 
|---|
| 4208 | my @working; | 
|---|
| 4209 | my $recsth = $dbh->prepare($sql); | 
|---|
| 4210 | $recsth->execute(@bindvars); | 
|---|
| 4211 | while (my $rec = $recsth->fetchrow_hashref) { | 
|---|
| 4212 | if ($args{revrec} eq 'y' && $args{defrec} eq 'n' && | 
|---|
| 4213 | ($self->{showrev_arpa} eq 'record' || $self->{showrev_arpa} eq 'all') && | 
|---|
| 4214 | $rec->{val} !~ /\.arpa$/ ) { | 
|---|
| 4215 | # skip all reverse zone .arpa "hostnames" since they're already .arpa names. | 
|---|
| 4216 | ##enhance:  extend {showrev_arpa} eq 'record' to specify record types | 
|---|
| 4217 | my $tmpip = new NetAddr::IP $rec->{val} if $rec->{val} =~ /^(?:[\d.\/]+|[a-fA-F0-9:\/]+)$/; | 
|---|
| 4218 | $rec->{val} = DNSDB::_ZONE($tmpip, 'ZONE', 'r', '.').($tmpip->{isv6} ? '.ip6.arpa' : '.in-addr.arpa') if $tmpip; | 
|---|
| 4219 | } | 
|---|
| 4220 | push @working, $rec; | 
|---|
| 4221 | } | 
|---|
| 4222 | return \@working; | 
|---|
| 4223 | } # end getRecList() | 
|---|
| 4224 |  | 
|---|
| 4225 |  | 
|---|
| 4226 | ## DNSDB::getRecCount() | 
|---|
| 4227 | # Return count of non-SOA records in zone (or default records in a group) | 
|---|
| 4228 | # Takes a database handle, default/live flag, reverse/forward flag, group/domain ID, | 
|---|
| 4229 | # and optional filtering modifier | 
|---|
| 4230 | # Returns the count | 
|---|
| 4231 | sub getRecCount { | 
|---|
| 4232 | my $self = shift; | 
|---|
| 4233 | my $dbh = $self->{dbh}; | 
|---|
| 4234 |  | 
|---|
| 4235 | my %args = @_; | 
|---|
| 4236 |  | 
|---|
| 4237 | $args{defrec} = 'n' if !$args{defrec}; | 
|---|
| 4238 | $args{revrec} = 'n' if !$args{revrec}; | 
|---|
| 4239 |  | 
|---|
| 4240 | my @bindvars; | 
|---|
| 4241 | my $sql = "SELECT count(*) FROM ". | 
|---|
| 4242 | _rectable($args{defrec},$args{revrec}). | 
|---|
| 4243 | " WHERE NOT type=$reverse_typemap{SOA}"; | 
|---|
| 4244 | if ($args{id}) { | 
|---|
| 4245 | $sql .= " AND "._recparent($args{defrec},$args{revrec})." = ?"; | 
|---|
| 4246 | push @bindvars, $args{id}; | 
|---|
| 4247 | } | 
|---|
| 4248 |  | 
|---|
| 4249 | # Filtering on host/val (mainly normal record list) | 
|---|
| 4250 | if ($args{filter}) { | 
|---|
| 4251 | $sql .= " AND (r.host ~* ? OR r.val ~* ? OR r.host ~* ? OR r.val ~* ?)"; | 
|---|
| 4252 | my $tmp = join('.',reverse(split(/\./,$args{filter}))); | 
|---|
| 4253 | push @bindvars, ($args{filter},$args{filter}); | 
|---|
| 4254 | push @bindvars, ($tmp, $tmp); | 
|---|
| 4255 | } | 
|---|
| 4256 |  | 
|---|
| 4257 | # Filtering on other fields | 
|---|
| 4258 | foreach (qw(type distance weight port ttl description)) { | 
|---|
| 4259 | if ($args{$_}) { | 
|---|
| 4260 | $sql .= " AND $_ ~* ?"; | 
|---|
| 4261 | push @bindvars, $args{$_}; | 
|---|
| 4262 | } | 
|---|
| 4263 | } | 
|---|
| 4264 |  | 
|---|
| 4265 | my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) ); | 
|---|
| 4266 |  | 
|---|
| 4267 | return $count; | 
|---|
| 4268 |  | 
|---|
| 4269 | } # end getRecCount() | 
|---|
| 4270 |  | 
|---|
| 4271 |  | 
|---|
| 4272 | ## DNSDB::addRec() | 
|---|
| 4273 | # Add a new record to a domain or a group's default records | 
|---|
| 4274 | # Takes a database handle, default/live flag, group/domain ID, | 
|---|
| 4275 | # host, type, value, and TTL | 
|---|
| 4276 | # Some types require additional detail: "distance" for MX and SRV, | 
|---|
| 4277 | # and weight/port for SRV | 
|---|
| 4278 | # Returns a status code and detail message in case of error | 
|---|
| 4279 | ##fixme:  pass a hash with the record data, not a series of separate values | 
|---|
| 4280 | sub addRec { | 
|---|
| 4281 | $errstr = ''; | 
|---|
| 4282 | my $self = shift; | 
|---|
| 4283 | my $dbh = $self->{dbh}; | 
|---|
| 4284 | my $defrec = shift; | 
|---|
| 4285 | my $revrec = shift; | 
|---|
| 4286 | my $id = shift;       # parent (group_id for defrecs, rdns_id for reverse records, | 
|---|
| 4287 | # domain_id for domain records) | 
|---|
| 4288 |  | 
|---|
| 4289 | my $host = shift; | 
|---|
| 4290 | my $rectype = shift;  # reference so we can coerce it if "+"-types can't find both zones | 
|---|
| 4291 | my $val = shift; | 
|---|
| 4292 | my $ttl = shift; | 
|---|
| 4293 | my $location = shift; | 
|---|
| 4294 | $location  = '' if !$location; | 
|---|
| 4295 |  | 
|---|
| 4296 | my $expires = shift || ''; | 
|---|
| 4297 | $expires = 1 if $expires eq 'until';  # Turn some special values into the appropriate booleans. | 
|---|
| 4298 | $expires = 0 if $expires eq 'after'; | 
|---|
| 4299 | my $stamp = shift; | 
|---|
| 4300 | $stamp = '' if !$stamp;        # Timestamp should be a string at this point. | 
|---|
| 4301 |  | 
|---|
| 4302 | # extra safety net - apparently RPC can squeak this by.  O_o | 
|---|
| 4303 | return ('FAIL', "host must contain a value") if !$$host; | 
|---|
| 4304 | return ('FAIL', "val must contain a value") if !$$val; | 
|---|
| 4305 |  | 
|---|
| 4306 | # Spaces are evil. | 
|---|
| 4307 | $$host =~ s/^\s+//; | 
|---|
| 4308 | $$host =~ s/\s+$//; | 
|---|
| 4309 | if ($typemap{$$rectype} ne 'TXT') { | 
|---|
| 4310 | # Leading or trailng spaces could be legit in TXT records. | 
|---|
| 4311 | $$val =~ s/^\s+//; | 
|---|
| 4312 | $$val =~ s/\s+$//; | 
|---|
| 4313 | } | 
|---|
| 4314 |  | 
|---|
| 4315 | _caseclean($rectype, $host, $val, $defrec, $revrec) if $self->{lowercase}; | 
|---|
| 4316 |  | 
|---|
| 4317 | # prep for validation | 
|---|
| 4318 | my $addr = NetAddr::IP->new($$val) if _maybeip($val); | 
|---|
| 4319 | $$host =~ s/\.+$//;   # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI. | 
|---|
| 4320 |  | 
|---|
| 4321 | my $domid = 0; | 
|---|
| 4322 | my $revid = 0; | 
|---|
| 4323 |  | 
|---|
| 4324 | my $retcode = 'OK';   # assume everything will go OK | 
|---|
| 4325 | my $retmsg = ''; | 
|---|
| 4326 |  | 
|---|
| 4327 | # do simple validation first | 
|---|
| 4328 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^-?\d+$/; | 
|---|
| 4329 |  | 
|---|
| 4330 | # Collect these even if we're only doing a simple A record so we can call *any* validation sub | 
|---|
| 4331 | my $dist = shift; | 
|---|
| 4332 | my $weight = shift; | 
|---|
| 4333 | my $port = shift; | 
|---|
| 4334 |  | 
|---|
| 4335 | my $fields; | 
|---|
| 4336 | my @vallist; | 
|---|
| 4337 |  | 
|---|
| 4338 | # Call the validation sub for the type requested. | 
|---|
| 4339 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec, id => $id, | 
|---|
| 4340 | host => $host, rectype => $rectype, val => $val, addr => $addr, | 
|---|
| 4341 | dist => \$dist, port => \$port, weight => \$weight, | 
|---|
| 4342 | fields => \$fields, vallist => \@vallist); | 
|---|
| 4343 |  | 
|---|
| 4344 | return ($retcode,$retmsg) if $retcode eq 'FAIL'; | 
|---|
| 4345 |  | 
|---|
| 4346 | # Set up database fields and bind parameters | 
|---|
| 4347 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec); | 
|---|
| 4348 | push @vallist, ($$host,$$rectype,$$val,$ttl,$id); | 
|---|
| 4349 |  | 
|---|
| 4350 | if ($defrec eq 'n') { | 
|---|
| 4351 | # locations are not for default records, silly coder! | 
|---|
| 4352 | $fields .= ",location"; | 
|---|
| 4353 | push @vallist, $location; | 
|---|
| 4354 | # timestamps are rare. | 
|---|
| 4355 | if ($stamp) { | 
|---|
| 4356 | $fields .= ",stamp,expires,stampactive"; | 
|---|
| 4357 | push @vallist, $stamp, $expires, 'y'; | 
|---|
| 4358 | } else { | 
|---|
| 4359 | $fields .= ",stampactive"; | 
|---|
| 4360 | push @vallist, 'n'; | 
|---|
| 4361 | } | 
|---|
| 4362 | } | 
|---|
| 4363 |  | 
|---|
| 4364 | # a little magic to get the right number of ? placeholders based on how many values we're providing | 
|---|
| 4365 | my $vallen = '?'.(',?'x$#vallist); | 
|---|
| 4366 |  | 
|---|
| 4367 | # Put together the success log entry.  We have to use this horrible kludge | 
|---|
| 4368 | # because domain_id and rdns_id may or may not be present, and if they are, | 
|---|
| 4369 | # they're not at a guaranteed consistent index in the array.  wheee! | 
|---|
| 4370 | my %logdata; | 
|---|
| 4371 | my @ftmp = split /,/, $fields; | 
|---|
| 4372 | for (my $i=0; $i <= $#vallist; $i++) { | 
|---|
| 4373 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id'; | 
|---|
| 4374 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id'; | 
|---|
| 4375 | } | 
|---|
| 4376 | $logdata{group_id} = $id if $defrec eq 'y'; | 
|---|
| 4377 | $logdata{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) | 
|---|
| 4378 | if $defrec eq 'n'; | 
|---|
| 4379 | $logdata{entry} = "Added ".($defrec eq 'y' ? 'default record' : 'record'); | 
|---|
| 4380 | # Log reverse records to match the formal .arpa tree | 
|---|
| 4381 | if ($revrec eq 'y') { | 
|---|
| 4382 | $logdata{entry} .= " '$$val $typemap{$$rectype} $$host"; | 
|---|
| 4383 | } else { | 
|---|
| 4384 | $logdata{entry} .= " '$$host $typemap{$$rectype} $$val"; | 
|---|
| 4385 | } | 
|---|
| 4386 |  | 
|---|
| 4387 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX'; | 
|---|
| 4388 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]" | 
|---|
| 4389 | if $typemap{$$rectype} eq 'SRV'; | 
|---|
| 4390 | $logdata{entry} .= "', TTL $ttl"; | 
|---|
| 4391 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location; | 
|---|
| 4392 | $logdata{entry} .= ($expires ? ', expires at ' : ', valid after ').$stamp if $stamp; | 
|---|
| 4393 |  | 
|---|
| 4394 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 4395 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 4396 | local $dbh->{AutoCommit} = 0; | 
|---|
| 4397 | local $dbh->{RaiseError} = 1; | 
|---|
| 4398 |  | 
|---|
| 4399 | eval { | 
|---|
| 4400 | $dbh->do("INSERT INTO "._rectable($defrec, $revrec)." ($fields) VALUES ($vallen)", | 
|---|
| 4401 | undef, @vallist); | 
|---|
| 4402 | $self->_log(%logdata); | 
|---|
| 4403 | $dbh->commit; | 
|---|
| 4404 | }; | 
|---|
| 4405 | if ($@) { | 
|---|
| 4406 | my $msg = $@; | 
|---|
| 4407 | eval { $dbh->rollback; }; | 
|---|
| 4408 | if ($self->{log_failures}) { | 
|---|
| 4409 | $logdata{entry} = "Failed adding ".($defrec eq 'y' ? 'default ' : ''). | 
|---|
| 4410 | "record '$$host $typemap{$$rectype} $$val', TTL $ttl ($msg)"; | 
|---|
| 4411 | $self->_log(%logdata); | 
|---|
| 4412 | $dbh->commit; | 
|---|
| 4413 | } | 
|---|
| 4414 | return ('FAIL',$msg); | 
|---|
| 4415 | } | 
|---|
| 4416 |  | 
|---|
| 4417 | $resultstr = $logdata{entry}; | 
|---|
| 4418 | return ($retcode, $retmsg); | 
|---|
| 4419 |  | 
|---|
| 4420 | } # end addRec() | 
|---|
| 4421 |  | 
|---|
| 4422 |  | 
|---|
| 4423 | ## DNSDB::updateRec() | 
|---|
| 4424 | # Update a record | 
|---|
| 4425 | # Takes a database handle, default and reverse flags, record ID, immediate parent ID, and new record data. | 
|---|
| 4426 | # Returns a status code and message | 
|---|
| 4427 | sub updateRec { | 
|---|
| 4428 | $errstr = ''; | 
|---|
| 4429 |  | 
|---|
| 4430 | my $self = shift; | 
|---|
| 4431 | my $dbh = $self->{dbh}; | 
|---|
| 4432 |  | 
|---|
| 4433 | my $defrec = shift; | 
|---|
| 4434 | my $revrec = shift; | 
|---|
| 4435 | my $id = shift; | 
|---|
| 4436 | my $parid = shift;    # immediate parent entity that we're descending from to update the record | 
|---|
| 4437 |  | 
|---|
| 4438 | # all records have these | 
|---|
| 4439 | my $host = shift; | 
|---|
| 4440 | my $hostbk = $$host;  # Keep a backup copy of the original, so we can WARN if the update mangles the domain | 
|---|
| 4441 | my $rectype = shift; | 
|---|
| 4442 | my $val = shift; | 
|---|
| 4443 | my $ttl = shift; | 
|---|
| 4444 | my $location = shift; # may be empty/null/undef depending on caller | 
|---|
| 4445 | $location  = '' if !$location; | 
|---|
| 4446 |  | 
|---|
| 4447 | my $expires = shift || ''; | 
|---|
| 4448 | $expires = 1 if $expires eq 'until';  # Turn some special values into the appropriate booleans. | 
|---|
| 4449 | $expires = 0 if $expires eq 'after'; | 
|---|
| 4450 | my $stamp = shift; | 
|---|
| 4451 | $stamp = '' if !$stamp;        # Timestamp should be a string at this point. | 
|---|
| 4452 |  | 
|---|
| 4453 | # just set it to an empty string;  failures will be caught later. | 
|---|
| 4454 | $$host = '' if !$$host; | 
|---|
| 4455 |  | 
|---|
| 4456 | # Spaces are evil. | 
|---|
| 4457 | $$host =~ s/^\s+//; | 
|---|
| 4458 | $$host =~ s/\s+$//; | 
|---|
| 4459 | if ($typemap{$$rectype} ne 'TXT') { | 
|---|
| 4460 | # Leading or trailng spaces could be legit in TXT records. | 
|---|
| 4461 | $$val =~ s/^\s+//; | 
|---|
| 4462 | $$val =~ s/\s+$//; | 
|---|
| 4463 | } | 
|---|
| 4464 |  | 
|---|
| 4465 | _caseclean($rectype, $host, $val, $defrec, $revrec) if $self->{lowercase}; | 
|---|
| 4466 |  | 
|---|
| 4467 | # prep for validation | 
|---|
| 4468 | my $addr = NetAddr::IP->new($$val) if _maybeip($val); | 
|---|
| 4469 | $$host =~ s/\.+$//;   # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI. | 
|---|
| 4470 |  | 
|---|
| 4471 | my $domid = 0; | 
|---|
| 4472 | my $revid = 0; | 
|---|
| 4473 |  | 
|---|
| 4474 | my $retcode = 'OK';   # assume everything will go OK | 
|---|
| 4475 | my $retmsg = ''; | 
|---|
| 4476 |  | 
|---|
| 4477 | # do simple validation first | 
|---|
| 4478 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^-?\d+$/; | 
|---|
| 4479 |  | 
|---|
| 4480 | # only MX and SRV will use these | 
|---|
| 4481 | my $dist = shift || 0; | 
|---|
| 4482 | my $weight = shift || 0; | 
|---|
| 4483 | my $port = shift || 0; | 
|---|
| 4484 |  | 
|---|
| 4485 | my $fields; | 
|---|
| 4486 | my @vallist; | 
|---|
| 4487 |  | 
|---|
| 4488 | # get old record data so we have the right parent ID | 
|---|
| 4489 | # and for logging (eventually) | 
|---|
| 4490 | my $oldrec = $self->getRecLine($defrec, $revrec, $id); | 
|---|
| 4491 |  | 
|---|
| 4492 | # Call the validation sub for the type requested. | 
|---|
| 4493 | # Note the ID to pass here is the *parent*, not the record | 
|---|
| 4494 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec, | 
|---|
| 4495 | id => ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})), | 
|---|
| 4496 | host => $host, rectype => $rectype, val => $val, addr => $addr, | 
|---|
| 4497 | dist => \$dist, port => \$port, weight => \$weight, | 
|---|
| 4498 | fields => \$fields, vallist => \@vallist, | 
|---|
| 4499 | update => $id); | 
|---|
| 4500 |  | 
|---|
| 4501 | return ($retcode,$retmsg) if $retcode eq 'FAIL'; | 
|---|
| 4502 |  | 
|---|
| 4503 | # Set up database fields and bind parameters.  Note only the optional fields | 
|---|
| 4504 | # (distance, weight, port, secondary parent ID) are added in the validation call above | 
|---|
| 4505 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec); | 
|---|
| 4506 | push @vallist, ($$host,$$rectype,$$val,$ttl, | 
|---|
| 4507 | ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})) ); | 
|---|
| 4508 |  | 
|---|
| 4509 | if ($defrec eq 'n') { | 
|---|
| 4510 | # locations are not for default records, silly coder! | 
|---|
| 4511 | $fields .= ",location"; | 
|---|
| 4512 | push @vallist, $location; | 
|---|
| 4513 | # timestamps are rare. | 
|---|
| 4514 | if ($stamp) { | 
|---|
| 4515 | $fields .= ",stamp,expires,stampactive"; | 
|---|
| 4516 | push @vallist, $stamp, $expires, 'y'; | 
|---|
| 4517 | } else { | 
|---|
| 4518 | $fields .= ",stampactive"; | 
|---|
| 4519 | push @vallist, 'n'; | 
|---|
| 4520 | } | 
|---|
| 4521 | } | 
|---|
| 4522 |  | 
|---|
| 4523 | # hack hack PTHUI | 
|---|
| 4524 | # need to forcibly make sure we disassociate a record with a parent it's no longer related to. | 
|---|
| 4525 | # eg, PTR records may not have a domain parent, or A/AAAA records may not have a revzone parent. | 
|---|
| 4526 | # needed for crossover types that got coerced down to "standard" types due to data changes | 
|---|
| 4527 | # need to *avoid* funky records being updated like A/AAAA records in revzones, or PTRs in forward zones. | 
|---|
| 4528 | if ($defrec eq 'n' && $oldrec->{type} > 65000) { | 
|---|
| 4529 | if ($$rectype == $reverse_typemap{PTR}) { | 
|---|
| 4530 | $fields .= ",domain_id"; | 
|---|
| 4531 | push @vallist, 0; | 
|---|
| 4532 | } | 
|---|
| 4533 | if ($$rectype == $reverse_typemap{A} || $$rectype == $reverse_typemap{AAAA}) { | 
|---|
| 4534 | $fields .= ",rdns_id"; | 
|---|
| 4535 | push @vallist, 0; | 
|---|
| 4536 | } | 
|---|
| 4537 | } | 
|---|
| 4538 | # fix fat-finger-originated record type changes | 
|---|
| 4539 | if ($$rectype == 65285) {  # delegation | 
|---|
| 4540 | $fields .= ",rdns_id" if $revrec eq 'n'; | 
|---|
| 4541 | $fields .= ",domain_id" if $revrec eq 'y'; | 
|---|
| 4542 | push @vallist, 0; | 
|---|
| 4543 | } | 
|---|
| 4544 | # ... and now make sure we *do* associate a record with the "calling" parent | 
|---|
| 4545 | if ($defrec eq 'n') { | 
|---|
| 4546 | $domid = $parid if $revrec eq 'n'; | 
|---|
| 4547 | $revid = $parid if $revrec eq 'y'; | 
|---|
| 4548 | } | 
|---|
| 4549 |  | 
|---|
| 4550 | # Put together the success log entry.  Horrible kludge from addRec() copied as-is since | 
|---|
| 4551 | # we don't know whether the passed arguments or retrieved values for domain_id and rdns_id | 
|---|
| 4552 | # will be maintained (due to "not-in-zone" validation changes) | 
|---|
| 4553 | my %logdata; | 
|---|
| 4554 | $logdata{domain_id} = $domid; | 
|---|
| 4555 | $logdata{rdns_id} = $revid; | 
|---|
| 4556 | my @ftmp = split /,/, $fields; | 
|---|
| 4557 | for (my $i=0; $i <= $#vallist; $i++) { | 
|---|
| 4558 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id'; | 
|---|
| 4559 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id'; | 
|---|
| 4560 | } | 
|---|
| 4561 | $logdata{group_id} = $parid if $defrec eq 'y'; | 
|---|
| 4562 | $logdata{group_id} = $self->parentID(id => $parid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) | 
|---|
| 4563 | if $defrec eq 'n'; | 
|---|
| 4564 | $logdata{entry} = "Updated ".($defrec eq 'y' ? 'default record' : 'record')." from\n"; | 
|---|
| 4565 | # Log reverse records "naturally", since they're stored, um, unnaturally. | 
|---|
| 4566 | if ($revrec eq 'y') { | 
|---|
| 4567 | $logdata{entry} .= " '$oldrec->{val} $typemap{$oldrec->{type}} $oldrec->{host}"; | 
|---|
| 4568 | } else { | 
|---|
| 4569 | $logdata{entry} .= " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}"; | 
|---|
| 4570 | } | 
|---|
| 4571 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX'; | 
|---|
| 4572 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]" | 
|---|
| 4573 | if $typemap{$oldrec->{type}} eq 'SRV'; | 
|---|
| 4574 | $logdata{entry} .= "', TTL $oldrec->{ttl}"; | 
|---|
| 4575 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location}; | 
|---|
| 4576 | $logdata{entry} .= ($oldrec->{expires} ? ', expires at ' : ', valid after ').$oldrec->{stamp} | 
|---|
| 4577 | if $oldrec->{stampactive}; | 
|---|
| 4578 | $logdata{entry} .= "\nto\n"; | 
|---|
| 4579 | # Log reverse records "naturally", since they're stored, um, unnaturally. | 
|---|
| 4580 | if ($revrec eq 'y') { | 
|---|
| 4581 | $logdata{entry} .= "'$$val $typemap{$$rectype} $$host"; | 
|---|
| 4582 | } else { | 
|---|
| 4583 | $logdata{entry} .= "'$$host $typemap{$$rectype} $$val"; | 
|---|
| 4584 | } | 
|---|
| 4585 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX'; | 
|---|
| 4586 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$$rectype} eq 'SRV'; | 
|---|
| 4587 | $logdata{entry} .= "', TTL $ttl"; | 
|---|
| 4588 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location; | 
|---|
| 4589 | $logdata{entry} .= ($expires ? ', expires at ' : ', valid after ').$stamp if $stamp; | 
|---|
| 4590 |  | 
|---|
| 4591 | local $dbh->{AutoCommit} = 0; | 
|---|
| 4592 | local $dbh->{RaiseError} = 1; | 
|---|
| 4593 |  | 
|---|
| 4594 | # Fiddle the field list into something suitable for updates | 
|---|
| 4595 | $fields =~ s/,/=?,/g; | 
|---|
| 4596 | $fields .= "=?"; | 
|---|
| 4597 |  | 
|---|
| 4598 | eval { | 
|---|
| 4599 | $dbh->do("UPDATE "._rectable($defrec,$revrec)." SET $fields WHERE record_id=?", undef, (@vallist, $id) ); | 
|---|
| 4600 | $self->_log(%logdata); | 
|---|
| 4601 | $dbh->commit; | 
|---|
| 4602 | }; | 
|---|
| 4603 | if ($@) { | 
|---|
| 4604 | my $msg = $@; | 
|---|
| 4605 | eval { $dbh->rollback; }; | 
|---|
| 4606 | if ($self->{log_failures}) { | 
|---|
| 4607 | $logdata{entry} = "Failed updating ".($defrec eq 'y' ? 'default ' : ''). | 
|---|
| 4608 | "record '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)"; | 
|---|
| 4609 | $self->_log(%logdata); | 
|---|
| 4610 | $dbh->commit; | 
|---|
| 4611 | } | 
|---|
| 4612 | return ('FAIL', $msg); | 
|---|
| 4613 | } | 
|---|
| 4614 |  | 
|---|
| 4615 | $resultstr = $logdata{entry}; | 
|---|
| 4616 | return ($retcode, $retmsg); | 
|---|
| 4617 | } # end updateRec() | 
|---|
| 4618 |  | 
|---|
| 4619 |  | 
|---|
| 4620 | ## DNSDB::downconvert() | 
|---|
| 4621 | # A mostly internal (not exported) semiutilty sub to downconvert from pseudotype <x> | 
|---|
| 4622 | # to a compatible component type.  Only a handful of operations are valid, anything | 
|---|
| 4623 | # else is a null-op. | 
|---|
| 4624 | # Takes the record ID and the new type.  Returns boolean. | 
|---|
| 4625 | sub downconvert { | 
|---|
| 4626 | my $self = shift; | 
|---|
| 4627 | my $dbh = $self->{dbh}; | 
|---|
| 4628 | my $recid = shift; | 
|---|
| 4629 | my $newtype = shift; | 
|---|
| 4630 |  | 
|---|
| 4631 | # also, only work on live records;  little to no value trying to do this on default records. | 
|---|
| 4632 | my $rec = $self->getRecLine('n', 'y', $recid); | 
|---|
| 4633 |  | 
|---|
| 4634 | # hm? | 
|---|
| 4635 | #return 1 if !$rec; | 
|---|
| 4636 |  | 
|---|
| 4637 | return 1 if $rec->{type} < 65000;     # Only the reverse-record pseudotypes can be downconverted | 
|---|
| 4638 | return 1 if $rec->{type} == 65282;    # Nowhere to go | 
|---|
| 4639 |  | 
|---|
| 4640 | my $delpar; | 
|---|
| 4641 | my @sqlargs; | 
|---|
| 4642 | if ($rec->{type} == 65280) { | 
|---|
| 4643 | return 1 if $newtype != 1 && $newtype != 12; | 
|---|
| 4644 | $delpar = ($newtype == 1 ? 'rdns_id' : 'domain_id'); | 
|---|
| 4645 | push @sqlargs, 0, $newtype, $recid; | 
|---|
| 4646 | } elsif ($rec->{type} == 65281) { | 
|---|
| 4647 | return 1 if $newtype != 28 && $newtype != 12; | 
|---|
| 4648 | $delpar = ($newtype == 28 ? 'rdns_id' : 'domain_id'); | 
|---|
| 4649 | push @sqlargs, 0, $newtype, $recid; | 
|---|
| 4650 | } elsif ($rec->{type} == 65283) { | 
|---|
| 4651 | return 1 if $newtype != 65282; | 
|---|
| 4652 | $delpar = 'rdns_id'; | 
|---|
| 4653 | } elsif ($rec->{type} == 65284) { | 
|---|
| 4654 | return 1 if $newtype != 65282; | 
|---|
| 4655 | $delpar = 'rdns_id'; | 
|---|
| 4656 | } else { | 
|---|
| 4657 | # Your llama is on fire. | 
|---|
| 4658 | } | 
|---|
| 4659 |  | 
|---|
| 4660 | local $dbh->{AutoCommit} = 0; | 
|---|
| 4661 | local $dbh->{RaiseError} = 1; | 
|---|
| 4662 |  | 
|---|
| 4663 | eval { | 
|---|
| 4664 | $dbh->do("UPDATE records SET $delpar = ?, type = ? WHERE record_id = ?", undef, @sqlargs); | 
|---|
| 4665 | $self->_log(domain_id => $rec->{domain_id}, rdns_id => $rec->{rdns_id}, | 
|---|
| 4666 | group_id => $self->parentID(id => $rec->{rdns_id}, type => 'revzone', revrec => 'y'), | 
|---|
| 4667 | entry => "'$rec->{host} $typemap{$rec->{type}} $rec->{val}' downconverted to ". | 
|---|
| 4668 | "'$rec->{host} $typemap{$newtype} $rec->{val}'"); | 
|---|
| 4669 | $dbh->commit; | 
|---|
| 4670 | }; | 
|---|
| 4671 | if ($@) { | 
|---|
| 4672 | $errstr = $@; | 
|---|
| 4673 | eval { $dbh->rollback; }; | 
|---|
| 4674 | return 0; | 
|---|
| 4675 | } | 
|---|
| 4676 | return 1; | 
|---|
| 4677 | } # end downconvert() | 
|---|
| 4678 |  | 
|---|
| 4679 |  | 
|---|
| 4680 | ## DNSDB::delRec() | 
|---|
| 4681 | # Delete a record. | 
|---|
| 4682 | # Takes a default/live flag, forward/reverse flag, and the ID of the record to delete. | 
|---|
| 4683 | sub delRec { | 
|---|
| 4684 | $errstr = ''; | 
|---|
| 4685 | my $self = shift; | 
|---|
| 4686 | my $dbh = $self->{dbh}; | 
|---|
| 4687 | my $defrec = shift; | 
|---|
| 4688 | my $revrec = shift; | 
|---|
| 4689 | my $id = shift; | 
|---|
| 4690 |  | 
|---|
| 4691 | my $oldrec = $self->getRecLine($defrec, $revrec, $id); | 
|---|
| 4692 |  | 
|---|
| 4693 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 4694 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 4695 | local $dbh->{AutoCommit} = 0; | 
|---|
| 4696 | local $dbh->{RaiseError} = 1; | 
|---|
| 4697 |  | 
|---|
| 4698 | # Put together the log entry | 
|---|
| 4699 | my %logdata; | 
|---|
| 4700 | $logdata{domain_id} = $oldrec->{domain_id}; | 
|---|
| 4701 | $logdata{rdns_id} = $oldrec->{rdns_id}; | 
|---|
| 4702 | $logdata{group_id} = $oldrec->{group_id} if $defrec eq 'y'; | 
|---|
| 4703 | $logdata{group_id} = $self->parentID(id => ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id}), | 
|---|
| 4704 | type => 'domain', revrec => $revrec) | 
|---|
| 4705 | if $defrec eq 'n'; | 
|---|
| 4706 | $logdata{entry} = "Deleted ".($defrec eq 'y' ? 'default record ' : 'record '). | 
|---|
| 4707 | "'$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}"; | 
|---|
| 4708 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX'; | 
|---|
| 4709 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]" | 
|---|
| 4710 | if $typemap{$oldrec->{type}} eq 'SRV'; | 
|---|
| 4711 | $logdata{entry} .= "', TTL $oldrec->{ttl}"; | 
|---|
| 4712 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location}; | 
|---|
| 4713 |  | 
|---|
| 4714 | eval { | 
|---|
| 4715 | my $sth = $dbh->do("DELETE FROM "._rectable($defrec,$revrec)." WHERE record_id=?", undef, ($id)); | 
|---|
| 4716 | $self->_log(%logdata); | 
|---|
| 4717 | $dbh->commit; | 
|---|
| 4718 | }; | 
|---|
| 4719 | if ($@) { | 
|---|
| 4720 | my $msg = $@; | 
|---|
| 4721 | eval { $dbh->rollback; }; | 
|---|
| 4722 | if ($self->{log_failures}) { | 
|---|
| 4723 | $logdata{entry} = "Error deleting ".($defrec eq 'y' ? 'default record' : 'record'). | 
|---|
| 4724 | " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)"; | 
|---|
| 4725 | $self->_log(%logdata); | 
|---|
| 4726 | $dbh->commit; | 
|---|
| 4727 | } | 
|---|
| 4728 | return ('FAIL', $msg); | 
|---|
| 4729 | } | 
|---|
| 4730 |  | 
|---|
| 4731 | return ('OK',$logdata{entry}); | 
|---|
| 4732 | } # end delRec() | 
|---|
| 4733 |  | 
|---|
| 4734 |  | 
|---|
| 4735 | ## DNSDB::getLogCount() | 
|---|
| 4736 | # Get a count of log entries | 
|---|
| 4737 | # Takes a database handle and a hash containing at least: | 
|---|
| 4738 | # - Entity ID and entity type as the primary log "slice" | 
|---|
| 4739 | sub getLogCount { | 
|---|
| 4740 | my $self = shift; | 
|---|
| 4741 | my $dbh = $self->{dbh}; | 
|---|
| 4742 |  | 
|---|
| 4743 | my %args = @_; | 
|---|
| 4744 |  | 
|---|
| 4745 | my @filterargs; | 
|---|
| 4746 | ##fixme:  which fields do we want to filter on? | 
|---|
| 4747 | # push @filterargs, | 
|---|
| 4748 |  | 
|---|
| 4749 | $errstr = 'Missing primary parent ID and/or type'; | 
|---|
| 4750 | # fail early if we don't have a "prime" ID to look for log entries for | 
|---|
| 4751 | return if !$args{id}; | 
|---|
| 4752 |  | 
|---|
| 4753 | # or if the prime id type is missing or invalid | 
|---|
| 4754 | return if !$args{logtype}; | 
|---|
| 4755 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns';       # hack pthui | 
|---|
| 4756 | $args{logtype} = 'domain' if $args{logtype} eq 'dom';         # hack pthui | 
|---|
| 4757 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user'); | 
|---|
| 4758 |  | 
|---|
| 4759 | my $sql = "SELECT count(*) FROM log ". | 
|---|
| 4760 | "WHERE $id_col{$args{logtype}}=?". | 
|---|
| 4761 | ($args{filter} ? " AND entry ~* ?" : ''); | 
|---|
| 4762 | my ($count) = $dbh->selectrow_array($sql, undef, ($args{id}, @filterargs) ); | 
|---|
| 4763 | $errstr = $dbh->errstr if !$count; | 
|---|
| 4764 | return $count; | 
|---|
| 4765 | } # end getLogCount() | 
|---|
| 4766 |  | 
|---|
| 4767 |  | 
|---|
| 4768 | ## DNSDB::getLogEntries() | 
|---|
| 4769 | # Get a list of log entries | 
|---|
| 4770 | # Takes arguments as with getLogCount() above, plus optional: | 
|---|
| 4771 | # - sort field | 
|---|
| 4772 | # - sort order | 
|---|
| 4773 | # - offset for pagination | 
|---|
| 4774 | sub getLogEntries { | 
|---|
| 4775 | my $self = shift; | 
|---|
| 4776 | my $dbh = $self->{dbh}; | 
|---|
| 4777 |  | 
|---|
| 4778 | my %args = @_; | 
|---|
| 4779 |  | 
|---|
| 4780 | my @filterargs; | 
|---|
| 4781 |  | 
|---|
| 4782 | # fail early if we don't have a "prime" ID to look for log entries for | 
|---|
| 4783 | return if !$args{id}; | 
|---|
| 4784 |  | 
|---|
| 4785 | # or if the prime id type is missing or invalid | 
|---|
| 4786 | return if !$args{logtype}; | 
|---|
| 4787 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns';       # hack pthui | 
|---|
| 4788 | $args{logtype} = 'domain' if $args{logtype} eq 'dom';         # hack pthui | 
|---|
| 4789 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user'); | 
|---|
| 4790 |  | 
|---|
| 4791 | # Sorting defaults | 
|---|
| 4792 | $args{sortorder} = 'DESC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC'); | 
|---|
| 4793 | $args{sortby} = 'stamp' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/; | 
|---|
| 4794 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/; | 
|---|
| 4795 |  | 
|---|
| 4796 | my %sortmap = (fname => 'name', username => 'email', entry => 'entry', stamp => 'stamp'); | 
|---|
| 4797 | $args{sortby} = $sortmap{$args{sortby}}; | 
|---|
| 4798 |  | 
|---|
| 4799 | my $sql = "SELECT user_id AS userid, email AS useremail, name AS userfname, entry AS logentry, ". | 
|---|
| 4800 | "date_trunc('second',stamp) AS logtime ". | 
|---|
| 4801 | "FROM log ". | 
|---|
| 4802 | "WHERE $id_col{$args{logtype}}=?". | 
|---|
| 4803 | ($args{filter} ? " AND entry ~* ?" : ''). | 
|---|
| 4804 | " ORDER BY $args{sortby} $args{sortorder}, log_id $args{sortorder}". | 
|---|
| 4805 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage}); | 
|---|
| 4806 | my $loglist = $dbh->selectall_arrayref($sql, { Slice => {} }, ($args{id}, @filterargs) ); | 
|---|
| 4807 | $errstr = $dbh->errstr if !$loglist; | 
|---|
| 4808 | return $loglist; | 
|---|
| 4809 | } # end getLogEntries() | 
|---|
| 4810 |  | 
|---|
| 4811 |  | 
|---|
| 4812 | ## DNSDB::getRevPattern() | 
|---|
| 4813 | # Get the narrowest template pattern applicable to a passed CIDR address (may be a netblock or an IP) | 
|---|
| 4814 | sub getRevPattern { | 
|---|
| 4815 | my $self = shift; | 
|---|
| 4816 | my $dbh = $self->{dbh}; | 
|---|
| 4817 | my $cidr = shift; | 
|---|
| 4818 | my $group = shift || 1;       # just in case | 
|---|
| 4819 |  | 
|---|
| 4820 | # for speed!  Casting and comparing even ~7K records takes ~2.5s, so narrow it down to one revzone first. | 
|---|
| 4821 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >>= ?", | 
|---|
| 4822 | undef, ($cidr) ); | 
|---|
| 4823 |  | 
|---|
| 4824 | ##fixme?  may need to narrow things down more by octet-chopping and doing text comparisons before casting. | 
|---|
| 4825 | my ($revpatt) = $dbh->selectrow_array("SELECT host FROM records ". | 
|---|
| 4826 | "WHERE (type in (12,65280,65281,65282,65283,65284)) AND rdns_id = ? AND inetlazy(val) >>= ? ". | 
|---|
| 4827 | "ORDER BY inetlazy(val) DESC LIMIT 1", undef, ($revid, $cidr) ); | 
|---|
| 4828 | return $revpatt; | 
|---|
| 4829 | } # end getRevPattern() | 
|---|
| 4830 |  | 
|---|
| 4831 |  | 
|---|
| 4832 | ## DNSDB::getRevSet() | 
|---|
| 4833 | # Return the unique per-IP reverse hostnames, if any, for the passed | 
|---|
| 4834 | # CIDR address (may be a netblock or an IP) | 
|---|
| 4835 | sub getRevSet { | 
|---|
| 4836 | my $self = shift; | 
|---|
| 4837 | my $dbh = $self->{dbh}; | 
|---|
| 4838 | my $cidr = shift; | 
|---|
| 4839 | my $group = shift || 1;       # just in case | 
|---|
| 4840 |  | 
|---|
| 4841 | # for speed!  Casting and comparing even ~7K records takes ~2.5s, so narrow it down to one revzone first. | 
|---|
| 4842 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >>= ?", | 
|---|
| 4843 | undef, ($cidr) ); | 
|---|
| 4844 |  | 
|---|
| 4845 | $cidr = new NetAddr::IP $cidr; | 
|---|
| 4846 | if ($cidr->num > 256) {       # should also catch v6! | 
|---|
| 4847 | # Even reverse entries for a v4 /24 of IPs is a bit much.  I don't expect | 
|---|
| 4848 | # there to be a sane reason to retrive more than a /27 at once, really. | 
|---|
| 4849 | # v6 is going to be hairy no matter how you slice it. | 
|---|
| 4850 | $errstr = "Reverse hostname detail range too large"; | 
|---|
| 4851 | return; | 
|---|
| 4852 | } | 
|---|
| 4853 |  | 
|---|
| 4854 | my $sth = $dbh->prepare("SELECT val, host FROM records ". | 
|---|
| 4855 | "WHERE (type in (12,65280,65281,65282,65283,65284)) AND rdns_id = ? AND inetlazy(val) = ?"); | 
|---|
| 4856 |  | 
|---|
| 4857 | my @ret; | 
|---|
| 4858 | foreach my $ip (@{$cidr->splitref()}) { | 
|---|
| 4859 | $sth->execute($revid, $ip); | 
|---|
| 4860 | my @data = $sth->fetchrow_array(); | 
|---|
| 4861 | my %row; | 
|---|
| 4862 | if (@data) { | 
|---|
| 4863 | $row{r_ip} = $data[0]; | 
|---|
| 4864 | $row{iphost} = $data[1]; | 
|---|
| 4865 | } else { | 
|---|
| 4866 | $row{r_ip} = $ip->addr; | 
|---|
| 4867 | $row{iphost} = ''; | 
|---|
| 4868 | } | 
|---|
| 4869 | push @ret, \%row; | 
|---|
| 4870 | } | 
|---|
| 4871 |  | 
|---|
| 4872 | return \@ret; | 
|---|
| 4873 | } # end getRevSet() | 
|---|
| 4874 |  | 
|---|
| 4875 |  | 
|---|
| 4876 | ## DNSDB::getTypelist() | 
|---|
| 4877 | # Get a list of record types for various UI dropdowns | 
|---|
| 4878 | # Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A) | 
|---|
| 4879 | # Returns an arrayref to list of hashrefs perfect for HTML::Template | 
|---|
| 4880 | sub getTypelist { | 
|---|
| 4881 | my $self = shift; | 
|---|
| 4882 | my $dbh = $self->{dbh}; | 
|---|
| 4883 | my $recgroup = shift; | 
|---|
| 4884 | my $type = shift || $reverse_typemap{A}; | 
|---|
| 4885 |  | 
|---|
| 4886 | # also accepting $webvar{revrec}! | 
|---|
| 4887 | $recgroup = 'f' if $recgroup eq 'n'; | 
|---|
| 4888 | $recgroup = 'r' if $recgroup eq 'y'; | 
|---|
| 4889 |  | 
|---|
| 4890 | my $sql = "SELECT val,name FROM rectypes WHERE "; | 
|---|
| 4891 | if ($recgroup eq 'r') { | 
|---|
| 4892 | # reverse zone types | 
|---|
| 4893 | $sql .= "stdflag=2 OR stdflag=3"; | 
|---|
| 4894 | } elsif ($recgroup eq 'l') { | 
|---|
| 4895 | # DNS lookup types.  Note we avoid our custom types >= 65280, since those are entirely internal. | 
|---|
| 4896 | $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280"; | 
|---|
| 4897 | } else { | 
|---|
| 4898 | # default;  forward zone types.  technically $type eq 'f' but not worth the error message. | 
|---|
| 4899 | $sql .= "stdflag=1 OR stdflag=2"; | 
|---|
| 4900 | $sql .= " AND val < 65280" if $recgroup eq 'fo';  # An extra flag to trim off the pseudotypes as well. | 
|---|
| 4901 | } | 
|---|
| 4902 | $sql .= " ORDER BY listorder"; | 
|---|
| 4903 |  | 
|---|
| 4904 | my $sth = $dbh->prepare($sql); | 
|---|
| 4905 | $sth->execute; | 
|---|
| 4906 | my @typelist; | 
|---|
| 4907 | # track whether the passed type is in the list at all.  allows you to edit a record | 
|---|
| 4908 | # that wouldn't otherwise be generally available in that zone (typically, reverse zones) | 
|---|
| 4909 | # without changing its type (accidentally or otherwise) | 
|---|
| 4910 | my $selflag = 0; | 
|---|
| 4911 | while (my ($rval,$rname) = $sth->fetchrow_array()) { | 
|---|
| 4912 | my %row = ( recval => $rval, recname => $rname ); | 
|---|
| 4913 | if ($rval == $type) { | 
|---|
| 4914 | $row{tselect} = 1; | 
|---|
| 4915 | $selflag = 1; | 
|---|
| 4916 | } | 
|---|
| 4917 | push @typelist, \%row; | 
|---|
| 4918 | } | 
|---|
| 4919 |  | 
|---|
| 4920 | # add the passed type if it wasn't in the list | 
|---|
| 4921 | if (!$selflag) { | 
|---|
| 4922 | my %row = ( recval => $type, recname => $typemap{$type}, tselect => 1 ); | 
|---|
| 4923 | push @typelist, \%row; | 
|---|
| 4924 | } | 
|---|
| 4925 |  | 
|---|
| 4926 | # Add SOA on lookups since it's not listed in other dropdowns. | 
|---|
| 4927 | if ($recgroup eq 'l') { | 
|---|
| 4928 | my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' ); | 
|---|
| 4929 | $row{tselect} = 1 if $reverse_typemap{SOA} == $type; | 
|---|
| 4930 | push @typelist, \%row; | 
|---|
| 4931 | } | 
|---|
| 4932 |  | 
|---|
| 4933 | return \@typelist; | 
|---|
| 4934 | } # end getTypelist() | 
|---|
| 4935 |  | 
|---|
| 4936 |  | 
|---|
| 4937 | ## DNSDB::parentID() | 
|---|
| 4938 | # Get ID of entity that is nearest parent to requested id | 
|---|
| 4939 | # Takes a database handle and a hash of entity ID, entity type, optional parent type flag | 
|---|
| 4940 | # (domain/reverse zone or group), and optional default/live and forward/reverse flags | 
|---|
| 4941 | # Returns the ID or undef on failure | 
|---|
| 4942 | sub parentID { | 
|---|
| 4943 | my $self = shift; | 
|---|
| 4944 | my $dbh = $self->{dbh}; | 
|---|
| 4945 |  | 
|---|
| 4946 | my %args = @_; | 
|---|
| 4947 |  | 
|---|
| 4948 | # clean up defrec and revrec.  default to live record, forward zone | 
|---|
| 4949 | $args{defrec} = 'n' if !$args{defrec}; | 
|---|
| 4950 | $args{revrec} = 'n' if !$args{revrec}; | 
|---|
| 4951 |  | 
|---|
| 4952 | # clean up the parent-type.  Set it to group if not set | 
|---|
| 4953 | $args{partype} = 'group' if !$args{partype}; | 
|---|
| 4954 |  | 
|---|
| 4955 | # allow callers to be lazy with type | 
|---|
| 4956 | $args{type} = 'revzone' if $args{type} eq 'domain' && $args{revrec} eq 'y'; | 
|---|
| 4957 |  | 
|---|
| 4958 | if ($par_type{$args{partype}} eq 'domain' || $par_type{$args{partype}} eq 'revzone') { | 
|---|
| 4959 | # only live records can have a domain/zone parent | 
|---|
| 4960 | return unless ($args{type} eq 'record' && $args{defrec} eq 'n'); | 
|---|
| 4961 | my $result = $dbh->selectrow_hashref("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id'). | 
|---|
| 4962 | " FROM records WHERE record_id = ?", | 
|---|
| 4963 | undef, ($args{id}) ) or return; | 
|---|
| 4964 | return $result; | 
|---|
| 4965 | } else { | 
|---|
| 4966 | # snag some arguments that will either fall through or be overwritten to save some code duplication | 
|---|
| 4967 | my $tmpid = $args{id}; | 
|---|
| 4968 | my $type = $args{type}; | 
|---|
| 4969 | if ($type eq 'record' && $args{defrec} eq 'n') { | 
|---|
| 4970 | # Live records go through the records table first. | 
|---|
| 4971 | ($tmpid) = $dbh->selectrow_array("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id'). | 
|---|
| 4972 | " FROM records WHERE record_id = ?", | 
|---|
| 4973 | undef, ($args{id}) ) or return; | 
|---|
| 4974 | $type = ($args{revrec} eq 'n' ? 'domain' : 'revzone'); | 
|---|
| 4975 | } | 
|---|
| 4976 | my ($result) = $dbh->selectrow_array("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?", | 
|---|
| 4977 | undef, ($tmpid) ); | 
|---|
| 4978 | return $result; | 
|---|
| 4979 | } | 
|---|
| 4980 | # should be impossible to get here with even remotely sane arguments | 
|---|
| 4981 | return; | 
|---|
| 4982 | } # end parentID() | 
|---|
| 4983 |  | 
|---|
| 4984 |  | 
|---|
| 4985 | ## DNSDB::isParent() | 
|---|
| 4986 | # Returns true if $id1 is a parent of $id2, false otherwise | 
|---|
| 4987 | sub isParent { | 
|---|
| 4988 | my $self = shift; | 
|---|
| 4989 | my $dbh = $self->{dbh}; | 
|---|
| 4990 | my $id1 = shift; | 
|---|
| 4991 | my $type1 = shift; | 
|---|
| 4992 | my $id2 = shift; | 
|---|
| 4993 | my $type2 = shift; | 
|---|
| 4994 | ##todo:  immediate, secondary, full (default) | 
|---|
| 4995 |  | 
|---|
| 4996 | # Return false on invalid types | 
|---|
| 4997 | return 0 if !grep /^$type1$/, ('record','defrec','defrevrec','user','domain','revzone','group'); | 
|---|
| 4998 | return 0 if !grep /^$type2$/, ('record','defrec','defrevrec','user','domain','revzone','group'); | 
|---|
| 4999 |  | 
|---|
| 5000 | # Return false on impossible relations | 
|---|
| 5001 | return 0 if $type1 eq 'record';       # nothing may be a child of a record | 
|---|
| 5002 | return 0 if $type1 eq 'defrec';       # nothing may be a child of a record | 
|---|
| 5003 | return 0 if $type1 eq 'defrevrec';    # nothing may be a child of a record | 
|---|
| 5004 | return 0 if $type1 eq 'user';         # nothing may be child of a user | 
|---|
| 5005 | return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record | 
|---|
| 5006 | return 0 if $type1 eq 'revzone' && $type2 ne 'record';# reverse zone may not be a parent of anything other than a record | 
|---|
| 5007 |  | 
|---|
| 5008 | # ennnhhhh....  if we're passed an id of 0, it will never be found.  usual | 
|---|
| 5009 | # case would be the UI creating a new <thing>, and so we don't have an ID for | 
|---|
| 5010 | # <thing> to look up yet.  in that case the UI should check the parent as well. | 
|---|
| 5011 | return 0 if $id1 == 0;        # nothing can have a parent id of 0 | 
|---|
| 5012 | return 1 if $id2 == 0;        # anything could have a child id of 0 (or "unknown") | 
|---|
| 5013 |  | 
|---|
| 5014 | # group 1 is the ultimate root parent | 
|---|
| 5015 | return 1 if $type1 eq 'group' && $id1 == 1; | 
|---|
| 5016 |  | 
|---|
| 5017 | # groups are always (a) parent of themselves | 
|---|
| 5018 | return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2; | 
|---|
| 5019 |  | 
|---|
| 5020 | my $id = $id2; | 
|---|
| 5021 | my $type = $type2; | 
|---|
| 5022 | my $foundparent = 0; | 
|---|
| 5023 |  | 
|---|
| 5024 | # Records are the only entity with two possible parents.  We need to split the parent checks on | 
|---|
| 5025 | # domain/rdns. | 
|---|
| 5026 | if ($type eq 'record') { | 
|---|
| 5027 | my ($dom,$rdns) = $dbh->selectrow_array("SELECT domain_id,rdns_id FROM records WHERE record_id=?", | 
|---|
| 5028 | undef, ($id)); | 
|---|
| 5029 | # check immediate parent against request | 
|---|
| 5030 | return 1 if $type1 eq 'domain' && $id1 == $dom; | 
|---|
| 5031 | return 1 if $type1 eq 'revzone' && $id1 == $rdns; | 
|---|
| 5032 | # if request is group, check *both* parents.  Only check if the parent is nonzero though. | 
|---|
| 5033 | return 1 if $dom && $self->isParent($id1, $type1, $dom, 'domain'); | 
|---|
| 5034 | return 1 if $rdns && $self->isParent($id1, $type1, $rdns, 'revzone'); | 
|---|
| 5035 | # exit here since we've executed the loop below by proxy in the above recursive calls. | 
|---|
| 5036 | return 0; | 
|---|
| 5037 | } | 
|---|
| 5038 |  | 
|---|
| 5039 | # almost the same loop as getParents() above | 
|---|
| 5040 | my $limiter = 0; | 
|---|
| 5041 | while (1) { | 
|---|
| 5042 | my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?"; | 
|---|
| 5043 | my $result = $dbh->selectrow_hashref($sql, | 
|---|
| 5044 | undef, ($id) ); | 
|---|
| 5045 | if (!$result) { | 
|---|
| 5046 | $limiter++; | 
|---|
| 5047 | ##fixme:  how often will this happen on a live site?  fail at max limiter <n>? | 
|---|
| 5048 | # 2013/10/22 only seems to happen when you request an entity that doesn't exist. | 
|---|
| 5049 | warn "no results looking for $sql with id $id (depth $limiter)\n"; | 
|---|
| 5050 | last; | 
|---|
| 5051 | } | 
|---|
| 5052 | if ($result && $result->{$par_col{$type}} == $id1) { | 
|---|
| 5053 | $foundparent = 1; | 
|---|
| 5054 | last; | 
|---|
| 5055 | } else { | 
|---|
| 5056 | ##fixme: do we care about trying to return a "no such record/domain/user/group" error? | 
|---|
| 5057 | # should be impossible to create an inconsistent DB just with API calls. | 
|---|
| 5058 | warn $dbh->errstr." $sql, $id" if $dbh->errstr; | 
|---|
| 5059 | } | 
|---|
| 5060 | # group 1 is its own parent.  need this here more to break strange loops than for detecting a parent | 
|---|
| 5061 | last if $result->{$par_col{$type}} == 1; | 
|---|
| 5062 | $id = $result->{$par_col{$type}}; | 
|---|
| 5063 | $type = $par_type{$type}; | 
|---|
| 5064 | } | 
|---|
| 5065 |  | 
|---|
| 5066 | return $foundparent; | 
|---|
| 5067 | } # end isParent() | 
|---|
| 5068 |  | 
|---|
| 5069 |  | 
|---|
| 5070 | ## DNSDB::zoneStatus() | 
|---|
| 5071 | # Returns and optionally sets a zone's status | 
|---|
| 5072 | # Takes a database handle, domain/revzone ID, forward/reverse flag, and optionally a status argument | 
|---|
| 5073 | # Returns status, or undef on errors. | 
|---|
| 5074 | sub zoneStatus { | 
|---|
| 5075 | my $self = shift; | 
|---|
| 5076 | my $dbh = $self->{dbh}; | 
|---|
| 5077 | my $id = shift; | 
|---|
| 5078 | my $revrec = shift; | 
|---|
| 5079 | my $newstatus = shift || 'mu'; | 
|---|
| 5080 |  | 
|---|
| 5081 | return undef if $id !~ /^\d+$/; | 
|---|
| 5082 |  | 
|---|
| 5083 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 5084 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 5085 | local $dbh->{AutoCommit} = 0; | 
|---|
| 5086 | local $dbh->{RaiseError} = 1; | 
|---|
| 5087 |  | 
|---|
| 5088 | if ($newstatus ne 'mu') { | 
|---|
| 5089 | # ooo, fun!  let's see what we were passed for status | 
|---|
| 5090 | eval { | 
|---|
| 5091 | $newstatus = 0 if $newstatus eq 'domoff'; | 
|---|
| 5092 | $newstatus = 1 if $newstatus eq 'domon'; | 
|---|
| 5093 | $dbh->do("UPDATE ".($revrec eq 'n' ? 'domains' : 'revzones')." SET status=? WHERE ". | 
|---|
| 5094 | ($revrec eq 'n' ? 'domain_id' : 'rdns_id')."=?", undef, ($newstatus,$id) ); | 
|---|
| 5095 |  | 
|---|
| 5096 | ##fixme  switch to more consise "Enabled <domain"/"Disabled <domain>" as with users? | 
|---|
| 5097 | $resultstr = "Changed ".($revrec eq 'n' ? $self->domainName($id) : $self->revName($id)). | 
|---|
| 5098 | " state to ".($newstatus ? 'active' : 'inactive'); | 
|---|
| 5099 |  | 
|---|
| 5100 | my %loghash; | 
|---|
| 5101 | $loghash{domain_id} = $id if $revrec eq 'n'; | 
|---|
| 5102 | $loghash{rdns_id} = $id if $revrec eq 'y'; | 
|---|
| 5103 | $loghash{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec); | 
|---|
| 5104 | $loghash{entry} = $resultstr; | 
|---|
| 5105 | $self->_log(%loghash); | 
|---|
| 5106 |  | 
|---|
| 5107 | $dbh->commit; | 
|---|
| 5108 | }; | 
|---|
| 5109 | if ($@) { | 
|---|
| 5110 | my $msg = $@; | 
|---|
| 5111 | eval { $dbh->rollback; }; | 
|---|
| 5112 | $resultstr = ''; | 
|---|
| 5113 | $errstr = $msg; | 
|---|
| 5114 | return; | 
|---|
| 5115 | } | 
|---|
| 5116 | } | 
|---|
| 5117 |  | 
|---|
| 5118 | my ($status) = $dbh->selectrow_array("SELECT status FROM ". | 
|---|
| 5119 | ($revrec eq 'n' ? "domains WHERE domain_id=?" : "revzones WHERE rdns_id=?"), | 
|---|
| 5120 | undef, ($id) ); | 
|---|
| 5121 | return $status; | 
|---|
| 5122 | } # end zoneStatus() | 
|---|
| 5123 |  | 
|---|
| 5124 |  | 
|---|
| 5125 | ## DNSDB::getZonesByCIDR() | 
|---|
| 5126 | # Get a list of zone names and IDs that records for a passed CIDR block are within. | 
|---|
| 5127 | sub getZonesByCIDR { | 
|---|
| 5128 | my $self = shift; | 
|---|
| 5129 | my $dbh = $self->{dbh}; | 
|---|
| 5130 | my %args = @_; | 
|---|
| 5131 |  | 
|---|
| 5132 | my $result = $dbh->selectall_arrayref("SELECT rdns_id,revnet FROM revzones WHERE revnet >>= ? OR revnet <<= ?", | 
|---|
| 5133 | { Slice => {} }, ($args{cidr}, $args{cidr}) ); | 
|---|
| 5134 | return $result; | 
|---|
| 5135 | } # end getZonesByCIDR() | 
|---|
| 5136 |  | 
|---|
| 5137 |  | 
|---|
| 5138 | ## DNSDB::importAXFR | 
|---|
| 5139 | # Import a domain via AXFR | 
|---|
| 5140 | # Takes AXFR host, domain to transfer, group to put the domain in, | 
|---|
| 5141 | # and an optional hash containing: | 
|---|
| 5142 | #  status - active/inactive state flag (defaults to active) | 
|---|
| 5143 | #  rwsoa - overwrite-SOA flag (defaults to off) | 
|---|
| 5144 | #  rwns - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records) | 
|---|
| 5145 | #  merge - flag to automerge A or AAAA records with matching PTR records | 
|---|
| 5146 | # Returns a status code (OK, WARN, or FAIL) and message - message should be blank | 
|---|
| 5147 | # if status is OK, but WARN includes conditions that are not fatal but should | 
|---|
| 5148 | # really be reported. | 
|---|
| 5149 | sub importAXFR { | 
|---|
| 5150 | my $self = shift; | 
|---|
| 5151 | my $dbh = $self->{dbh}; | 
|---|
| 5152 | my $ifrom_in = shift; | 
|---|
| 5153 | my $zone = shift; | 
|---|
| 5154 | my $group = shift; | 
|---|
| 5155 |  | 
|---|
| 5156 | my %args = @_; | 
|---|
| 5157 |  | 
|---|
| 5158 | ##fixme:  add mode to delete&replace, merge+overwrite, merge new? | 
|---|
| 5159 |  | 
|---|
| 5160 | $args{status} = (defined($args{status}) ? $args{status} : 0); | 
|---|
| 5161 | $args{status} = 1 if $args{status} eq 'on'; | 
|---|
| 5162 |  | 
|---|
| 5163 | my $nrecs = 0; | 
|---|
| 5164 | my $soaflag = 0; | 
|---|
| 5165 | my $nsflag = 0; | 
|---|
| 5166 | my $warnmsg = ''; | 
|---|
| 5167 | my $ifrom; | 
|---|
| 5168 |  | 
|---|
| 5169 | my $rev = 'n'; | 
|---|
| 5170 | my $code = 'OK'; | 
|---|
| 5171 | my $msg = 'foobar?'; | 
|---|
| 5172 |  | 
|---|
| 5173 | # choke on possible bad setting in ifrom | 
|---|
| 5174 | # IPv4 and v6, and valid hostnames! | 
|---|
| 5175 | ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i); | 
|---|
| 5176 | return ('FAIL', "Bad AXFR source host $ifrom") | 
|---|
| 5177 | unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i); | 
|---|
| 5178 |  | 
|---|
| 5179 | my $errmsg; | 
|---|
| 5180 |  | 
|---|
| 5181 | my $zone_id; | 
|---|
| 5182 | my $domain_id = 0; | 
|---|
| 5183 | my $rdns_id = 0; | 
|---|
| 5184 | my $cidr; | 
|---|
| 5185 |  | 
|---|
| 5186 | # magic happens!  detect if we're importing a domain or a reverse zone | 
|---|
| 5187 | # while we're at it, figure out what the CIDR netblock is (if we got a .arpa) | 
|---|
| 5188 | # or what the formal .arpa zone is (if we got a CIDR netblock) | 
|---|
| 5189 | # Handles sub-octet v4 zones in the format specified in the Cricket Book, 2nd Ed, p217-218 | 
|---|
| 5190 |  | 
|---|
| 5191 | if ($zone =~ m{(?:\.arpa\.?|/\d+|^[\d.]+|^[a-fA-F0-9:]+)$}) { | 
|---|
| 5192 | # we seem to have a reverse zone | 
|---|
| 5193 | $rev = 'y'; | 
|---|
| 5194 |  | 
|---|
| 5195 | if ($zone =~ /\.arpa\.?$/) { | 
|---|
| 5196 | # we have a formal reverse zone.  call _zone2cidr and get the CIDR block. | 
|---|
| 5197 | ($code,$msg) = _zone2cidr($zone); | 
|---|
| 5198 | return ($code, $msg) if $code eq 'FAIL'; | 
|---|
| 5199 | $cidr = $msg; | 
|---|
| 5200 | } elsif ($zone =~ m|^[\d.]+/\d+$|) { | 
|---|
| 5201 | # v4 revzone, CIDR netblock | 
|---|
| 5202 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block"); | 
|---|
| 5203 | $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.'); | 
|---|
| 5204 | } elsif ($zone =~ /^[\d.]+$/) { | 
|---|
| 5205 | # v4 revzone, leading-octet format | 
|---|
| 5206 | my $mask = 32; | 
|---|
| 5207 | while ($zone !~ /^\d+\.\d+\.\d+\.\d+$/) { | 
|---|
| 5208 | $zone .= '.0'; | 
|---|
| 5209 | $mask -= 8; | 
|---|
| 5210 | } | 
|---|
| 5211 | $zone .= "/$mask"; | 
|---|
| 5212 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block"); | 
|---|
| 5213 | $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.'); | 
|---|
| 5214 | } elsif ($zone =~ m|^[a-fA-F\d:]+/\d+$|) { | 
|---|
| 5215 | # v6 revzone, CIDR netblock | 
|---|
| 5216 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block"); | 
|---|
| 5217 | return ('FAIL', "$zone is not a nibble-aligned block") if $cidr->masklen % 4 != 0; | 
|---|
| 5218 | $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.'); | 
|---|
| 5219 | } elsif ($zone =~ /^[a-fA-F\d:]+$/) { | 
|---|
| 5220 | # v6 revzone, leading-group format | 
|---|
| 5221 | $zone =~ s/::$//; | 
|---|
| 5222 | my $mask = 128; | 
|---|
| 5223 | while ($zone !~ /^(?:[a-fA-F\d]{1,4}:){7}[a-fA-F\d]$/) { | 
|---|
| 5224 | $zone .= ":0"; | 
|---|
| 5225 | $mask -= 16; | 
|---|
| 5226 | } | 
|---|
| 5227 | $zone .= "/$mask"; | 
|---|
| 5228 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block"); | 
|---|
| 5229 | $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.'); | 
|---|
| 5230 | } else { | 
|---|
| 5231 | # there is. no. else! | 
|---|
| 5232 | return ('FAIL', "Unknown zone name format '$zone'"); | 
|---|
| 5233 | } | 
|---|
| 5234 |  | 
|---|
| 5235 | # several places this can be triggered from;  better to do it once. | 
|---|
| 5236 | $warnmsg .= "Apparent sub-/64 IPv6 reverse zone\n" if $cidr->masklen > 64; | 
|---|
| 5237 |  | 
|---|
| 5238 | # quick check to start to see if we've already got one | 
|---|
| 5239 |  | 
|---|
| 5240 | ($zone_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", | 
|---|
| 5241 | undef, ("$cidr")); | 
|---|
| 5242 | $rdns_id = $zone_id; | 
|---|
| 5243 | } else { | 
|---|
| 5244 | # default to domain | 
|---|
| 5245 | ($zone_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)", | 
|---|
| 5246 | undef, ($zone)); | 
|---|
| 5247 | $domain_id = $zone_id; | 
|---|
| 5248 | } | 
|---|
| 5249 |  | 
|---|
| 5250 | return ('FAIL', ($rev eq 'n' ? 'Domain' : 'Reverse zone')." already exists") if $zone_id; | 
|---|
| 5251 |  | 
|---|
| 5252 | # little local utility sub to swap $val and $host for revzone records. | 
|---|
| 5253 | sub _revswap { | 
|---|
| 5254 | my $rechost = shift; | 
|---|
| 5255 | my $recdata = shift; | 
|---|
| 5256 |  | 
|---|
| 5257 | if ($rechost =~ /\.in-addr\.arpa\.?$/) { | 
|---|
| 5258 | $rechost =~ s/\.in-addr\.arpa\.?$//; | 
|---|
| 5259 | $rechost = join '.', reverse split /\./, $rechost; | 
|---|
| 5260 | } else { | 
|---|
| 5261 | $rechost =~ s/\.ip6\.arpa\.?$//; | 
|---|
| 5262 | my @nibs = reverse split /\./, $rechost; | 
|---|
| 5263 | $rechost = ''; | 
|---|
| 5264 | my $nc; | 
|---|
| 5265 | foreach (@nibs) { | 
|---|
| 5266 | #        # fail on multicharacter nibbles;  it's syntactically valid but no standard lookup | 
|---|
| 5267 | #        # will ever reach it, because it doesn't directly represent a real IP address. | 
|---|
| 5268 | #        return ('FAIL', "Invalid reverse v6 entry") if $_ !~ /^.$/; | 
|---|
| 5269 | $rechost.= $_; | 
|---|
| 5270 | $rechost .= ":" if ++$nc % 4 == 0 && $nc < 32; | 
|---|
| 5271 | } | 
|---|
| 5272 | $rechost .= ":" if $nc < 32 && $rechost !~ /\*$/; # close netblock records? | 
|---|
| 5273 | ##fixme:  there's a case that ends up with a partial entry here: | 
|---|
| 5274 | # ip:add:re:ss:: | 
|---|
| 5275 | # can't reproduce after letting it sit overnight after discovery.  :( | 
|---|
| 5276 | #print "$rechost\n"; | 
|---|
| 5277 | # canonicalize with NetAddr::IP | 
|---|
| 5278 | $rechost = NetAddr::IP->new($rechost)->addr unless $rechost =~ /\*$/; | 
|---|
| 5279 | } | 
|---|
| 5280 | return ($recdata,$rechost) | 
|---|
| 5281 | } | 
|---|
| 5282 |  | 
|---|
| 5283 |  | 
|---|
| 5284 | # Allow transactions, and raise an exception on errors so we can catch it later. | 
|---|
| 5285 | # Use local to make sure these get "reset" properly on exiting this block | 
|---|
| 5286 | local $dbh->{AutoCommit} = 0; | 
|---|
| 5287 | local $dbh->{RaiseError} = 1; | 
|---|
| 5288 |  | 
|---|
| 5289 | my $sth; | 
|---|
| 5290 | eval { | 
|---|
| 5291 |  | 
|---|
| 5292 | if ($rev eq 'n') { | 
|---|
| 5293 | ##fixme:  serial | 
|---|
| 5294 | $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef, | 
|---|
| 5295 | ($zone, $group, $args{status}) ); | 
|---|
| 5296 | # get domain id so we can do the records | 
|---|
| 5297 | ($zone_id) = $dbh->selectrow_array("SELECT currval('domains_domain_id_seq')"); | 
|---|
| 5298 | $domain_id = $zone_id; | 
|---|
| 5299 | $self->_log(group_id => $group, domain_id => $domain_id, | 
|---|
| 5300 | entry => "[Added ".($args{status} ? 'active' : 'inactive')." domain $zone via AXFR]"); | 
|---|
| 5301 | } else { | 
|---|
| 5302 | ##fixme:  serial | 
|---|
| 5303 | $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef, | 
|---|
| 5304 | ($cidr,$group,$args{status}) ); | 
|---|
| 5305 | # get revzone id so we can do the records | 
|---|
| 5306 | ($zone_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')"); | 
|---|
| 5307 | $rdns_id = $zone_id; | 
|---|
| 5308 | $self->_log(group_id => $group, rdns_id => $rdns_id, | 
|---|
| 5309 | entry => "[Added ".($args{status} ? 'active' : 'inactive')." reverse zone $cidr via AXFR]"); | 
|---|
| 5310 | } | 
|---|
| 5311 |  | 
|---|
| 5312 | ## bizarre DBI<->Net::DNS interaction bug: | 
|---|
| 5313 | ## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while() | 
|---|
| 5314 | ## fixed, apparently I was doing *something* odd, but not certain what it was that | 
|---|
| 5315 | ## caused a commit instead of barfing | 
|---|
| 5316 |  | 
|---|
| 5317 | my $res = Net::DNS::Resolver->new; | 
|---|
| 5318 | $res->nameservers($ifrom); | 
|---|
| 5319 | $res->axfr_start($zone) | 
|---|
| 5320 | or die "Couldn't begin AXFR\n"; | 
|---|
| 5321 |  | 
|---|
| 5322 | $sth = $dbh->prepare("INSERT INTO records (domain_id,rdns_id,host,type,val,distance,weight,port,ttl)". | 
|---|
| 5323 | " VALUES (?,?,?,?,?,?,?,?,?)"); | 
|---|
| 5324 |  | 
|---|
| 5325 | # Stash info about sub-octet v4 revzones here so we don't have | 
|---|
| 5326 | # to store the CNAMEs used to delegate a suboctet zone | 
|---|
| 5327 | # $suboct{zone}{ns}[] -> array of nameservers | 
|---|
| 5328 | # $suboct{zone}{cname}[] -> array of extant CNAMEs (Just In Case someone did something bizarre) | 
|---|
| 5329 | ## commented pending actual use of this data.  for now, we'll just | 
|---|
| 5330 | ## auto-(re)create the CNAMEs in revzones on export | 
|---|
| 5331 | #    my %suboct; | 
|---|
| 5332 |  | 
|---|
| 5333 | while (my $rr = $res->axfr_next()) { | 
|---|
| 5334 |  | 
|---|
| 5335 | # Discard out-of-zone records.  After trying for a while to replicate this with | 
|---|
| 5336 | # *nix-based DNS servers, it appears that only MS DNS is prone to including these | 
|---|
| 5337 | # in the AXFR data in the first place, and possibly only older versions at that... | 
|---|
| 5338 | # so it can't be reasonably tested.  Yay Microsoft. | 
|---|
| 5339 | if ($rr->name !~ /$zone$/i) { | 
|---|
| 5340 | $warnmsg .= "Discarding out-of-zone record ".$rr->string."\n"; | 
|---|
| 5341 | } | 
|---|
| 5342 |  | 
|---|
| 5343 | my $val; | 
|---|
| 5344 | my $distance = 0; | 
|---|
| 5345 | my $weight = 0; | 
|---|
| 5346 | my $port = 0; | 
|---|
| 5347 | my $logfrag = ''; | 
|---|
| 5348 |  | 
|---|
| 5349 | # Collect some record parts | 
|---|
| 5350 | my $type = $rr->type; | 
|---|
| 5351 | my $host = $rr->name; | 
|---|
| 5352 | my $ttl = ($args{newttl} ? $args{newttl} : $rr->ttl);     # allow force-override TTLs | 
|---|
| 5353 |  | 
|---|
| 5354 | # Info flags for SOA and NS records | 
|---|
| 5355 | $soaflag = 1 if $type eq 'SOA'; | 
|---|
| 5356 | $nsflag = 1 if $type eq 'NS'; | 
|---|
| 5357 |  | 
|---|
| 5358 | # "Primary" types: | 
|---|
| 5359 | # A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF | 
|---|
| 5360 | # maybe KEY | 
|---|
| 5361 |  | 
|---|
| 5362 | # BIND supports: | 
|---|
| 5363 | # [standard] | 
|---|
| 5364 | # A AAAA CNAME MX NS PTR SOA TXT | 
|---|
| 5365 | # [variously experimental, obsolete, or obscure] | 
|---|
| 5366 | # 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 | 
|---|
| 5367 | # ... if one can ever find the right magic to format them correctly | 
|---|
| 5368 |  | 
|---|
| 5369 | # Net::DNS supports: | 
|---|
| 5370 | # RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO | 
|---|
| 5371 | # EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY | 
|---|
| 5372 | # DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem | 
|---|
| 5373 |  | 
|---|
| 5374 | # nasty big ugly case-like thing here, since we have to do *some* different | 
|---|
| 5375 | # processing depending on the record.  le sigh. | 
|---|
| 5376 |  | 
|---|
| 5377 | # do the initial processing as if the record was in a forward zone.  If we're | 
|---|
| 5378 | # doing a revzone, we can flip $host and $val as needed, once, after this | 
|---|
| 5379 | # monster if-elsif-...-elsif-else.  This actually simplifies things a lot. | 
|---|
| 5380 |  | 
|---|
| 5381 | ##fixme:  what record types other than TXT can/will have >255-byte payloads? | 
|---|
| 5382 |  | 
|---|
| 5383 | if ($type eq 'A') { | 
|---|
| 5384 | $val = $rr->address; | 
|---|
| 5385 | } elsif ($type eq 'NS') { | 
|---|
| 5386 | # hmm.  should we warn here if subdomain NS'es are left alone?  OTOH, those should rarely be rewritten anyway. | 
|---|
| 5387 | next if ($args{rwns} && ($host eq $zone)); | 
|---|
| 5388 | $val = $rr->nsdname; | 
|---|
| 5389 | $warnmsg .= "Suspect record '".$rr->string."' may not be imported correctly: NS records may not be bare IP addresses\n" | 
|---|
| 5390 | if $val =~ /^(?:(?:\d+\.){3}\d+|[a-fA-F0-9:]+)$/; | 
|---|
| 5391 | $nsflag = 1; | 
|---|
| 5392 | } elsif ($type eq 'CNAME') { | 
|---|
| 5393 | $val = $rr->cname; | 
|---|
| 5394 | $warnmsg .= "Suspect record '".$rr->string."' may not be imported correctly: CNAME records may not be bare IP addresses\n" | 
|---|
| 5395 | if $val =~ /^(?:(?:\d+\.){3}\d+|[a-fA-F0-9:]+)$/; | 
|---|
| 5396 | } elsif ($type eq 'SOA') { | 
|---|
| 5397 | next if $args{rwsoa}; | 
|---|
| 5398 | $host = $rr->rname.":".$rr->mname; | 
|---|
| 5399 | $val = $rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum; | 
|---|
| 5400 | $soaflag = 1; | 
|---|
| 5401 | } elsif ($type eq 'PTR') { | 
|---|
| 5402 | $val = $rr->ptrdname; | 
|---|
| 5403 | } elsif ($type eq 'MX') { | 
|---|
| 5404 | $val = $rr->exchange; | 
|---|
| 5405 | $distance = $rr->preference; | 
|---|
| 5406 | } elsif ($type eq 'TXT') { | 
|---|
| 5407 | ##fixme:  Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(), | 
|---|
| 5408 | ## but don't really seem enthusiastic about it. | 
|---|
| 5409 | #print "should use rdatastr:\n\t".$rr->rdatastr."\n  or char_str_list:\n\t".join(' ',$rr->char_str_list())."\n"; | 
|---|
| 5410 | # rdatastr returns a BIND-targetted logical string, including opening and closing quotes | 
|---|
| 5411 | # char_str_list returns a list of the individual string fragments in the record | 
|---|
| 5412 | # txtdata returns the more useful all-in-one form (since we want to push such protocol | 
|---|
| 5413 | # details as far down the stack as we can) | 
|---|
| 5414 | # NB:  this may turn out to be more troublesome if we ever have need of >512-byte TXT records. | 
|---|
| 5415 | $val = $rr->txtdata; | 
|---|
| 5416 | } elsif ($type eq 'SPF') { | 
|---|
| 5417 | ##fixme: and the same caveat here, since it is apparently a clone of ::TXT | 
|---|
| 5418 | $val = $rr->txtdata; | 
|---|
| 5419 | } elsif ($type eq 'AAAA') { | 
|---|
| 5420 | $val = $rr->address; | 
|---|
| 5421 | } elsif ($type eq 'SRV') { | 
|---|
| 5422 | $val = $rr->target; | 
|---|
| 5423 | $distance = $rr->priority; | 
|---|
| 5424 | $weight = $rr->weight; | 
|---|
| 5425 | $port = $rr->port; | 
|---|
| 5426 | $warnmsg .= "Suspect record '".$rr->string."' may not be imported correctly: SRV records may not be bare IP addresses\n" | 
|---|
| 5427 | if $val =~ /^(?:(?:\d+\.){3}\d+|[a-fA-F0-9:]+)$/; | 
|---|
| 5428 | } elsif ($type eq 'KEY') { | 
|---|
| 5429 | # we don't actually know what to do with these... | 
|---|
| 5430 | $val = $rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname; | 
|---|
| 5431 | } else { | 
|---|
| 5432 | $val = $rr->rdatastr; | 
|---|
| 5433 | # Finding a different record type is not fatal.... just problematic. | 
|---|
| 5434 | # We may not be able to export it correctly. | 
|---|
| 5435 | $warnmsg .= "Unusual record ".$rr->name." ($type) found\n"; | 
|---|
| 5436 | } | 
|---|
| 5437 |  | 
|---|
| 5438 | if ($rev eq 'y' && $type ne 'SOA') { | 
|---|
| 5439 | # up to this point we haven't meddled with the record's hostname part or rdata part. | 
|---|
| 5440 | # for reverse records, (except SOA) we must swap the two. | 
|---|
| 5441 | $host = $val; | 
|---|
| 5442 | $val = $rr->name; | 
|---|
| 5443 | my ($tmpcode,$tmpmsg) = _zone2cidr($val); | 
|---|
| 5444 | if ($tmpcode eq 'FAIL') { | 
|---|
| 5445 | # $val did not have a valid IP value.  It's syntactically valid but WTF? | 
|---|
| 5446 | $warnmsg .= "Suspect record '".$rr->string."' may not be imported correctly: $tmpmsg\n"; | 
|---|
| 5447 | } else { | 
|---|
| 5448 | # $val has a valid IP value.  See if we can store it as that IP value. | 
|---|
| 5449 | # Note we're enumerating do-nothing cases for clarity. | 
|---|
| 5450 | ##enhance:  this is where we will implement the more subtle variations on #53 | 
|---|
| 5451 | if ($type ne 'PTR' && $type ne 'NS' && $type ne 'CNAME' && $type ne 'TXT') { | 
|---|
| 5452 | # case: the record is "weird" - ie, not a PTR, NS, CNAME, or TXT | 
|---|
| 5453 | # $warnmsg .= "Discarding suspect record '".$rr->string."'\n" if $self->{strict} eq 'full'; | 
|---|
| 5454 | } elsif ($type eq 'PTR' && $tmpmsg->masklen != 32 && $tmpmsg->masklen != 128) { | 
|---|
| 5455 | # case: PTR with netblock value, not IP value | 
|---|
| 5456 | # eg, "@ PTR foo" in zone f.e.e.b.d.a.e.d.ip6.arpa should not be | 
|---|
| 5457 | # stored/displayed as dead:beef::/32 PTR foo | 
|---|
| 5458 |  | 
|---|
| 5459 | ## hrm.  WTF is this case for, anyway?  Needs testing to check the logic. | 
|---|
| 5460 | #          } elsif ( ($type eq 'PTR' || $type eq 'NS' || $type eq 'CNAME' || $type eq 'TXT') && | 
|---|
| 5461 | #                    ($tmpmsg->masklen != $cidr->masklen) | 
|---|
| 5462 | #                  ) { | 
|---|
| 5463 | #            # leave $val as-is if the record is "normal" (a PTR, NS, CNAME, or TXT), | 
|---|
| 5464 | #            # and the mask does not match the zone | 
|---|
| 5465 | #$warnmsg .= "WTF case: $host $type $val\n"; | 
|---|
| 5466 | #            # $warnmsg .= "Discarding suspect record '".$rr->string."'\n" if $self->{strict} eq 'full'; | 
|---|
| 5467 |  | 
|---|
| 5468 | } else { | 
|---|
| 5469 | $val = $tmpmsg; | 
|---|
| 5470 | $val =~ s/\/(?:32|128)$//;  # automagically converts $val back to a string before s/// | 
|---|
| 5471 | #$val =~ s/:0$//g; | 
|---|
| 5472 | } | 
|---|
| 5473 | } | 
|---|
| 5474 | # magic?  convert * records to PTR template (not sure this actually makes sense) | 
|---|
| 5475 | #if ($val =~ /^\*/) { | 
|---|
| 5476 | #  $val =~ s/\*\.//; | 
|---|
| 5477 | #  ($tmpcode,$tmpmsg) = _zone2cidr($val); | 
|---|
| 5478 | #  if ($tmpcode eq 'FAIL') { | 
|---|
| 5479 | #    $val = "*.$val"; | 
|---|
| 5480 | #    $warnmsg .= "Suspect record '".$rr->string."' may not be converted to PTR template correctly: $tmpmsg\n"; | 
|---|
| 5481 | #  } else { | 
|---|
| 5482 | #    $type = 'PTR template'; | 
|---|
| 5483 | #    $val = $tmpmsg; if $tmp | 
|---|
| 5484 | #    $val =~ s/\/(?:32|128)$//;  # automagically converts $val back to a string before s/// | 
|---|
| 5485 | #  } | 
|---|
| 5486 | #} | 
|---|
| 5487 | } # non-SOA revrec $host/$val inversion and munging | 
|---|
| 5488 |  | 
|---|
| 5489 | my $logentry = "[AXFR ".($rev eq 'n' ? $zone : $cidr)."] "; | 
|---|
| 5490 |  | 
|---|
| 5491 | if ($args{merge}) { | 
|---|
| 5492 | if ($rev eq 'n') { | 
|---|
| 5493 | # importing a domain;  we have A and AAAA records that could be merged with matching PTR records | 
|---|
| 5494 | my $etype; | 
|---|
| 5495 | my ($erdns,$erid,$ettl) = $dbh->selectrow_array("SELECT rdns_id,record_id,ttl FROM records ". | 
|---|
| 5496 | "WHERE host=? AND val=? AND type=12", | 
|---|
| 5497 | undef, ($host, $val) ); | 
|---|
| 5498 | if ($erid) { | 
|---|
| 5499 | if ($type eq 'A') { # PTR -> A+PTR | 
|---|
| 5500 | $etype = 65280; | 
|---|
| 5501 | $logentry .= "Merged A record with existing PTR record '$host A+PTR $val', TTL $ettl"; | 
|---|
| 5502 | } | 
|---|
| 5503 | if ($type eq 'AAAA') {      # PTR -> AAAA+PTR | 
|---|
| 5504 | $etype = 65281; | 
|---|
| 5505 | $logentry .= "Merged AAAA record with existing PTR record '$host AAAA+PTR $val', TTL $ettl"; | 
|---|
| 5506 | } | 
|---|
| 5507 | $ettl = ($ettl < $ttl ? $ettl : $ttl);    # use lower TTL | 
|---|
| 5508 | $dbh->do("UPDATE records SET domain_id=?,ttl=?,type=? WHERE record_id=?", undef, | 
|---|
| 5509 | ($domain_id, $ettl, $etype, $erid)); | 
|---|
| 5510 | $nrecs++; | 
|---|
| 5511 | $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $erdns, entry => $logentry); | 
|---|
| 5512 | next;       # while axfr_next | 
|---|
| 5513 | } | 
|---|
| 5514 | } # $rev eq 'n' | 
|---|
| 5515 | else { | 
|---|
| 5516 | # importing a revzone, we have PTR records that could be merged with matching A/AAAA records | 
|---|
| 5517 | my ($domid,$erid,$ettl,$etype) = $dbh->selectrow_array("SELECT domain_id,record_id,ttl,type FROM records ". | 
|---|
| 5518 | "WHERE host=? AND val=? AND (type=1 OR type=28)", | 
|---|
| 5519 | undef, ($host, $val) ); | 
|---|
| 5520 | if ($erid) { | 
|---|
| 5521 | if ($etype == 1) {  # A -> A+PTR | 
|---|
| 5522 | $etype = 65280; | 
|---|
| 5523 | $logentry .= "Merged PTR record with existing matching A record '$host A+PTR $val', TTL $ettl"; | 
|---|
| 5524 | } | 
|---|
| 5525 | if ($etype == 28) { # AAAA -> AAAA+PTR | 
|---|
| 5526 | $etype = 65281; | 
|---|
| 5527 | $logentry .= "Merged PTR record with existing matching AAAA record '$host AAAA+PTR $val', TTL $ettl"; | 
|---|
| 5528 | } | 
|---|
| 5529 | $ettl = ($ettl < $ttl ? $ettl : $ttl);    # use lower TTL | 
|---|
| 5530 | $dbh->do("UPDATE records SET rdns_id=?,ttl=?,type=? WHERE record_id=?", undef, | 
|---|
| 5531 | ($rdns_id, $ettl, $etype, $erid)); | 
|---|
| 5532 | $nrecs++; | 
|---|
| 5533 | $self->_log(group_id => $group, domain_id => $domid, rdns_id => $rdns_id, entry => $logentry); | 
|---|
| 5534 | next;       # while axfr_next | 
|---|
| 5535 | } | 
|---|
| 5536 | } # $rev eq 'y' | 
|---|
| 5537 | } # if $args{merge} | 
|---|
| 5538 |  | 
|---|
| 5539 | # Insert the new record | 
|---|
| 5540 | $sth->execute($domain_id, $rdns_id, $host, $reverse_typemap{$type}, $val, | 
|---|
| 5541 | $distance, $weight, $port, $ttl); | 
|---|
| 5542 |  | 
|---|
| 5543 | $nrecs++; | 
|---|
| 5544 |  | 
|---|
| 5545 | if ($type eq 'SOA') { | 
|---|
| 5546 | # also !$args{rwsoa}, but if that's set, it should be impossible to get here. | 
|---|
| 5547 | my @tmp1 = split /:/, $host; | 
|---|
| 5548 | my @tmp2 = split /:/, $val; | 
|---|
| 5549 | $logentry .= "Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ". | 
|---|
| 5550 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"; | 
|---|
| 5551 | } elsif ($logfrag) { | 
|---|
| 5552 | # special case for log entries we need to meddle with a little. | 
|---|
| 5553 | $logentry .= $logfrag; | 
|---|
| 5554 | } else { | 
|---|
| 5555 | $logentry .= "Added record '".($rev eq 'y' ? $val : $host)." $type"; | 
|---|
| 5556 | $logentry .= " [distance $distance]" if $type eq 'MX'; | 
|---|
| 5557 | $logentry .= " [priority $distance] [weight $weight] [port $port]" if $type eq 'SRV'; | 
|---|
| 5558 | $logentry .= " ".($rev eq 'y' ? $host : $val)."', TTL $ttl"; | 
|---|
| 5559 | } | 
|---|
| 5560 | $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $rdns_id, entry => $logentry); | 
|---|
| 5561 |  | 
|---|
| 5562 | } # while axfr_next | 
|---|
| 5563 |  | 
|---|
| 5564 | # Detect and handle delegated subzones | 
|---|
| 5565 | # Placeholder for when we decide what to actually do with this, see previous comments in NS and CNAME handling. | 
|---|
| 5566 | #foreach (keys %suboct) { | 
|---|
| 5567 | #  print "found ".($suboct{$_}{ns} ? @{$suboct{$_}{ns}} : '0')." NS records and ". | 
|---|
| 5568 | #       ($suboct{$_}{cname} ? @{$suboct{$_}{cname}} : '0')." CNAMEs for $_\n"; | 
|---|
| 5569 | #} | 
|---|
| 5570 |  | 
|---|
| 5571 | # Overwrite SOA record | 
|---|
| 5572 | if ($args{rwsoa}) { | 
|---|
| 5573 | $soaflag = 1; | 
|---|
| 5574 | my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM "._rectable('y', $rev)." WHERE group_id=? AND type=?"); | 
|---|
| 5575 | my $sthputsoa = $dbh->prepare("INSERT INTO records (". | 
|---|
| 5576 | ($rev eq 'n' ? 'domain_id' : 'rdns_id').",host,type,val,ttl) VALUES (?,?,?,?,?)"); | 
|---|
| 5577 | $sthgetsoa->execute($group,$reverse_typemap{SOA}); | 
|---|
| 5578 | while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) { | 
|---|
| 5579 | if ($rev eq 'n') { | 
|---|
| 5580 | $host =~ s/DOMAIN/$zone/g; | 
|---|
| 5581 | $val =~ s/DOMAIN/$zone/g;     # arguably useless | 
|---|
| 5582 | } else { | 
|---|
| 5583 | $host =~ s/ADMINDOMAIN/$self->{domain}/g; | 
|---|
| 5584 | } | 
|---|
| 5585 | $sthputsoa->execute($zone_id,$host,$reverse_typemap{SOA},$val,$ttl); | 
|---|
| 5586 | } | 
|---|
| 5587 | } | 
|---|
| 5588 |  | 
|---|
| 5589 | # Add standard NS records.  The old one(s) should have been skipped by this point. | 
|---|
| 5590 | if ($args{rwns}) { | 
|---|
| 5591 | $nsflag = 1; | 
|---|
| 5592 | my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM "._rectable('y',$rev)." WHERE group_id=? AND type=?"); | 
|---|
| 5593 | my $sthputns = $dbh->prepare("INSERT INTO records (". | 
|---|
| 5594 | ($rev eq 'n' ? 'domain_id' : 'rdns_id').",host,type,val,ttl) VALUES (?,?,?,?,?)"); | 
|---|
| 5595 | $sthgetns->execute($group,$reverse_typemap{NS}); | 
|---|
| 5596 | while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) { | 
|---|
| 5597 | if ($rev eq 'n') { | 
|---|
| 5598 | $host =~ s/DOMAIN/$zone/g; | 
|---|
| 5599 | $val =~ s/DOMAIN/$zone/g;     #hmm. | 
|---|
| 5600 | } else { | 
|---|
| 5601 | $host =~ s/ADMINDOMAIN/$self->{domain}/g;     #hmm. | 
|---|
| 5602 | $val =~ s/ZONE/$cidr/g; | 
|---|
| 5603 | } | 
|---|
| 5604 | $sthputns->execute($zone_id,$host,$reverse_typemap{NS},$val,$ttl); | 
|---|
| 5605 | } | 
|---|
| 5606 | } | 
|---|
| 5607 |  | 
|---|
| 5608 | die "No records found;  either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs; | 
|---|
| 5609 | die "Bad zone:  No SOA record!\n" if !$soaflag; | 
|---|
| 5610 | die "Bad zone:  No NS records!\n" if !$nsflag; | 
|---|
| 5611 |  | 
|---|
| 5612 | $dbh->commit; | 
|---|
| 5613 |  | 
|---|
| 5614 | }; | 
|---|
| 5615 |  | 
|---|
| 5616 | if ($@) { | 
|---|
| 5617 | my $msg = $@; | 
|---|
| 5618 | eval { $dbh->rollback; }; | 
|---|
| 5619 | return ('FAIL',$msg." $warnmsg"); | 
|---|
| 5620 | } else { | 
|---|
| 5621 | return ('WARN', $warnmsg) if $warnmsg; | 
|---|
| 5622 | return ('OK',"Imported OK"); | 
|---|
| 5623 | } | 
|---|
| 5624 |  | 
|---|
| 5625 | # it should be impossible to get here. | 
|---|
| 5626 | return ('WARN',"OOOK!"); | 
|---|
| 5627 | } # end importAXFR() | 
|---|
| 5628 |  | 
|---|
| 5629 |  | 
|---|
| 5630 | ## DNSDB::importBIND() | 
|---|
| 5631 | sub importBIND { | 
|---|
| 5632 | } # end importBIND() | 
|---|
| 5633 |  | 
|---|
| 5634 |  | 
|---|
| 5635 | ## DNSDB::import_tinydns() | 
|---|
| 5636 | sub import_tinydns { | 
|---|
| 5637 | } # end import_tinydns() | 
|---|
| 5638 |  | 
|---|
| 5639 |  | 
|---|
| 5640 | ## DNSDB::export() | 
|---|
| 5641 | # Export the DNS database, or a part of it | 
|---|
| 5642 | # Takes a string indicating the export type, plus optional arguments depending on type | 
|---|
| 5643 | # Writes zone data to targets as appropriate for type | 
|---|
| 5644 | sub export { | 
|---|
| 5645 | my $self = shift; | 
|---|
| 5646 | my $target = shift; | 
|---|
| 5647 |  | 
|---|
| 5648 | if ($target eq 'tiny') { | 
|---|
| 5649 | eval { | 
|---|
| 5650 | $self->__export_tiny(@_); | 
|---|
| 5651 | }; | 
|---|
| 5652 | if ($@) { | 
|---|
| 5653 | $errstr = $@; | 
|---|
| 5654 | return undef; | 
|---|
| 5655 | } | 
|---|
| 5656 | } | 
|---|
| 5657 | # elsif ($target eq 'foo') { | 
|---|
| 5658 | #   __export_foo(@_); | 
|---|
| 5659 | #} | 
|---|
| 5660 | # etc | 
|---|
| 5661 |  | 
|---|
| 5662 | return 1; | 
|---|
| 5663 | } # end export() | 
|---|
| 5664 |  | 
|---|
| 5665 |  | 
|---|
| 5666 | ## DNSDB::__export_tiny | 
|---|
| 5667 | # Internal sub to implement tinyDNS (compatible) export | 
|---|
| 5668 | # Takes filehandle to write export to, optional argument(s) | 
|---|
| 5669 | # to determine which data gets exported | 
|---|
| 5670 | sub __export_tiny { | 
|---|
| 5671 | my $self = shift; | 
|---|
| 5672 | my $dbh = $self->{dbh}; | 
|---|
| 5673 | my $datafile = shift; | 
|---|
| 5674 | my $zonefilehandle = $datafile;       # makes cache/no-cache a little simpler | 
|---|
| 5675 |  | 
|---|
| 5676 | ##fixme: slurp up further options to specify particular zone(s) to export | 
|---|
| 5677 |  | 
|---|
| 5678 | ##fixme: fail if $datafile isn't an open, writable file | 
|---|
| 5679 |  | 
|---|
| 5680 | # Error check - does the cache dir exist, if we're using one? | 
|---|
| 5681 | if ($self->{usecache}) { | 
|---|
| 5682 | die "Cache directory does not exist\n" if !-e $self->{exportcache}; | 
|---|
| 5683 | die "$self->{exportcache} is not a directory\n" if !-d $self->{exportcache}; | 
|---|
| 5684 | die "$self->{exportcache} must be both readable and writable\n" | 
|---|
| 5685 | if !-r $self->{exportcache} || !-w $self->{exportcache}; | 
|---|
| 5686 | } | 
|---|
| 5687 |  | 
|---|
| 5688 | # easy case - export all evarything | 
|---|
| 5689 | # not-so-easy case - export item(s) specified | 
|---|
| 5690 | # todo:  figure out what kind of list we use to export items | 
|---|
| 5691 |  | 
|---|
| 5692 | # raw packet in unknown format:  first byte indicates length | 
|---|
| 5693 | # of remaining data, allows up to 255 raw bytes | 
|---|
| 5694 |  | 
|---|
| 5695 | # note: the only I/O failures we seem to be able to actually catch | 
|---|
| 5696 | # here are "closed filehandle" errors.  we're probably not writing | 
|---|
| 5697 | # enough data at this point to properly trigger an "out of space" | 
|---|
| 5698 | # error.  :/ | 
|---|
| 5699 | eval { | 
|---|
| 5700 | use warnings FATAL => ('io'); | 
|---|
| 5701 | # Locations/views - worth including in the caching setup? | 
|---|
| 5702 | my $lochash = $dbh->selectall_hashref("SELECT location,iplist FROM locations", 'location'); | 
|---|
| 5703 | foreach my $location (keys %$lochash) { | 
|---|
| 5704 | foreach my $ipprefix (split /[,\s]+/, $lochash->{$location}{iplist}) { | 
|---|
| 5705 | $ipprefix =~ s/\s+//g; | 
|---|
| 5706 | $ipprefix = new NetAddr::IP $ipprefix; | 
|---|
| 5707 | ##fixme:  how to handle IPv6? | 
|---|
| 5708 | next if $ipprefix->{isv6}; | 
|---|
| 5709 | # have to account for /nn CIDR entries.  tinydns only speaks octet-sliced prefix. | 
|---|
| 5710 | if ($ipprefix->masklen <= 8) { | 
|---|
| 5711 | foreach ($ipprefix->split(8)) { | 
|---|
| 5712 | my $tmp = $_->addr; | 
|---|
| 5713 | $tmp =~ s/\.\d+\.\d+\.\d+$//; | 
|---|
| 5714 | print $datafile "%$location:$tmp\n"; | 
|---|
| 5715 | } | 
|---|
| 5716 | } elsif ($ipprefix->masklen <= 16) { | 
|---|
| 5717 | foreach ($ipprefix->split(16)) { | 
|---|
| 5718 | my $tmp = $_->addr; | 
|---|
| 5719 | $tmp =~ s/\.\d+\.\d+$//; | 
|---|
| 5720 | print $datafile "%$location:$tmp\n"; | 
|---|
| 5721 | } | 
|---|
| 5722 | } elsif ($ipprefix->masklen <= 24) { | 
|---|
| 5723 | foreach ($ipprefix->split(24)) { | 
|---|
| 5724 | my $tmp = $_->addr; | 
|---|
| 5725 | $tmp =~ s/\.\d+$//; | 
|---|
| 5726 | print $datafile "%$location:$tmp\n"; | 
|---|
| 5727 | } | 
|---|
| 5728 | } else { | 
|---|
| 5729 | foreach ($ipprefix->split(32)) { | 
|---|
| 5730 | print $datafile "%$location:".$_->addr."\n"; | 
|---|
| 5731 | } | 
|---|
| 5732 | } | 
|---|
| 5733 | } | 
|---|
| 5734 | print $datafile "%$location\n" if !$lochash->{$location}{iplist}; | 
|---|
| 5735 | } | 
|---|
| 5736 | }; | 
|---|
| 5737 | if ($@) { | 
|---|
| 5738 | die "Error writing locations to master file: $@, $!\n"; | 
|---|
| 5739 | } | 
|---|
| 5740 |  | 
|---|
| 5741 | # tracking hash so we don't double-export A+PTR or AAAA+PTR records. | 
|---|
| 5742 | my %recflags; | 
|---|
| 5743 |  | 
|---|
| 5744 | # For reasons unknown, we can't sanely UNION these statements.  Feh. | 
|---|
| 5745 | # Supposedly it should work though (note last 3 lines): | 
|---|
| 5746 | ## PG manual | 
|---|
| 5747 | #UNION Clause | 
|---|
| 5748 | # | 
|---|
| 5749 | #The UNION clause has this general form: | 
|---|
| 5750 | # | 
|---|
| 5751 | #    select_statement UNION [ ALL ] select_statement | 
|---|
| 5752 | # | 
|---|
| 5753 | #select_statement is any SELECT statement without an ORDER BY, LIMIT, FOR UPDATE, or FOR SHARE clause. (ORDER BY | 
|---|
| 5754 | #and LIMIT can be attached to a subexpression if it is enclosed in parentheses. Without parentheses, these | 
|---|
| 5755 | #clauses will be taken to apply to the result of the UNION, not to its right-hand input expression.) | 
|---|
| 5756 | my $soasth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ". | 
|---|
| 5757 | "FROM records WHERE rdns_id=? AND type=6"); | 
|---|
| 5758 | my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location,extract(epoch from stamp),expires,stampactive ". | 
|---|
| 5759 | "FROM records WHERE rdns_id=? AND NOT type=6 ". | 
|---|
| 5760 | "ORDER BY masklen(inetlazy(val)) DESC, inetlazy(val)"); | 
|---|
| 5761 | my $revsth = $dbh->prepare("SELECT rdns_id,revnet,status,changed FROM revzones WHERE status=1 ". | 
|---|
| 5762 | "ORDER BY masklen(revnet) DESC, rdns_id"); | 
|---|
| 5763 | my $zonesth = $dbh->prepare("UPDATE revzones SET changed='n' WHERE rdns_id=?"); | 
|---|
| 5764 | $revsth->execute(); | 
|---|
| 5765 | while (my ($revid,$revzone,$revstat,$changed) = $revsth->fetchrow_array) { | 
|---|
| 5766 | ##fixme: need to find a way to block opening symlinked files without introducing a race. | 
|---|
| 5767 | #       O_NOFOLLOW | 
|---|
| 5768 | #              If  pathname  is a symbolic link, then the open fails.  This is a FreeBSD extension, which was | 
|---|
| 5769 | #              added to Linux in version 2.1.126.  Symbolic links in earlier components of the pathname  will | 
|---|
| 5770 | #              still be followed. | 
|---|
| 5771 | # but that doesn't help other platforms.  :/ | 
|---|
| 5772 | my $tmpzone = NetAddr::IP->new($revzone); | 
|---|
| 5773 | ##fixme:  locations/views?  subnet mask?  need to avoid possible collisions with zone/superzone | 
|---|
| 5774 | ##        (eg /20 vs /24, starting on .0.0) | 
|---|
| 5775 | my $cz = $tmpzone->network->addr."-".$tmpzone->masklen; | 
|---|
| 5776 | my $cachefile = "$self->{exportcache}/$cz"; | 
|---|
| 5777 | my $tmpcache = "$self->{exportcache}/tmp.$cz.$$"; | 
|---|
| 5778 | eval { | 
|---|
| 5779 |  | 
|---|
| 5780 | # write fresh records if: | 
|---|
| 5781 | #  - we are not using the cache | 
|---|
| 5782 | #  - force_refresh is set | 
|---|
| 5783 | #  - the zone has changed | 
|---|
| 5784 | #  - the cache file does not exist | 
|---|
| 5785 | #  - the cache file is empty | 
|---|
| 5786 | if (!$self->{usecache} || $self->{force_refresh} || $changed || !-e $cachefile || -z $cachefile) { | 
|---|
| 5787 | if ($self->{usecache}) { | 
|---|
| 5788 | open ZONECACHE, ">$tmpcache" or die "Error creating temporary file $tmpcache: $!\n"; | 
|---|
| 5789 | $zonefilehandle = *ZONECACHE; | 
|---|
| 5790 | } | 
|---|
| 5791 |  | 
|---|
| 5792 | # need to fetch this separately since the rest of the records all (should) have real IPs in val | 
|---|
| 5793 | $soasth->execute($revid); | 
|---|
| 5794 | my (@zsoa) = $soasth->fetchrow_array(); | 
|---|
| 5795 | $self->_printrec_tiny($zonefilehandle, $zsoa[7], 'y',\%recflags,$revzone, | 
|---|
| 5796 | $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],''); | 
|---|
| 5797 |  | 
|---|
| 5798 | $recsth->execute($revid); | 
|---|
| 5799 | my $fullzone = _ZONE($tmpzone, 'ZONE', 'r', '.').($tmpzone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa'); | 
|---|
| 5800 |  | 
|---|
| 5801 | while (my ($host, $type, $val, $dist, $weight, $port, $ttl, $recid, $loc, $stamp, $expires, $stampactive) | 
|---|
| 5802 | = $recsth->fetchrow_array) { | 
|---|
| 5803 | next if $recflags{$recid}; | 
|---|
| 5804 |  | 
|---|
| 5805 | # Check for out-of-zone data | 
|---|
| 5806 | if ($val =~ /\.arpa$/) { | 
|---|
| 5807 | # val is non-IP | 
|---|
| 5808 | if ($val !~ /$fullzone$/) { | 
|---|
| 5809 | warn "Not exporting out-of-zone record $val $typemap{$type} $host, $ttl (zone $tmpzone)\n"; | 
|---|
| 5810 | next; | 
|---|
| 5811 | } | 
|---|
| 5812 | } else { | 
|---|
| 5813 | my $ipval = new NetAddr::IP $val; | 
|---|
| 5814 | if (!$tmpzone->contains($ipval)) { | 
|---|
| 5815 | warn "Not exporting out-of-zone record $val $typemap{$type} $host, $ttl (zone $tmpzone)\n"; | 
|---|
| 5816 | next; | 
|---|
| 5817 | } | 
|---|
| 5818 | } # is $val a raw .arpa name? | 
|---|
| 5819 |  | 
|---|
| 5820 | # Spaces are evil. | 
|---|
| 5821 | $val =~ s/^\s+//; | 
|---|
| 5822 | $val =~ s/\s+$//; | 
|---|
| 5823 | if ($typemap{$type} ne 'TXT') { | 
|---|
| 5824 | # Leading or trailng spaces could be legit in TXT records. | 
|---|
| 5825 | $host =~ s/^\s+//; | 
|---|
| 5826 | $host =~ s/\s+$//; | 
|---|
| 5827 | } | 
|---|
| 5828 |  | 
|---|
| 5829 | $self->_printrec_tiny($zonefilehandle, $recid, 'y', \%recflags, $revzone, | 
|---|
| 5830 | $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp, $expires, $stampactive); | 
|---|
| 5831 |  | 
|---|
| 5832 | $recflags{$recid} = 1; | 
|---|
| 5833 |  | 
|---|
| 5834 | } # while ($recsth) | 
|---|
| 5835 |  | 
|---|
| 5836 | if ($self->{usecache}) { | 
|---|
| 5837 | close ZONECACHE; # force the file to be written | 
|---|
| 5838 | # catch obvious write errors that leave an empty temp file | 
|---|
| 5839 | if (-s $tmpcache) { | 
|---|
| 5840 | rename $tmpcache, $cachefile | 
|---|
| 5841 | or die "Error overwriting cache file $cachefile with temporary file: $!\n"; | 
|---|
| 5842 | } | 
|---|
| 5843 | } | 
|---|
| 5844 |  | 
|---|
| 5845 | } # if $changed or cache filesize is 0 | 
|---|
| 5846 |  | 
|---|
| 5847 | }; | 
|---|
| 5848 | if ($@) { | 
|---|
| 5849 | die "error writing ".($self->{usecache} ? 'new data for ' : '')."$revzone: $@\n"; | 
|---|
| 5850 | # error!  something borked, and we should be able to fall back on the old cache file | 
|---|
| 5851 | # report the error, somehow. | 
|---|
| 5852 | } else { | 
|---|
| 5853 | # mark zone as unmodified.  Only do this if no errors, that way | 
|---|
| 5854 | # export failures should recover a little more automatically. | 
|---|
| 5855 | $zonesth->execute($revid); | 
|---|
| 5856 | } | 
|---|
| 5857 |  | 
|---|
| 5858 | if ($self->{usecache}) { | 
|---|
| 5859 | # We've already made as sure as we can that a cached zone file is "good", | 
|---|
| 5860 | # although possibly stale/obsolete due to errors creating a new one. | 
|---|
| 5861 | eval { | 
|---|
| 5862 | open CACHE, "<$cachefile" or die $!; | 
|---|
| 5863 | print $datafile $_ or die "error copying cached $revzone to master file: $!" while <CACHE>; | 
|---|
| 5864 | close CACHE; | 
|---|
| 5865 | }; | 
|---|
| 5866 | die $@ if $@; | 
|---|
| 5867 | } | 
|---|
| 5868 |  | 
|---|
| 5869 | } # while ($revsth) | 
|---|
| 5870 |  | 
|---|
| 5871 | $soasth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ". | 
|---|
| 5872 | "FROM records WHERE domain_id=? AND type=6"); | 
|---|
| 5873 | $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location,extract(epoch from stamp),expires,stampactive ". | 
|---|
| 5874 | "FROM records WHERE domain_id=? AND NOT type=6");       # Just exclude all types relating to rDNS | 
|---|
| 5875 | #       "FROM records WHERE domain_id=? AND type < 65280");     # Just exclude all types relating to rDNS | 
|---|
| 5876 | my $domsth = $dbh->prepare("SELECT domain_id,domain,status,changed FROM domains WHERE status=1 ORDER BY domain_id"); | 
|---|
| 5877 | $zonesth = $dbh->prepare("UPDATE domains SET changed='n' WHERE domain_id=?"); | 
|---|
| 5878 | $domsth->execute(); | 
|---|
| 5879 | while (my ($domid,$dom,$domstat,$changed) = $domsth->fetchrow_array) { | 
|---|
| 5880 | ##fixme: need to find a way to block opening symlinked files without introducing a race. | 
|---|
| 5881 | #       O_NOFOLLOW | 
|---|
| 5882 | #              If  pathname  is a symbolic link, then the open fails.  This is a FreeBSD extension, which was | 
|---|
| 5883 | #              added to Linux in version 2.1.126.  Symbolic links in earlier components of the pathname  will | 
|---|
| 5884 | #              still be followed. | 
|---|
| 5885 | # but that doesn't help other platforms.  :/ | 
|---|
| 5886 | my $cachefile = "$self->{exportcache}/$dom"; | 
|---|
| 5887 | my $tmpcache = "$self->{exportcache}/tmp.$dom.$$"; | 
|---|
| 5888 | eval { | 
|---|
| 5889 |  | 
|---|
| 5890 | # write fresh records if: | 
|---|
| 5891 | #  - we are not using the cache | 
|---|
| 5892 | #  - force_refresh is set | 
|---|
| 5893 | #  - the zone has changed | 
|---|
| 5894 | #  - the cache file does not exist | 
|---|
| 5895 | #  - the cache file is empty | 
|---|
| 5896 | if (!$self->{usecache} || $self->{force_refresh} || $changed || !-e $cachefile || -z $cachefile) { | 
|---|
| 5897 | if ($self->{usecache}) { | 
|---|
| 5898 | open ZONECACHE, ">$tmpcache" or die "Error creating temporary file $tmpcache: $!\n"; | 
|---|
| 5899 | $zonefilehandle = *ZONECACHE; | 
|---|
| 5900 | } | 
|---|
| 5901 |  | 
|---|
| 5902 | # need to fetch this separately so the SOA comes first in the flatfile.... | 
|---|
| 5903 | # Just In Case we need/want to reimport from the flatfile later on. | 
|---|
| 5904 | $soasth->execute($domid); | 
|---|
| 5905 | my (@zsoa) = $soasth->fetchrow_array(); | 
|---|
| 5906 | $self->_printrec_tiny($zonefilehandle, $zsoa[7], 'n',\%recflags,$dom, | 
|---|
| 5907 | $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],''); | 
|---|
| 5908 |  | 
|---|
| 5909 | $recsth->execute($domid); | 
|---|
| 5910 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc,$stamp,$expires,$stampactive) = $recsth->fetchrow_array) { | 
|---|
| 5911 | next if $recflags{$recid}; | 
|---|
| 5912 |  | 
|---|
| 5913 | # Check for out-of-zone data | 
|---|
| 5914 | $host = $dom if $host eq '@'; | 
|---|
| 5915 | if ($host !~ /$dom$/i) { | 
|---|
| 5916 | warn "Not exporting out-of-zone record $host $type $val, $ttl (zone $dom)\n"; | 
|---|
| 5917 | next; | 
|---|
| 5918 | } | 
|---|
| 5919 |  | 
|---|
| 5920 | # Spaces are evil. | 
|---|
| 5921 | $host =~ s/^\s+//; | 
|---|
| 5922 | $host =~ s/\s+$//; | 
|---|
| 5923 | if ($typemap{$type} ne 'TXT') { | 
|---|
| 5924 | # Leading or trailng spaces could be legit in TXT records. | 
|---|
| 5925 | $val =~ s/^\s+//; | 
|---|
| 5926 | $val =~ s/\s+$//; | 
|---|
| 5927 | } | 
|---|
| 5928 |  | 
|---|
| 5929 | $self->_printrec_tiny($zonefilehandle, $recid, 'n', \%recflags, | 
|---|
| 5930 | $dom, $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp, $expires, $stampactive); | 
|---|
| 5931 |  | 
|---|
| 5932 | $recflags{$recid} = 1; | 
|---|
| 5933 |  | 
|---|
| 5934 | } # while ($recsth) | 
|---|
| 5935 |  | 
|---|
| 5936 |  | 
|---|
| 5937 | if ($self->{usecache}) { | 
|---|
| 5938 | close ZONECACHE; # force the file to be written | 
|---|
| 5939 | # catch obvious write errors that leave an empty temp file | 
|---|
| 5940 | if (-s $tmpcache) { | 
|---|
| 5941 | rename $tmpcache, $cachefile | 
|---|
| 5942 | or die "Error overwriting cache file $cachefile with temporary file: $!\n"; | 
|---|
| 5943 | } | 
|---|
| 5944 | } | 
|---|
| 5945 |  | 
|---|
| 5946 | } # if $changed or cache filesize is 0 | 
|---|
| 5947 |  | 
|---|
| 5948 | }; | 
|---|
| 5949 | if ($@) { | 
|---|
| 5950 | die "error writing ".($self->{usecache} ? 'new data for ' : '')."$dom: $@\n"; | 
|---|
| 5951 | # error!  something borked, and we should be able to fall back on the old cache file | 
|---|
| 5952 | # report the error, somehow. | 
|---|
| 5953 | } else { | 
|---|
| 5954 | # mark domain as unmodified.  Only do this if no errors, that way | 
|---|
| 5955 | # export failures should recover a little more automatically. | 
|---|
| 5956 | $zonesth->execute($domid); | 
|---|
| 5957 | } | 
|---|
| 5958 |  | 
|---|
| 5959 | if ($self->{usecache}) { | 
|---|
| 5960 | # We've already made as sure as we can that a cached zone file is "good", | 
|---|
| 5961 | # although possibly stale/obsolete due to errors creating a new one. | 
|---|
| 5962 | eval { | 
|---|
| 5963 | open CACHE, "<$cachefile" or die $!; | 
|---|
| 5964 | print $datafile $_ or die "error copying cached $dom to master file: $!" while <CACHE>; | 
|---|
| 5965 | close CACHE; | 
|---|
| 5966 | }; | 
|---|
| 5967 | die $@ if $@; | 
|---|
| 5968 | } | 
|---|
| 5969 |  | 
|---|
| 5970 | } # while ($domsth) | 
|---|
| 5971 |  | 
|---|
| 5972 | return 1; | 
|---|
| 5973 | } # end __export_tiny() | 
|---|
| 5974 |  | 
|---|
| 5975 |  | 
|---|
| 5976 | # Utility sub for __export_tiny above | 
|---|
| 5977 | sub _printrec_tiny { | 
|---|
| 5978 | my $self = shift; | 
|---|
| 5979 | my ($datafile, $recid, $revrec, $recflags, $zone, $host, $type, $val, $dist, $weight, $port, $ttl, | 
|---|
| 5980 | $loc, $stamp, $expires, $stampactive) = @_; | 
|---|
| 5981 |  | 
|---|
| 5982 | $loc = '' if !$loc;   # de-nullify - just in case | 
|---|
| 5983 | ##fixme:  handle case of record-with-location-that-doesn't-exist better. | 
|---|
| 5984 | # note this currently fails safe (tested) - records with a location that | 
|---|
| 5985 | # doesn't exist will not be sent to any client | 
|---|
| 5986 | #       $loc = '' if !$lochash->{$loc}; | 
|---|
| 5987 |  | 
|---|
| 5988 |  | 
|---|
| 5989 | ## Records that are valid only before or after a set time | 
|---|
| 5990 |  | 
|---|
| 5991 | # record due to expire sometime is the complex case.  we don't want to just | 
|---|
| 5992 | # rely on tinydns' auto-adjusting TTLs, because the default TTL in that case | 
|---|
| 5993 | # is one day instead of the SOA minttl as BIND might do. | 
|---|
| 5994 |  | 
|---|
| 5995 | # consider the case where a record is set to expire a week ahead, but the next | 
|---|
| 5996 | # day later you want to change it NOW (or as NOWish as you get with your DNS | 
|---|
| 5997 | # management practice).  but now you're stuck, because someone, somewhere, | 
|---|
| 5998 | # has just done a lookup before your latest change was published, and they'll | 
|---|
| 5999 | # be caching that old, broken record for 1 day instead of your zone default | 
|---|
| 6000 | # TTL. | 
|---|
| 6001 |  | 
|---|
| 6002 | # $stamp-$ttl is the *latest* we can publish the record with the defined TTL | 
|---|
| 6003 | # to still have the expiry happen as scheduled, but we need to find some | 
|---|
| 6004 | # *earlier* point.  We can maybe guess, and 2x TTL is probably reasonable, | 
|---|
| 6005 | # but we need info on the export frequency. | 
|---|
| 6006 |  | 
|---|
| 6007 | # export the normal, non-expiring record up until $stamp-<guesstimate>, then | 
|---|
| 6008 | # switch to exporting a record with the TAI64 stamp and a 0 TTL so tinydns | 
|---|
| 6009 | # takes over TTL management. | 
|---|
| 6010 |  | 
|---|
| 6011 | if ($stampactive) { | 
|---|
| 6012 | if ($expires) { | 
|---|
| 6013 | # record expires at $stamp;  decide if we need to keep the TTL and ignore | 
|---|
| 6014 | # the stamp for a time or if we need to change the TTL to 0 and convert | 
|---|
| 6015 | # $stamp to TAI64 so tinydns can use $stamp to autoadjust the TTL on the fly. | 
|---|
| 6016 | # extra hack, optimally needs more knowledge of data export frequency | 
|---|
| 6017 | # smack the idiot customer who insists on 0 TTLs;  they can suck up and | 
|---|
| 6018 | # deal with a 10-minute TTL.  especially on scheduled changes.  note this | 
|---|
| 6019 | # should be (export freq * 2), but we don't know the actual export frequency. | 
|---|
| 6020 | $ttl = 300 if $ttl == 0;        #hack phtui | 
|---|
| 6021 | my $ahead = (86400 < $ttl*2 ? 86400 : $ttl*2); | 
|---|
| 6022 | if ((time() + $ahead) < $stamp) { | 
|---|
| 6023 | # more than 2x TTL OR more than one day (whichever is less) from expiry time;  publish normal record | 
|---|
| 6024 | $stamp = ''; | 
|---|
| 6025 | } else { | 
|---|
| 6026 | # less than 2x TTL from expiry time, let tinydns take over TTL management and publish the TAI64 stamp. | 
|---|
| 6027 | $ttl = 0; | 
|---|
| 6028 | $stamp = unixtai64($stamp); | 
|---|
| 6029 | $stamp =~ s/\@//; | 
|---|
| 6030 | } | 
|---|
| 6031 | } else { | 
|---|
| 6032 | # record is "active after";  convert epoch from database to TAI64, publish, and collect $200. | 
|---|
| 6033 | $stamp = unixtai64($stamp); | 
|---|
| 6034 | $stamp =~ s/\@//; | 
|---|
| 6035 | } | 
|---|
| 6036 | } else { | 
|---|
| 6037 | # flag for active timestamp is false;  don't actually put a timestamp in the output | 
|---|
| 6038 | $stamp = ''; | 
|---|
| 6039 | } | 
|---|
| 6040 |  | 
|---|
| 6041 | # support tinydns' auto-TTL | 
|---|
| 6042 | $ttl = '' if $ttl == -1; | 
|---|
| 6043 | # these are WAY FREAKING HIGH - higher even than most TLD registry TTLs! | 
|---|
| 6044 | # NS          259200  => 3d | 
|---|
| 6045 | # all others   86400  => 1d | 
|---|
| 6046 |  | 
|---|
| 6047 | if ($revrec eq 'y') { | 
|---|
| 6048 | $val = $zone if $val eq '@'; | 
|---|
| 6049 | } else { | 
|---|
| 6050 | $host = $zone if $host eq '@'; | 
|---|
| 6051 | } | 
|---|
| 6052 |  | 
|---|
| 6053 | ## Convert a bare number into an octal-coded pair of octets. | 
|---|
| 6054 | # Take optional arg to indicate a decimal or hex input.  Defaults to hex. | 
|---|
| 6055 | sub octalize { | 
|---|
| 6056 | my $tmp = shift; | 
|---|
| 6057 | my $srctype = shift || 'h'; # default assumes hex string | 
|---|
| 6058 | $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h';       # 0-pad hex to 4 digits | 
|---|
| 6059 | $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd';    # 0-pad decimal to 4 hex digits | 
|---|
| 6060 | my @o = ($tmp =~ /^(..)(..)$/);     # split into octets | 
|---|
| 6061 | return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]); | 
|---|
| 6062 | } | 
|---|
| 6063 |  | 
|---|
| 6064 | # Utility sub-sub for reverse records;  with "any-record-in-any-zone" | 
|---|
| 6065 | # we may need to do extra processing on $val to make it publishable. | 
|---|
| 6066 | sub __revswap { | 
|---|
| 6067 | my $host = shift; | 
|---|
| 6068 | my $val = shift; | 
|---|
| 6069 | return ($val, $host) if $val =~ /\.arpa/; | 
|---|
| 6070 | $val = new NetAddr::IP $val; | 
|---|
| 6071 | my $newval = _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa'); | 
|---|
| 6072 | return ($newval, $host); | 
|---|
| 6073 | } | 
|---|
| 6074 |  | 
|---|
| 6075 | ## WARNING:  This works to export even the whole Internet's worth of IP space... | 
|---|
| 6076 | ##  if you have the disk/RAM to handle the dataset, and you call this sub based on /16-sized chunks | 
|---|
| 6077 | ##  A /16 took ~3 seconds with a handful of separate records;  adding a /8 pushed export time out to ~13m:40s | 
|---|
| 6078 | ##  0/0 is estimated to take ~54 hours and ~256G of disk | 
|---|
| 6079 | ##  RAM usage depends on how many non-template entries you have in the set. | 
|---|
| 6080 | ##  This should probably be done on record addition rather than export;  large blocks may need to be done in a | 
|---|
| 6081 | ##  forked process | 
|---|
| 6082 | sub __publish_subnet { | 
|---|
| 6083 | my $self = shift;   # *sigh*  need to pass in the DNSDB object so we can read a couple of options | 
|---|
| 6084 | my $sub = shift; | 
|---|
| 6085 | my $recflags = shift; | 
|---|
| 6086 | my $hpat = shift; | 
|---|
| 6087 | my $fh = shift; | 
|---|
| 6088 | my $ttl = shift; | 
|---|
| 6089 | my $stamp = shift; | 
|---|
| 6090 | my $loc = shift; | 
|---|
| 6091 | my $zone = new NetAddr::IP shift; | 
|---|
| 6092 | my $ptronly = shift || 0; | 
|---|
| 6093 |  | 
|---|
| 6094 | # do this conversion once, not (number-of-ips-in-subnet) times | 
|---|
| 6095 | my $arpabase = _ZONE($zone, 'ZONE.in-addr.arpa', 'r', '.'); | 
|---|
| 6096 |  | 
|---|
| 6097 | my $iplist = $sub->splitref(32); | 
|---|
| 6098 | my $ipindex = -1; | 
|---|
| 6099 | foreach (@$iplist) { | 
|---|
| 6100 | my $ip = $_->addr; | 
|---|
| 6101 | $ipindex++; | 
|---|
| 6102 | # make as if we split the non-octet-aligned block into octet-aligned blocks as with SOA | 
|---|
| 6103 | my $lastoct = (split /\./, $ip)[3]; | 
|---|
| 6104 | next if $$recflags{$ip}; # && $self->{skip_bcast_255} | 
|---|
| 6105 | $$recflags{$ip}++; | 
|---|
| 6106 | next if $hpat eq '%blank%';       # Allows blanking a subnet so no records are published. | 
|---|
| 6107 | my $rec = $hpat;  # start fresh with the template for each IP | 
|---|
| 6108 | ##fixme:  there really isn't a good way to handle sub-/24 zones here.  This way at least | 
|---|
| 6109 | # seems less bad than some alternatives. | 
|---|
| 6110 | $self->_template4_expand(\$rec, $ip, \$sub, $ipindex); | 
|---|
| 6111 | # _template4_expand may blank $rec;  if so, don't publish a record | 
|---|
| 6112 | next if !$rec; | 
|---|
| 6113 | if ($ptronly || $zone->masklen > 24) { | 
|---|
| 6114 | print $fh "^$lastoct.$arpabase:$rec:$ttl:$stamp:$loc\n" or die $!; | 
|---|
| 6115 | if (!$ptronly) { | 
|---|
| 6116 | # print a separate A record.  Arguably we could use an = record here instead. | 
|---|
| 6117 | print $fh "+$rec:$ip:$ttl:$stamp:$loc\n" or die $!; | 
|---|
| 6118 | } | 
|---|
| 6119 | } else { | 
|---|
| 6120 | print $fh "=$rec:$ip:$ttl:$stamp:$loc\n" or die $!; | 
|---|
| 6121 | } | 
|---|
| 6122 | } | 
|---|
| 6123 | } # __publish_subnet | 
|---|
| 6124 |  | 
|---|
| 6125 | ## And now the meat. | 
|---|
| 6126 |  | 
|---|
| 6127 | ##fixme?  append . to all host/val hostnames | 
|---|
| 6128 | #print "debug: rawdata: $host $typemap{$type} $val\n"; | 
|---|
| 6129 |  | 
|---|
| 6130 | if ($typemap{$type} eq 'SOA') { | 
|---|
| 6131 | # host contains pri-ns:responsible | 
|---|
| 6132 | # val is abused to contain refresh:retry:expire:minttl | 
|---|
| 6133 | ##fixme:  "manual" serial vs tinydns-autoserial | 
|---|
| 6134 | # let's be explicit about abusing $host and $val | 
|---|
| 6135 | my ($email, $primary) = (split /:/, $host)[0,1]; | 
|---|
| 6136 | my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3]; | 
|---|
| 6137 | if ($revrec eq 'y') { | 
|---|
| 6138 | ##fixme:  have to publish SOA records for each v4 /24 in sub-/16, and each /16 in sub-/8 | 
|---|
| 6139 | # what about v6? | 
|---|
| 6140 | # -> only need SOA for local chunks offset from reverse delegation boundaries, so v6 is fine | 
|---|
| 6141 | # anyone who says they need sub-nibble v6 delegations, at this time, needs their head examined. | 
|---|
| 6142 | $zone = NetAddr::IP->new($zone); | 
|---|
| 6143 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones | 
|---|
| 6144 | if (!$zone->{isv6} && ($zone->masklen < 24) && ($zone->masklen % 8 != 0)) { | 
|---|
| 6145 | foreach my $szone ($zone->split($zone->masklen + (8 - $zone->masklen % 8))) { | 
|---|
| 6146 | $szone = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.'); | 
|---|
| 6147 | print $datafile "Z$szone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n" | 
|---|
| 6148 | or die $!; | 
|---|
| 6149 | } | 
|---|
| 6150 | return; # skips "default" bits just below | 
|---|
| 6151 | } | 
|---|
| 6152 | $zone = _ZONE($zone, 'ZONE', 'r', '.').($zone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa'); | 
|---|
| 6153 | } | 
|---|
| 6154 | print $datafile "Z$zone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n" | 
|---|
| 6155 | or die $!; | 
|---|
| 6156 |  | 
|---|
| 6157 | } elsif ($typemap{$type} eq 'A') { | 
|---|
| 6158 |  | 
|---|
| 6159 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y'; | 
|---|
| 6160 | print $datafile "+$host:$val:$ttl:$stamp:$loc\n" or die $!; | 
|---|
| 6161 |  | 
|---|
| 6162 | } elsif ($typemap{$type} eq 'NS') { | 
|---|
| 6163 |  | 
|---|
| 6164 | if ($revrec eq 'y') { | 
|---|
| 6165 | $val = NetAddr::IP->new($val); | 
|---|
| 6166 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones | 
|---|
| 6167 | if (!$val->{isv6} && ($val->masklen < 24) && ($val->masklen % 8 != 0)) { | 
|---|
| 6168 | foreach my $szone ($val->split($val->masklen + (8 - $val->masklen % 8))) { | 
|---|
| 6169 | my $szone2 = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.'); | 
|---|
| 6170 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen; | 
|---|
| 6171 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n" or die $!; | 
|---|
| 6172 | $$recflags{$szone2} = $val->masklen; | 
|---|
| 6173 | } | 
|---|
| 6174 | } elsif ($val->{isv6} && ($val->masklen < 64) && ($val->masklen % 4 !=0)) { | 
|---|
| 6175 | foreach my $szone ($val->split($val->masklen + (4 - $val->masklen % 4))) { | 
|---|
| 6176 | my $szone2 = _ZONE($szone, 'ZONE.ip6.arpa', 'r', '.'); | 
|---|
| 6177 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen; | 
|---|
| 6178 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n" or die $!; | 
|---|
| 6179 | $$recflags{$szone2} = $val->masklen; | 
|---|
| 6180 | } | 
|---|
| 6181 | } else { | 
|---|
| 6182 | my $val2 = _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa'); | 
|---|
| 6183 | print $datafile "\&$val2"."::$host:$ttl:$stamp:$loc\n" or die $!; | 
|---|
| 6184 | $$recflags{$val2} = $val->masklen; | 
|---|
| 6185 | } | 
|---|
| 6186 | } else { | 
|---|
| 6187 | print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n" or die $!; | 
|---|
| 6188 | } | 
|---|
| 6189 |  | 
|---|
| 6190 | } elsif ($typemap{$type} eq 'AAAA') { | 
|---|
| 6191 |  | 
|---|
| 6192 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y'; | 
|---|
| 6193 | my $altgrp = 0; | 
|---|
| 6194 | my @altconv; | 
|---|
| 6195 | # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing) | 
|---|
| 6196 | foreach (split /:/, $val) { | 
|---|
| 6197 | if (/^$/) { | 
|---|
| 6198 | # flag blank entry;  this is a series of 0's of (currently) unknown length | 
|---|
| 6199 | $altconv[$altgrp++] = 's'; | 
|---|
| 6200 | } else { | 
|---|
| 6201 | # call sub to convert 1-4 hex digits to 2 string-rep octal bytes | 
|---|
| 6202 | $altconv[$altgrp++] = octalize($_) | 
|---|
| 6203 | } | 
|---|
| 6204 | } | 
|---|
| 6205 | my $prefix = ":$host:28:"; | 
|---|
| 6206 | foreach my $octet (@altconv) { | 
|---|
| 6207 | # if not 's', output | 
|---|
| 6208 | $prefix .= $octet unless $octet =~ /^s$/; | 
|---|
| 6209 | # if 's', output (9-array length)x literal '\000\000' | 
|---|
| 6210 | $prefix .= '\000\000'x(9-$altgrp) if $octet =~ /^s$/; | 
|---|
| 6211 | } | 
|---|
| 6212 | print $datafile "$prefix:$ttl:$stamp:$loc\n" or die $!; | 
|---|
| 6213 |  | 
|---|
| 6214 | } elsif ($typemap{$type} eq 'MX') { | 
|---|
| 6215 |  | 
|---|
| 6216 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y'; | 
|---|
| 6217 | print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n" or die $!; | 
|---|
| 6218 |  | 
|---|
| 6219 | } elsif ($typemap{$type} eq 'TXT') { | 
|---|
| 6220 |  | 
|---|
| 6221 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y'; | 
|---|
| 6222 | ##fixme:  split v-e-r-y long TXT strings?  will need to do so for BIND export, at least | 
|---|
| 6223 | $val =~ s/:/\\072/g;        # may need to replace other symbols | 
|---|
| 6224 | print $datafile "'$host:$val:$ttl:$stamp:$loc\n" or die $!; | 
|---|
| 6225 |  | 
|---|
| 6226 | # by-hand TXT | 
|---|
| 6227 | #:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600 | 
|---|
| 6228 | #@       IN      TXT     "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all" | 
|---|
| 6229 | #'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600 | 
|---|
| 6230 |  | 
|---|
| 6231 | #txttest IN      TXT     "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?" | 
|---|
| 6232 | #: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 | 
|---|
| 6233 |  | 
|---|
| 6234 | # very long TXT record as brought in by axfr-get | 
|---|
| 6235 | # note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that | 
|---|
| 6236 | # also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either.  :/ | 
|---|
| 6237 | #:longtxt.deepnet.cx:16: | 
|---|
| 6238 | #\170this is a very long txt record.  it is really long.  long. very long.  really very long. this is a very long txt record. | 
|---|
| 6239 | #\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. | 
|---|
| 6240 | #\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. | 
|---|
| 6241 | #:3600 | 
|---|
| 6242 |  | 
|---|
| 6243 | } elsif ($typemap{$type} eq 'CNAME') { | 
|---|
| 6244 |  | 
|---|
| 6245 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y'; | 
|---|
| 6246 | print $datafile "C$host:$val:$ttl:$stamp:$loc\n" or die $!; | 
|---|
| 6247 |  | 
|---|
| 6248 | } elsif ($typemap{$type} eq 'SRV') { | 
|---|
| 6249 |  | 
|---|
| 6250 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y'; | 
|---|
| 6251 |  | 
|---|
| 6252 | # data is two-byte values for priority, weight, port, in that order, | 
|---|
| 6253 | # followed by length/string data | 
|---|
| 6254 |  | 
|---|
| 6255 | my $prefix = ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d'); | 
|---|
| 6256 |  | 
|---|
| 6257 | $val .= '.' if $val !~ /\.$/; | 
|---|
| 6258 | foreach (split /\./, $val) { | 
|---|
| 6259 | $prefix .= sprintf "\\%0.3o%s", length($_), $_ or die $!; | 
|---|
| 6260 | } | 
|---|
| 6261 | print $datafile "$prefix\\000:$ttl:$stamp:$loc\n" or die $!; | 
|---|
| 6262 |  | 
|---|
| 6263 | } elsif ($typemap{$type} eq 'RP') { | 
|---|
| 6264 |  | 
|---|
| 6265 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y'; | 
|---|
| 6266 | # RP consists of two mostly free-form strings. | 
|---|
| 6267 | # The first is supposed to be an email address with @ replaced by . (as with the SOA contact) | 
|---|
| 6268 | # The second is the "hostname" of a TXT record with more info. | 
|---|
| 6269 | my $prefix = ":$host:17:"; | 
|---|
| 6270 | my ($who,$what) = split /\s/, $val; | 
|---|
| 6271 | foreach (split /\./, $who) { | 
|---|
| 6272 | $prefix .= sprintf "\\%0.3o%s", length($_), $_; | 
|---|
| 6273 | } | 
|---|
| 6274 | $prefix .= '\000'; | 
|---|
| 6275 | foreach (split /\./, $what) { | 
|---|
| 6276 | $prefix .= sprintf "\\%0.3o%s", length($_), $_; | 
|---|
| 6277 | } | 
|---|
| 6278 | print $datafile "$prefix\\000:$ttl:$stamp:$loc\n" or die $!; | 
|---|
| 6279 |  | 
|---|
| 6280 | } elsif ($typemap{$type} eq 'PTR') { | 
|---|
| 6281 |  | 
|---|
| 6282 | $$recflags{$val}++; | 
|---|
| 6283 | if ($revrec eq 'y') { | 
|---|
| 6284 |  | 
|---|
| 6285 | if ($val =~ /\.arpa$/) { | 
|---|
| 6286 | # someone put in the formal .arpa name.  humor them. | 
|---|
| 6287 | print $datafile "^$val:$host:$ttl:$stamp:$loc\n" or die $!; | 
|---|
| 6288 | } else { | 
|---|
| 6289 | $zone = NetAddr::IP->new($zone); | 
|---|
| 6290 | if (!$zone->{isv6} && $zone->masklen > 24) { | 
|---|
| 6291 | # sub-octet v4 zone | 
|---|
| 6292 | ($val) = ($val =~ /\.(\d+)$/); | 
|---|
| 6293 | print $datafile "^$val."._ZONE($zone, 'ZONE', 'r', '.').'.in-addr.arpa'. | 
|---|
| 6294 | ":$host:$ttl:$stamp:$loc\n" or die $!; | 
|---|
| 6295 | } else { | 
|---|
| 6296 | # not going to care about strange results if $val is not an IP value and is resolveable in DNS | 
|---|
| 6297 | $val = NetAddr::IP->new($val); | 
|---|
| 6298 | print $datafile "^". | 
|---|
| 6299 | _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa'). | 
|---|
| 6300 | ":$host:$ttl:$stamp:$loc\n" or die $!; | 
|---|
| 6301 | } | 
|---|
| 6302 | } # non-".arpa" $val | 
|---|
| 6303 |  | 
|---|
| 6304 | } else { | 
|---|
| 6305 | # PTRs in forward zones are less bizarre and insane than some other record types | 
|---|
| 6306 | # in reverse zones...  OTOH we can't validate them any which way, so we cross our | 
|---|
| 6307 | # fingers and close our eyes and make it Someone Else's Problem. | 
|---|
| 6308 | print $datafile "^$host:$val:$ttl:$stamp:$loc\n" or die $!; | 
|---|
| 6309 | } | 
|---|
| 6310 |  | 
|---|
| 6311 | } elsif ($type == 65280) { # A+PTR | 
|---|
| 6312 |  | 
|---|
| 6313 | $$recflags{$val}++; | 
|---|
| 6314 | print $datafile "=$host:$val:$ttl:$stamp:$loc\n" or die $!; | 
|---|
| 6315 |  | 
|---|
| 6316 | } elsif ($type == 65281) { # AAAA+PTR | 
|---|
| 6317 |  | 
|---|
| 6318 | $$recflags{$val}++; | 
|---|
| 6319 | # treat these as two separate records.  since tinydns doesn't have | 
|---|
| 6320 | # a native combined type, we have to create them separately anyway. | 
|---|
| 6321 | # print both;  a dangling record is harmless, and impossible via web | 
|---|
| 6322 | # UI anyway | 
|---|
| 6323 | $self->_printrec_tiny($datafile,$recid,'n',$recflags, $self->domainName($self->_hostparent($host)), | 
|---|
| 6324 | $host, 28, $val, $dist, $weight, $port, $ttl, $loc, $stamp); | 
|---|
| 6325 | $self->_printrec_tiny($datafile, $recid, 'y', $recflags, $zone, | 
|---|
| 6326 | $host, 12, $val, $dist, $weight, $port, $ttl, $loc, $stamp); | 
|---|
| 6327 |  | 
|---|
| 6328 | ##fixme: add a config flag to indicate use of the patch from http://www.fefe.de/dns/ | 
|---|
| 6329 | # type 6 is for AAAA+PTR, type 3 is for AAAA | 
|---|
| 6330 |  | 
|---|
| 6331 | } elsif ($type == 65282) { # PTR template | 
|---|
| 6332 |  | 
|---|
| 6333 | # only useful for v4 with standard DNS software, since this expands all | 
|---|
| 6334 | # IPs in $zone (or possibly $val?) with autogenerated records | 
|---|
| 6335 | $val = NetAddr::IP->new($val); | 
|---|
| 6336 | return if $val->{isv6}; | 
|---|
| 6337 |  | 
|---|
| 6338 | if ($val->masklen <= 16) { | 
|---|
| 6339 | foreach my $sub ($val->split(16)) { | 
|---|
| 6340 | $self->__publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, $zone, 1); | 
|---|
| 6341 | } | 
|---|
| 6342 | } else { | 
|---|
| 6343 | $self->__publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, $zone, 1); | 
|---|
| 6344 | } | 
|---|
| 6345 |  | 
|---|
| 6346 | } elsif ($type == 65283) { # A+PTR template | 
|---|
| 6347 |  | 
|---|
| 6348 | $val = NetAddr::IP->new($val); | 
|---|
| 6349 | # Just In Case.  An A+PTR should be impossible to add to a v6 revzone via API. | 
|---|
| 6350 | return if $val->{isv6}; | 
|---|
| 6351 |  | 
|---|
| 6352 | if ($val->masklen < 16) { | 
|---|
| 6353 | foreach my $sub ($val->split(16)) { | 
|---|
| 6354 | $self->__publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, $zone, 0); | 
|---|
| 6355 | } | 
|---|
| 6356 | } else { | 
|---|
| 6357 | $self->__publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, $zone, 0); | 
|---|
| 6358 | } | 
|---|
| 6359 |  | 
|---|
| 6360 | } elsif ($type == 65284) { # AAAA+PTR template | 
|---|
| 6361 | # Stub for completeness.  Could be exported to DNS software that supports | 
|---|
| 6362 | # some degree of internal automagic in generic-record-creation | 
|---|
| 6363 | # (eg http://search.cpan.org/dist/AllKnowingDNS/ ) | 
|---|
| 6364 |  | 
|---|
| 6365 | } elsif ($type == 65285) { # Delegation | 
|---|
| 6366 | # This is intended for reverse zones, but may prove useful in forward zones. | 
|---|
| 6367 |  | 
|---|
| 6368 | # All delegations need to create one or more NS records.  The NS record handler knows what to do. | 
|---|
| 6369 | $self->_printrec_tiny($datafile,$recid,$revrec,$recflags,$zone,$host,$reverse_typemap{'NS'}, | 
|---|
| 6370 | $val,$dist,$weight,$port,$ttl,$loc,$stamp); | 
|---|
| 6371 | if ($revrec eq 'y') { | 
|---|
| 6372 | # In the case of a sub-/24 v4 reverse delegation, we need to generate CNAMEs | 
|---|
| 6373 | # to redirect all of the individual IP lookups as well. | 
|---|
| 6374 | # OR | 
|---|
| 6375 | # create NS records for each IP | 
|---|
| 6376 | # Not sure how this would actually resolve if a /24 or larger was delegated | 
|---|
| 6377 | # one way, and a sub-/24 in that >=/24 was delegated elsewhere... | 
|---|
| 6378 | my $dblock = NetAddr::IP->new($val); | 
|---|
| 6379 | if (!$dblock->{isv6} && $dblock->masklen > 24) { | 
|---|
| 6380 | my @subs = $dblock->split; | 
|---|
| 6381 | foreach (@subs) { | 
|---|
| 6382 | next if $$recflags{"$_"}; | 
|---|
| 6383 | my ($oct) = ($_->addr =~ /(\d+)$/); | 
|---|
| 6384 | print $datafile "C"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$oct.". | 
|---|
| 6385 | _ZONE($dblock, 'ZONE.in-addr.arpa', 'r', '.').":$ttl:$stamp:$loc\n" or die $!; | 
|---|
| 6386 | $$recflags{"$_"}++; | 
|---|
| 6387 | } | 
|---|
| 6388 | } | 
|---|
| 6389 | } | 
|---|
| 6390 |  | 
|---|
| 6391 | ## | 
|---|
| 6392 | ## Uncommon types.  These will need better UI support Any Day Sometime Maybe(TM). | 
|---|
| 6393 | ## | 
|---|
| 6394 |  | 
|---|
| 6395 | } elsif ($type == 44) { # SSHFP | 
|---|
| 6396 |  | 
|---|
| 6397 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y'; | 
|---|
| 6398 |  | 
|---|
| 6399 | my ($algo,$fpt,$fp) = split /\s+/, $val; | 
|---|
| 6400 |  | 
|---|
| 6401 | my $rec = sprintf ":$host:44:\\%0.3o\\%0.3o", $algo, $fpt; | 
|---|
| 6402 | while (my ($byte) = ($fp =~ /^(..)/) ) { | 
|---|
| 6403 | $rec .= sprintf "\\%0.3o", hex($byte); | 
|---|
| 6404 | $fp =~ s/^..//; | 
|---|
| 6405 | } | 
|---|
| 6406 | print $datafile "$rec:$ttl:$stamp:$loc\n" or die $!; | 
|---|
| 6407 |  | 
|---|
| 6408 | } else { | 
|---|
| 6409 | # raw record.  we don't know what's in here, so we ASS-U-ME the user has | 
|---|
| 6410 | # put it in correctly, since either the user is messing directly with the | 
|---|
| 6411 | # database, or the record was imported via AXFR | 
|---|
| 6412 | # <split by char> | 
|---|
| 6413 | # convert anything not a-zA-Z0-9.- to octal coding | 
|---|
| 6414 |  | 
|---|
| 6415 | ##fixme: add flag to export "unknown" record types - note we'll probably end up | 
|---|
| 6416 | # mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr. | 
|---|
| 6417 | #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n"; | 
|---|
| 6418 |  | 
|---|
| 6419 | } # record type if-else | 
|---|
| 6420 |  | 
|---|
| 6421 | } # end _printrec_tiny() | 
|---|
| 6422 |  | 
|---|
| 6423 |  | 
|---|
| 6424 | ## DNSDB::mailNotify() | 
|---|
| 6425 | # Sends notification mail to recipients regarding a DNSDB operation | 
|---|
| 6426 | sub mailNotify { | 
|---|
| 6427 | my $self = shift; | 
|---|
| 6428 | my $dbh = $self->{dbh}; | 
|---|
| 6429 | my ($subj,$message) = @_; | 
|---|
| 6430 |  | 
|---|
| 6431 | return if $self->{mailhost} eq 'smtp.example.com';   # do nothing if still using default SMTP host. | 
|---|
| 6432 |  | 
|---|
| 6433 | my $mailer = Net::SMTP->new($self->{mailhost}, Hello => "dnsadmin.$self->{domain}"); | 
|---|
| 6434 |  | 
|---|
| 6435 | my $mailsender = ($self->{mailsender} ? $self->{mailsender} : $self->{mailnotify}); | 
|---|
| 6436 |  | 
|---|
| 6437 | $mailer->mail($mailsender); | 
|---|
| 6438 | $mailer->to($self->{mailnotify}); | 
|---|
| 6439 | $mailer->data("From: \"$self->{mailname}\" <$mailsender>\n", | 
|---|
| 6440 | "To: <$self->{mailnotify}>\n", | 
|---|
| 6441 | "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n", | 
|---|
| 6442 | "Subject: $subj\n", | 
|---|
| 6443 | "X-Mailer: DNSAdmin v".$DNSDB::VERSION." Notify\n", | 
|---|
| 6444 | "Organization: $self->{orgname}\n", | 
|---|
| 6445 | "\n$message\n"); | 
|---|
| 6446 | $mailer->quit; | 
|---|
| 6447 | } | 
|---|
| 6448 |  | 
|---|
| 6449 | # shut Perl up | 
|---|
| 6450 | 1; | 
|---|