<?php

/**
 * Netflix Traffic Whitelist Router
 * 
 * Determines if an incoming client request originates from a known Netflix IP range.
 * Serves HTML File A if matched, or HTML File B if not matched.
 *
 * PHP Version 8.2+
 * PSR-12 Compliant Formatting
 */

declare(strict_types=1);

// Configuration Constants
// The two are for use with relative paths where the base path is the Apache ServerRoot (/var/www/html).
// const FILE_A_PATH = __DIR__ . '/var/www/private/netflix_resume.html';
// const FILE_B_PATH = __DIR__ . '/var/www.private/resume.html';
const FILE_A_PATH = '/var/www/private/netflix_resume.html';
const FILE_B_PATH = '/var/www/private/resume.html';
const CACHE_FILE = __DIR__ . '/netflix_ips.cache';
const CACHE_LIFETIME_SECONDS = 86400; // 24 hours
const NETFLIX_IP_FEED_URL = 'https://netflix.com';

/**
 * Retrieves the genuine client IP address, accounting for DigitalOcean
 * Cloud Firewalls or reverse proxies if configured.
 *
 * @return string
 */
function getClientIp(): string
{
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        // Capture the first IP in the comma-separated proxy chain
        $ipList = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $ip = trim(end($ipList));
    } else {
        $ip = $_SERVER['REMOTE_ADDR'] ?? '';
    }

    return filter_var($ip, FILTER_VALIDATE_IP) ?: '';
}

/**
 * Fetches Netflix IP ranges from the official feed or a local fallback cache.
 *
 * @return array{ipv4: string[], ipv6: string[]}
 */
function getNetflixIpRanges(): array
{
    $fallbackStructure = ['ipv4' => [], 'ipv6' => []];

    // Check if valid cache file exists
    if (file_exists(CACHE_FILE) && (time() - filemtime(CACHE_FILE) < CACHE_LIFETIME_SECONDS)) {
        $cacheData = file_get_contents(CACHE_FILE);
        if ($cacheData !== false) {
            $decoded = json_decode($cacheData, true);
            if (is_array($decoded)) {
                return $decoded;
            }
        }
    }

    // Fetch fresh payload from Netflix
    $context = stream_context_create([
        'http' => [
            'timeout' => 5,
            'header'  => "User-Agent: NetflixWhitelistRouter/1.0 (DigitalOcean VPC)\r\n"
        ]
    ]);

    $rawJson = @file_get_contents(NETFLIX_IP_FEED_URL, false, $context);
    if ($rawJson === false) {
        // Remote fetch failed, reuse expired cache silently if available
        if (file_exists(CACHE_FILE)) {
            $cacheData = file_get_contents(CACHE_FILE);
            return json_decode($cacheData, true) ?: $fallbackStructure;
        }
        return $fallbackStructure;
    }

    $data = json_decode($rawJson, true);
    if (!json_validate($rawJson) || !isset($data['records'])) {
        return $fallbackStructure;
    }

    // Parse and map macro CIDRs
    $ranges = ['ipv4' => [], 'ipv6' => []];
    foreach ($data['records'] as $record) {
        if (!isset($record['cidr'])) {
            continue;
        }
        
        if (str_contains($record['cidr'], ':')) {
            $ranges['ipv6'][] = $record['cidr'];
        } else {
            $ranges['ipv4'][] = $record['cidr'];
        }
    }

    // Update Cache atomicity using a temp file
    file_put_contents(CACHE_FILE, json_encode($ranges), LOCK_EX);

    return $ranges;
}

/**
 * Validates whether an IP matches a specific CIDR notation network.
 * Supports both IPv4 and IPv6 protocols natively.
 *
 * @param string $ip
 * @param string $cidr
 * @return bool
 */
function ipInCidr(string $ip, string $cidr): bool
{
    if (str_contains($cidr, '/')) {
        [$subnet, $mask] = explode('/', $cidr);
    } else {
        $subnet = $cidr;
        $mask = str_contains($ip, ':') ? '128' : '32';
    }

    $mask = (int)$mask;
    $ipPacked = inet_pton($ip);
    $subnetPacked = inet_pton($subnet);

    if ($ipPacked === false || $subnetPacked === false || strlen($ipPacked) !== strlen($subnetPacked)) {
        return false;
    }

    $totalBytes = strlen($ipPacked);
    
    // Check complete whole bytes matched by the mask
    $wholeBytes = (int)($mask / 8);
    for ($i = 0; $i < $wholeBytes; $i++) {
        if ($ipPacked[$i] !== $subnetPacked[$i]) {
            return false;
        }
    }

    // Check remaining bits inside the fractional byte
    $remainingBits = $mask % 8;
    if ($remainingBits > 0 && $wholeBytes < $totalBytes) {
        $bitmask = ~(0xFF >> $remainingBits) & 0xFF;
        if ((ord($ipPacked[$wholeBytes]) & $bitmask) !== (ord($subnetPacked[$wholeBytes]) & $bitmask)) {
            return false;
        }
    }

    return true;
}

/**
 * Evaluates the client IP status against the full array of CIDR lists.
 *
 * @param string $clientIp
 * @param array{ipv4: string[], ipv6: string[]} $netflixRanges
 * @return bool
 */
function isClientFromNetflix(string $clientIp, array $netflixRanges): bool
{
    if (empty($clientIp)) {
        return false;
    }

    $isIpv6 = str_contains($clientIp, ':');
    $targetBlock = $isIpv6 ? $netflixRanges['ipv6'] : $netflixRanges['ipv4'];

    foreach ($targetBlock as $cidr) {
        if (ipInCidr($clientIp, $cidr)) {
            return true;
        }
    }

    return false;
}

// --- Execution Flow ---

$clientIp = getClientIp();
$netflixRanges = getNetflixIpRanges();

if (isClientFromNetflix($clientIp, $netflixRanges)) {
    if (file_exists(FILE_A_PATH)) {
        // "readfile" is used instead of "include" to prevent arbitrary PHP code execution 
        // vulnerability inside the static target HTML files.
        readfile(FILE_A_PATH);
        exit;
    }
    
    http_response_code(500);
    echo "Configuration Error: File A missing.";
} else {
    if (file_exists(FILE_B_PATH)) {
        readfile(FILE_B_PATH);
        exit;
    }
    
    http_response_code(500);
    echo "Configuration Error: File B missing.";
}
