URL.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "../../Include/RmlUi/Core/Log.h"
  29. #include "../../Include/RmlUi/Core/StringUtilities.h"
  30. #include "../../Include/RmlUi/Core/URL.h"
  31. #include <string.h>
  32. #include <stdio.h>
  33. namespace Rml {
  34. const char* DEFAULT_PROTOCOL = "file";
  35. // Constructs an Empty URL.
  36. URL::URL()
  37. {
  38. port = 0;
  39. url_dirty = false;
  40. }
  41. // Constructs a new URL from the given string.
  42. URL::URL(const String& _url)
  43. {
  44. port = 0;
  45. RMLUI_VERIFY(SetURL(_url));
  46. }
  47. // Constructs a new URL from the given string.
  48. URL::URL(const char* _url)
  49. {
  50. port = 0;
  51. RMLUI_VERIFY(SetURL(_url));
  52. }
  53. // Destroys the URL.
  54. URL::~URL()
  55. {
  56. }
  57. // Assigns a new URL to the object.
  58. bool URL::SetURL(const String& _url)
  59. {
  60. url_dirty = false;
  61. url = _url;
  62. // Make sure an Empty URL is completely Empty.
  63. if (url.empty())
  64. {
  65. protocol.clear();
  66. login.clear();
  67. password.clear();
  68. host.clear();
  69. port = 0;
  70. path.clear();
  71. file_name.clear();
  72. extension.clear();
  73. return true;
  74. }
  75. // Find the protocol. This consists of the string appearing before the
  76. // '://' token (ie, file://, http://).
  77. const char* host_begin = strchr(_url.c_str(), ':');
  78. if (nullptr != host_begin)
  79. {
  80. protocol = String(_url.c_str(), host_begin);
  81. if (0 != strncmp(host_begin, "://", 3))
  82. {
  83. char malformed_terminator[4] = {0, 0, 0, 0};
  84. strncpy(malformed_terminator, host_begin, 3);
  85. Log::Message(Log::LT_ERROR, "Malformed protocol identifier found in URL %s; expected %s://, found %s%s.\n", _url.c_str(), protocol.c_str(), protocol.c_str(), malformed_terminator);
  86. return false;
  87. }
  88. host_begin += 3;
  89. }
  90. else
  91. {
  92. protocol = DEFAULT_PROTOCOL;
  93. host_begin = _url.c_str();
  94. }
  95. // We only want to look for a host if a protocol was specified.
  96. const char* path_begin;
  97. if (host_begin != _url.c_str())
  98. {
  99. // Find the host. This is the string appearing after the protocol or after
  100. // the username:password combination, and terminated either with a colon,
  101. // if a port is specified, or a forward slash if there is no port.
  102. // Check for a login pair
  103. const char* at_symbol = strchr( host_begin, '@' );
  104. if ( at_symbol )
  105. {
  106. String login_password;
  107. login_password = String( host_begin, at_symbol );
  108. host_begin = at_symbol + 1;
  109. const char* password_ptr = strchr( login_password.c_str(), ':' );
  110. if ( password_ptr )
  111. {
  112. login = String( login_password.c_str(), password_ptr );
  113. password = String( password_ptr + 1 );
  114. }
  115. else
  116. {
  117. login = login_password;
  118. }
  119. }
  120. // Get the host portion
  121. path_begin = strchr(host_begin, '/');
  122. // Search for the colon in the host name, which will indicate a port.
  123. const char* port_begin = strchr(host_begin, ':');
  124. if (nullptr != port_begin && (nullptr == path_begin || port_begin < path_begin))
  125. {
  126. if (1 != sscanf(port_begin, ":%d", &port))
  127. {
  128. Log::Message(Log::LT_ERROR, "Malformed port number found in URL %s.\n", _url.c_str());
  129. return false;
  130. }
  131. host = String(host_begin, port_begin);
  132. // Don't continue if there is no path.
  133. if (nullptr == path_begin)
  134. {
  135. return true;
  136. }
  137. // Increment the path string past the trailing slash.
  138. ++path_begin;
  139. }
  140. else
  141. {
  142. port = -1;
  143. if (nullptr == path_begin)
  144. {
  145. host = host_begin;
  146. return true;
  147. }
  148. else
  149. {
  150. // Assign the host name, then increment the path string past the
  151. // trailing slash.
  152. host = String(host_begin, path_begin);
  153. ++path_begin;
  154. }
  155. }
  156. }
  157. else
  158. {
  159. path_begin = _url.c_str();
  160. }
  161. // Check for parameters
  162. String path_segment;
  163. const char* parameters = strchr(path_begin, '?');
  164. if ( parameters )
  165. {
  166. // Pull the path segment out, so further processing doesn't read the parameters
  167. path_segment = String(path_begin, parameters);
  168. path_begin = path_segment.c_str();
  169. // Loop through all parameters, loading them
  170. StringList parameter_list;
  171. StringUtilities::ExpandString( parameter_list, parameters + 1, '&' );
  172. for ( size_t i = 0; i < parameter_list.size(); i++ )
  173. {
  174. // Split into key and value
  175. StringList key_value;
  176. StringUtilities::ExpandString( key_value, parameter_list[i], '=' );
  177. key_value[0] = UrlDecode(key_value[0]);
  178. if ( key_value.size() == 2 )
  179. this->parameters[key_value[0]] = UrlDecode(key_value[1]);
  180. else
  181. this->parameters[key_value[0]] = "";
  182. }
  183. }
  184. // Find the path. This is the string appearing after the host, terminated
  185. // by the last forward slash.
  186. const char* file_name_begin = strrchr(path_begin, '/');
  187. if (nullptr == file_name_begin)
  188. {
  189. // No path!
  190. file_name_begin = path_begin;
  191. path = "";
  192. }
  193. else
  194. {
  195. // Copy the path including the trailing slash.
  196. path = String(path_begin, ++file_name_begin);
  197. // Normalise the path, stripping any ../'s from it
  198. size_t parent_dir_pos = String::npos;
  199. while ((parent_dir_pos = path.find("/../")) != String::npos && parent_dir_pos != 0)
  200. {
  201. // Find the start of the parent directory.
  202. size_t parent_dir_start_pos = path.rfind('/', parent_dir_pos - 1);
  203. if (parent_dir_start_pos == String::npos)
  204. parent_dir_start_pos = 0;
  205. else
  206. parent_dir_start_pos += 1;
  207. // Strip out the parent dir and the /..
  208. path.erase(parent_dir_start_pos, parent_dir_pos - parent_dir_start_pos + 4);
  209. // We've altered the URL, mark it dirty
  210. url_dirty = true;
  211. }
  212. }
  213. // Find the file name. This is the string after the trailing slash of the
  214. // path, and just before the extension.
  215. const char* extension_begin = strrchr(file_name_begin, '.');
  216. if (nullptr == extension_begin)
  217. {
  218. file_name = file_name_begin;
  219. extension = "";
  220. }
  221. else
  222. {
  223. file_name = String(file_name_begin, extension_begin);
  224. extension = extension_begin + 1;
  225. }
  226. return true;
  227. }
  228. // Returns the entire URL.
  229. const String& URL::GetURL() const
  230. {
  231. if (url_dirty)
  232. ConstructURL();
  233. return url;
  234. }
  235. // Sets the URL's protocol.
  236. bool URL::SetProtocol(const String& _protocol)
  237. {
  238. protocol = _protocol;
  239. url_dirty = true;
  240. return true;
  241. }
  242. // Returns the protocol this URL is utilising.
  243. const String& URL::GetProtocol() const
  244. {
  245. return protocol;
  246. }
  247. /// Sets the URL's login
  248. bool URL::SetLogin( const String& _login )
  249. {
  250. login = _login;
  251. url_dirty = true;
  252. return true;
  253. }
  254. /// Returns the URL's login
  255. const String& URL::GetLogin() const
  256. {
  257. return login;
  258. }
  259. /// Sets the URL's password
  260. bool URL::SetPassword(const String& _password)
  261. {
  262. password = _password;
  263. url_dirty = true;
  264. return true;
  265. }
  266. /// Returns the URL's password
  267. const String& URL::GetPassword() const
  268. {
  269. return password;
  270. }
  271. // Sets the URL's host.
  272. bool URL::SetHost(const String& _host)
  273. {
  274. host = _host;
  275. url_dirty = true;
  276. return true;
  277. }
  278. // Returns the URL's host.
  279. const String& URL::GetHost() const
  280. {
  281. return host;
  282. }
  283. // Sets the URL's port number.
  284. bool URL::SetPort(int _port)
  285. {
  286. port = _port;
  287. url_dirty = true;
  288. return true;
  289. }
  290. // Returns the URL's port number.
  291. int URL::GetPort() const
  292. {
  293. return port;
  294. }
  295. // Sets the URL's path.
  296. bool URL::SetPath(const String& _path)
  297. {
  298. path = _path;
  299. url_dirty = true;
  300. return true;
  301. }
  302. // Prefixes the URL's existing path with the given prefix.
  303. bool URL::PrefixPath(const String& prefix)
  304. {
  305. // If there's no trailing slash on the end of the prefix, add one.
  306. if (!prefix.empty() &&
  307. prefix[prefix.size() - 1] != '/')
  308. path = prefix + "/" + path;
  309. else
  310. path = prefix + path;
  311. url_dirty = true;
  312. return true;
  313. }
  314. // Returns the URL's path.
  315. const String& URL::GetPath() const
  316. {
  317. return path;
  318. }
  319. // Sets the URL's file name.
  320. bool URL::SetFileName(const String& _file_name)
  321. {
  322. file_name = _file_name;
  323. url_dirty = true;
  324. return true;
  325. }
  326. // Returns the URL's file name.
  327. const String& URL::GetFileName() const
  328. {
  329. return file_name;
  330. }
  331. // Sets the URL's file extension.
  332. bool URL::SetExtension(const String& _extension)
  333. {
  334. extension = _extension;
  335. url_dirty = true;
  336. return true;
  337. }
  338. // Returns the URL's file extension.
  339. const String& URL::GetExtension() const
  340. {
  341. return extension;
  342. }
  343. // Gets the current parameters
  344. const URL::Parameters& URL::GetParameters() const
  345. {
  346. return parameters;
  347. }
  348. // Set an individual parameter
  349. void URL::SetParameter(const String& key, const String& value)
  350. {
  351. parameters[key] = value;
  352. url_dirty = true;
  353. }
  354. // Set all parameters
  355. void URL::SetParameters(const Parameters& _parameters)
  356. {
  357. parameters = _parameters;
  358. url_dirty = true;
  359. }
  360. // Clear the parameters
  361. void URL::ClearParameters()
  362. {
  363. parameters.clear();
  364. }
  365. // Returns the URL's path, file name and extension.
  366. String URL::GetPathedFileName() const
  367. {
  368. String pathed_file_name = path;
  369. // Append the file name.
  370. pathed_file_name += file_name;
  371. // Append the extension.
  372. if (!extension.empty())
  373. {
  374. pathed_file_name += ".";
  375. pathed_file_name += extension;
  376. }
  377. return pathed_file_name;
  378. }
  379. String URL::GetQueryString() const
  380. {
  381. String query_string;
  382. int count = 0;
  383. for ( Parameters::const_iterator itr = parameters.begin(); itr != parameters.end(); ++itr )
  384. {
  385. query_string += ( count == 0 ) ? "" : "&";
  386. query_string += UrlEncode((*itr).first);
  387. query_string += "=";
  388. query_string += UrlEncode((*itr).second);
  389. count++;
  390. }
  391. return query_string;
  392. }
  393. // Less-than operator for use as a key in STL containers.
  394. bool URL::operator<(const URL& rhs) const
  395. {
  396. if (url_dirty)
  397. ConstructURL();
  398. if (rhs.url_dirty)
  399. rhs.ConstructURL();
  400. return url < rhs.url;
  401. }
  402. void URL::ConstructURL() const
  403. {
  404. url = "";
  405. // Append the protocol.
  406. if (!protocol.empty() && !host.empty())
  407. {
  408. url = protocol;
  409. url += "://";
  410. }
  411. // Append login and password
  412. if (!login.empty())
  413. {
  414. url += login ;
  415. if (!password.empty())
  416. {
  417. url += ":" ;
  418. url += password ;
  419. }
  420. url += "@" ;
  421. }
  422. RMLUI_ASSERTMSG( password.empty() || ( !password.empty() && !login.empty() ), "Can't have a password without a login!" );
  423. // Append the host.
  424. url += host;
  425. // Only check ports if there is some host/protocol part
  426. if ( !url.empty() )
  427. {
  428. if (port > 0)
  429. {
  430. RMLUI_ASSERTMSG( !host.empty(), "Can't have a port without a host!" );
  431. constexpr size_t port_buffer_size = 16;
  432. char port_string[port_buffer_size];
  433. snprintf(port_string, port_buffer_size, ":%d/", port);
  434. url += port_string;
  435. }
  436. else
  437. {
  438. url += "/";
  439. }
  440. }
  441. // Append the path.
  442. if (!path.empty())
  443. {
  444. url += path;
  445. }
  446. // Append the file name.
  447. url += file_name;
  448. // Append the extension.
  449. if (!extension.empty())
  450. {
  451. url += ".";
  452. url += extension;
  453. }
  454. // Append parameters
  455. if (!parameters.empty())
  456. {
  457. url += "?";
  458. url += GetQueryString();
  459. }
  460. url_dirty = false;
  461. }
  462. String URL::UrlEncode(const String &value)
  463. {
  464. String encoded;
  465. constexpr size_t hex_buffer_size = 4;
  466. char hex[hex_buffer_size] = {0, 0, 0, 0};
  467. encoded.clear();
  468. const char *value_c = value.c_str();
  469. for (String::size_type i = 0; value_c[i]; i++)
  470. {
  471. char c = value_c[i];
  472. if (IsUnreservedChar(c))
  473. encoded += c;
  474. else
  475. {
  476. snprintf(hex, hex_buffer_size, "%%%02X", c);
  477. encoded += hex;
  478. }
  479. }
  480. return encoded;
  481. }
  482. String URL::UrlDecode(const String &value)
  483. {
  484. String decoded;
  485. decoded.clear();
  486. const char *value_c = value.c_str();
  487. String::size_type value_len = value.size();
  488. for (String::size_type i = 0; i < value_len; i++)
  489. {
  490. char c = value_c[i];
  491. if (c == '+')
  492. {
  493. decoded += ' ';
  494. }
  495. else if (c == '%')
  496. {
  497. char *endp;
  498. String t = value.substr(i+1, 2);
  499. int ch = strtol(t.c_str(), &endp, 16);
  500. if (*endp == '\0')
  501. decoded += char(ch);
  502. else
  503. decoded += t;
  504. i += 2;
  505. }
  506. else
  507. {
  508. decoded += c;
  509. }
  510. }
  511. return decoded;
  512. }
  513. bool URL::IsUnreservedChar(const char in)
  514. {
  515. switch (in)
  516. {
  517. case '0': case '1': case '2': case '3': case '4':
  518. case '5': case '6': case '7': case '8': case '9':
  519. case 'a': case 'b': case 'c': case 'd': case 'e':
  520. case 'f': case 'g': case 'h': case 'i': case 'j':
  521. case 'k': case 'l': case 'm': case 'n': case 'o':
  522. case 'p': case 'q': case 'r': case 's': case 't':
  523. case 'u': case 'v': case 'w': case 'x': case 'y': case 'z':
  524. case 'A': case 'B': case 'C': case 'D': case 'E':
  525. case 'F': case 'G': case 'H': case 'I': case 'J':
  526. case 'K': case 'L': case 'M': case 'N': case 'O':
  527. case 'P': case 'Q': case 'R': case 'S': case 'T':
  528. case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z':
  529. case '-': case '.': case '_': case '~':
  530. return true;
  531. default:
  532. break;
  533. }
  534. return false;
  535. }
  536. } // namespace Rml