|
| 1 | +#include <sourcemeta/core/dns.h> |
| 2 | + |
| 3 | +namespace sourcemeta::core { |
| 4 | + |
| 5 | +// RFC 952 §B: let-dig = ALPHA / DIGIT |
| 6 | +// RFC 1123 §2.1: first character of a label is letter or digit |
| 7 | +static constexpr auto is_let_dig(const char character) -> bool { |
| 8 | + return (character >= 'A' && character <= 'Z') || |
| 9 | + (character >= 'a' && character <= 'z') || |
| 10 | + (character >= '0' && character <= '9'); |
| 11 | +} |
| 12 | + |
| 13 | +// RFC 952 §B: let-dig-hyp = ALPHA / DIGIT / "-" |
| 14 | +static constexpr auto is_let_dig_hyp(const char character) -> bool { |
| 15 | + return is_let_dig(character) || character == '-'; |
| 16 | +} |
| 17 | + |
| 18 | +auto is_hostname(const std::string_view value) -> bool { |
| 19 | + // RFC 952 §B: <hname> requires at least one <name> |
| 20 | + if (value.empty()) { |
| 21 | + return false; |
| 22 | + } |
| 23 | + |
| 24 | + // RFC 1123 §2.1: SHOULD handle host names of up to 255 characters |
| 25 | + if (value.size() > 255) { |
| 26 | + return false; |
| 27 | + } |
| 28 | + |
| 29 | + std::string_view::size_type position{0}; |
| 30 | + |
| 31 | + while (position < value.size()) { |
| 32 | + const auto label_start{position}; |
| 33 | + |
| 34 | + // RFC 1123 §2.1: first character is letter or digit |
| 35 | + if (!is_let_dig(value[position])) { |
| 36 | + return false; |
| 37 | + } |
| 38 | + position += 1; |
| 39 | + |
| 40 | + while (position < value.size() && value[position] != '.') { |
| 41 | + // RFC 952 §B: interior characters are let-dig-hyp |
| 42 | + if (!is_let_dig_hyp(value[position])) { |
| 43 | + return false; |
| 44 | + } |
| 45 | + position += 1; |
| 46 | + } |
| 47 | + |
| 48 | + const auto label_length{position - label_start}; |
| 49 | + |
| 50 | + // RFC 1123 §2.1: MUST handle host names of up to 63 characters (per label) |
| 51 | + if (label_length > 63) { |
| 52 | + return false; |
| 53 | + } |
| 54 | + |
| 55 | + // RFC 952 §B + ASSUMPTIONS: last character must not be a minus sign |
| 56 | + if (value[position - 1] == '-') { |
| 57 | + return false; |
| 58 | + } |
| 59 | + |
| 60 | + // If we stopped on a dot, there must be another label following it |
| 61 | + if (position < value.size()) { |
| 62 | + // value[position] == '.' |
| 63 | + position += 1; |
| 64 | + // Trailing dot: JSON Schema test suite requires rejection (TS d7+ #15) |
| 65 | + if (position >= value.size()) { |
| 66 | + return false; |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + return true; |
| 72 | +} |
| 73 | + |
| 74 | +} // namespace sourcemeta::core |
0 commit comments