format.h 25 KB

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