isLogo($cachedLogo)) { $this->output($cachedLogo); return; } $cachedMiss = $cacheReady ? PrivateFileCache::read($miss, self::NEGATIVE_TTL, 0) : null; if ($cachedMiss !== null) { $this->notFound(); return; } $data = $this->fetch($domain); if ($data === null) { if ($cacheReady) { $this->writeCacheFile($dir, $miss, ''); } $this->notFound(); return; } if ($cacheReady) { $this->writeCacheFile($dir, $logo, $data); if (is_file($miss) && !@unlink($miss)) { error_log("[bimi] Could not remove negative cache entry: {$miss}"); } } $this->output($data); } private function writeCacheFile($dir, $file, $data) { return PrivateFileCache::write($dir, $file, $data, '.bimi-', '[bimi] Could not remove temporary cache file'); } private function fetch($domain) { $records = @dns_get_record('default._bimi.' . $domain, DNS_TXT); if (empty($records)) { return null; } $url = null; foreach ($records as $record) { $txt = $record['txt'] ?? ''; if (stripos($txt, 'v=BIMI1') !== 0) { continue; } foreach (explode(';', $txt) as $tag) { $tag = trim($tag); if (stripos($tag, 'l=') === 0) { $url = trim(substr($tag, 2)); } } } if (empty($url) || !preg_match('#^https://#i', $url)) { return null; } $data = PublicHttpsResource::fetch($url, self::MAX_SIZE, 2, [ 'Accept: image/svg+xml', 'User-Agent: grommunio-web', ]); return $data !== null && $this->isLogo($data) ? $data : null; } private function isLogo($data) { $previous = libxml_use_internal_errors(true); $doc = new DOMDocument(); $ok = $doc->loadXML($data, LIBXML_NONET) && $doc->documentElement !== null && strtolower($doc->documentElement->localName) === 'svg' && $doc->getElementsByTagName('script')->length === 0 && $doc->getElementsByTagName('foreignObject')->length === 0; libxml_clear_errors(); libxml_use_internal_errors($previous); return $ok; } private function output($data) { header('Content-Type: image/svg+xml'); header('Content-Length: ' . strlen($data)); header('Content-Disposition: inline; filename="bimi.svg"'); header('Cache-Control: private, max-age=86400'); header('X-Content-Type-Options: nosniff'); header("Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'"); echo $data; } private function notFound() { header('HTTP/1.1 404 Not Found'); header('Cache-Control: private, max-age=3600'); } } if (!WebAppAuthentication::isAuthenticated()) { header('HTTP/1.1 401 Unauthorized'); exit; } $domain = strtolower(sanitizeGetValue('domain', '', '/^[a-z0-9.-]{3,253}$/i')); if (!ENABLE_BIMI || $domain === '' || str_contains($domain, '..')) { header('HTTP/1.1 404 Not Found'); exit; } (new BimiLogo())->serve($domain);