Uri.cpp 9.7 KB

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