function gethostbyaddr6($ip) { include_once 'Net/DNS2.php'; include_once 'Net/DNS2/RR/PTR.php'; $ptr = FALSE; $resolver = new Net_DNS2_Resolver(); try { $response = $resolver->query($ip, 'PTR'); if ($response) { $ptr = $response->answer[0]->ptrdname; } } catch (Net_DNS2_Exception $e) { } return $ptr; }
/** * function to test the resolver * * @return void * @access public * */ public function testResolver() { $ns = array('8.8.8.8', '8.8.4.4'); $r = new Net_DNS2_Resolver(array('nameservers' => $ns)); $result = $r->query('google.com', 'MX'); $this->assertSame($result->header->qr, Net_DNS2_Lookups::QR_RESPONSE); $this->assertSame(count($result->question), 1); $this->assertTrue(count($result->answer) > 0); $this->assertTrue($result->answer[0] instanceof Net_DNS2_RR_MX); }
/** * function to test the TSIG logic * * @return void * @access public * */ public function testDNSSEC() { $ns = array('8.8.8.8', '8.8.4.4'); $r = new Net_DNS2_Resolver(array('nameservers' => $ns)); $r->dnssec = true; $result = $r->query('org', 'SOA', 'IN'); $this->assertTrue($result->header->ad == 1); $this->assertTrue($result->additional[0] instanceof Net_DNS2_RR_OPT); $this->assertTrue($result->additional[0]->do == 1); }
public function check($ip) { $r = new Net_DNS2_Resolver(array()); $parts = explode('.', $ip); $fails = array(); foreach (self::$blacklists as $b) { try { $r->query(sprintf('%d.%d.%d.%d.%s', $parts[3], $parts[2], $parts[1], $parts[0], $b), 'A'); } catch (Net_DNS2_Exception $e) { continue; } $fails[] = array('ip' => $ip, 'list' => $b); } return $fails; }
function has_dns_propagated($domain, $token) { //use a public DNS server as that's what Let's Encrypt will use $ns = array('8.8.8.8', '8.8.4.4'); try { $r = new Net_DNS2_Resolver(array('nameservers' => $ns)); $result = $r->query($domain, 'TXT'); } catch (Net_DNS2_Exception $e) { return false; } if ($result->answer[0]->text[0] == $token) { return true; } else { return false; } }
/** * Recieve MX records for a host. * * @param string $host Mail host. * * @return mixed Sorted MX list or false on error. */ protected function _getMx($host) { $mx = array(); if ($this->params['netdns']) { $this->_loadNetDns(); try { $response = $this->_resolver->query($host, 'MX'); if (!$response) { return false; } } catch (Exception $e) { throw new Horde_Mail_Exception($e); } foreach ($response->answer as $rr) { if ($rr->type == 'MX') { $mx[$rr->exchange] = $rr->preference; } } } else { $mxHost = $mxWeight = array(); if (!getmxrr($host, $mxHost, $mxWeight)) { return false; } for ($i = 0; $i < count($mxHost); ++$i) { $mx[$mxHost[$i]] = $mxWeight[$i]; } } asort($mx); return $mx; }
/** * Gets records form name server for given dns zone * * @param string $zone DNS zone to look for e.g. example.com * @param string $ns Name server ip * @param string $type Record type * @return array */ public static function getRecords($zone, $ns, $type) { $r = new Net_DNS2_Resolver(['nameservers' => [gethostbyname($ns)]]); try { $records = $r->query($zone, $type)->answer; } catch (Net_DNS2_Exception $e) { if ($e->getCode() == Net_DNS2_Lookups::RCODE_NXDOMAIN) { return []; } else { if ($e->getCode() == Net_DNS2_Lookups::RCODE_NOTAUTH) { return false; } else { return $e->getMessage() . " {$ns} quered by query( {$zone}, {$type} )"; } } } return $records; }
public function create(Horde_Injector $injector) { if (!class_exists('Net_DNS2_Resolver')) { return null; } if ($tmpdir = Horde::getTempDir()) { $config = array('cache_file' => $tmpdir . '/horde_dns.cache', 'cache_size' => 100000, 'cache_type' => 'file'); } else { $config = array(); } $resolver = new Net_DNS2_Resolver($config); if (is_readable('/etc/resolv.conf')) { try { $resolver->setServers('/etc/resolv.conf'); } catch (Net_DNS2_Exception $e) { } } return $resolver; }
function VerifMXemail($email) { if (CHECKMX) { $domaine = explode('@', $email); $r = new Net_DNS2_Resolver(array('nameservers' => array(NS1, NS2))); try { $result = $r->query($domaine[1], 'MX'); } catch (Net_DNS2_Exception $e) { return false; } if ($result->answer) { return true; } else { return false; } } else { return true; } }
public function getresult() { $ip = $_GET['ip']; $id = $_GET['id']; $domain = $_GET['url']; $parametro = $_GET['type']; $data = array(); $r = new \Net_DNS2_Resolver(array('nameservers' => array($ip))); try { $result = $r->query($domain, $parametro); foreach ($result->answer as $record) { if ($parametro == 'A' || $parametro == 'AAAA') { $show = $record->address; } elseif ($parametro == 'CNAME') { $show = $record; } elseif ($parametro == 'MX') { $show = $record->preference . ' ' . $record->exchange; } elseif ($parametro == 'NS') { $show = $record->nsdname; } elseif ($parametro == 'PTR') { $show = $record; } elseif ($parametro == 'SOA') { $show = $record->mname . ' ' . $record->rname . ' ' . $record->serial . ' ' . $record->refresh . ' ' . $record->retry . ' ' . $record->expire . ' ' . $record->minimum; } elseif ($parametro == 'SRV') { $show = $record; } elseif ($parametro == 'TXT') { $show = $record->text; } if ($show) { $data[] = $show; } else { $data[] = 0; } } } catch (\Net_DNS2_Exception $e) { if ($e->getMessage()) { $data[] = 'error'; } } $data2[$id] = $data; echo json_encode($data2); }
/** * Looks up a hostname by ip address to see if we can infer and institution * * We use this instead of standard php function gethostbyaddr because we need * the timeout to prevent load issues. * * @param string $ip the ip address to look up * @param string|array $dns the dns server to use * @param int $timeout the timeout after which requests should expire * @return string **/ private static function getHostByAddress($ip, $dns, $timeout = 2) { try { $resolver = new Net_DNS2_Resolver(['nameservers' => (array) $dns, 'timeout' => $timeout]); $result = $resolver->query($ip, 'PTR'); } catch (Net_DNS2_Exception $e) { return $ip; } if ($result && isset($result->answer) && count($result->answer) > 0 && isset($result->answer[0]->ptrdname)) { return $result->answer[0]->ptrdname; } return $ip; }
function check_dns($domain) { $todo = array(); $dns_records = dns_get_record($domain, DNS_NS); if (!count($dns_records)) { echo "\n[1;33mhost {$domain} not found[0m\n"; } $dns_servers = array(); foreach ($dns_records as $dns_record) { foreach (gethostbynamel($dns_record['target']) as $ip) { // Round-robin DNS array_push($dns_servers, $ip); } } foreach ($dns_servers as $dns_server) { echo "\n[1;32m" . $dns_server . ' (' . gethostbyaddr($dns_server) . ") AXFR {$domain}[0m\n"; $result = NULL; $r = new Net_DNS2_Resolver(array('nameservers' => array($dns_server))); try { $result = $r->query($domain, 'AXFR'); } catch (Net_DNS2_Exception $e) { echo "[1;31m::query() failed: ", $e->getMessage(), "[0m\n"; } if ($result) { foreach ($result->answer as $rr) { if (preg_match('/ IN NS /i', $rr) && !preg_match("/^{$domain}/i", $rr)) { echo "[1;35m{$rr}[0m\n"; $ns = rtrim(reset(explode(' ', $rr)), '.'); array_push($todo, $ns); } else { echo "{$rr}\n"; } } } } $todo = array_unique($todo); return $todo; }
/** * Filter list by removing non-existent hosts. * * @param array $hosts List of possible servers (objects). * * @return mixed Array of existing hosts, or false if none exist. */ protected function _resolveHosts($hosts) { $out = array(); if (is_null($this->dns)) { $this->dns = new Net_DNS2_Resolver(); } foreach ($hosts as $val) { try { $this->dns->query($val->host, 'A'); $out[] = $val; } catch (Net_DNS2_Exception $e) { // Not found; ignore. } } return count($out) ? $out : false; }
/** * Get country information from a hostname or IP address. * * @param string $host The hostname or IP address. * @param string $datafile The datafile for the GeoIP lookup. If not set, * will skip this lookup. * * @return mixed On success, return an array with the following entries: * 'code' => Country Code * 'name' => Country Name * On failure, return false. */ public static function getCountryByHost($host, $datafile = null) { /* List of generic domains that we know is not in the country TLD list. See: http://www.iana.org/gtld/gtld.htm */ $generic = array('aero', 'biz', 'com', 'coop', 'edu', 'gov', 'info', 'int', 'mil', 'museum', 'name', 'net', 'org', 'pro'); $checkHost = null; if (preg_match('/^\\d+\\.\\d+\\.\\d+\\.\\d+$/', $host)) { if (isset(self::$dnsResolver)) { try { $response = self::$dnsResolver->query($host, 'PTR'); foreach ($response->answer as $val) { if (isset($val->ptrdname)) { $checkHost = $val->ptrdname; break; } } } catch (Net_DNS2_Exception $e) { } } if (is_null($checkHost)) { $checkHost = @gethostbyaddr($host); } } else { $checkHost = $host; } /* Get the TLD of the hostname. */ $pos = strrpos($checkHost, '.'); if ($pos === false) { return false; } $domain = Horde_String::lower(substr($checkHost, $pos + 1)); /* Try lookup via TLD first. */ if (!in_array($domain, $generic)) { $name = self::tldLookup($domain); if ($name) { return array('code' => $domain, 'name' => $name); } } /* Try GeoIP lookup next. */ $geoip = new Horde_Nls_Geoip($datafile); return $geoip->getCountryInfo($checkHost); }
public static function GetDNSRecord($domain, $types = array("MX", "A"), $nameservers = array("8.8.8.8", "8.8.4.4"), $cache = true) { // Check for a mail server based on a DNS lookup. if (!class_exists("Net_DNS2_Resolver")) { require_once str_replace("\\", "/", dirname(__FILE__)) . "/Net/DNS2.php"; } $resolver = new Net_DNS2_Resolver(array("nameservers" => $nameservers)); try { foreach ($types as $type) { $response = $resolver->query($domain, $type); if ($response && count($response->answer)) { if ($cache) { $minttl = -1; foreach ($response->answer as $answer) { if ($minttl < 0 || $answer->ttl > 0 && $answer->ttl < $minttl) { $minttl = $answer->ttl; } } self::$dnsttlcache[$domain] = time() + $minttl; } return array("success" => true, "type" => $type, "records" => $response); } } return array("success" => false, "error" => self::SMTP_Translate("Invalid domain name or missing DNS record."), "errorcode" => "invalid_domain_or_missing_record", "info" => $domain); } catch (Exception $e) { return array("success" => false, "error" => self::SMTP_Translate("Invalid domain name. Internal exception occurred."), "errorcode" => "dns_library_exception", "info" => self::SMTP_Translate("%s (%s).", $e->getMessage(), $domain)); } }
function axfr($args) { foreach (array("zone", "key-name", "key-type", "key", "server") as $val) { if (empty($args[$val])) { output_error('Invalid request, "' . $val . '" field is mandatory', 400); } } $r = new Net_DNS2_Resolver(array('nameservers' => array($args['server']))); $r->signTSIG($args['key-name'], $args['key'], $args['key-type']); $data = resolve($r, $args['zone'], 'AXFR'); $records = array_map(function ($r) { return array('name' => $r->name, 'ttl' => $r->ttl, 'type' => $r->type, 'data' => implode(' ', array_slice(explode(' ', $r), 4))); }, $data->answer); output(array("records" => $records)); }
function query() { $resolv = new resolv_conf(); $dns = new DNSTypes(); $DNS = array(); $extendanswer = true; $q = new mysql_squid_builder(); $sql = "SELECT * FROM dns_servers ORDER BY zOrder"; $results = $q->QUERY_SQL($sql); $c = 1; $DNS[] = $_GET["dns"]; while ($ligne = mysql_fetch_assoc($results)) { $DNS[] = $ligne["dnsserver"]; } $query = $_GET["query"]; if ($query == null) { $query = "www.artica.fr"; } if ($resolv->MainArray["DNS1"] != null) { $DNS[] = $resolv->MainArray["DNS1"]; } if ($resolv->MainArray["DNS2"] != null) { $DNS[] = $resolv->MainArray["DNS2"]; } if ($resolv->MainArray["DNS3"] != null) { $DNS[] = $resolv->MainArray["DNS3"]; } $type = $dns->types_by_id[$_GET["type"]]; echo "<div style='width:98%' class=form>"; while (list($index, $dnsA) = each($DNS)) { $type = "A"; echo "<hr><div style='font-size:18px;margin-top:10px'>DNS {$dnsA} - {$type}</div>"; $rs = new Net_DNS2_Resolver(array('nameservers' => array($dnsA))); try { $result = $rs->query($query, "A"); } catch (Net_DNS2_Exception $e) { echo "<div style='font-size:16px;color:#d32d2d'>Failed to query: " . $e->getMessage() . "</div>"; continue; } echo "<ul>"; foreach ($result->answer as $record) { echo "<li><strong>Name:</strong> {$record->name}</li>"; echo "<li><strong>Type:</strong> {$record->type}</li>"; echo "<li><strong>Address:</strong> {$record->address}</li>"; echo "<li><strong>TTL:</strong> {$record->ttl}</li>"; } echo "</ul>"; } echo "</div>"; }
/** * Perform the SRV search. * * @param array $domains List of domains to search. * @param array $queries The SRV queries to run. * * @return mixed False if no servers found, or a list of server objects * in order of decreasing priority. */ protected function _srvSearch($domains, $queries) { $obs = $out = array(); if (is_null($this->dns)) { $this->dns = new Net_DNS2_Resolver(); } foreach ($domains as $val) { foreach ($queries as $val2) { try { $res = $this->dns->query($val2 . '._tcp.' . $val, 'SRV'); foreach ($res->answer as $val3) { if (strlen($val3->target)) { $val3->query = $val2; $obs[$val3->priority][] = $val3; } } } catch (Net_DNS2_Exception $e) { // Not found; ignore. } } } if (empty($obs)) { return false; } /* Sort via priority ranking. Lower value is higher priority. */ ksort($obs, SORT_NUMERIC); foreach ($obs as $val) { /* Do weight determination if a multiple servers have identical * priorities. */ if (count($val) > 1) { /* Weight determination algorithm is defined in RFC 2782. * First, move all entries with weight 0 to beginning of * list. */ $tmp = array(); foreach ($val as $key2 => $val2) { if (empty($val2->weight)) { $tmp[] = $val2; unset($val[$key2]); } } $tmp = array_merge($tmp, $val); $val = array(); while (count($tmp) > 1) { $i = 0; /* Next, iterate over list and update the "running * sum": the incremental value of each entry's weight. */ foreach ($tmp as $val2) { $i += $val2->weight; $val2->running = $i; } /* Finally, select a random number in the range of 0->$i. * The first entry in the list (sequentially) that has a * running total >= to this random number is the next * server in the priority list. */ $rand = mt_rand(0, $i); foreach ($tmp as $key2 => $val2) { if ($val2->running >= $rand) { $val[] = $val2; /* Remove this server from the list. */ unset($tmp[$key2]); break; } } /* Repeat until we have a single entry left in $tmp. */ } /* One entry left in $tmp, so add to $val. */ $val[] = reset($tmp); } foreach ($val as $val2) { switch ($val2->query) { case '_imap': $tmp = new Horde_Mail_Autoconfig_Server_Imap(); break; case '_imaps': $tmp = new Horde_Mail_Autoconfig_Server_Imap(); $tmp->tls = 'tls'; break; case '_pop3': $tmp = new Horde_Mail_Autoconfig_Server_Pop3(); break; case '_pop3s': $tmp = new Horde_Mail_Autoconfig_Server_Pop3(); $tmp->tls = 'tls'; break; case '_submission': $tmp = new Horde_Mail_Autoconfig_Server_Msa(); break; } $tmp->host = strval($val2->target); $tmp->port = intval($val2->port); $out[] = $tmp; } } return $out; }
function get_geolocation($address, $geo_db = array()) { global $config; $location = array('location' => $address); // Init location array switch (strtolower($config['geocoding']['api'])) { case 'osm': case 'openstreetmap': $location['location_geoapi'] = 'openstreetmap'; // Openstreetmap. The usage limits are stricter here. (http://wiki.openstreetmap.org/wiki/Nominatim_usage_policy) $url = "http://nominatim.openstreetmap.org/search?format=json&accept-language=en&addressdetails=1&limit=1&q="; $reverse_url = "http://nominatim.openstreetmap.org/reverse?format=json&accept-language=en&"; break; case 'google': $location['location_geoapi'] = 'google'; // See documentation here: https:// developers.google.com/maps/documentation/geocoding/ // Use of the Google Geocoding API is subject to a query limit of 2,500 geolocation requests per day. $url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&language=en&address="; $reverse_url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&language=en&"; break; case 'yandex': $location['location_geoapi'] = 'yandex'; $url = "http://geocode-maps.yandex.ru/1.x/?format=json&lang=en_US&results=1&geocode="; $reverse_url = "http://geocode-maps.yandex.ru/1.x/?format=json&lang=en_US&results=1&sco=latlong&"; break; case 'mapquest': default: $location['location_geoapi'] = 'mapquest'; // Mapquest open data. There are no usage limits. $url = "http://open.mapquestapi.com/nominatim/v1/search.php?format=json&accept-language=en&addressdetails=1&limit=1&q="; $reverse_url = "http://open.mapquestapi.com/nominatim/v1/reverse.php?format=json&accept-language=en&"; } if (isset($config['geocoding']['enable']) && $config['geocoding']['enable']) { $reverse = FALSE; // by default forward geocoding $debug_msg = "Geocoding启用, 尝试定位设备坐标." . PHP_EOL; // If device coordinates set manually, use Reverse Geocoding. if ($geo_db['location_manual']) { $location['location_lat'] = $geo_db['location_lat']; $location['location_lon'] = $geo_db['location_lon']; $reverse = TRUE; $debug_msg .= ' MANUAL coordinates - SET' . PHP_EOL; } else { if ($config['geocoding']['dns']) { /** * Ack! dns_get_record not only cannot retrieve LOC records, but it also actively filters them when using * DNS_ANY as query type (which, admittedly would not be all that reliable as per the manual). * * Example LOC: * "20 31 55.893 N 4 57 38.269 E 45.00m 10m 100m 10m" * * From Wikipedia: d1 [m1 [s1]] {"N"|"S"} d2 [m2 [s2]] {"E"|"W"} * * Parsing this is something for Net_DNS2 as it has the code for it. */ if ($geo_db['hostname']) { include_once 'Net/DNS2.php'; include_once 'Net/DNS2/RR/LOC.php'; $resolver = new Net_DNS2_Resolver(); try { $response = $resolver->query($geo_db['hostname'], 'LOC', 'IN'); } catch (Net_DNS2_Exception $e) { print_debug(' ' . $e->getMessage() . ' (' . $geo_db['hostname'] . ')'); } } else { $response = FALSE; print_debug(" DNS 位置已激活, 不过设备主机名为空."); } if ($response) { if (OBS_DEBUG > 1) { var_dump($response->answer); } foreach ($response->answer as $answer) { if (is_numeric($answer->latitude) && is_numeric($answer->longitude)) { $location['location_lat'] = $answer->latitude; $location['location_lon'] = $answer->longitude; $reverse = TRUE; break; } else { if (is_numeric($answer->degree_latitude) && is_numeric($answer->degree_longitude)) { $ns_multiplier = $answer->ns_hem == 'N' ? 1 : -1; $ew_multiplier = $answer->ew_hem == 'E' ? 1 : -1; $location['location_lat'] = round($answer->degree_latitude + $answer->min_latitude / 60 + $answer->sec_latitude / 3600, 7) * $ns_multiplier; $location['location_lon'] = round($answer->degree_longitude + $answer->min_longitude / 60 + $answer->sec_longitude / 3600, 7) * $ew_multiplier; $reverse = TRUE; break; } } } if (isset($location['location_lat'])) { $debug_msg .= ' 通过DNS位置记录 - 找到' . PHP_EOL; } else { $debug_msg .= ' 通过DNS位置记录 - 未找到' . PHP_EOL; } } } } if ($reverse || !preg_match('/^<?(unknown|none)>?$/i', $address)) { /** * If location string contains coordinates use Reverse Geocoding. * Valid strings: * Some location [33.234, -56.22] * Some location (33.234 -56.22) * Some location [33.234;-56.22] * 33.234,-56.22 */ $pattern = '/(?:^|[\\[(])\\s*(?<lat>[+-]?\\d+(?:\\.\\d+)*)\\s*[,; ]\\s*(?<lon>[+-]?\\d+(?:\\.\\d+)*)\\s*(?:[\\])]|$)/'; if (!$reverse && preg_match($pattern, $address, $matches)) { if ($matches['lat'] >= -90 && $matches['lat'] <= 90 && $matches['lon'] >= -180 && $matches['lon'] <= 180) { $location['location_lat'] = $matches['lat']; $location['location_lon'] = $matches['lon']; $reverse = TRUE; } } if ($reverse) { $debug_msg .= ' by REVERSE query (API: ' . strtoupper($config['geocoding']['api']) . ', LAT: ' . $location['location_lat'] . ', LON: ' . $location['location_lon'] . ') - '; if (!is_numeric($location['location_lat']) || !is_numeric($location['location_lat'])) { // Do nothing for empty, skip requests for empty coordinates } else { if ($config['geocoding']['api'] == 'google') { // latlng=40.714224,-73.961452 $request = $reverse_url . 'latlng=' . $location['location_lat'] . ',' . $location['location_lon']; } else { if ($config['geocoding']['api'] == 'yandex') { // geocode=40.714224,-73.961452 $request = $reverse_url . 'geocode=' . $location['location_lat'] . ',' . $location['location_lon']; } else { // lat=51.521435&lon=-0.162714 $request = $reverse_url . 'lat=' . $location['location_lat'] . '&lon=' . $location['location_lon']; } } } } else { $debug_msg .= ' by PARSING sysLocation (API: ' . strtoupper($config['geocoding']['api']) . ') - '; if ($address != '') { $request = $url . urlencode($address); } } if ($request) { // First request $mapresponse = get_http_request($request); $data = json_decode($mapresponse, TRUE); $geo_status = 'NOT FOUND'; if ($config['geocoding']['api'] == 'google') { if ($data['status'] == 'OVER_QUERY_LIMIT') { $debug_msg .= $geo_status; print_debug($debug_msg); // Return empty array for overquery limit (for later recheck) return array('location_status' => $debug_msg); } // Use google data only with good status response if ($data['status'] == 'OK') { $data = $data['results'][0]; if ($data['geometry']['location_type'] == 'APPROXIMATE') { // It might be that the first element of the address is a business name. // Lets drop the first element and see if we get anything better! list(, $address) = explode(',', $address, 2); $request_new = $url . urlencode($address); $mapresponse = get_http_request($request_new); $data_new = json_decode($mapresponse, TRUE); if ($data_new['status'] == 'OK' && $data_new['results'][0]['geometry']['location_type'] != 'APPROXIMATE') { $request = $request_new; $data = $data_new['results'][0]; } } } } else { if ($config['geocoding']['api'] == 'yandex') { $try_new = FALSE; if ($data['response']['GeoObjectCollection']['metaDataProperty']['GeocoderResponseMetaData']['found'] > 0) { $data = $data['response']['GeoObjectCollection']['featureMember'][0]; if ($data['GeoObject']['metaDataProperty']['GeocoderMetaData']['precision'] == 'other') { $try_new = TRUE; } } else { $try_new = TRUE; } if ($try_new && strpos($address, ',')) { // It might be that the first element of the address is a business name. // Lets drop the first element and see if we get anything better! list(, $address) = explode(',', $address, 2); $request_new = $url . urlencode($address); $mapresponse = get_http_request($request_new); $data_new = json_decode($mapresponse, TRUE); if ($data_new['response']['GeoObjectCollection']['metaDataProperty']['GeocoderResponseMetaData']['found'] > 0 && $data_new['response']['GeoObjectCollection']['featureMember'][0]['GeoObject']['metaDataProperty']['GeocoderMetaData']['precision'] != 'other') { $request = $request_new; $data = $data_new['response']['GeoObjectCollection']['featureMember'][0]; } } } else { if (!isset($location['location_lat'])) { $data = $data[0]; if (!count($data) && strpos($address, ',')) { // We seem to have hit a snag geocoding. It might be that the first element of the address is a business name. // Lets drop the first element and see if we get anything better! This works more often than one might expect. list(, $address) = explode(',', $address, 2); $request_new = $url . urlencode($address); $mapresponse = get_http_request($request_new); $data_new = json_decode($mapresponse, TRUE); if (count($data_new[0])) { // We only want the first entry in the returned data. $data = $data_new[0]; $request = $request_new; } } } } } if (OBS_DEBUG > 1 && count($data)) { var_dump($data); } } else { $geo_status = '没有要求'; } } } // Put the values from the data array into the return array where they exist, else replace them with defaults or Unknown. if ($config['geocoding']['api'] == 'google') { $location['location_lat'] = $data['geometry']['location']['lat']; $location['location_lon'] = $data['geometry']['location']['lng']; foreach ($data['address_components'] as $entry) { switch ($entry['types'][0]) { case 'postal_town': case 'locality': $location['location_city'] = $entry['long_name']; break; case 'administrative_area_level_2': $location['location_county'] = $entry['long_name']; break; case 'administrative_area_level_1': $location['location_state'] = $entry['long_name']; break; case 'country': $location['location_country'] = strtolower($entry['short_name']); break; } } } else { if ($config['geocoding']['api'] == 'yandex') { list($location['location_lon'], $location['location_lat']) = explode(' ', $data['GeoObject']['Point']['pos']); $data = $data['GeoObject']['metaDataProperty']['GeocoderMetaData']['AddressDetails']; $location['location_country'] = strtolower($data['Country']['CountryNameCode']); $location['location_state'] = $data['Country']['AdministrativeArea']['AdministrativeAreaName']; $location['location_county'] = $data['Country']['AdministrativeArea']['SubAdministrativeArea']['SubAdministrativeAreaName']; $location['location_city'] = $data['Country']['AdministrativeArea']['SubAdministrativeArea']['Locality']['LocalityName']; } else { $location['location_lat'] = $data['lat']; $location['location_lon'] = $data['lon']; $location['location_city'] = strlen($data['address']['town']) ? $data['address']['town'] : $data['address']['city']; // Would be nice to have an array of countries where we want state, and ones where we want County. For example, USA wants state, UK wants county. $location['location_county'] = $data['address']['county']; $location['location_state'] = $data['address']['state']; $location['location_country'] = $data['address']['country_code']; } } // Use defaults if empty values if (!strlen($location['location_lat']) || !strlen($location['location_lon'])) { // Reset to empty coordinates $location['location_lat'] = array('NULL'); $location['location_lon'] = array('NULL'); //$location['location_lat'] = $config['geocoding']['default']['lat']; //$location['location_lon'] = $config['geocoding']['default']['lon']; //if (is_numeric($config['geocoding']['default']['lat']) && is_numeric($config['geocoding']['default']['lon'])) //{ // $location['location_manual'] = 1; // Set manual key for ability reset from WUI //} } else { // Always round lat/lon same as DB precision (DECIMAL(10,7)) $location['location_lat'] = round($location['location_lat'], 7); $location['location_lon'] = round($location['location_lon'], 7); } if (!strlen($location['location_city'])) { $location['location_city'] = '未知的城市'; } if (!strlen($location['location_county'])) { $location['location_county'] = '未知的城镇'; } if (!strlen($location['location_state'])) { $location['location_state'] = '未知的省份'; } if (!strlen($location['location_country'])) { $location['location_country'] = '未知的国家'; } else { $geo_status = 'FOUND'; } // Print some debug informations $debug_msg .= $geo_status . PHP_EOL; $debug_msg .= ' GEO API REQUEST: ' . $request; if ($geo_status == 'FOUND') { $debug_msg .= PHP_EOL . ' GEOLOCATION: '; $debug_msg .= country_from_code($location['location_country']) . ' (Country), ' . $location['location_state'] . ' (State), '; $debug_msg .= $location['location_county'] . ' (County), ' . $location['location_city'] . ' (City)'; $debug_msg .= PHP_EOL . ' GEO COORDINATES: '; $debug_msg .= $location['location_lat'] . ' (Latitude), ' . $location['location_lon'] . ' (Longitude)'; } else { $debug_msg .= PHP_EOL . ' QUERY DATE: ' . date('r'); // This is requered for increase data in DB } print_debug($debug_msg); $location['location_status'] = $debug_msg; return $location; }
/** * Function: isVerified * * This will help verify the content, integrity, oversight, and origin * of plugins, language packs and other modules distributed for * osTicket. * * This idea is that the signature of the PHAR file will be registered * in DNS, for instance, * `7afc8bf80b0555bed88823306744258d6030f0d9.updates.osticket.com`, for * a PHAR file with a SHA1 signature of * `7afc8bf80b0555bed88823306744258d6030f0d9 `, which will resolve to a * string like the following: * ``` * "v=1; i=storage:s3; s=MEUCIFw6A489eX4Oq17BflxCZ8+MH6miNjtcpScUoKDjmb * lsAiEAjiBo9FzYtV3WQtW6sbhPlJXcoPpDfYyQB+BFVBMps4c=; V=0.1;" * ``` * Which is a simple semicolon separated key-value pair string with the * following keys * * Key | Description * :----|:--------------------------------------------------- * v | Algorithm version * i | Plugin 'id' registered in plugin.php['id'] * V | Plugin 'version' registered in plugin.php['version'] * s | OpenSSL signature of the PHAR SHA1 signature using a * | private key (specified on the command line) * * The public key, which will be distributed with osTicket, can be used * to verify the signature of the PHAR file from the data received from * DNS. * * Parameters: * $phar - (string) filename of phar file to verify * * Returns: * (int) - * Plugin::VERIFIED upon success * Plugin::VERIFY_DNS_PASS if found in DNS but cannot verify sig * Plugin::VERIFY_NO_KEY if public key not found in include/plugins * Plugin::VERIFY_FAILED if the plugin fails validation * Plugin::VERIFY_EXT_MISSING if a PHP extension is required * Plugin::VERIFY_ERROR if an unexpected error occurred */ static function isVerified($phar) { static $pubkey = null; if (!class_exists('Phar')) { return self::VERIFY_EXT_MISSING; } elseif (!file_exists(INCLUDE_DIR . '/plugins/updates.pem')) { return self::VERIFY_NO_KEY; } if (!isset($pubkey)) { $pubkey = openssl_pkey_get_public(file_get_contents(INCLUDE_DIR . 'plugins/updates.pem')); } if (!$pubkey) { return self::VERIFY_ERROR; } require_once PEAR_DIR . 'Net/DNS2.php'; $P = new Phar($phar); $sig = $P->getSignature(); $info = array(); try { $q = new Net_DNS2_Resolver(); $r = $q->query(strtolower($sig['hash']) . '.' . self::$verify_domain, 'TXT'); foreach ($r->answer as $rec) { foreach ($rec->text as $txt) { foreach (explode(';', $txt) as $kv) { list($k, $v) = explode('=', trim($kv)); $info[$k] = trim($v); } if ($info['v'] && $info['s']) { break; } } } } catch (Net_DNS2_Exception $e) { // TODO: Differenciate NXDOMAIN and DNS failure } if (is_array($info) && isset($info['v'])) { switch ($info['v']) { case '1': if (!($signature = base64_decode($info['s']))) { return self::VERIFY_FAILED; } elseif (!function_exists('openssl_verify')) { return self::VERIFY_DNS_PASS; } $codes = array(-1 => self::VERIFY_ERROR, 0 => self::VERIFY_FAILED, 1 => self::VERIFIED); $result = openssl_verify($sig['hash'], $signature, $pubkey, OPENSSL_ALGO_SHA1); return $codes[$result]; } } return self::VERIFY_FAILED; }
function check_CNAME_conflict($domain, &$err) { $resolver = new Net_DNS2_Resolver(array('nameservers' => array('127.0.0.1'), 'use_tcp' => true)); try { $res = $resolver->query($domain, 'CNAME'); } catch (Net_DNS2_Exception $e) { // array_push($errors, $e->getMessage()); return true; } if (isset($res->authority[0])) { $err .= tr('conflict with CNAME record'); return false; } /* if ($res === false) { return true; } $err .= tr('conflict with CNAME record'); // return false; */ return true; }
function ah_db_current_host($db_cluster_id) { require_once "/usr/share/php/Net/DNS2_wrapper.php"; try { $resolver = new Net_DNS2_Resolver(array('nameservers' => array('127.0.0.1', 'dns-master'))); $response = $resolver->query("cluster-{$db_cluster_id}.mysql", 'CNAME'); $cached_id = $response->answer[0]->cname; } catch (Net_DNS2_Exception $e) { $cached_id = ""; } return $cached_id; }
function CheckDNS($hostname, $dns) { $ipClass = new IP(); $rs = new Net_DNS2_Resolver(array('nameservers' => array($dns))); try { $result = $rs->query($hostname, "A"); } catch (Net_DNS2_Exception $e) { echo $e->getMessage(); return null; } foreach ($result->answer as $record) { if ($ipClass->isIPAddress($record->address)) { return $record->address; } } }
<?php // We need to also include the netdns2 PEAR lib require_once 'Net/DNS2.php'; $dnsResolver = new Net_DNS2_Resolver(['nameservers' => ['127.0.0.1']]); define('WHOIS_EOL', "\r\n"); define('WHOIS_PORT', 43); // Needs to be in CDIR format (same as BGP announcement) $input = $_GET['input']; // Cleanup input $inputParts = explode("/", $input); // Check if IP if (filter_var($inputParts[0], FILTER_VALIDATE_IP)) { if (isset($inputParts[1]) === true) { $finalInput = $inputParts[0] . "/" . $inputParts[1]; } else { if (!filter_var($input, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) { $finalInput = $inputParts[0] . "/48"; } else { $finalInput = $inputParts[0] . "/24"; } } } else { $finalInput = "AS" . str_ireplace("as", "", $inputParts[0]); } $whois_server = strtolower($_GET['whois_server']); switch (strtolower($whois_server)) { case 'whois.ripe.net': case 'whois.afrinic.net': $finalInput .= " -B"; break;
function get_geolocation($address, $hostname) { global $config; switch (strtolower($config['geocoding']['api'])) { case 'osm': case 'openstreetmap': $location['location_geoapi'] = 'openstreetmap'; // Openstreetmap. The usage limits are stricter here. (http://wiki.openstreetmap.org/wiki/Nominatim_usage_policy) $url = "http://nominatim.openstreetmap.org/search?format=json&addressdetails=1&limit=1&q="; $reverse_url = "http://nominatim.openstreetmap.org/reverse?format=json&"; break; case 'google': $location['location_geoapi'] = 'google'; // See documentation here: https:// developers.google.com/maps/documentation/geocoding/ // Use of the Google Geocoding API is subject to a query limit of 2,500 geolocation requests per day. $url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address="; $reverse_url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&"; break; case 'mapquest': default: $location['location_geoapi'] = 'mapquest'; // Mapquest open data. There are no usage limits. $url = "http://open.mapquestapi.com/nominatim/v1/search.php?format=json&addressdetails=1&limit=1&q="; $reverse_url = "http://open.mapquestapi.com/nominatim/v1/reverse.php?format=json&"; } if ($address != "Unknown" && $config['geocoding']['enable']) { $reverse = FALSE; // Forward geocoding by default // If location string contains coordinates ([33.234, -56.22]) use Reverse Geocoding. $pattern = '/\\[\\s*([+-]*\\d+[\\d\\.]*)[,\\s]+([+-]*\\d+[\\d\\.]*)[\\s\\]]+/'; if (preg_match($pattern, $address, $matches)) { $location['location_lat'] = $matches[1]; $location['location_lon'] = $matches[2]; $reverse = TRUE; } // If DNS LOC support is enabled and DNS LOC record is set, use Reverse Geocoding. if ($config['geocoding']['dns']) { // Ack! dns_get_record not only cannot retrieve LOC records, but it also actively filters them when using // DNS_ANY as query type (which, admittedly would not be all that reliable as per the manual). // Example LOC: // "20 31 55.893 N 4 57 38.269 E 45.00m 10m 100m 10m" // // From Wikipedia: d1 [m1 [s1]] {"N"|"S"} d2 [m2 [s2]] {"E"|"W"} // // Parsing this is something for Net_DNS2 as it has the code for it. include_once 'Net/DNS2.php'; include_once 'Net/DNS2/RR/LOC.php'; $resolver = new Net_DNS2_Resolver(); $response = $resolver->query($hostname, 'LOC', 'IN'); if ($response) { foreach ($response->answer as $answer) { if (is_numeric($answer->degree_latitude)) { $ns_multiplier = $answer->ns_hem == 'N' ? 1 : -1; $ew_multiplier = $answer->ew_hem == 'E' ? 1 : -1; $location['location_lat'] = round($answer->degree_latitude + $answer->min_latitude / 60 + $answer->sec_latitude / 3600, 7) * $ns_multiplier; $location['location_lon'] = round($answer->degree_longitude + $answer->min_longitude / 60 + $answer->sec_longitude / 3600, 7) * $ew_multiplier; $reverse = TRUE; } } } } if ($reverse) { if ($config['geocoding']['api'] == 'google') { // latlng=40.714224,-73.961452 $request = $reverse_url . 'latlng=' . $location['location_lat'] . ',' . $location['location_lon']; } else { // lat=51.521435&lon=-0.162714 $request = $reverse_url . 'lat=' . $location['location_lat'] . '&lon=' . $location['location_lon']; } } else { $request = $url . urlencode($address); } $mapresponse = get_http_request($request); $data = json_decode($mapresponse, true); if ($config['geocoding']['api'] == 'google') { if ($data['status'] == 'OVER_QUERY_LIMIT') { // Return empty array for overquery limit (for later recheck) return array(); } // Use google data only with good status response if ($data['status'] == 'OK') { $data = $data['results'][0]; if ($data['geometry']['location_type'] == 'APPROXIMATE') { // It might be that the first element of the address is a business name. // Lets drop the first element and see if we get anything better! list(, $address) = explode(',', $address, 2); $mapresponse = get_http_request($url . urlencode($address)); $data_new = json_decode($mapresponse, true); if ($data_new['status'] == 'OK' && $data_new['results'][0]['geometry']['location_type'] != 'APPROXIMATE') { $data = $data_new['results'][0]; } } } } elseif (!isset($location['location_lat'])) { $data = $data[0]; if (!count($data)) { // We seem to have hit a snag geocoding. It might be that the first element of the address is a business name. // Lets drop the first element and see if we get anything better! This works more often than one might expect. list(, $address) = explode(',', $address, 2); $mapresponse = get_http_request($url . urlencode($address)); $data = json_decode($mapresponse, true); // We only want the first entry in the returned data. $data = $data[0]; } } } print_debug("GEO-API REQUEST: {$request}"); // Put the values from the data array into the return array where they exist, else replace them with defaults or Unknown. if ($config['geocoding']['api'] == 'google') { $location['location_lat'] = $data['geometry']['location']['lat']; $location['location_lon'] = $data['geometry']['location']['lng']; foreach ($data['address_components'] as $entry) { switch ($entry['types'][0]) { case 'locality': $location['location_city'] = $entry['long_name']; break; case 'administrative_area_level_2': $location['location_county'] = $entry['long_name']; break; case 'administrative_area_level_1': $location['location_state'] = $entry['long_name']; break; case 'country': $location['location_country'] = strtolower($entry['short_name']); break; } } } else { $location['location_lat'] = $data['lat']; $location['location_lon'] = $data['lon']; $location['location_city'] = strlen($data['address']['town']) ? $data['address']['town'] : $data['address']['city']; // Would be nice to have an array of countries where we want state, and ones where we want County. For example, USA wants state, UK wants county. $location['location_county'] = $data['address']['county']; $location['location_state'] = $data['address']['state']; $location['location_country'] = $data['address']['country_code']; } // Use defaults if empty values if (!strlen($location['location_lat'])) { $location['location_lat'] = $config['geocoding']['default']['lat']; } if (!strlen($location['location_lon'])) { $location['location_lon'] = $config['geocoding']['default']['lon']; } if (!strlen($location['location_city'])) { $location['location_city'] = 'Unknown'; } if (!strlen($location['location_county'])) { $location['location_county'] = 'Unknown'; } if (!strlen($location['location_state'])) { $location['location_state'] = 'Unknown'; } if (!strlen($location['location_country'])) { $location['location_country'] = 'Unknown'; } return $location; }
function get_geolocation($address, $geo_db = array(), $dns_only = FALSE) { global $config; $ok = FALSE; $location = array('location' => $address); // Init location array $location['location_geoapi'] = strtolower(trim($config['geocoding']['api'])); if (!isset($config['geo_api'][$location['location_geoapi']])) { // Use default if unknown api $location['location_geoapi'] = 'openstreetmap'; } $api_params =& $config['geo_api'][$location['location_geoapi']]; // Link to api specific params $params = $api_params['params']; // Init base request params // GEO API KEY and rate limits $ratelimit = FALSE; if (strlen($config['geocoding']['api_key']) && isset($api_params['request_params']['key'])) { $param = $api_params['request_params']['key']; $params[$param] = escape_html($config['geocoding']['api_key']); // KEYs is never used special characters if (isset($api_params['ratelimit_key'])) { $ratelimit = $api_params['ratelimit_key']; } } else { if (isset($api_params['ratelimit'])) { $ratelimit = $api_params['ratelimit']; } } if (isset($api_params['request_params']['id'])) { $params[$api_params['request_params']['id']] = OBSERVIUM_PRODUCT . '-' . substr(get_unique_id(), 0, 8); } if (isset($api_params['request_params']['uuid'])) { $params[$api_params['request_params']['uuid']] = get_unique_id(); } if (isset($config['geocoding']['enable']) && $config['geocoding']['enable']) { $reverse = FALSE; // by default forward geocoding $debug_msg = "Geocoding ENABLED, try detect device coordinates:" . PHP_EOL; // If device coordinates set manually, use Reverse Geocoding. if ($geo_db['location_manual']) { $location['location_lat'] = $geo_db['location_lat']; $location['location_lon'] = $geo_db['location_lon']; $reverse = TRUE; $debug_msg .= ' MANUAL coordinates - SET' . PHP_EOL; } else { if ($config['geocoding']['dns']) { /** * Ack! dns_get_record not only cannot retrieve LOC records, but it also actively filters them when using * DNS_ANY as query type (which, admittedly would not be all that reliable as per the manual). * * Example LOC: * "20 31 55.893 N 4 57 38.269 E 45.00m 10m 100m 10m" * * From Wikipedia: d1 [m1 [s1]] {"N"|"S"} d2 [m2 [s2]] {"E"|"W"} * * Parsing this is something for Net_DNS2 as it has the code for it. */ if ($geo_db['hostname']) { //include_once('Net/DNS2.php'); //include_once('Net/DNS2/RR/LOC.php'); $resolver = new Net_DNS2_Resolver(); try { $response = $resolver->query($geo_db['hostname'], 'LOC', 'IN'); } catch (Net_DNS2_Exception $e) { print_debug(' ' . $e->getMessage() . ' (' . $geo_db['hostname'] . ')'); } } else { $response = FALSE; print_debug(" DNS LOC enabled, but device hostname empty."); } if ($response) { if (OBS_DEBUG > 1) { var_dump($response->answer); } foreach ($response->answer as $answer) { if (is_numeric($answer->latitude) && is_numeric($answer->longitude)) { $location['location_lat'] = $answer->latitude; $location['location_lon'] = $answer->longitude; $reverse = TRUE; break; } else { if (is_numeric($answer->degree_latitude) && is_numeric($answer->degree_longitude)) { $ns_multiplier = $answer->ns_hem == 'N' ? 1 : -1; $ew_multiplier = $answer->ew_hem == 'E' ? 1 : -1; $location['location_lat'] = round($answer->degree_latitude + $answer->min_latitude / 60 + $answer->sec_latitude / 3600, 7) * $ns_multiplier; $location['location_lon'] = round($answer->degree_longitude + $answer->min_longitude / 60 + $answer->sec_longitude / 3600, 7) * $ew_multiplier; $reverse = TRUE; break; } } } if (isset($location['location_lat'])) { $debug_msg .= ' DNS LOC records - FOUND' . PHP_EOL; } else { $debug_msg .= ' DNS LOC records - NOT FOUND' . PHP_EOL; if ($dns_only) { // If we check only DNS LOC records but it not found, exit print_debug($debug_msg); return FALSE; } } } } } if ($reverse || !preg_match('/^<?(unknown|none)>?$/i', $address)) { /** * If location string contains coordinates use Reverse Geocoding. * Valid strings: * Some location [33.234, -56.22] * Some location (33.234 -56.22) * Some location [33.234;-56.22] * 33.234,-56.22 */ $pattern = '/(?:^|[\\[(])\\s*(?<lat>[+-]?\\d+(?:\\.\\d+)*)\\s*[,; ]\\s*(?<lon>[+-]?\\d+(?:\\.\\d+)*)\\s*(?:[\\])]|$)/'; if (!$reverse && preg_match($pattern, $address, $matches)) { if ($matches['lat'] >= -90 && $matches['lat'] <= 90 && $matches['lon'] >= -180 && $matches['lon'] <= 180) { $location['location_lat'] = $matches['lat']; $location['location_lon'] = $matches['lon']; $reverse = TRUE; } } if ($reverse) { $debug_msg .= ' by REVERSE query (API: ' . strtoupper($config['geocoding']['api']) . ', LAT: ' . $location['location_lat'] . ', LON: ' . $location['location_lon'] . ') - '; $url = $api_params['reverse_url']; if (isset($api_params['reverse_params'])) { // Additional params for reverse query $params = array_merge($params, $api_params['reverse_params']); } if (!is_numeric($location['location_lat']) || !is_numeric($location['location_lat'])) { // Do nothing for empty, skip requests for empty coordinates } else { if (isset($api_params['request_params']['lat']) && isset($api_params['request_params']['lon'])) { $ok = TRUE; $param = $api_params['request_params']['lat']; $params[$param] = $location['location_lat']; $param = $api_params['request_params']['lon']; $params[$param] = $location['location_lon']; } else { if (isset($api_params['request_params']['latlon'])) { $ok = TRUE; $param = $api_params['request_params']['latlon']; $params[$param] = $location['location_lat'] . ',' . $location['location_lon']; } } } } else { $debug_msg .= ' by PARSING sysLocation (API: ' . strtoupper($config['geocoding']['api']) . ') - '; $url = $api_params['direct_url']; if (isset($api_params['direct_params'])) { // Additional params for reverse query $params = array_merge($params, $api_params['direct_params']); } if ($address != '') { $ok = TRUE; $param = $api_params['request_params']['address']; $params[$param] = urlencode($address); //$request = $url . urlencode($address); } } if (OBS_DEBUG > 1) { print_vars($api_params); print_vars($params); } if ($ok) { // Build request query $request = build_request_url($url, $params, $api_params['method']); // First request $mapresponse = get_http_request($request, NULL, $ratelimit); switch ($GLOBALS['response_headers']['code'][0]) { case '4': // 4xx (timeout, rate limit, forbidden) // 4xx (timeout, rate limit, forbidden) case '5': // 5xx (server error) $geo_status = strtoupper($GLOBALS['response_headers']['status']); $debug_msg .= $geo_status . PHP_EOL; if (OBS_DEBUG < 2) { // Hide API KEY from output $request = str_replace($api_params['request_params']['key'] . '=' . escape_html($config['geocoding']['api_key']), $api_params['request_params']['key'] . '=' . '***', $request); } $debug_msg .= ' GEO API REQUEST: ' . $request; print_debug($debug_msg); // Return old array with new status (for later recheck) unset($geo_db['hostname'], $geo_db['location_updated']); $location['location_status'] = $debug_msg; $location['location_updated'] = format_unixtime($config['time']['now'], 'Y-m-d G:i:s'); //print_vars($location); //print_vars($geo_db); return array_merge($geo_db, $location); } $data = json_decode($mapresponse, TRUE); //print_vars($data); $geo_status = 'NOT FOUND'; $api_specific = is_file($config['install_dir'] . '/includes/geolocation/' . $location['location_geoapi'] . '.inc.php'); if ($api_specific) { // API specific parser require_once $config['install_dir'] . '/includes/geolocation/' . $location['location_geoapi'] . '.inc.php'; if ($data === FALSE) { // Return old array with new status (for later recheck) unset($geo_db['hostname'], $geo_db['location_updated']); //$location['location_status'] = $debug_msg; $location['location_updated'] = format_unixtime($config['time']['now'], 'Y-m-d G:i:s'); //print_vars($location); //print_vars($geo_db); return array_merge($geo_db, $location); } } else { if (!isset($location['location_lat'])) { $data = $data[0]; if (!count($data) && strpos($address, ',')) { // We seem to have hit a snag geocoding. It might be that the first element of the address is a business name. // Lets drop the first element and see if we get anything better! This works more often than one might expect. list(, $address_new) = explode(',', $address, 2); //$request_new = $url.urlencode($address); $param = $api_params['request_params']['address']; $params[$param] = urlencode($address_new); $request_new = build_request_url($url, $params, $api_params['method']); $mapresponse = get_http_request($request_new, NULL, $ratelimit); $data_new = json_decode($mapresponse, TRUE); if (count($data_new[0])) { // We only want the first entry in the returned data. $data = $data_new[0]; $request = $request_new; } } } } if (OBS_DEBUG > 1 && count($data)) { var_dump($data); } } else { $geo_status = 'NOT REQUESTED'; } } } if (!$api_specific) { // Nominatum if (!$reverse) { // If using reverse queries, do not change lat/lon $location['location_lat'] = $data['lat']; $location['location_lon'] = $data['lon']; } foreach (array('town', 'city', 'hamlet', 'village') as $param) { if (isset($data['address'][$param])) { $location['location_city'] = $data['address'][$param]; break; } } $location['location_state'] = $data['address']['state']; $location['location_county'] = isset($data['address']['county']) ? $data['address']['county'] : $data['address']['state_district']; $location['location_country'] = $data['address']['country_code']; } // Use defaults if empty values if (!strlen($location['location_lat']) || !strlen($location['location_lon'])) { // Reset to empty coordinates $location['location_lat'] = array('NULL'); $location['location_lon'] = array('NULL'); //$location['location_lat'] = $config['geocoding']['default']['lat']; //$location['location_lon'] = $config['geocoding']['default']['lon']; //if (is_numeric($config['geocoding']['default']['lat']) && is_numeric($config['geocoding']['default']['lon'])) //{ // $location['location_manual'] = 1; // Set manual key for ability reset from WUI //} } else { // Always round lat/lon same as DB precision (DECIMAL(10,7)) $location['location_lat'] = round($location['location_lat'], 7); $location['location_lon'] = round($location['location_lon'], 7); } foreach (array('city', 'county', 'state') as $entry) { // Remove duplicate County/State words $param = 'location_' . $entry; $location[$param] = strlen($location[$param]) ? str_ireplace(' ' . $entry, '', $location[$param]) : 'Unknown'; } if (strlen($location['location_country'])) { $location['location_country'] = strtolower($location['location_country']); $geo_status = 'FOUND'; } else { $location['location_country'] = 'Unknown'; } // Print some debug informations $debug_msg .= $geo_status . PHP_EOL; if (OBS_DEBUG < 2) { // Hide API KEY from output $request = str_replace($api_params['request_params']['key'] . '=' . escape_html($config['geocoding']['api_key']), $api_params['request_params']['key'] . '=' . '***', $request); } $debug_msg .= ' GEO API REQUEST: ' . $request; if ($geo_status == 'FOUND') { $debug_msg .= PHP_EOL . ' GEO LOCATION: '; $debug_msg .= country_from_code($location['location_country']) . ' (Country), ' . $location['location_state'] . ' (State), '; $debug_msg .= $location['location_county'] . ' (County), ' . $location['location_city'] . ' (City)'; $debug_msg .= PHP_EOL . ' GEO COORDINATES: '; $debug_msg .= $location['location_lat'] . ' (Latitude), ' . $location['location_lon'] . ' (Longitude)'; } else { $debug_msg .= PHP_EOL . ' QUERY DATE: ' . date('r'); // This is requered for increase data in DB } print_debug($debug_msg); $location['location_status'] = $debug_msg; return $location; }
function CHECK_DNS_SYSTEMS() { $unix = new unix(); $pidtime = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".time"; $pidFile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid"; $BigTime = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".week.time"; $pid = $unix->get_pid_from_file($pidFile); if ($unix->process_exists($pid)) { if ($unix->PROCCESS_TIME_MIN($pid, 10) < 2) { return; } } if ($GLOBALS["VERBOSE"]) { echo "pidtime ={$pidtime}\n"; } @file_put_contents($pidFile, getmypid()); $time = $unix->file_time_min($pidtime); if (!$GLOBALS["FORCE"]) { if ($time < 5) { Events("{$time}mn < 5mn ( use --force to bypass)"); if ($GLOBALS["VERBOSE"]) { echo "{$time}mn < 5mn ( use --force to bypass)\n"; } return; } } @unlink($pidtime); @file_put_contents($pidtime, time()); $BigTimeEx = $unix->file_time_min($BigTime); if ($GLOBALS["VERBOSE"]) { echo "{$BigTimeEx}M for {$BigTime}\n"; } if ($BigTimeEx > 4320) { $q = new mysql(); @unlink($BigTimeEx); @file_put_contents($BigTimeEx, time()); Events("DELETE FROM dnsperfs_week WHERE zDate<DATE_SUB(NOW(),INTERVAL 8 DAY)"); $q->QUERY_SQL("DELETE QUICK FROM dnsperfs_week WHERE zDate<DATE_SUB(NOW(),INTERVAL 8 DAY)", "artica_events"); $q->QUERY_SQL("OPTIMIZE TABLE dnsperfs_week", "artica_events"); } $resolv = new resolv_conf(); $q = new mysql_squid_builder(); $sock = new sockets(); include_once dirname(__FILE__) . "/ressources/externals/Net_DNS2/DNS2.php"; include_once dirname(__FILE__) . "/ressources/class.resolv.conf.inc"; $sql = "SELECT * FROM dns_servers ORDER BY zOrder"; $results = $q->QUERY_SQL($sql); if (!$q->ok) { ToSyslog("{$q->mysql_error}"); return; } while ($ligne = mysql_fetch_assoc($results)) { $DNS[] = $ligne["dnsserver"]; } $sock = new sockets(); if ($sock->dnsmasq_enabled() == 1) { $DNS[] = "127.0.0.1"; } $q = new mysql(); $sql = "CREATE TABLE IF NOT EXISTS `dnsperfs` (\n\t\t\t\t`dnsserver` VARCHAR(128) PRIMARY KEY,\n\t\t\t\t`performance` FLOAT(5),\n\t\t\t\t `percent` smallint(2),\n\t\t\t\t `zDate` datetime\n\t\t\t\t ) ENGINE=MyISAM;"; $q->QUERY_SQL($sql, 'artica_events'); $sql = "CREATE TABLE IF NOT EXISTS `dnsperfs_week` (\n\t\t\t\t`dnsserver` VARCHAR(128),\n\t\t\t\t`performance` FLOAT(5),\n\t\t\t\t `percent` smallint(2),\n\t\t\t\t `zDate` datetime,\n\t\t\t\t KEY `zDate` (`zDate`),\n\t\t\t KEY `dnsserver` (`dnsserver`)\n\t\t\t\t ) ENGINE=MyISAM;"; $q->QUERY_SQL($sql, 'artica_events'); $nameserver = explode("\n", @file_get_contents("/etc/resolv.conf")); while (list($index, $line) = each($nameserver)) { $line = trim($line); if ($line == null) { continue; } if (!preg_match("#^nameserver\\s+(.+)#i", $line, $re)) { continue; } $COMP[trim($re[1])] = true; } $q->QUERY_SQL("TRUNCATE TABLE `dnsperfs`", 'artica_events'); //ref=518379 if ($resolv->MainArray["DNS1"] != null) { $DNS[] = $resolv->MainArray["DNS1"]; } if ($resolv->MainArray["DNS2"] != null) { $DNS[] = $resolv->MainArray["DNS2"]; } if ($resolv->MainArray["DNS3"] != null) { $DNS[] = $resolv->MainArray["DNS3"]; } $type = "A"; $ipClass = new IP(); $minperf = $sock->GET_INFO("DNSPerfsPointer"); if (!is_numeric($minperf)) { $minperf = 301450; } while (list($index, $dnsA) = each($DNS)) { $COMP[$dnsA] = true; } while (list($dnsA, $none) = each($COMP)) { Events("Checks DNS {$dnsA}"); if (!$ipClass->isIPAddress($dnsA)) { continue; } if ($GLOBALS["VERBOSE"]) { echo "{$dnsA}\n"; } $t['start'] = microtime(true); $rs = new Net_DNS2_Resolver(array('nameservers' => array($dnsA))); try { $date = date("Y-m-d H:i:s"); $tA = rand("10000", "208460"); $result = $rs->query("p4-cpsk2owex6nby-dwvedtapjla4ebei-{$tA}-i2-v6exp3-v4.metric.gstatic.com", "A"); $t[$dnsA] = microtime(true); $time = mini_bench_to($t); $timeC = $time * 10000; } catch (Net_DNS2_Exception $e) { $error = $e->getMessage(); $q->QUERY_SQL("INSERT IGNORE INTO `dnsperfs` (dnsserver,performance,percent,zDate) VALUES ('{$dnsA}','0','0','{$date}')", "artica_events"); $q->QUERY_SQL("INSERT IGNORE INTO `dnsperfs_week` (dnsserver,performance,percent,zDate) VALUES ('{$dnsA}','0','0','{$date}')", "artica_events"); continue; } $perc = $minperf / $timeC; $perc = round($perc * 100); Events("{$dnsA} Response Time:{$time} = {$timeC}/{$minperf} {$perc}%"); foreach ($result->answer as $record) { if ($ipClass->isIPAddress($record->address)) { if ($perc > 100) { $perc = 100; } $q->QUERY_SQL("INSERT IGNORE INTO `dnsperfs` (dnsserver,performance,percent,zDate) VALUES ('{$dnsA}','{$time}','{$perc}','{$date}')", "artica_events"); if ($GLOBALS["VERBOSE"]) { echo "INSERT IGNORE INTO `dnsperfs_week` (dnsserver,performance,percent,zDate) VALUES ('{$dnsA}','{$time}','{$perc}','{$date}')\n"; } $q->QUERY_SQL("INSERT IGNORE INTO `dnsperfs_week` (dnsserver,performance,percent,zDate) VALUES ('{$dnsA}','{$time}','{$perc}','{$date}')", "artica_events"); break; } } } $cacheFile = "/usr/share/artica-postfix/ressources/logs/web/dnsperformances.cache"; $sql = "SELECT * FROM dnsperfs ORDER BY percent DESC"; $results = $q->QUERY_SQL($sql, "artica_events"); while ($ligne = mysql_fetch_assoc($results)) { $percentage = $ligne["percent"]; $dnsserver = $ligne["dnsserver"]; if ($percentage > 100) { $percentage = 100; } $TTR[] = "\n\t\t<tr>\n\t\t\t<td style='font-weight:bold;font-size:12px' align='right'>{$dnsserver}:</td>\n\t\t\t<td style='font-weight:bold;font-size:12px'><td>" . pourcentage($percentage, 10, "green") . "</td>\n\t\t</tr>\n\t\t"; } if (count($TTR) > 0) { $data = RoundedLightGreen("<div style='min-height:147px'>\n\t\t<table style='width:100%'>\n\t\t\t\t<tr><td colspan=3><span style='font-weight:bold;font-size:12px'>{dns_performance}</span></td></tr>\n\t\t\t\t" . @implode($TTR, "\n") . "\n\t\t\t\t\n\t\t<tr>\n\t\t\t<td colspan=3 align='right'>\n\t\t\t\t<i><a href=\"javascript:blur();\" OnClick=\"javascript:Loadjs('dnsperfs.php',true)\" style='font-weight:normal;font-size:12px;text-decoration:underline'>{more_infos}</a> | \n\t\t\t\t<a href=\"javascript:blur();\" OnClick=\"javascript:Loadjs('squid.popups.php?script=dns');\" style='font-weight:normal;font-size:12px;text-decoration:underline'>{settings}</a>\n\t\t\t\t</i>\n\t\t\t</td>\n\t\t</tr>\t\t\t\t\n\t\t\t\t\n\t\t</table></div>") . "<br>"; @file_put_contents($cacheFile, $data); } }
/** * Retrieves list of domain controllers from DNS through SRV records. * * @param string Domain name (fqdn-style) for the AD domain. * * @return array Array of server names to be used for LDAP. */ function ldap_domain_servers_from_dns($domain) { global $config; include_once 'Net/DNS2.php'; include_once 'Net/DNS2/RR/SRV.php'; $servers = array(); $resolver = new Net_DNS2_Resolver(); $response = $resolver->query("_ldap._tcp.dc._msdcs.{$domain}", 'SRV', 'IN'); if ($response) { foreach ($response->answer as $answer) { $servers[] = $answer->target; } } return $servers; }
if (count($dns_arpa)) { $dns_records = dns_get_record($arpa_ns, DNS_NS); if (!count($dns_records)) { echo "\n[1;33mhost {$arpa_ns} not found[0m\n"; } $dns_servers = array(); foreach ($dns_records as $dns_record) { foreach (gethostbynamel($dns_record['target']) as $ip) { array_push($dns_servers, $ip); } } $domain_list = array(); foreach ($dns_servers as $dns_server) { echo "\n[1;32m" . $dns_server . ' (' . gethostbyaddr($dns_server) . ") AXFR {$arpa_ns}[0m\n"; $result = NULL; $r = new Net_DNS2_Resolver(array('nameservers' => array($dns_server))); try { $result = $r->query($arpa_ns, 'AXFR'); } catch (Net_DNS2_Exception $e) { echo "[1;31m::query() failed: ", $e->getMessage(), "[0m\n"; } if ($result) { foreach ($result->answer as $rr) { if (preg_match("/{$domain}/i", $rr)) { $rr = "[1;35m{$rr}[0m"; echo "{$rr}\n"; array_push($domain_list, $rr); } else { echo "{$rr}\n"; } }
function autodiscover($domain, $dns = array()) { require_once PEAR_DIR . 'Net/DNS2.php'; // TODO: Lookup DNS server from hosts file if not set $q = new Net_DNS2_Resolver(); if ($dns) { $q->setServers($dns); } $servers = array(); try { $r = $q->query('_ldap._tcp.' . $domain, 'SRV'); } catch (Net_DNS2_Exception $e) { // TODO: Log warning or something return $servers; } foreach ($r->answer as $srv) { // TODO: Get the actual IP of the server (?) $servers[] = array('host' => "{$srv->target}:{$srv->port}", 'priority' => $srv->priority, 'weight' => $srv->weight); } // Sort servers by priority ASC, then weight DESC usort($servers, function ($a, $b) { return ($a['priority'] << 15) - $a['weight'] - ($b['priority'] << 15) + $b['weight']; }); return $servers; }