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