format.h 8.7 KB

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