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