<?php
// NERGtrack network lookup: finds the owner (ASN), IP range and type of each visitor IP.
// Runs from the command line (systemd timer every 10 min). Not reachable from the web.
declare(strict_types=1);
if (PHP_SAPI !== 'cli') { http_response_code(404); exit; }
require __DIR__ . '/config.php';

$limit = max(1, (int)($argv[1] ?? 300));

$db = new PDO('mysql:host=' . NT_DB_HOST . ';dbname=' . NT_DB_NAME . ';charset=utf8mb4',
    NT_DB_USER, NT_DB_PASS,
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => false,
     PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]);

// IPs seen in the last 30 days that have no (recent) lookup yet
$st = $db->prepare("SELECT ip FROM (
        SELECT ip FROM nt_hits WHERE ts >= NOW() - INTERVAL 30 DAY
        UNION SELECT ip FROM nt_floods WHERE minute >= NOW() - INTERVAL 30 DAY
    ) a WHERE ip NOT IN (SELECT ip FROM nt_ipinfo WHERE checked >= NOW() - INTERVAL 30 DAY)
    LIMIT ?");
$st->bindValue(1, $limit, PDO::PARAM_INT);
$st->execute();
$ips = array_column($st->fetchAll(), 'ip');

function txt(string $name): string {
    $r = @dns_get_record($name, DNS_TXT);
    if (!$r) return '';
    return (string)($r[0]['txt'] ?? ($r[0]['entries'][0] ?? ''));
}

function cymru_origin(string $ip): array {
    $bin = @inet_pton($ip);
    if ($bin === false) return [];
    if (strlen($bin) === 4) {
        $q = implode('.', array_reverse(explode('.', $ip))) . '.origin.asn.cymru.com';
    } else {
        $q = implode('.', array_reverse(str_split(bin2hex($bin)))) . '.origin6.asn.cymru.com';
    }
    $t = txt($q);                       // "15169 | 66.249.64.0/19 | US | arin | 2004-03-05"
    if ($t === '') return [];
    $f = array_map('trim', explode('|', $t));
    $asn = (int)preg_split('/\s+/', $f[0] ?? '')[0];
    return ['asn' => $asn ?: null, 'prefix' => $f[1] ?? '', 'cc' => strtoupper(substr($f[2] ?? '', 0, 2))];
}

$asNames = [];
function as_name(int $asn): string {
    global $asNames;
    if (!isset($asNames[$asn])) {
        $t = txt("AS{$asn}.asn.cymru.com");  // "15169 | US | arin | 2000-03-30 | GOOGLE - Google LLC, US"
        $f = array_map('trim', explode('|', $t));
        $asNames[$asn] = mb_substr($f[4] ?? '', 0, 200);
    }
    return $asNames[$asn];
}

function forward_confirms(string $host, string $ip): bool {
    $want = @inet_pton($ip);
    if ($want === false) return false;
    if (strlen($want) === 4) {
        foreach ((@gethostbynamel($host) ?: []) as $a) if (@inet_pton($a) === $want) return true;
    } else {
        foreach ((@dns_get_record($host, DNS_AAAA) ?: []) as $r) if (isset($r['ipv6']) && @inet_pton($r['ipv6']) === $want) return true;
    }
    return false;
}

function classify(string $asName, string $rdns, bool $rdnsOk): string {
    if ($rdns !== '' && $rdnsOk && preg_match(
        '/\.(googlebot\.com|google\.com|search\.msn\.com|crawl\.yahoo\.net|applebot\.apple\.com|yandex\.(ru|net|com)|baidu\.(com|jp)|duckduckgo\.com|petalsearch\.com)$/i', $rdns))
        return 'search';
    if (preg_match('/SHOPIFY/i', $asName)) return 'shopify';
    if (preg_match('/GOOGLE-FIBER/i', $asName)) return 'isp';
    // Apple iCloud Private Relay / Cloudflare WARP / Fastly — often real people
    if (preg_match('/CLOUDFLARENET|CLOUDFLARE|AKAMAI-AS|AKAMAI-ASN|FASTLY|APPLE/i', $asName)) return 'relay';
    if (preg_match('/AMAZON|AWS|GOOGLE|MICROSOFT|AZURE|DIGITALOCEAN|OVH|HETZNER|LINODE|AKAMAI|VULTR|CHOOPA|ALIBABA|TENCENT|HUAWEI|ORACLE|CONTABO|M247|LEASEWEB|SCALEWAY|COLOCROSSING|HOSTINGER|IONOS|DATACAMP|CDN77|HOSTWINDS|PSYCHZ|QUADRANET|ZENLAYER|GCORE|G-CORE|HOSTING|HOST|SERVER|DATA ?CENT|CLOUD|VPS|\bCOLO\b|COLOCATION|DEDICATED|COMPUTE|PONYNET|FRANTECH|BUYVM|IPXO|EGIHOSTING|SERVERION|STARK INDUSTRIES|AEZA|PQ HOSTING|KAMATERA|NETCUP|IP VOLUME|BYTEDANCE/i', $asName))
        return 'cloud';
    if ($rdns !== '' && preg_match('/amazonaws|compute|googleusercontent|cloud|vps|server|hosted|dedicated|colo|linode|vultr|hetzner|ovh|contabo/i', $rdns))
        return 'cloud';
    return $asName !== '' ? 'isp' : 'unknown';
}

$ins = $db->prepare('REPLACE INTO nt_ipinfo (ip, asn, as_name, prefix, cc, rdns, kind, checked)
    VALUES (?,?,?,?,?,?,?,NOW())');

$n = 0;
foreach ($ips as $ip) {
    $o = cymru_origin($ip);
    $asn = $o['asn'] ?? null;
    $name = $asn ? as_name($asn) : '';
    $rdns = @gethostbyaddr($ip);
    if ($rdns === false || $rdns === $ip) $rdns = '';
    $rdnsOk = $rdns !== '' && forward_confirms($rdns, $ip);
    $kind = classify($name, $rdns, $rdnsOk);
    $ins->execute([$ip, $asn, $name, $o['prefix'] ?? '', $o['cc'] ?? '', mb_substr($rdns, 0, 255), $kind]);
    $n++;
}

$db->exec('DELETE FROM nt_ipinfo WHERE checked < NOW() - INTERVAL ' . (int)NT_KEEP_DAYS . ' DAY');
echo "NERGtrack: looked up $n IPs\n";
