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