| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410 |
- <?php
- declare(strict_types=1);
- /**
- * Works out where a sending mail server (MTA) would actually try to deliver mail
- * for a domain, following RFC 5321 §5.1 routing rules:
- *
- * 1. Look up the recipient domain's MX records and sort them by preference
- * (lowest number = tried first). Equal preferences are chosen at random.
- * 2. Resolve each MX target to its A / AAAA addresses — those are the hosts a
- * sender opens an SMTP connection to, in preference order.
- * 3. Null MX (RFC 7505): a single "0 ." record means the domain accepts no mail.
- * 4. Implicit MX (RFC 5321 §5.1): with no MX records, the domain's own A / AAAA
- * records are used as an implicit MX at preference 0.
- *
- * The result is the ordered list of servers/IPs a sender would attempt, enriched
- * with ASN / country / company for each address.
- */
- class DeliveryResolver
- {
- /** @var string[] Human-readable notes / warnings about the routing. */
- public array $warnings = [];
- /** @var array<int,array{pref:int,host:string,implicit:bool,cname:?string,addresses:array<int,array{ip:string,version:string}>,error:?string}> */
- public array $targets = [];
- public bool $nullMx = false; // RFC 7505 — domain explicitly refuses mail
- public bool $hasMx = false; // at least one usable MX record was found
- public ?string $error = null;
- public function resolve(string $domain): void
- {
- $mx = @dns_get_record($domain, DNS_MX) ?: [];
- // RFC 7505 Null MX: exactly one record, preference 0, target "." (root).
- if (count($mx) === 1
- && (int) ($mx[0]['pri'] ?? -1) === 0
- && rtrim((string) ($mx[0]['target'] ?? ''), '.') === '') {
- $this->nullMx = true;
- $this->warnings[] = 'This domain publishes a Null MX record (RFC 7505: "0 .") — '
- . 'it explicitly does not accept email. Senders should bounce immediately.';
- return;
- }
- if (!empty($mx)) {
- $this->hasMx = true;
- // Sort by preference ascending; senders try the lowest number first.
- usort($mx, static fn($a, $b) => ($a['pri'] ?? 0) <=> ($b['pri'] ?? 0));
- $prefs = array_map(static fn($r) => (int) ($r['pri'] ?? 0), $mx);
- if (count($prefs) !== count(array_unique($prefs))) {
- $this->warnings[] = 'Several MX records share the same preference. A sender picks '
- . 'between equal-preference hosts at random, so the exact host order can vary per delivery.';
- }
- foreach ($mx as $r) {
- $host = rtrim((string) ($r['target'] ?? ''), '.');
- $this->targets[] = $this->buildTarget((int) ($r['pri'] ?? 0), $host, false);
- }
- return;
- }
- // No MX record → RFC 5321 implicit MX: try the domain's own A / AAAA.
- $implicit = $this->buildTarget(0, $domain, true);
- if (empty($implicit['addresses'])) {
- $this->error = 'No MX records and no A/AAAA records for the domain — '
- . 'there is nowhere to deliver mail. Senders will return a bounce.';
- return;
- }
- $this->warnings[] = 'No MX records found. Under RFC 5321 the domain\'s own address (A/AAAA) '
- . 'is used as an implicit MX at preference 0.';
- $this->targets[] = $implicit;
- }
- /**
- * Resolves one MX target to its addresses and flags common misconfigurations
- * (a CNAME where a hostname is required, or a target that does not resolve).
- */
- private function buildTarget(int $pref, string $host, bool $implicit): array
- {
- $target = [
- 'pref' => $pref,
- 'host' => $host,
- 'implicit' => $implicit,
- 'cname' => null,
- 'addresses' => [],
- 'error' => null,
- ];
- if ($host === '') {
- $target['error'] = 'Empty MX target.';
- return $target;
- }
- // RFC 2181 §10.3 / RFC 5321 §5.1: an MX target must be a hostname with
- // address records, never a CNAME. Flag it, but still follow the chain.
- $cname = @dns_get_record($host, DNS_CNAME) ?: [];
- foreach ($cname as $c) {
- if (($c['host'] ?? '') === $host && !empty($c['target'])) {
- $target['cname'] = rtrim((string) $c['target'], '.');
- if (!$implicit) {
- $this->warnings[] = sprintf(
- 'MX target "%s" is a CNAME pointing to "%s". RFC 2181 forbids this; some '
- . 'senders reject such records. It should be an A/AAAA hostname.',
- $host,
- $target['cname']
- );
- }
- break;
- }
- }
- foreach (@dns_get_record($host, DNS_A) ?: [] as $r) {
- if (!empty($r['ip'])) {
- $target['addresses'][] = ['ip' => $r['ip'], 'version' => 'IPv4'];
- }
- }
- foreach (@dns_get_record($host, DNS_AAAA) ?: [] as $r) {
- if (!empty($r['ipv6'])) {
- $target['addresses'][] = ['ip' => $r['ipv6'], 'version' => 'IPv6'];
- }
- }
- if (empty($target['addresses'])) {
- $target['error'] = $target['cname'] !== null
- ? 'Target is a CNAME and did not resolve to any address.'
- : 'MX host has no A/AAAA records — a sender cannot connect to it.';
- }
- return $target;
- }
- /** @return string[] Every unique IP across all targets, for batch enrichment. */
- public function allIps(): array
- {
- $ips = [];
- foreach ($this->targets as $t) {
- foreach ($t['addresses'] as $a) {
- $ips[] = $a['ip'];
- }
- }
- return array_values(array_unique($ips));
- }
- }
- /**
- * Enriches IPs with ASN / country / company via ip-api.com's free batch endpoint.
- * @param string[] $ips
- * @return array<string,array>
- */
- function lookupIpInfo(array $ips): array
- {
- $out = [];
- $ips = array_values(array_unique(array_filter($ips)));
- if (empty($ips)) {
- return $out;
- }
- $fields = 'query,status,message,country,countryCode,as,asname,isp,org,reverse';
- foreach (array_chunk($ips, 100) as $chunk) {
- $payload = array_map(static fn($ip) => ['query' => $ip, 'fields' => $fields], $chunk);
- $ch = curl_init('http://ip-api.com/batch');
- curl_setopt_array($ch, [
- CURLOPT_POST => true,
- CURLOPT_POSTFIELDS => json_encode($payload),
- CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
- CURLOPT_RETURNTRANSFER => true,
- CURLOPT_TIMEOUT => 20,
- ]);
- $resp = curl_exec($ch);
- curl_close($ch);
- foreach ((json_decode((string) $resp, true) ?: []) as $item) {
- if (isset($item['query'])) {
- $out[$item['query']] = $item;
- }
- }
- }
- return $out;
- }
- $domain = trim((string) ($_GET['domain'] ?? ''));
- $resolver = null;
- $ipInfo = [];
- $inputError = null;
- if ($domain !== '') {
- // Accept a bare hostname; strip scheme/path if a URL was pasted, and an
- // email address if someone enters user@example.com.
- $domain = preg_replace('#^\w+://#', '', $domain);
- $domain = explode('/', $domain)[0];
- if (str_contains($domain, '@')) {
- $domain = substr($domain, strrpos($domain, '@') + 1);
- }
- $domain = strtolower(trim($domain));
- if (!preg_match('/^(?=.{1,253}$)([a-z0-9](-?[a-z0-9])*\.)+[a-z]{2,}$/', $domain)) {
- $inputError = 'Please enter a valid domain name (e.g. example.com) or an email address.';
- } else {
- $resolver = new DeliveryResolver();
- $resolver->resolve($domain);
- $ipInfo = lookupIpInfo($resolver->allIps());
- }
- }
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Mail Delivery Route Checker</title>
- <style>
- body {
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
- max-width: 1100px;
- margin: 40px auto;
- padding: 0 20px;
- background: #f5f5f5;
- color: #333;
- }
- h1 { color: #333; }
- .info { background: #e3f2fd; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
- form.lookup { margin-bottom: 20px; display: flex; gap: 10px; flex-wrap: wrap; }
- input[type=text] {
- flex: 1; min-width: 240px; padding: 10px; font-size: 15px;
- border: 1px solid #ccc; border-radius: 5px;
- }
- .btn {
- display: inline-block; padding: 10px 20px; background: #2196F3; color: white;
- text-decoration: none; border-radius: 5px; border: none; cursor: pointer; font-size: 15px;
- }
- .btn:hover { background: #1976D2; }
- .error { background: #ffebee; color: #c62828; padding: 10px; border-radius: 5px; margin: 10px 0; }
- .warning {
- background: #fff8e1; color: #e65100; padding: 12px 15px; border-radius: 5px;
- margin: 10px 0; border-left: 5px solid #ff9800;
- }
- .verdict {
- display: flex; align-items: center; gap: 12px; padding: 16px 20px; border-radius: 6px;
- font-size: 17px; font-weight: 600; margin: 16px 0;
- }
- .verdict.ok { background: #e8f5e9; color: #2e7d32; border-left: 6px solid #43a047; }
- .verdict.fail { background: #ffebee; color: #c62828; border-left: 6px solid #e53935; }
- h2 { color: #333; margin-top: 30px; }
- .target {
- background: white; border-radius: 6px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);
- margin: 12px 0; padding: 14px 16px; border-left: 5px solid #2196F3;
- }
- .target.dead { border-left-color: #e53935; opacity: 0.85; }
- .target-head { display: flex; align-items: baseline; gap: 12px; flex-wrap: wrap; }
- .pref {
- display: inline-flex; align-items: center; justify-content: center; min-width: 30px; height: 30px;
- background: #2196F3; color: white; border-radius: 50%; font-weight: 700; font-size: 14px; padding: 0 6px;
- }
- .target.dead .pref { background: #e53935; }
- .mxhost { font-family: monospace; font-size: 16px; font-weight: 600; word-break: break-all; }
- .tag {
- display: inline-block; padding: 2px 8px; border-radius: 10px; font-size: 11px; font-weight: 700;
- }
- .tag.implicit { background: #ede7f6; color: #5e35b1; }
- .tag.cname { background: #fff3e0; color: #e65100; }
- .tag.first { background: #e8f5e9; color: #2e7d32; }
- .tag-err { color: #c62828; font-size: 13px; margin-top: 6px; }
- table { width: 100%; border-collapse: collapse; margin-top: 10px; }
- th, td { padding: 8px 12px; text-align: left; border-bottom: 1px solid #eee; font-size: 13px; }
- th { color: #555; background: #fafafa; font-weight: 600; }
- td.ip { font-family: monospace; }
- .ver { display: inline-block; padding: 1px 6px; border-radius: 3px; font-size: 11px; font-weight: 700; }
- .ver.IPv4 { background: #e3f2fd; color: #1565c0; }
- .ver.IPv6 { background: #f3e5f5; color: #6a1b9a; }
- .empty { text-align: center; color: #999; padding: 40px; }
- .muted { color: #888; font-size: 12px; }
- ol.flat { padding-left: 20px; }
- ol.flat li { margin: 4px 0; font-size: 14px; }
- ol.flat code { font-family: monospace; }
- </style>
- </head>
- <body>
- <h1>📮 Mail Delivery Route Checker</h1>
- <div class="info">
- Shows <strong>where a sending mail server would try to deliver</strong> email for a domain, following
- <strong>RFC 5321</strong> routing: MX records sorted by <strong>preference</strong> (lowest first), each MX
- resolved to its <strong>A / AAAA addresses</strong>, plus <strong>Null MX</strong> (RFC 7505) and
- <strong>implicit MX</strong> fallback. Every address is enriched with its ASN, country and company.
- </div>
- <form class="lookup" method="GET">
- <input type="text" name="domain" placeholder="example.com (or user@example.com)"
- value="<?= htmlspecialchars($domain) ?>" autofocus>
- <button type="submit" class="btn">🔍 Trace delivery</button>
- </form>
- <?php if ($inputError): ?>
- <div class="error"><?= htmlspecialchars($inputError) ?></div>
- <?php endif; ?>
- <?php if ($resolver !== null): ?>
- <?php if ($resolver->nullMx): ?>
- <div class="verdict fail">🚫 <?= htmlspecialchars($domain) ?> does not accept mail (Null MX).</div>
- <?php elseif ($resolver->error !== null): ?>
- <div class="verdict fail">❌ Mail cannot be delivered to <?= htmlspecialchars($domain) ?>.</div>
- <?php else:
- $reachable = array_filter($resolver->targets, static fn($t) => !empty($t['addresses']));
- ?>
- <?php if (!empty($reachable)): ?>
- <div class="verdict ok">✅ Mail for <?= htmlspecialchars($domain) ?> would be delivered to
- <?= count($reachable) ?> reachable <?= $resolver->hasMx ? 'MX host' : 'implicit MX host' ?><?= count($reachable) === 1 ? '' : 's' ?>.</div>
- <?php else: ?>
- <div class="verdict fail">❌ MX records exist but none resolve to a usable address.</div>
- <?php endif; ?>
- <?php endif; ?>
- <?php foreach ($resolver->warnings as $w): ?>
- <div class="warning">⚠️ <?= htmlspecialchars($w) ?></div>
- <?php endforeach; ?>
- <?php if ($resolver->error !== null): ?>
- <div class="error"><?= htmlspecialchars($resolver->error) ?></div>
- <?php endif; ?>
- <?php if (!empty($resolver->targets)): ?>
- <h2>Delivery targets, in the order a sender tries them</h2>
- <?php foreach ($resolver->targets as $i => $t): ?>
- <div class="target <?= empty($t['addresses']) ? 'dead' : '' ?>">
- <div class="target-head">
- <span class="pref" title="MX preference"><?= (int) $t['pref'] ?></span>
- <span class="mxhost"><?= htmlspecialchars($t['host']) ?></span>
- <?php if ($i === 0 && !empty($t['addresses'])): ?>
- <span class="tag first">tried first</span>
- <?php endif; ?>
- <?php if ($t['implicit']): ?>
- <span class="tag implicit">implicit MX (A/AAAA)</span>
- <?php endif; ?>
- <?php if ($t['cname'] !== null): ?>
- <span class="tag cname">CNAME → <?= htmlspecialchars($t['cname']) ?></span>
- <?php endif; ?>
- </div>
- <?php if ($t['error'] !== null): ?>
- <div class="tag-err">⚠️ <?= htmlspecialchars($t['error']) ?></div>
- <?php else: ?>
- <table>
- <thead>
- <tr>
- <th style="width:60px;">#</th>
- <th>IP address</th>
- <th>Type</th>
- <th>PTR (reverse)</th>
- <th>ASN</th>
- <th>Company / ISP</th>
- <th>Country</th>
- </tr>
- </thead>
- <tbody>
- <?php foreach ($t['addresses'] as $j => $a): ?>
- <?php
- $info = $ipInfo[$a['ip']] ?? null;
- $ok = $info && ($info['status'] ?? '') === 'success';
- $asn = $ok ? ($info['as'] ?: '—') : '—';
- $company = $ok ? ($info['org'] ?: ($info['isp'] ?? '') ?: ($info['asname'] ?? '')) : '';
- $country = $ok ? trim(($info['country'] ?? '') . ' (' . ($info['countryCode'] ?? '') . ')', ' ()') : '';
- $ptr = $ok ? ($info['reverse'] ?? '') : '';
- ?>
- <tr>
- <td><?= $j + 1 ?></td>
- <td class="ip"><?= htmlspecialchars($a['ip']) ?></td>
- <td><span class="ver <?= $a['version'] ?>"><?= $a['version'] ?></span></td>
- <td class="ip"><?= htmlspecialchars($ptr ?: '—') ?></td>
- <td><?= htmlspecialchars($asn) ?></td>
- <td><?= htmlspecialchars($company ?: '—') ?></td>
- <td><?= htmlspecialchars($country ?: '—') ?></td>
- </tr>
- <?php endforeach; ?>
- </tbody>
- </table>
- <?php endif; ?>
- </div>
- <?php endforeach; ?>
- <?php
- // Flat "connection attempt" order across every reachable address.
- $flat = [];
- foreach ($resolver->targets as $t) {
- foreach ($t['addresses'] as $a) {
- $flat[] = ['pref' => $t['pref'], 'host' => $t['host'], 'ip' => $a['ip']];
- }
- }
- ?>
- <?php if (!empty($flat)): ?>
- <h2>Connection attempt order</h2>
- <p class="muted">A sender opens an SMTP connection to these addresses in turn, moving on only when one is unreachable or defers.</p>
- <ol class="flat">
- <?php foreach ($flat as $f): ?>
- <li><code><?= htmlspecialchars($f['host']) ?></code> [pref <?= (int) $f['pref'] ?>] → <code><?= htmlspecialchars($f['ip']) ?></code></li>
- <?php endforeach; ?>
- </ol>
- <p class="muted">
- Note: equal-preference MX hosts, and the choice between IPv4/IPv6 per host, are ultimately up to
- the sending MTA — so the exact order can differ between deliveries.
- </p>
- <?php endif; ?>
- <?php elseif (!$resolver->nullMx && $resolver->error === null): ?>
- <div class="empty">No delivery targets were found.</div>
- <?php endif; ?>
- <p class="muted" style="margin-top:20px;">IP intelligence via ip-api.com (free tier).</p>
- <?php endif; ?>
- </body>
- </html>
|