format.h 14 KB

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