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