format.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. #pragma once
  2. #include <jvalidate/_config.h>
  3. #include <cctype>
  4. #include <chrono>
  5. #include <cstddef>
  6. #include <cstring>
  7. #include <ctime>
  8. #include <string>
  9. #include <string_view>
  10. #include <unordered_map>
  11. #include <utility>
  12. #ifdef JVALIDATE_HAS_IDNA
  13. #include <ada/idna/to_unicode.h>
  14. #include <ada/idna/validity.h>
  15. #endif
  16. #include <jvalidate/detail/idna_special_cases.h>
  17. #include <jvalidate/detail/pointer.h>
  18. #include <jvalidate/detail/relative_pointer.h>
  19. #include <jvalidate/detail/string.h>
  20. #include <jvalidate/forward.h>
  21. #define CONSTRUCTS(TYPE) format::ctor_as_valid<detail::TYPE>
  22. #define UTF32(FN) format::utf32<format::FN<char32_t>>
  23. namespace jvalidate::format::detail {
  24. struct result {
  25. ptrdiff_t consumed;
  26. bool valid;
  27. };
  28. inline bool is_leapyear(int y) { return (y % 400) == 0 || ((y % 4) == 0 && (y % 100) != 0); }
  29. inline bool illegal_date(int y, int m, int d) {
  30. static constexpr int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  31. if (is_leapyear(y) && m == 1) {
  32. --d;
  33. }
  34. return d > days[m];
  35. }
  36. inline result date(std::string_view dt) {
  37. struct tm tm;
  38. if (auto end = strptime(dt.data(), "%Y-%m-%d", &tm); end) {
  39. if ((end - dt.data()) != 10 || illegal_date(tm.tm_year + 1900, tm.tm_mon, tm.tm_mday)) {
  40. return {.consumed = 0, .valid = false};
  41. }
  42. return {.consumed = end - dt.data(), .valid = true};
  43. }
  44. return {.consumed = 0L, .valid = false};
  45. }
  46. inline bool is_leapsecond(std::tm tm) {
  47. if (tm.tm_sec != 60) {
  48. return true;
  49. }
  50. #if __cpp_lib_chrono >= 201907L
  51. tm.tm_isdst = -1;
  52. std::chrono::seconds time(std::mktime(&tm));
  53. auto const &leap_seconds = std::chrono::get_tzdb().leap_seconds;
  54. return std::ranges::find(leap_seconds, time) != leap_seconds.end();
  55. #else
  56. return false;
  57. #endif
  58. }
  59. }
  60. namespace jvalidate::format {
  61. inline bool date(std::string_view dt) {
  62. auto [consumed, valid] = detail::date(dt);
  63. return valid && consumed == dt.size();
  64. }
  65. inline bool time(std::string_view dt) {
  66. std::tm tm;
  67. char const * end = strptime(dt.data(), "%T", &tm);
  68. if (end == nullptr || end == dt.end() || (end - dt.data()) < 8) {
  69. return false;
  70. }
  71. dt.remove_prefix(end - dt.begin());
  72. if (dt[0] == '.') {
  73. dt.remove_prefix(1);
  74. if (dt.empty() || not std::isdigit(dt[0])) {
  75. return false;
  76. }
  77. while (std::isdigit(dt[0])) {
  78. dt.remove_prefix(1);
  79. }
  80. }
  81. if (dt[0] == 'Z' || dt[0] == 'z') {
  82. return dt.size() == 1 && detail::is_leapsecond(tm);
  83. }
  84. if (std::strchr("+-", dt[0])) {
  85. return strptime(dt.data() + 1, "%R", &tm) == dt.end() && detail::is_leapsecond(tm);
  86. }
  87. return false;
  88. }
  89. inline bool date_time(std::string_view dt) {
  90. auto [size, good] = detail::date(dt);
  91. if (not good || std::strchr("Tt", dt[size]) == nullptr) {
  92. return false;
  93. }
  94. dt.remove_prefix(size + 1);
  95. return time(dt);
  96. }
  97. inline bool uuid(std::string_view id) {
  98. constexpr char const * g_hex_digits = "0123456789ABCDEFabcdef";
  99. constexpr size_t g_uuid_len = 36;
  100. constexpr size_t g_uuid_tokens = 5;
  101. char tok0[9], tok1[5], tok2[5], tok3[5], tok4[13];
  102. auto is_hex = [](std::string_view s) {
  103. return s.find_first_not_of(g_hex_digits) == std::string::npos;
  104. };
  105. return id.size() == g_uuid_len &&
  106. sscanf(id.data(), "%8s-%4s-%4s-%4s-%12s", tok0, tok1, tok2, tok3, tok4) == g_uuid_tokens &&
  107. is_hex(tok0) && is_hex(tok1) && is_hex(tok2) && is_hex(tok3) && is_hex(tok4);
  108. }
  109. inline bool duration(std::string_view dur) {
  110. auto eat = [&dur](std::string_view text) {
  111. char type;
  112. unsigned int rep;
  113. if (sscanf(dur.data(), "%u%c", &rep, &type) != 2 || text.find(type) == std::string::npos) {
  114. return std::string::npos;
  115. }
  116. dur.remove_prefix(dur.find(type) + 1);
  117. return text.find(type);
  118. };
  119. if (dur[0] != 'P' || dur.size() == 1) {
  120. return false;
  121. }
  122. dur.remove_prefix(1);
  123. if (dur[0] != 'T') {
  124. if (eat("W") != std::string::npos) {
  125. return dur.empty();
  126. }
  127. std::string_view ymd{"YMD"};
  128. while (not ymd.empty() && not dur.empty()) {
  129. if (size_t n = eat(ymd); n != std::string::npos) {
  130. ymd.remove_prefix(n + 1);
  131. } else {
  132. return false;
  133. }
  134. }
  135. if (dur.empty()) {
  136. return true;
  137. }
  138. }
  139. if (dur[0] != 'T' || dur.size() == 1) {
  140. return false;
  141. }
  142. dur.remove_prefix(1);
  143. std::string_view hms{"HMS"};
  144. while (not hms.empty() && not dur.empty()) {
  145. if (size_t n = eat(hms); n != std::string::npos) {
  146. hms.remove_prefix(n + 1);
  147. } else {
  148. return false;
  149. }
  150. }
  151. return dur.empty();
  152. }
  153. template <typename CharT> bool is_invalid_host_char(CharT c) {
  154. return c != '-' && not(std::isalnum(c) || c > 0x7F);
  155. }
  156. template <typename CharT>
  157. bool is_invalid_size_or_boundary_hostname(std::basic_string_view<CharT> name) {
  158. using delim = detail::char_delimiters<CharT>;
  159. return (name.empty() || detail::length_u8(name) >= 64 ||
  160. (name.size() >= 4 && name.substr(2).starts_with(delim::illegal_dashes_ulabel)) ||
  161. name[0] == '-' || name.back() == '-');
  162. }
  163. #ifndef JVALIDATE_HAS_IDNA
  164. inline bool hostname_part(std::string_view name) {
  165. using delim = detail::char_delimiters<char>;
  166. if (is_invalid_size_or_boundary_hostname(name)) {
  167. return false;
  168. }
  169. return std::ranges::none_of(name, [](char c) { return c != '-' && not std::isalnum(c); });
  170. }
  171. #else
  172. template <typename CharT> inline bool hostname_part(std::basic_string_view<CharT> name) {
  173. using delim = detail::char_delimiters<CharT>;
  174. if (name.starts_with(delim::punycode_prefix)) {
  175. std::u32string decoded = detail::to_u32(ada::idna::to_unicode(detail::to_u8(name)));
  176. return (decoded != detail::to_u32(name)) && hostname_part<char32_t>(decoded);
  177. }
  178. if (is_invalid_size_or_boundary_hostname(name)) {
  179. return false;
  180. }
  181. if constexpr (std::is_same_v<char, CharT>) {
  182. return std::ranges::none_of(name, [](char c) { return c != '-' && not std::isalnum(c); });
  183. } else {
  184. return ada::idna::is_label_valid(name);
  185. }
  186. }
  187. #endif
  188. // Limitation - does not inspect graphemes, so it cannot check idn-hostname
  189. // to fix this - we'd need to
  190. template <typename CharT = char> inline bool hostname(std::basic_string_view<CharT> name) {
  191. using delim = detail::char_delimiters<CharT>;
  192. if (name.find_first_of(delim::illegal_hostname_chars) != name.npos) {
  193. return false;
  194. }
  195. if (detail::to_u8(name).size() > (name.back() == '.' ? 254 : 253)) {
  196. return false;
  197. }
  198. if (not std::ranges::all_of(delim::special_cases,
  199. [name](auto & sc) { return sc.accepts(name); })) {
  200. return false;
  201. }
  202. for (size_t n = name.find('.'); n != std::string::npos;
  203. name.remove_prefix(n + 1), n = name.find('.')) {
  204. if (not hostname_part(name.substr(0, n))) {
  205. return false;
  206. }
  207. }
  208. return name.empty() || hostname_part(name);
  209. }
  210. inline bool ipv4(std::string_view ip) {
  211. unsigned int ip0, ip1, ip2, ip3;
  212. char eof;
  213. if (ip.find_first_not_of("0123456789.") != std::string::npos) {
  214. return false;
  215. }
  216. if (ip[0] == '0' && std::isdigit(ip[1])) {
  217. return false;
  218. }
  219. if (size_t n = ip.find(".0"); n != std::string::npos && std::isdigit(ip[n + 2])) {
  220. return false;
  221. }
  222. if (sscanf(std::string(ip).c_str(), "%3u.%3u.%3u.%3u%c", &ip0, &ip1, &ip2, &ip3, &eof) != 4) {
  223. return false;
  224. }
  225. return ip0 <= 0xFF && ip1 <= 0xFF && ip2 <= 0xFF && ip3 <= 0xFF;
  226. }
  227. inline bool ipv6(std::string_view ip) {
  228. int expected_spans = 8;
  229. if (size_t n = ip.find('.'); n != std::string::npos) {
  230. if (not ipv4(ip.substr(ip.find_last_of(':') + 1))) {
  231. return false;
  232. }
  233. // This is a cheat to allow e.g. ::127.0.0.1 to validate
  234. expected_spans = 7;
  235. ip = ip.substr(0, n);
  236. }
  237. if (ip.find_first_not_of("0123456789ABCDEFabcdef:") != std::string::npos) {
  238. return false;
  239. }
  240. if (ip.size() >= 40) {
  241. return false;
  242. }
  243. bool has_compressed = false;
  244. int groups = 0;
  245. if (ip.starts_with("::")) {
  246. has_compressed = true;
  247. ip.remove_prefix(2);
  248. }
  249. while (!ip.empty()) {
  250. int data;
  251. if (sscanf(ip.data(), "%4x", &data) != 1) {
  252. return false;
  253. }
  254. if (size_t n = ip.find(':'); std::min(n, ip.size()) > 4) {
  255. return false;
  256. } else if (n != std::string::npos) {
  257. ip.remove_prefix(n + 1);
  258. } else {
  259. ip = "";
  260. }
  261. ++groups;
  262. if (ip[0] == ':') {
  263. if (std::exchange(has_compressed, true)) {
  264. return false;
  265. }
  266. ip.remove_prefix(1);
  267. }
  268. }
  269. return groups == expected_spans || (has_compressed && groups < expected_spans);
  270. }
  271. // Let's be honest - no matter what RFC 5321 §4.1.2 or RFC 6531 say, the only
  272. // way to know if an email address is valid is to try and send a message to it.
  273. // Therefore, there's no point in trying to validate things according to a
  274. // complex grammar - as long as it has an '@' sign with at least one character
  275. // on each side, we ought to call it an email.
  276. template <typename CharT = char> inline bool email(std::basic_string_view<CharT> em) {
  277. using delim = detail::char_delimiters<CharT>;
  278. size_t n = em.find_last_of('@');
  279. if (n == 0 || n >= em.size() - 1) {
  280. return false;
  281. }
  282. auto const who = em.substr(0, n);
  283. if (who.starts_with('"') && who.ends_with('"')) {
  284. // No validation
  285. } else if (who.starts_with('.') || who.ends_with('.')) {
  286. return false;
  287. } else if (em.substr(0, n).find(delim::dotdot) != em.npos) {
  288. return false;
  289. }
  290. auto domain = em.substr(n + 1);
  291. if (not(domain.starts_with('[') && domain.ends_with(']'))) {
  292. return hostname(domain);
  293. }
  294. domain.remove_prefix(1);
  295. domain.remove_suffix(1);
  296. if (auto ip = detail::to_u8(domain); ip.starts_with("IPv6:")) {
  297. return ipv6(ip.substr(5));
  298. } else {
  299. return ipv4(ip);
  300. }
  301. }
  302. template <typename T> inline bool ctor_as_valid(std::string_view str) {
  303. try {
  304. [[maybe_unused]] auto _ = T(str);
  305. return true;
  306. } catch (std::exception const &) { return false; }
  307. }
  308. template <auto Predicate> bool utf32(std::string_view str) {
  309. return Predicate(detail::to_u32(str));
  310. }
  311. }
  312. namespace jvalidate {
  313. class FormatValidator {
  314. public:
  315. using Predicate = bool (*)(std::string_view);
  316. enum class Status { Unknown, Unimplemented, Valid, Invalid };
  317. private:
  318. std::unordered_map<std::string, Predicate> supported_formats_{
  319. {"date", &format::date},
  320. {"date-time", &format::date_time},
  321. {"duration", &format::duration},
  322. {"email", &format::email},
  323. {"hostname", &format::hostname},
  324. {"idn-email", UTF32(email)},
  325. {"idn-hostname", UTF32(hostname)},
  326. {"ipv4", &format::ipv4},
  327. {"ipv6", &format::ipv6},
  328. {"iri", nullptr},
  329. {"iri-reference", nullptr},
  330. {"json-pointer", CONSTRUCTS(Pointer)},
  331. {"relative-json-pointer", CONSTRUCTS(RelativePointer)},
  332. {"regex", nullptr},
  333. {"time", &format::time},
  334. {"uri", nullptr},
  335. {"uri-reference", nullptr},
  336. {"uri-template", nullptr},
  337. {"uuid", &format::uuid},
  338. };
  339. public:
  340. FormatValidator() = default;
  341. FormatValidator(Predicate is_regex) { supported_formats_.insert_or_assign("regex", is_regex); }
  342. Status operator()(std::string const & format, std::string_view text) const {
  343. if (auto it = supported_formats_.find(format); it != supported_formats_.end() && it->second) {
  344. if (not it->second) {
  345. return Status::Unimplemented;
  346. }
  347. return it->second(text) ? Status::Valid : Status::Invalid;
  348. }
  349. return Status::Unknown;
  350. }
  351. };
  352. }
  353. #undef CONSTRUCTS
  354. #undef UTF32