format.h 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  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 <system_error>
  11. #include <unordered_map>
  12. #include <unordered_set>
  13. #include <utility>
  14. #ifdef JVALIDATE_HAS_IDNA
  15. #include <ada/idna/to_unicode.h>
  16. #include <ada/idna/validity.h>
  17. #endif
  18. #include <jvalidate/detail/expect.h>
  19. #include <jvalidate/detail/idna_special_cases.h>
  20. #include <jvalidate/detail/pointer.h>
  21. #include <jvalidate/detail/relative_pointer.h>
  22. #include <jvalidate/detail/string.h>
  23. #include <jvalidate/enum.h>
  24. #include <jvalidate/forward.h>
  25. #define CONSTRUCTS(TYPE) format::ctor_as_valid<detail::TYPE>
  26. #define UTF32(FN) JVALIDATE_IIF(JVALIDATE_HAS_IDNA, format::utf32<format::FN<char32_t>>, nullptr)
  27. namespace jvalidate::format {
  28. bool date(std::string_view dt);
  29. bool time(std::string_view dt);
  30. bool date_time(std::string_view dt);
  31. bool duration(std::string_view dur);
  32. template <typename CharT = char> bool uri(std::basic_string_view<CharT> uri);
  33. template <typename CharT = char> bool uri_reference(std::basic_string_view<CharT> uri);
  34. bool uri_template(std::u32string_view uri);
  35. bool uuid(std::string_view id);
  36. template <typename CharT = char> bool hostname(std::basic_string_view<CharT> name);
  37. bool ipv4(std::string_view ip);
  38. bool ipv6(std::string_view ip);
  39. template <typename CharT = char> bool email(std::basic_string_view<CharT> em);
  40. }
  41. namespace jvalidate::format::detail {
  42. inline bool is_hex(std::string_view s) {
  43. constexpr char const * g_hex_digits = "0123456789ABCDEFabcdef";
  44. return s.find_first_not_of(g_hex_digits) == std::string::npos;
  45. }
  46. struct result {
  47. ptrdiff_t consumed;
  48. bool valid;
  49. };
  50. inline bool is_leapyear(int y) { return (y % 400) == 0 || ((y % 4) == 0 && (y % 100) != 0); }
  51. inline bool illegal_date(int y, int m, int d) {
  52. static constexpr int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  53. if (is_leapyear(y) && m == 1) {
  54. --d;
  55. }
  56. return d > days[m];
  57. }
  58. inline result date(std::string_view dt) {
  59. struct tm tm;
  60. if (auto end = strptime(dt.data(), "%Y-%m-%d", &tm); end) {
  61. if ((end - dt.data()) != 10 || illegal_date(tm.tm_year + 1900, tm.tm_mon, tm.tm_mday)) {
  62. return {.consumed = 0, .valid = false};
  63. }
  64. return {.consumed = end - dt.data(), .valid = true};
  65. }
  66. return {.consumed = 0L, .valid = false};
  67. }
  68. inline bool is_leapsecond(std::tm tm) {
  69. if (tm.tm_sec != 60) {
  70. return true;
  71. }
  72. #if __cpp_lib_chrono >= 201907L
  73. tm.tm_isdst = -1;
  74. std::chrono::seconds time(std::mktime(&tm));
  75. auto const & leap_seconds = std::chrono::get_tzdb().leap_seconds;
  76. return std::ranges::find(leap_seconds, time) != leap_seconds.end();
  77. #else
  78. return false;
  79. #endif
  80. }
  81. // https://www.rfc-editor.org/rfc/rfc6570.html#section-1.5
  82. inline bool is_uschar(int c) {
  83. using P = std::pair<int, int>;
  84. constexpr std::array data{
  85. P{0xA0, 0xD7FF}, P{0xF900, 0xFDCF}, P{0xFDF0, 0xFFEF}, P{0x10000, 0x1FFFD},
  86. P{0x20000, 0x2FFFD}, P{0x30000, 0x3FFFD}, P{0x40000, 0x4FFFD}, P{0x50000, 0x5FFFD},
  87. P{0x60000, 0x6FFFD}, P{0x70000, 0x7FFFD}, P{0x80000, 0x8FFFD}, P{0x90000, 0x9FFFD},
  88. P{0xA0000, 0xAFFFD}, P{0xB0000, 0xBFFFD}, P{0xC0000, 0xCFFFD}, P{0xD0000, 0xDFFFD},
  89. P{0xE0000, 0xEFFFD},
  90. };
  91. return std::ranges::any_of(data,
  92. [c](auto & pair) { return c >= pair.first && c <= pair.second; });
  93. }
  94. template <typename CharT>
  95. inline bool is_pchar(std::basic_string_view<CharT> part, size_t & pos,
  96. std::string_view extra_valid_chars = ":@") {
  97. constexpr char const * g_hex_digits = "0123456789ABCDEFabcdef";
  98. if (std::isalnum(part[pos]) || is_uschar(part[pos]) ||
  99. std::strchr("-._~!$&'()*+,;=", part[pos])) {
  100. return true;
  101. }
  102. if (part[pos] == '%') {
  103. return pos + 2 < part.size() && std::strchr(g_hex_digits, part[++pos]) &&
  104. std::strchr(g_hex_digits, part[++pos]);
  105. }
  106. return extra_valid_chars.find(part[pos]) != part.npos;
  107. };
  108. inline bool is_uri_template_literal(std::u32string_view part, size_t & pos) {
  109. constexpr char const * g_hex_digits = "0123456789ABCDEFabcdef";
  110. if (part[pos] == '%') {
  111. return pos + 2 < part.size() && std::strchr(g_hex_digits, part[++pos]) &&
  112. std::strchr(g_hex_digits, part[++pos]);
  113. }
  114. return !std::strchr(R"( "'%<>\^`{|}`)", part[pos]) && part[pos] > 0x1F && part[pos] != 0x7F;
  115. }
  116. inline bool is_uri_template_varchar(std::u32string_view part, size_t & pos) {
  117. constexpr char const * g_hex_digits = "0123456789ABCDEFabcdef";
  118. if (part[pos] == '%') {
  119. return pos + 2 < part.size() && std::strchr(g_hex_digits, part[++pos]) &&
  120. std::strchr(g_hex_digits, part[++pos]);
  121. }
  122. return std::isalnum(part[pos]) || part[pos] == '_';
  123. }
  124. inline bool is_uri_template_expression(std::u32string_view part) {
  125. if (part.empty()) {
  126. return false;
  127. }
  128. if (std::strchr("+#./;?&=,!@|", part[0])) {
  129. part.remove_prefix(1);
  130. }
  131. for (size_t pos = part.find(','); !part.empty();
  132. part.remove_prefix(std::min(part.size(), pos)), pos = part.find(',')) {
  133. std::u32string_view varspec = part.substr(0, pos);
  134. std::u32string_view expand;
  135. if (size_t const mod = varspec.find_first_of(U":*"); mod != varspec.npos) {
  136. expand = varspec.substr(mod + 1);
  137. varspec.remove_suffix(expand.size() + 1);
  138. }
  139. if (expand.empty() || expand == U"*") {
  140. // No Modifier, or Explode
  141. } else if (expand.size() > 4 || expand[0] == '0' ||
  142. not std::ranges::all_of(expand, [](char c) { return std::isdigit(c); })) {
  143. return false;
  144. }
  145. for (size_t i = 0; i < varspec.size(); ++i) {
  146. RETURN_UNLESS(is_uri_template_varchar(varspec, i) || (i > 0 && varspec[i] == '.'), false);
  147. }
  148. }
  149. return true;
  150. }
  151. template <typename CharT> bool is_uri_authority(std::basic_string_view<CharT> uri) {
  152. // A URI Authority section MAY contain user info, which is every character up
  153. // to the first "@" character, as long as that character is not part of the path
  154. if (size_t pos = uri.find('@'); pos != uri.npos) {
  155. for (size_t i = 0; i < pos; ++i) {
  156. if (not is_pchar(uri, i, ":")) {
  157. return false;
  158. }
  159. }
  160. uri.remove_prefix(pos + 1);
  161. }
  162. // A URI Authority HOST section
  163. // If the URI starts with '[', then it MUST BE an IPv6 or an "IPvFuture"
  164. if (uri[0] == '[') {
  165. size_t pos = uri.find(']');
  166. auto ip = uri.substr(1, pos - 1);
  167. uri.remove_prefix(pos + 1);
  168. if (not ipv6(to_u8(ip))) {
  169. return false;
  170. }
  171. }
  172. // A URI Authority PORT section. Technically allows any number of digits
  173. if (size_t pos = uri.find(':'); pos != uri.npos) {
  174. if (not std::ranges::all_of(uri.substr(pos + 1), [](auto c) { return std::isdigit(c); })) {
  175. return false;
  176. }
  177. uri.remove_suffix(uri.size() - pos + 1);
  178. }
  179. // Normal URI Authority HOST section is either an IPv4 or a HOSTNAME
  180. return ipv4(to_u8(uri)) || hostname(uri);
  181. }
  182. // Tests if a URI "Query Part" or "Fragment Part" is valid and remove the part
  183. template <typename CharT> bool test_uri_part(std::basic_string_view<CharT> & uri, char delim) {
  184. size_t const pos = uri.find(delim);
  185. if (pos == uri.npos) {
  186. return true;
  187. }
  188. auto part = uri.substr(pos + 1);
  189. uri = uri.substr(0, pos);
  190. for (size_t pos = 0; pos < part.size(); ++pos) {
  191. RETURN_UNLESS(detail::is_pchar(part, pos, ":@/?"), false);
  192. }
  193. return true;
  194. };
  195. }
  196. namespace jvalidate::format::draft03 {
  197. namespace detail = jvalidate::format::detail;
  198. inline bool time(std::string_view dt) {
  199. std::tm tm;
  200. char const * end = strptime(dt.data(), "%T", &tm);
  201. if (end == nullptr || (end - dt.data()) < 8) {
  202. return false;
  203. }
  204. return end == dt.end();
  205. }
  206. inline bool utc_millisec(std::string_view utc) {
  207. int64_t itime;
  208. if (auto [end, ec] = std::from_chars(utc.begin(), utc.end(), itime);
  209. ec == std::errc{} && end == utc.end()) {
  210. return true;
  211. }
  212. double dtime;
  213. auto [end, ec] = std::from_chars(utc.begin(), utc.end(), dtime);
  214. return ec == std::errc{} && end == utc.end();
  215. }
  216. inline bool css_2_1_color(std::string_view color) {
  217. constexpr char const * g_hex_digits = "0123456789ABCDEFabcdef";
  218. if (color[0] == '#') {
  219. return color.size() <= 7 && detail::is_hex(color.substr(1));
  220. }
  221. static std::unordered_set<std::string_view> g_color_codes{
  222. "maroon", "red", "orange", "yellow", "olive", "purple", "fuchsia", "white", "lime",
  223. "green", "navy", "blue", "aqua", "teal", "black", "silver", "gray"};
  224. return g_color_codes.contains(color);
  225. }
  226. }
  227. namespace jvalidate::format {
  228. inline bool date(std::string_view dt) {
  229. auto [consumed, valid] = detail::date(dt);
  230. return valid && consumed == dt.size();
  231. }
  232. inline bool time(std::string_view dt) {
  233. std::tm tm;
  234. char const * end = strptime(dt.data(), "%T", &tm);
  235. if (end == nullptr || end == dt.end() || (end - dt.data()) < 8) {
  236. return false;
  237. }
  238. dt.remove_prefix(end - dt.begin());
  239. if (dt[0] == '.') {
  240. dt.remove_prefix(1);
  241. if (dt.empty() || not std::isdigit(dt[0])) {
  242. return false;
  243. }
  244. while (std::isdigit(dt[0])) {
  245. dt.remove_prefix(1);
  246. }
  247. }
  248. if (dt[0] == 'Z' || dt[0] == 'z') {
  249. return dt.size() == 1 && detail::is_leapsecond(tm);
  250. }
  251. if (std::strchr("+-", dt[0])) {
  252. return strptime(dt.data() + 1, "%R", &tm) == dt.end() && detail::is_leapsecond(tm);
  253. }
  254. return false;
  255. }
  256. inline bool date_time(std::string_view dt) {
  257. auto [size, good] = detail::date(dt);
  258. if (not good || std::strchr("Tt", dt[size]) == nullptr) {
  259. return false;
  260. }
  261. dt.remove_prefix(size + 1);
  262. return time(dt);
  263. }
  264. template <typename CharT> inline bool uri(std::basic_string_view<CharT> uri) {
  265. using delim = detail::char_delimiters<CharT>;
  266. // https://www.rfc-editor.org/rfc/rfc3986.html#appendix-A
  267. if (size_t const pos = uri.find(':'); pos != uri.npos) {
  268. RETURN_UNLESS(std::isalpha(uri[0]), false);
  269. for (size_t i = 1; i < pos; ++i) {
  270. RETURN_UNLESS(std::isalnum(uri[i]) || std::strchr("+-.", uri[i]), false);
  271. }
  272. uri.remove_prefix(pos + 1);
  273. } else {
  274. return false;
  275. }
  276. RETURN_UNLESS(detail::test_uri_part(uri, '#'), false);
  277. RETURN_UNLESS(detail::test_uri_part(uri, '?'), false);
  278. auto path = uri;
  279. if (uri.starts_with(delim::double_slash)) {
  280. uri.remove_prefix(2);
  281. path = uri.substr(std::min(uri.size(), uri.find('/')));
  282. uri.remove_suffix(path.size());
  283. RETURN_UNLESS(detail::is_uri_authority(uri), false);
  284. }
  285. for (size_t i = 0; i < path.size(); ++i) {
  286. RETURN_UNLESS(detail::is_pchar(path, i, "/:@"), false);
  287. }
  288. return true;
  289. }
  290. template <typename CharT> inline bool uri_reference(std::basic_string_view<CharT> uri) {
  291. using delim = detail::char_delimiters<CharT>;
  292. if (jvalidate::format::uri(uri)) {
  293. return true;
  294. }
  295. RETURN_UNLESS(detail::test_uri_part(uri, '#'), false);
  296. RETURN_UNLESS(detail::test_uri_part(uri, '?'), false);
  297. auto path = uri;
  298. if (uri.starts_with(delim::double_slash)) {
  299. uri.remove_prefix(2);
  300. path = uri.substr(std::min(uri.size(), uri.find('/')));
  301. uri.remove_suffix(path.size());
  302. RETURN_UNLESS(detail::is_uri_authority(uri), false);
  303. }
  304. if (size_t const pos = path.find('/'); pos != path.npos) {
  305. for (size_t i = 0; i < pos; ++i) {
  306. RETURN_UNLESS(detail::is_pchar(path, i, "@"), false);
  307. }
  308. path.remove_prefix(pos);
  309. }
  310. for (size_t i = 0; i < path.size(); ++i) {
  311. RETURN_UNLESS(detail::is_pchar(path, i, "/:@"), false);
  312. }
  313. return true;
  314. }
  315. inline bool uri_template(std::u32string_view uri) {
  316. for (size_t i = 0; i < uri.size(); ++i) {
  317. if (uri[i] != '{') {
  318. RETURN_UNLESS(detail::is_uri_template_literal(uri, i), false);
  319. continue;
  320. }
  321. std::u32string_view expr = uri.substr(i + 1);
  322. size_t const pos = expr.find('}');
  323. RETURN_UNLESS(pos != uri.npos, false);
  324. RETURN_UNLESS(detail::is_uri_template_expression(expr.substr(0, pos)), false);
  325. i += pos + 1;
  326. }
  327. return true;
  328. }
  329. inline bool uuid(std::string_view id) {
  330. constexpr size_t g_uuid_len = 36;
  331. constexpr size_t g_uuid_tokens = 5;
  332. char tok0[9], tok1[5], tok2[5], tok3[5], tok4[13];
  333. return id.size() == g_uuid_len &&
  334. sscanf(id.data(), "%8s-%4s-%4s-%4s-%12s", tok0, tok1, tok2, tok3, tok4) == g_uuid_tokens &&
  335. detail::is_hex(tok0) && detail::is_hex(tok1) && detail::is_hex(tok2) &&
  336. detail::is_hex(tok3) && detail::is_hex(tok4);
  337. }
  338. inline bool duration(std::string_view dur) {
  339. auto eat = [&dur](std::string_view text) {
  340. char type;
  341. unsigned int rep;
  342. if (sscanf(dur.data(), "%u%c", &rep, &type) != 2 || text.find(type) == std::string::npos) {
  343. return std::string::npos;
  344. }
  345. dur.remove_prefix(dur.find(type) + 1);
  346. return text.find(type);
  347. };
  348. // All DURATION entities must start with the prefix 'P', and cannot be empty
  349. // past that point.
  350. if (dur[0] != 'P' || dur.size() == 1) {
  351. return false;
  352. }
  353. dur.remove_prefix(1);
  354. // Special Case: a duration measured in weeks is incompatible with other
  355. // duration tokens.
  356. if (eat("W") != std::string::npos) {
  357. return dur.empty();
  358. }
  359. // DURATION takes the following form, because we use the same token for both
  360. // Months and Minutes.
  361. // "P[#Y][#M][#D][T[#H][#M][#S]]".
  362. // At least one of the optional fields must be present.
  363. if (dur[0] != 'T') {
  364. std::string_view ymd{"YMD"};
  365. // Read YMD duration offsets in that order, allowing us to skip past them.
  366. while (not ymd.empty() && not dur.empty()) {
  367. if (size_t n = eat(ymd); n != std::string::npos) {
  368. ymd.remove_prefix(n + 1);
  369. } else {
  370. return false;
  371. }
  372. }
  373. if (dur.empty()) {
  374. return true;
  375. }
  376. }
  377. // If we have a 'T' prefix for Hour/Minute/Second offsets, we must have at
  378. // least one of them present.
  379. if (dur[0] != 'T' || dur.size() == 1) {
  380. return false;
  381. }
  382. dur.remove_prefix(1);
  383. std::string_view hms{"HMS"};
  384. // Read HMS duration offsets in that order, allowing us to skip past them.
  385. while (not hms.empty() && not dur.empty()) {
  386. if (size_t n = eat(hms); n != std::string::npos) {
  387. hms.remove_prefix(n + 1);
  388. } else {
  389. return false;
  390. }
  391. }
  392. return dur.empty();
  393. }
  394. template <typename CharT>
  395. bool is_invalid_size_or_boundary_hostname(std::basic_string_view<CharT> name) {
  396. using delim = detail::char_delimiters<CharT>;
  397. return (name.empty() || detail::length_u8(name) >= 64 ||
  398. (name.size() >= 4 && name.substr(2).starts_with(delim::illegal_dashes_ulabel)) ||
  399. name[0] == '-' || name.back() == '-');
  400. }
  401. #if !JVALIDATE_HAS_IDNA
  402. inline bool hostname_part(std::string_view name) {
  403. using delim = detail::char_delimiters<char>;
  404. if (is_invalid_size_or_boundary_hostname(name)) {
  405. return false;
  406. }
  407. return std::ranges::none_of(name, [](char c) { return c != '-' && not std::isalnum(c); });
  408. }
  409. #else
  410. template <typename CharT> inline bool hostname_part(std::basic_string_view<CharT> name) {
  411. using delim = detail::char_delimiters<CharT>;
  412. // Punycode is a way to restructure UTF-8 strings to be ASCII compatibly
  413. // All Punycode string start with "xn--" (and would therefore fail below).
  414. if (name.starts_with(delim::punycode_prefix)) {
  415. std::u32string decoded = detail::to_u32(ada::idna::to_unicode(detail::to_u8(name)));
  416. return (decoded != detail::to_u32(name)) && hostname_part<char32_t>(decoded);
  417. }
  418. // An INVALID hostname part is one of the following:
  419. // - empty
  420. // - more than 63 UTF-8 characters long
  421. // - starts or ends with a '-'
  422. // - matches the regular expression /^..--.*$/
  423. if (is_invalid_size_or_boundary_hostname(name)) {
  424. return false;
  425. }
  426. // This is a much easier check in hostname than idn-hostname, since we can
  427. // just check for alphanumeric and '-'.
  428. if constexpr (std::is_same_v<char, CharT>) {
  429. return std::ranges::none_of(name, [](char c) { return c != '-' && not std::isalnum(c); });
  430. } else {
  431. return ada::idna::is_label_valid(name);
  432. }
  433. }
  434. #endif
  435. template <typename CharT> inline bool hostname(std::basic_string_view<CharT> name) {
  436. using delim = detail::char_delimiters<CharT>;
  437. if (name.find_first_of(delim::illegal_hostname_chars) != name.npos) {
  438. return false;
  439. }
  440. // In general, the maximum length of a hostname is 253 UTF-8 characters.
  441. if (detail::to_u8(name).size() > (name.back() == '.' ? 254 : 253)) {
  442. return false;
  443. }
  444. // Unfortunately, the ada-idna library does not validate things like
  445. // "is there a HEBREW character after the HEBREW COMMA".
  446. if (not std::ranges::all_of(delim::special_cases,
  447. [name](auto & sc) { return sc.accepts(name); })) {
  448. return false;
  449. }
  450. // We validate each sub-section of the hostname in parts, delimited by '.'
  451. for (size_t n = name.find('.'); n != std::string::npos;
  452. name.remove_prefix(n + 1), n = name.find('.')) {
  453. if (not hostname_part(name.substr(0, n))) {
  454. return false;
  455. }
  456. }
  457. // name.empty() would be true only if the final character in the input name
  458. // was '.', this is the only empty hostname part that we allow. Otherwise, we
  459. // have a trailing hostname_part.
  460. return name.empty() || hostname_part(name);
  461. }
  462. inline bool ipv4(std::string_view ip) {
  463. unsigned int ip0, ip1, ip2, ip3;
  464. char eof;
  465. // IPv4 address MAY only contain DIGITS and '.'
  466. if (ip.find_first_not_of("0123456789.") != ip.npos) {
  467. return false;
  468. }
  469. // Each OCTET of an IPv4 can only start with '0' if it is EXACTLY '0'
  470. if (ip[0] == '0' && std::isdigit(ip[1])) {
  471. return false;
  472. }
  473. if (size_t n = ip.find(".0"); n != ip.npos && std::isdigit(ip[n + 2])) {
  474. return false;
  475. }
  476. // sscanf returns the number of tokens parsed successfully.
  477. // Therefore, we can add a trailing character output to the format-string
  478. // and check that we failed to parse any token into the eof-character token.
  479. if (sscanf(std::string(ip).c_str(), "%3u.%3u.%3u.%3u%c", &ip0, &ip1, &ip2, &ip3, &eof) != 4) {
  480. return false;
  481. }
  482. // Affirm that each OCTET is only two bytes wide.
  483. return ip0 <= 0xFF && ip1 <= 0xFF && ip2 <= 0xFF && ip3 <= 0xFF;
  484. }
  485. inline bool ipv6(std::string_view ip) {
  486. int expected_spans = 8;
  487. // There is a special rule with IPv6 to allow an IPv4 address as a suffix
  488. if (size_t n = ip.find('.'); n != std::string::npos) {
  489. if (not ipv4(ip.substr(ip.find_last_of(':') + 1))) {
  490. return false;
  491. }
  492. // since ipv4 addresses contain 8 bytes of information, and each segment of
  493. // an ipv6 address contains 4 bytes - we should reduce the number of
  494. // expected spans to 6. Instead - we reduce it to 7 because we don't prune
  495. // the first OCTET of the IPv4 section (as it can read as a valid segment).
  496. expected_spans = 7;
  497. ip = ip.substr(0, n);
  498. }
  499. // IPv6 address MAY only contain HEXDIGITs and ':'
  500. if (ip.find_first_not_of("0123456789ABCDEFabcdef:") != std::string::npos) {
  501. return false;
  502. }
  503. // IPv6 addresses can have a maximum of 39 characters (8 4-char HEXDIGIT
  504. // segments with 7 dividing ':'s).
  505. if (ip.size() >= 40) {
  506. return false;
  507. }
  508. bool has_compressed = false;
  509. int groups = 0;
  510. if (ip.starts_with("::")) {
  511. has_compressed = true;
  512. ip.remove_prefix(2);
  513. }
  514. while (!ip.empty() && ++groups) {
  515. int data;
  516. if (sscanf(ip.data(), "%4x", &data) != 1) {
  517. // Not a 4-byte HEXDIGIT. Not sure that it's ever possible due to the
  518. // char filter above.
  519. return false;
  520. }
  521. if (size_t const n = ip.find(':'); std::min(n, ip.size()) > 4) {
  522. return false; // Segment too wide
  523. } else if (n != std::string::npos) {
  524. ip.remove_prefix(n + 1);
  525. } else {
  526. break; // End of String
  527. }
  528. // We removed the regular ':', so this is a check for a compression mark
  529. if (ip[0] != ':') {
  530. continue;
  531. }
  532. if (std::exchange(has_compressed, true)) {
  533. // The above trick allows us to ensure that there is no more than one
  534. // set of "::" compression tokens in this IPv6 adfress.
  535. return false;
  536. }
  537. ip.remove_prefix(1);
  538. }
  539. return groups == expected_spans || (has_compressed && groups < expected_spans);
  540. }
  541. // Let's be honest - no matter what RFC 5321 §4.1.2 or RFC 6531 say, the only
  542. // way to know if an email address is valid is to try and send a message to it.
  543. // Therefore, there's no point in trying to validate things according to a
  544. // complex grammar - as long as it has an '@' sign with at least one character
  545. // on each side, we ought to call it an email.
  546. template <typename CharT> inline bool email(std::basic_string_view<CharT> em) {
  547. using delim = detail::char_delimiters<CharT>;
  548. size_t const n = em.find_last_of('@');
  549. if (n == 0 || n >= em.size() - 1) {
  550. return false;
  551. }
  552. auto const who = em.substr(0, n);
  553. if (who.starts_with('"') && who.ends_with('"')) {
  554. // No validation
  555. } else if (who.starts_with('.') || who.ends_with('.')) {
  556. return false;
  557. } else if (em.substr(0, n).find(delim::dotdot) != em.npos) {
  558. return false;
  559. }
  560. // The DOMAIN section of an email address MAY be either a HOSTNAME, or an
  561. // IP Address surrounded in brackets.
  562. auto domain = em.substr(n + 1);
  563. if (not(domain.starts_with('[') && domain.ends_with(']'))) {
  564. return hostname(domain);
  565. }
  566. domain.remove_prefix(1);
  567. domain.remove_suffix(1);
  568. // When the DOMAIN is an IPv6, it must start with "IPv6:" for some
  569. // weird compatibility reason.
  570. if (auto ip = detail::to_u8(domain); ip.starts_with("IPv6:")) {
  571. return ipv6(ip.substr(5));
  572. } else {
  573. return ipv4(ip);
  574. }
  575. }
  576. template <typename T> inline bool ctor_as_valid(std::string_view str) {
  577. try {
  578. [[maybe_unused]] auto _ = T(str);
  579. return true;
  580. } catch (std::exception const &) { return false; }
  581. }
  582. template <auto Predicate> bool utf32(std::string_view str) {
  583. return Predicate(detail::to_u32(str));
  584. }
  585. }
  586. namespace jvalidate {
  587. class FormatValidator {
  588. public:
  589. using Predicate = bool (*)(std::string_view);
  590. enum class Status { Unknown, Unimplemented, Valid, Invalid };
  591. private:
  592. std::unordered_map<std::string, Predicate> user_formats_{{"regex", nullptr}};
  593. std::unordered_map<std::string, Predicate> supported_formats_{
  594. {"date", &format::date},
  595. {"date-time", &format::date_time},
  596. {"duration", &format::duration},
  597. {"email", &format::email},
  598. {"hostname", &format::hostname},
  599. {"idn-email", UTF32(email)},
  600. {"idn-hostname", UTF32(hostname)},
  601. {"ipv4", &format::ipv4},
  602. {"ipv6", &format::ipv6},
  603. {"iri", UTF32(uri)},
  604. {"iri-reference", UTF32(uri_reference)},
  605. {"json-pointer", CONSTRUCTS(Pointer)},
  606. {"relative-json-pointer", CONSTRUCTS(RelativePointer)},
  607. {"time", &format::time},
  608. {"uri", &format::uri},
  609. {"uri-reference", &format::uri_reference},
  610. {"uri-template", &format::utf32<format::uri_template>},
  611. {"uuid", &format::uuid},
  612. };
  613. std::unordered_map<std::string, Predicate> draft03_supported_formats_{
  614. {"date", &format::date},
  615. // One of the weird things about draft03 - date-time allows for timezone
  616. // and fraction-of-second in the argument, but time only allows hh:mm:ss.
  617. {"date-time", &format::date_time},
  618. {"time", &format::draft03::time},
  619. {"utc-millisec", &format::draft03::utc_millisec},
  620. {"color", &format::draft03::css_2_1_color},
  621. {"style", nullptr},
  622. {"phone", nullptr},
  623. {"uri", &format::uri},
  624. {"email", &format::email},
  625. {"ip-address", &format::ipv4},
  626. {"ipv6", &format::ipv6},
  627. {"host-name", &format::hostname},
  628. };
  629. public:
  630. FormatValidator() = default;
  631. FormatValidator(Predicate is_regex) { user_formats_.insert_or_assign("regex", is_regex); }
  632. Status operator()(std::string const & format, schema::Version for_version,
  633. std::string_view text) const {
  634. auto const & supported =
  635. for_version == schema::Version::Draft03 ? draft03_supported_formats_ : supported_formats_;
  636. if (Status rval = (*this)(supported, format, text); rval != Status::Unknown) {
  637. return rval;
  638. }
  639. return (*this)(user_formats_, format, text);
  640. }
  641. private:
  642. Status operator()(auto const & supported, std::string const & format,
  643. std::string_view text) const {
  644. if (auto it = supported.find(format); it != supported.end()) {
  645. if (not it->second) {
  646. return Status::Unimplemented;
  647. }
  648. return it->second(text) ? Status::Valid : Status::Invalid;
  649. }
  650. return Status::Unknown;
  651. }
  652. };
  653. }
  654. #undef CONSTRUCTS
  655. #undef UTF32