Skip to content

Instantly share code, notes, and snippets.

@ysugimoto
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ysugimoto/49bad7ffa0469f434d6e to your computer and use it in GitHub Desktop.
Save ysugimoto/49bad7ffa0469f434d6e to your computer and use it in GitHub Desktop.
<?php
class GetZoneInfo {
const ORIGIN_SIGNATURE = '$ORIGIN';
const IN_SIGNATURE = 'IN';
const A_RECORD = "A";
const CNAME_RECORD = "CNAME";
protected $fqdnList = [];
protected $cnames = [];
public function __construct($dirPath) {
$this->parse($dirPath);
}
public function getFQDN($ipAddress) {
$ret = [];
foreach ( $this->fqdnList as $fqdn ) {
if ( $fqdn->ipAddress !== $ipAddress ) {
continue;
}
$ret[] = $fqdn->fqdn;
}
return $ret;
}
protected function parse($dirPath) {
$iter = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dirPath)
);
// Initialize first
$isFirstOrigin = true;
// Get file path from file list.
foreach ( $iter as $file ) {
if ( $file->isDir() ) {
continue;
}
$lines = file($file->getPathname());
foreach ( $lines as $line ) {
$line = preg_replace("/[ \s]+/", " ", trim($line));
$this->parseLineData(explode(" ", $line), $isFirstOrigin);
}
}
// Parse stacked cnames and convert to FQDN list
$this->mergeCnamesToFQDN();
}
protected function parseLineData(array $lineData, &$isFirstOrigin) {
switch ( $lineData[0] ) {
case static::ORIGIN_SIGNATURE:
if ( $isFirstOrigin === true ) {
$isFirstOrigin = false;
} else {
$this->domain = $lineData[1];
}
break;
case static::A_RECORD:
$info = new stdClass;
$info->fqdn = $this->domain;
$info->ipAddress = $lineData[1];
$this->fqdnList[] = $info;
break;
default:
$this->detectLineData($lineData);
break;
}
}
private function detectLineData(&$lineData) {
if ( ! isset($lineData[1]) ) {
return;
}
switch ( $lineData[1] ) {
case static::IN_SIGNATURE:
$this->domain = $lineData[0];
break;
case static::A_RECORD:
$info = new stdClass;
$info->fqdn = $lineData[0] . "." . substr($this->domain, 0 , -1);
$info->ipAddress = $lineData[2];
$this->fqdnList[] = $info;
break;
case static::CNAME_RECORD:
$cname = new stdClass;
$cname->origin = substr($this->domain, 0, -1);
$cname->fqdn = $lineData[0] . "." . $cname->origin;
$cname->ipAddress = $lineData[2];
$this->cnames[] = $cname;
break;
}
}
protected function mergeCnamesToFQDN() {
foreach ( $this->cnames as $ci => $cname ) {
if ( false === ($fqdn = $this->findByFQDNList($cname)) ) {
continue;
}
$cname->ipAddress = $fqdn->ipAddress;
$this->fqdnList[] = $cname;
}
}
protected function findByFQDNList(stdClass $cname) {
foreach ( $this->fqdnList as $fqdn ) {
if ( $cname->ipAddress . "." . $cname->origin === $fqdn->fqdn ) {
return $fqdn;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment