format.h 8.5 KB

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