Uri.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. /*
  2. * Copyright 2017 Facebook, Inc.
  3. * Copyright (c) 2017 Chukong Technologies
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. * Uri class is based on the original file here https://github.com/facebook/folly/blob/master/folly/Uri.cpp
  17. */
  18. #include "network/Uri.h"
  19. #include "base/CCConsole.h" // For CCLOGERROR macro
  20. #include <regex>
  21. #include <sstream>
  22. #include <ctype.h>
  23. #include <stdlib.h>
  24. #undef LIKELY
  25. #undef UNLIKELY
  26. #if defined(__GNUC__) && __GNUC__ >= 4
  27. #define LIKELY(x) (__builtin_expect((x), 1))
  28. #define UNLIKELY(x) (__builtin_expect((x), 0))
  29. #else
  30. #define LIKELY(x) (x)
  31. #define UNLIKELY(x) (x)
  32. #endif
  33. namespace {
  34. template<typename T>
  35. std::string toString(T arg)
  36. {
  37. std::stringstream ss;
  38. ss << arg;
  39. return ss.str();
  40. }
  41. std::string submatch(const std::smatch& m, int idx)
  42. {
  43. auto& sub = m[idx];
  44. return std::string(sub.first, sub.second);
  45. }
  46. template <class String>
  47. void toLower(String& s)
  48. {
  49. for (auto& c : s) {
  50. c = char(tolower(c));
  51. }
  52. }
  53. } // namespace
  54. NS_CC_BEGIN
  55. namespace network {
  56. Uri::Uri()
  57. : _isValid(false)
  58. , _isSecure(false)
  59. , _hasAuthority(false)
  60. , _port(0)
  61. {
  62. }
  63. Uri::Uri(const Uri& o)
  64. {
  65. *this = o;
  66. }
  67. Uri::Uri(Uri&& o)
  68. {
  69. *this = std::move(o);
  70. }
  71. Uri& Uri::operator=(const Uri& o)
  72. {
  73. if (this != &o)
  74. {
  75. _isValid = o._isValid;
  76. _isSecure = o._isSecure;
  77. _scheme = o._scheme;
  78. _username = o._username;
  79. _password = o._password;
  80. _host = o._host;
  81. _hostName = o._hostName;
  82. _hasAuthority = o._hasAuthority;
  83. _port = o._port;
  84. _authority = o._authority;
  85. _pathEtc = o._pathEtc;
  86. _path = o._path;
  87. _query = o._query;
  88. _fragment = o._fragment;
  89. _queryParams = o._queryParams;
  90. }
  91. return *this;
  92. }
  93. Uri& Uri::operator=(Uri&& o)
  94. {
  95. if (this != &o)
  96. {
  97. _isValid = o._isValid;
  98. o._isValid = false;
  99. _isSecure = o._isSecure;
  100. o._isSecure = false;
  101. _scheme = std::move(o._scheme);
  102. _username = std::move(o._username);
  103. _password = std::move(o._password);
  104. _host = std::move(o._host);
  105. _hostName = std::move(o._hostName);
  106. _hasAuthority = o._hasAuthority;
  107. o._hasAuthority = false;
  108. _port = o._port;
  109. o._port = 0;
  110. _authority = std::move(o._authority);
  111. _pathEtc = std::move(o._pathEtc);
  112. _path = std::move(o._path);
  113. _query = std::move(o._query);
  114. _fragment = std::move(o._fragment);
  115. _queryParams = std::move(o._queryParams);
  116. }
  117. return *this;
  118. }
  119. bool Uri::operator==(const Uri& o) const
  120. {
  121. return (_isValid == o._isValid
  122. && _isSecure == o._isSecure
  123. && _scheme == o._scheme
  124. && _username == o._username
  125. && _password == o._password
  126. && _host == o._host
  127. && _hostName == o._hostName
  128. && _hasAuthority == o._hasAuthority
  129. && _port == o._port
  130. && _authority == o._authority
  131. && _pathEtc == o._pathEtc
  132. && _path == o._path
  133. && _query == o._query
  134. && _fragment == o._fragment
  135. && _queryParams == o._queryParams);
  136. }
  137. Uri Uri::parse(const std::string &str)
  138. {
  139. Uri uri;
  140. if (!uri.doParse(str))
  141. {
  142. uri.clear();
  143. }
  144. return uri;
  145. }
  146. bool Uri::doParse(const std::string& str)
  147. {
  148. static const std::regex uriRegex(
  149. "([a-zA-Z][a-zA-Z0-9+.-]*):" // scheme:
  150. "([^?#]*)" // authority and path
  151. "(?:\\?([^#]*))?" // ?query
  152. "(?:#(.*))?"); // #fragment
  153. static const std::regex authorityAndPathRegex("//([^/]*)(/.*)?");
  154. if (str.empty())
  155. {
  156. CCLOGERROR("%s", "Empty URI is invalid!");
  157. return false;
  158. }
  159. bool hasScheme = true;;
  160. std::string copied(str);
  161. if (copied.find("://") == std::string::npos)
  162. {
  163. hasScheme = false;
  164. copied.insert(0, "abc://"); // Just make regex happy.
  165. }
  166. std::smatch match;
  167. if (UNLIKELY(!std::regex_match(copied.cbegin(), copied.cend(), match, uriRegex))) {
  168. CCLOGERROR("Invalid URI: %s", str.c_str());
  169. return false;
  170. }
  171. if (hasScheme)
  172. {
  173. _scheme = submatch(match, 1);
  174. toLower(_scheme);
  175. if (_scheme == "https" || _scheme == "wss")
  176. {
  177. _isSecure = true;
  178. }
  179. }
  180. std::string authorityAndPath(match[2].first, match[2].second);
  181. std::smatch authorityAndPathMatch;
  182. if (!std::regex_match(authorityAndPath.cbegin(),
  183. authorityAndPath.cend(),
  184. authorityAndPathMatch,
  185. authorityAndPathRegex)) {
  186. // Does not start with //, doesn't have authority
  187. _hasAuthority = false;
  188. _path = authorityAndPath;
  189. } else {
  190. static const std::regex authorityRegex(
  191. "(?:([^@:]*)(?::([^@]*))?@)?" // username, password
  192. "(\\[[^\\]]*\\]|[^\\[:]*)" // host (IP-literal (e.g. '['+IPv6+']',
  193. // dotted-IPv4, or named host)
  194. "(?::(\\d*))?"); // port
  195. auto authority = authorityAndPathMatch[1];
  196. std::smatch authorityMatch;
  197. if (!std::regex_match(authority.first,
  198. authority.second,
  199. authorityMatch,
  200. authorityRegex)) {
  201. std::string invalidAuthority(authority.first, authority.second);
  202. CCLOGERROR("Invalid URI authority: %s", invalidAuthority.c_str());
  203. return false;
  204. }
  205. std::string port(authorityMatch[4].first, authorityMatch[4].second);
  206. if (!port.empty()) {
  207. _port = static_cast<uint16_t>(atoi(port.c_str()));
  208. }
  209. _hasAuthority = true;
  210. _username = submatch(authorityMatch, 1);
  211. _password = submatch(authorityMatch, 2);
  212. _host = submatch(authorityMatch, 3);
  213. _path = submatch(authorityAndPathMatch, 2);
  214. }
  215. _query = submatch(match, 3);
  216. _fragment = submatch(match, 4);
  217. _isValid = true;
  218. // Assign authority part
  219. //
  220. // Port is 5 characters max and we have up to 3 delimiters.
  221. _authority.reserve(getHost().size() + getUserName().size() + getPassword().size() + 8);
  222. if (!getUserName().empty() || !getPassword().empty()) {
  223. _authority.append(getUserName());
  224. if (!getPassword().empty()) {
  225. _authority.push_back(':');
  226. _authority.append(getPassword());
  227. }
  228. _authority.push_back('@');
  229. }
  230. _authority.append(getHost());
  231. if (getPort() != 0) {
  232. _authority.push_back(':');
  233. _authority.append(::toString(getPort()));
  234. }
  235. // Assign path etc part
  236. _pathEtc = _path;
  237. if (!_query.empty())
  238. {
  239. _pathEtc += '?';
  240. _pathEtc += _query;
  241. }
  242. if (!_fragment.empty())
  243. {
  244. _pathEtc += '#';
  245. _pathEtc += _fragment;
  246. }
  247. // Assign host name
  248. if (!_host.empty() && _host[0] == '[') {
  249. // If it starts with '[', then it should end with ']', this is ensured by
  250. // regex
  251. _hostName = _host.substr(1, _host.size() - 2);
  252. } else {
  253. _hostName = _host;
  254. }
  255. return true;
  256. }
  257. void Uri::clear()
  258. {
  259. _isValid = false;
  260. _isSecure = false;
  261. _scheme.clear();
  262. _username.clear();
  263. _password.clear();
  264. _host.clear();
  265. _hostName.clear();
  266. _hasAuthority = false;
  267. _port = 0;
  268. _authority.clear();
  269. _pathEtc.clear();
  270. _path.clear();
  271. _query.clear();
  272. _fragment.clear();
  273. _queryParams.clear();
  274. }
  275. const std::vector<std::pair<std::string, std::string>>& Uri::getQueryParams()
  276. {
  277. if (!_query.empty() && _queryParams.empty()) {
  278. // Parse query string
  279. static const std::regex queryParamRegex(
  280. "(^|&)" /*start of query or start of parameter "&"*/
  281. "([^=&]*)=?" /*parameter name and "=" if value is expected*/
  282. "([^=&]*)" /*parameter value*/
  283. "(?=(&|$))" /*forward reference, next should be end of query or
  284. start of next parameter*/);
  285. std::cregex_iterator paramBeginItr(
  286. _query.data(), _query.data() + _query.size(), queryParamRegex);
  287. std::cregex_iterator paramEndItr;
  288. for (auto itr = paramBeginItr; itr != paramEndItr; itr++) {
  289. if (itr->length(2) == 0) {
  290. // key is empty, ignore it
  291. continue;
  292. }
  293. _queryParams.emplace_back(
  294. std::string((*itr)[2].first, (*itr)[2].second), // parameter name
  295. std::string((*itr)[3].first, (*itr)[3].second) // parameter value
  296. );
  297. }
  298. }
  299. return _queryParams;
  300. }
  301. std::string Uri::toString() const
  302. {
  303. std::stringstream ss;
  304. if (_hasAuthority) {
  305. ss << _scheme << "://";
  306. if (!_password.empty()) {
  307. ss << _username << ":" << _password << "@";
  308. } else if (!_username.empty()) {
  309. ss << _username << "@";
  310. }
  311. ss << _host;
  312. if (_port != 0) {
  313. ss << ":" << _port;
  314. }
  315. } else {
  316. ss << _scheme << ":";
  317. }
  318. ss << _path;
  319. if (!_query.empty()) {
  320. ss << "?" << _query;
  321. }
  322. if (!_fragment.empty()) {
  323. ss << "#" << _fragment;
  324. }
  325. return ss.str();
  326. }
  327. } // namespace network {
  328. NS_CC_END