mail-delivery-check.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * Works out where a sending mail server (MTA) would actually try to deliver mail
  5. * for a domain, following RFC 5321 §5.1 routing rules:
  6. *
  7. * 1. Look up the recipient domain's MX records and sort them by preference
  8. * (lowest number = tried first). Equal preferences are chosen at random.
  9. * 2. Resolve each MX target to its A / AAAA addresses — those are the hosts a
  10. * sender opens an SMTP connection to, in preference order.
  11. * 3. Null MX (RFC 7505): a single "0 ." record means the domain accepts no mail.
  12. * 4. Implicit MX (RFC 5321 §5.1): with no MX records, the domain's own A / AAAA
  13. * records are used as an implicit MX at preference 0.
  14. *
  15. * The result is the ordered list of servers/IPs a sender would attempt, enriched
  16. * with ASN / country / company for each address.
  17. */
  18. class DeliveryResolver
  19. {
  20. /** @var string[] Human-readable notes / warnings about the routing. */
  21. public array $warnings = [];
  22. /** @var array<int,array{pref:int,host:string,implicit:bool,cname:?string,addresses:array<int,array{ip:string,version:string}>,error:?string}> */
  23. public array $targets = [];
  24. public bool $nullMx = false; // RFC 7505 — domain explicitly refuses mail
  25. public bool $hasMx = false; // at least one usable MX record was found
  26. public ?string $error = null;
  27. public function resolve(string $domain): void
  28. {
  29. $mx = @dns_get_record($domain, DNS_MX) ?: [];
  30. // RFC 7505 Null MX: exactly one record, preference 0, target "." (root).
  31. if (count($mx) === 1
  32. && (int) ($mx[0]['pri'] ?? -1) === 0
  33. && rtrim((string) ($mx[0]['target'] ?? ''), '.') === '') {
  34. $this->nullMx = true;
  35. $this->warnings[] = 'This domain publishes a Null MX record (RFC 7505: "0 .") — '
  36. . 'it explicitly does not accept email. Senders should bounce immediately.';
  37. return;
  38. }
  39. if (!empty($mx)) {
  40. $this->hasMx = true;
  41. // Sort by preference ascending; senders try the lowest number first.
  42. usort($mx, static fn($a, $b) => ($a['pri'] ?? 0) <=> ($b['pri'] ?? 0));
  43. $prefs = array_map(static fn($r) => (int) ($r['pri'] ?? 0), $mx);
  44. if (count($prefs) !== count(array_unique($prefs))) {
  45. $this->warnings[] = 'Several MX records share the same preference. A sender picks '
  46. . 'between equal-preference hosts at random, so the exact host order can vary per delivery.';
  47. }
  48. foreach ($mx as $r) {
  49. $host = rtrim((string) ($r['target'] ?? ''), '.');
  50. $this->targets[] = $this->buildTarget((int) ($r['pri'] ?? 0), $host, false);
  51. }
  52. return;
  53. }
  54. // No MX record → RFC 5321 implicit MX: try the domain's own A / AAAA.
  55. $implicit = $this->buildTarget(0, $domain, true);
  56. if (empty($implicit['addresses'])) {
  57. $this->error = 'No MX records and no A/AAAA records for the domain — '
  58. . 'there is nowhere to deliver mail. Senders will return a bounce.';
  59. return;
  60. }
  61. $this->warnings[] = 'No MX records found. Under RFC 5321 the domain\'s own address (A/AAAA) '
  62. . 'is used as an implicit MX at preference 0.';
  63. $this->targets[] = $implicit;
  64. }
  65. /**
  66. * Resolves one MX target to its addresses and flags common misconfigurations
  67. * (a CNAME where a hostname is required, or a target that does not resolve).
  68. */
  69. private function buildTarget(int $pref, string $host, bool $implicit): array
  70. {
  71. $target = [
  72. 'pref' => $pref,
  73. 'host' => $host,
  74. 'implicit' => $implicit,
  75. 'cname' => null,
  76. 'addresses' => [],
  77. 'error' => null,
  78. ];
  79. if ($host === '') {
  80. $target['error'] = 'Empty MX target.';
  81. return $target;
  82. }
  83. // RFC 2181 §10.3 / RFC 5321 §5.1: an MX target must be a hostname with
  84. // address records, never a CNAME. Flag it, but still follow the chain.
  85. $cname = @dns_get_record($host, DNS_CNAME) ?: [];
  86. foreach ($cname as $c) {
  87. if (($c['host'] ?? '') === $host && !empty($c['target'])) {
  88. $target['cname'] = rtrim((string) $c['target'], '.');
  89. if (!$implicit) {
  90. $this->warnings[] = sprintf(
  91. 'MX target "%s" is a CNAME pointing to "%s". RFC 2181 forbids this; some '
  92. . 'senders reject such records. It should be an A/AAAA hostname.',
  93. $host,
  94. $target['cname']
  95. );
  96. }
  97. break;
  98. }
  99. }
  100. foreach (@dns_get_record($host, DNS_A) ?: [] as $r) {
  101. if (!empty($r['ip'])) {
  102. $target['addresses'][] = ['ip' => $r['ip'], 'version' => 'IPv4'];
  103. }
  104. }
  105. foreach (@dns_get_record($host, DNS_AAAA) ?: [] as $r) {
  106. if (!empty($r['ipv6'])) {
  107. $target['addresses'][] = ['ip' => $r['ipv6'], 'version' => 'IPv6'];
  108. }
  109. }
  110. if (empty($target['addresses'])) {
  111. $target['error'] = $target['cname'] !== null
  112. ? 'Target is a CNAME and did not resolve to any address.'
  113. : 'MX host has no A/AAAA records — a sender cannot connect to it.';
  114. }
  115. return $target;
  116. }
  117. /** @return string[] Every unique IP across all targets, for batch enrichment. */
  118. public function allIps(): array
  119. {
  120. $ips = [];
  121. foreach ($this->targets as $t) {
  122. foreach ($t['addresses'] as $a) {
  123. $ips[] = $a['ip'];
  124. }
  125. }
  126. return array_values(array_unique($ips));
  127. }
  128. }
  129. /**
  130. * Enriches IPs with ASN / country / company via ip-api.com's free batch endpoint.
  131. * @param string[] $ips
  132. * @return array<string,array>
  133. */
  134. function lookupIpInfo(array $ips): array
  135. {
  136. $out = [];
  137. $ips = array_values(array_unique(array_filter($ips)));
  138. if (empty($ips)) {
  139. return $out;
  140. }
  141. $fields = 'query,status,message,country,countryCode,as,asname,isp,org,reverse';
  142. foreach (array_chunk($ips, 100) as $chunk) {
  143. $payload = array_map(static fn($ip) => ['query' => $ip, 'fields' => $fields], $chunk);
  144. $ch = curl_init('http://ip-api.com/batch');
  145. curl_setopt_array($ch, [
  146. CURLOPT_POST => true,
  147. CURLOPT_POSTFIELDS => json_encode($payload),
  148. CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
  149. CURLOPT_RETURNTRANSFER => true,
  150. CURLOPT_TIMEOUT => 20,
  151. ]);
  152. $resp = curl_exec($ch);
  153. curl_close($ch);
  154. foreach ((json_decode((string) $resp, true) ?: []) as $item) {
  155. if (isset($item['query'])) {
  156. $out[$item['query']] = $item;
  157. }
  158. }
  159. }
  160. return $out;
  161. }
  162. $domain = trim((string) ($_GET['domain'] ?? ''));
  163. $resolver = null;
  164. $ipInfo = [];
  165. $inputError = null;
  166. if ($domain !== '') {
  167. // Accept a bare hostname; strip scheme/path if a URL was pasted, and an
  168. // email address if someone enters user@example.com.
  169. $domain = preg_replace('#^\w+://#', '', $domain);
  170. $domain = explode('/', $domain)[0];
  171. if (str_contains($domain, '@')) {
  172. $domain = substr($domain, strrpos($domain, '@') + 1);
  173. }
  174. $domain = strtolower(trim($domain));
  175. if (!preg_match('/^(?=.{1,253}$)([a-z0-9](-?[a-z0-9])*\.)+[a-z]{2,}$/', $domain)) {
  176. $inputError = 'Please enter a valid domain name (e.g. example.com) or an email address.';
  177. } else {
  178. $resolver = new DeliveryResolver();
  179. $resolver->resolve($domain);
  180. $ipInfo = lookupIpInfo($resolver->allIps());
  181. }
  182. }
  183. ?>
  184. <!DOCTYPE html>
  185. <html lang="en">
  186. <head>
  187. <meta charset="UTF-8">
  188. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  189. <title>Mail Delivery Route Checker</title>
  190. <style>
  191. body {
  192. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  193. max-width: 1100px;
  194. margin: 40px auto;
  195. padding: 0 20px;
  196. background: #f5f5f5;
  197. color: #333;
  198. }
  199. h1 { color: #333; }
  200. .info { background: #e3f2fd; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
  201. form.lookup { margin-bottom: 20px; display: flex; gap: 10px; flex-wrap: wrap; }
  202. input[type=text] {
  203. flex: 1; min-width: 240px; padding: 10px; font-size: 15px;
  204. border: 1px solid #ccc; border-radius: 5px;
  205. }
  206. .btn {
  207. display: inline-block; padding: 10px 20px; background: #2196F3; color: white;
  208. text-decoration: none; border-radius: 5px; border: none; cursor: pointer; font-size: 15px;
  209. }
  210. .btn:hover { background: #1976D2; }
  211. .error { background: #ffebee; color: #c62828; padding: 10px; border-radius: 5px; margin: 10px 0; }
  212. .warning {
  213. background: #fff8e1; color: #e65100; padding: 12px 15px; border-radius: 5px;
  214. margin: 10px 0; border-left: 5px solid #ff9800;
  215. }
  216. .verdict {
  217. display: flex; align-items: center; gap: 12px; padding: 16px 20px; border-radius: 6px;
  218. font-size: 17px; font-weight: 600; margin: 16px 0;
  219. }
  220. .verdict.ok { background: #e8f5e9; color: #2e7d32; border-left: 6px solid #43a047; }
  221. .verdict.fail { background: #ffebee; color: #c62828; border-left: 6px solid #e53935; }
  222. h2 { color: #333; margin-top: 30px; }
  223. .target {
  224. background: white; border-radius: 6px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  225. margin: 12px 0; padding: 14px 16px; border-left: 5px solid #2196F3;
  226. }
  227. .target.dead { border-left-color: #e53935; opacity: 0.85; }
  228. .target-head { display: flex; align-items: baseline; gap: 12px; flex-wrap: wrap; }
  229. .pref {
  230. display: inline-flex; align-items: center; justify-content: center; min-width: 30px; height: 30px;
  231. background: #2196F3; color: white; border-radius: 50%; font-weight: 700; font-size: 14px; padding: 0 6px;
  232. }
  233. .target.dead .pref { background: #e53935; }
  234. .mxhost { font-family: monospace; font-size: 16px; font-weight: 600; word-break: break-all; }
  235. .tag {
  236. display: inline-block; padding: 2px 8px; border-radius: 10px; font-size: 11px; font-weight: 700;
  237. }
  238. .tag.implicit { background: #ede7f6; color: #5e35b1; }
  239. .tag.cname { background: #fff3e0; color: #e65100; }
  240. .tag.first { background: #e8f5e9; color: #2e7d32; }
  241. .tag-err { color: #c62828; font-size: 13px; margin-top: 6px; }
  242. table { width: 100%; border-collapse: collapse; margin-top: 10px; }
  243. th, td { padding: 8px 12px; text-align: left; border-bottom: 1px solid #eee; font-size: 13px; }
  244. th { color: #555; background: #fafafa; font-weight: 600; }
  245. td.ip { font-family: monospace; }
  246. .ver { display: inline-block; padding: 1px 6px; border-radius: 3px; font-size: 11px; font-weight: 700; }
  247. .ver.IPv4 { background: #e3f2fd; color: #1565c0; }
  248. .ver.IPv6 { background: #f3e5f5; color: #6a1b9a; }
  249. .empty { text-align: center; color: #999; padding: 40px; }
  250. .muted { color: #888; font-size: 12px; }
  251. ol.flat { padding-left: 20px; }
  252. ol.flat li { margin: 4px 0; font-size: 14px; }
  253. ol.flat code { font-family: monospace; }
  254. </style>
  255. </head>
  256. <body>
  257. <h1>📮 Mail Delivery Route Checker</h1>
  258. <div class="info">
  259. Shows <strong>where a sending mail server would try to deliver</strong> email for a domain, following
  260. <strong>RFC 5321</strong> routing: MX records sorted by <strong>preference</strong> (lowest first), each MX
  261. resolved to its <strong>A / AAAA addresses</strong>, plus <strong>Null MX</strong> (RFC 7505) and
  262. <strong>implicit MX</strong> fallback. Every address is enriched with its ASN, country and company.
  263. </div>
  264. <form class="lookup" method="GET">
  265. <input type="text" name="domain" placeholder="example.com (or user@example.com)"
  266. value="<?= htmlspecialchars($domain) ?>" autofocus>
  267. <button type="submit" class="btn">🔍 Trace delivery</button>
  268. </form>
  269. <?php if ($inputError): ?>
  270. <div class="error"><?= htmlspecialchars($inputError) ?></div>
  271. <?php endif; ?>
  272. <?php if ($resolver !== null): ?>
  273. <?php if ($resolver->nullMx): ?>
  274. <div class="verdict fail">🚫 <?= htmlspecialchars($domain) ?> does not accept mail (Null MX).</div>
  275. <?php elseif ($resolver->error !== null): ?>
  276. <div class="verdict fail">❌ Mail cannot be delivered to <?= htmlspecialchars($domain) ?>.</div>
  277. <?php else:
  278. $reachable = array_filter($resolver->targets, static fn($t) => !empty($t['addresses']));
  279. ?>
  280. <?php if (!empty($reachable)): ?>
  281. <div class="verdict ok">✅ Mail for <?= htmlspecialchars($domain) ?> would be delivered to
  282. <?= count($reachable) ?> reachable <?= $resolver->hasMx ? 'MX host' : 'implicit MX host' ?><?= count($reachable) === 1 ? '' : 's' ?>.</div>
  283. <?php else: ?>
  284. <div class="verdict fail">❌ MX records exist but none resolve to a usable address.</div>
  285. <?php endif; ?>
  286. <?php endif; ?>
  287. <?php foreach ($resolver->warnings as $w): ?>
  288. <div class="warning">⚠️ <?= htmlspecialchars($w) ?></div>
  289. <?php endforeach; ?>
  290. <?php if ($resolver->error !== null): ?>
  291. <div class="error"><?= htmlspecialchars($resolver->error) ?></div>
  292. <?php endif; ?>
  293. <?php if (!empty($resolver->targets)): ?>
  294. <h2>Delivery targets, in the order a sender tries them</h2>
  295. <?php foreach ($resolver->targets as $i => $t): ?>
  296. <div class="target <?= empty($t['addresses']) ? 'dead' : '' ?>">
  297. <div class="target-head">
  298. <span class="pref" title="MX preference"><?= (int) $t['pref'] ?></span>
  299. <span class="mxhost"><?= htmlspecialchars($t['host']) ?></span>
  300. <?php if ($i === 0 && !empty($t['addresses'])): ?>
  301. <span class="tag first">tried first</span>
  302. <?php endif; ?>
  303. <?php if ($t['implicit']): ?>
  304. <span class="tag implicit">implicit MX (A/AAAA)</span>
  305. <?php endif; ?>
  306. <?php if ($t['cname'] !== null): ?>
  307. <span class="tag cname">CNAME → <?= htmlspecialchars($t['cname']) ?></span>
  308. <?php endif; ?>
  309. </div>
  310. <?php if ($t['error'] !== null): ?>
  311. <div class="tag-err">⚠️ <?= htmlspecialchars($t['error']) ?></div>
  312. <?php else: ?>
  313. <table>
  314. <thead>
  315. <tr>
  316. <th style="width:60px;">#</th>
  317. <th>IP address</th>
  318. <th>Type</th>
  319. <th>PTR (reverse)</th>
  320. <th>ASN</th>
  321. <th>Company / ISP</th>
  322. <th>Country</th>
  323. </tr>
  324. </thead>
  325. <tbody>
  326. <?php foreach ($t['addresses'] as $j => $a): ?>
  327. <?php
  328. $info = $ipInfo[$a['ip']] ?? null;
  329. $ok = $info && ($info['status'] ?? '') === 'success';
  330. $asn = $ok ? ($info['as'] ?: '—') : '—';
  331. $company = $ok ? ($info['org'] ?: ($info['isp'] ?? '') ?: ($info['asname'] ?? '')) : '';
  332. $country = $ok ? trim(($info['country'] ?? '') . ' (' . ($info['countryCode'] ?? '') . ')', ' ()') : '';
  333. $ptr = $ok ? ($info['reverse'] ?? '') : '';
  334. ?>
  335. <tr>
  336. <td><?= $j + 1 ?></td>
  337. <td class="ip"><?= htmlspecialchars($a['ip']) ?></td>
  338. <td><span class="ver <?= $a['version'] ?>"><?= $a['version'] ?></span></td>
  339. <td class="ip"><?= htmlspecialchars($ptr ?: '—') ?></td>
  340. <td><?= htmlspecialchars($asn) ?></td>
  341. <td><?= htmlspecialchars($company ?: '—') ?></td>
  342. <td><?= htmlspecialchars($country ?: '—') ?></td>
  343. </tr>
  344. <?php endforeach; ?>
  345. </tbody>
  346. </table>
  347. <?php endif; ?>
  348. </div>
  349. <?php endforeach; ?>
  350. <?php
  351. // Flat "connection attempt" order across every reachable address.
  352. $flat = [];
  353. foreach ($resolver->targets as $t) {
  354. foreach ($t['addresses'] as $a) {
  355. $flat[] = ['pref' => $t['pref'], 'host' => $t['host'], 'ip' => $a['ip']];
  356. }
  357. }
  358. ?>
  359. <?php if (!empty($flat)): ?>
  360. <h2>Connection attempt order</h2>
  361. <p class="muted">A sender opens an SMTP connection to these addresses in turn, moving on only when one is unreachable or defers.</p>
  362. <ol class="flat">
  363. <?php foreach ($flat as $f): ?>
  364. <li><code><?= htmlspecialchars($f['host']) ?></code> [pref <?= (int) $f['pref'] ?>] → <code><?= htmlspecialchars($f['ip']) ?></code></li>
  365. <?php endforeach; ?>
  366. </ol>
  367. <p class="muted">
  368. Note: equal-preference MX hosts, and the choice between IPv4/IPv6 per host, are ultimately up to
  369. the sending MTA — so the exact order can differ between deliveries.
  370. </p>
  371. <?php endif; ?>
  372. <?php elseif (!$resolver->nullMx && $resolver->error === null): ?>
  373. <div class="empty">No delivery targets were found.</div>
  374. <?php endif; ?>
  375. <p class="muted" style="margin-top:20px;">IP intelligence via ip-api.com (free tier).</p>
  376. <?php endif; ?>
  377. </body>
  378. </html>