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