format.h 25 KB

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