format.h 9.2 KB

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