URL.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  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. namespace Rml {
  33. namespace Core {
  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. // Strip out the parent dir and the /..
  206. path.erase(parent_dir_start_pos, parent_dir_pos - parent_dir_start_pos + 3);
  207. // We've altered the URL, mark it dirty
  208. url_dirty = true;
  209. }
  210. }
  211. // Find the file name. This is the string after the trailing slash of the
  212. // path, and just before the extension.
  213. const char* extension_begin = strrchr(file_name_begin, '.');
  214. if (nullptr == extension_begin)
  215. {
  216. file_name = file_name_begin;
  217. extension = "";
  218. }
  219. else
  220. {
  221. file_name = String(file_name_begin, extension_begin);
  222. extension = extension_begin + 1;
  223. }
  224. return true;
  225. }
  226. // Returns the entire URL.
  227. const String& URL::GetURL() const
  228. {
  229. if (url_dirty)
  230. ConstructURL();
  231. return url;
  232. }
  233. // Sets the URL's protocol.
  234. bool URL::SetProtocol(const String& _protocol)
  235. {
  236. protocol = _protocol;
  237. url_dirty = true;
  238. return true;
  239. }
  240. // Returns the protocol this URL is utilising.
  241. const String& URL::GetProtocol() const
  242. {
  243. return protocol;
  244. }
  245. /// Sets the URL's login
  246. bool URL::SetLogin( const String& _login )
  247. {
  248. login = _login;
  249. url_dirty = true;
  250. return true;
  251. }
  252. /// Returns the URL's login
  253. const String& URL::GetLogin() const
  254. {
  255. return login;
  256. }
  257. /// Sets the URL's password
  258. bool URL::SetPassword(const String& _password)
  259. {
  260. password = _password;
  261. url_dirty = true;
  262. return true;
  263. }
  264. /// Returns the URL's password
  265. const String& URL::GetPassword() const
  266. {
  267. return password;
  268. }
  269. // Sets the URL's host.
  270. bool URL::SetHost(const String& _host)
  271. {
  272. host = _host;
  273. url_dirty = true;
  274. return true;
  275. }
  276. // Returns the URL's host.
  277. const String& URL::GetHost() const
  278. {
  279. return host;
  280. }
  281. // Sets the URL's port number.
  282. bool URL::SetPort(int _port)
  283. {
  284. port = _port;
  285. url_dirty = true;
  286. return true;
  287. }
  288. // Returns the URL's port number.
  289. int URL::GetPort() const
  290. {
  291. return port;
  292. }
  293. // Sets the URL's path.
  294. bool URL::SetPath(const String& _path)
  295. {
  296. path = _path;
  297. url_dirty = true;
  298. return true;
  299. }
  300. // Prefixes the URL's existing path with the given prefix.
  301. bool URL::PrefixPath(const String& prefix)
  302. {
  303. // If there's no trailing slash on the end of the prefix, add one.
  304. if (!prefix.empty() &&
  305. prefix[prefix.size() - 1] != '/')
  306. path = prefix + "/" + path;
  307. else
  308. path = prefix + path;
  309. url_dirty = true;
  310. return true;
  311. }
  312. // Returns the URL's path.
  313. const String& URL::GetPath() const
  314. {
  315. return path;
  316. }
  317. // Sets the URL's file name.
  318. bool URL::SetFileName(const String& _file_name)
  319. {
  320. file_name = _file_name;
  321. url_dirty = true;
  322. return true;
  323. }
  324. // Returns the URL's file name.
  325. const String& URL::GetFileName() const
  326. {
  327. return file_name;
  328. }
  329. // Sets the URL's file extension.
  330. bool URL::SetExtension(const String& _extension)
  331. {
  332. extension = _extension;
  333. url_dirty = true;
  334. return true;
  335. }
  336. // Returns the URL's file extension.
  337. const String& URL::GetExtension() const
  338. {
  339. return extension;
  340. }
  341. // Gets the current parameters
  342. const URL::Parameters& URL::GetParameters() const
  343. {
  344. return parameters;
  345. }
  346. // Set an individual parameter
  347. void URL::SetParameter(const String& key, const String& value)
  348. {
  349. parameters[key] = value;
  350. url_dirty = true;
  351. }
  352. // Set all parameters
  353. void URL::SetParameters(const Parameters& _parameters)
  354. {
  355. parameters = _parameters;
  356. url_dirty = true;
  357. }
  358. // Clear the parameters
  359. void URL::ClearParameters()
  360. {
  361. parameters.clear();
  362. }
  363. // Returns the URL's path, file name and extension.
  364. String URL::GetPathedFileName() const
  365. {
  366. String pathed_file_name = path;
  367. // Append the file name.
  368. pathed_file_name += file_name;
  369. // Append the extension.
  370. if (!extension.empty())
  371. {
  372. pathed_file_name += ".";
  373. pathed_file_name += extension;
  374. }
  375. return pathed_file_name;
  376. }
  377. String URL::GetQueryString() const
  378. {
  379. String query_string;
  380. int count = 0;
  381. for ( Parameters::const_iterator itr = parameters.begin(); itr != parameters.end(); ++itr )
  382. {
  383. query_string += ( count == 0 ) ? "" : "&";
  384. query_string += UrlEncode((*itr).first);
  385. query_string += "=";
  386. query_string += UrlEncode((*itr).second);
  387. count++;
  388. }
  389. return query_string;
  390. }
  391. // Less-than operator for use as a key in STL containers.
  392. bool URL::operator<(const URL& rhs) const
  393. {
  394. if (url_dirty)
  395. ConstructURL();
  396. if (rhs.url_dirty)
  397. rhs.ConstructURL();
  398. return url < rhs.url;
  399. }
  400. void URL::ConstructURL() const
  401. {
  402. url = "";
  403. // Append the protocol.
  404. if (!protocol.empty() && !host.empty())
  405. {
  406. url = protocol;
  407. url += "://";
  408. }
  409. // Append login and password
  410. if (!login.empty())
  411. {
  412. url += login ;
  413. if (!password.empty())
  414. {
  415. url += ":" ;
  416. url += password ;
  417. }
  418. url += "@" ;
  419. }
  420. RMLUI_ASSERTMSG( password.empty() || ( !password.empty() && !login.empty() ), "Can't have a password without a login!" );
  421. // Append the host.
  422. url += host;
  423. // Only check ports if there is some host/protocol part
  424. if ( !url.empty() )
  425. {
  426. if (port > 0)
  427. {
  428. RMLUI_ASSERTMSG( !host.empty(), "Can't have a port without a host!" );
  429. char port_string[16];
  430. sprintf(port_string, ":%d/", port);
  431. url += port_string;
  432. }
  433. else
  434. {
  435. url += "/";
  436. }
  437. }
  438. // Append the path.
  439. if (!path.empty())
  440. {
  441. url += path;
  442. }
  443. // Append the file name.
  444. url += file_name;
  445. // Append the extension.
  446. if (!extension.empty())
  447. {
  448. url += ".";
  449. url += extension;
  450. }
  451. // Append parameters
  452. if (!parameters.empty())
  453. {
  454. url += "?";
  455. url += GetQueryString();
  456. }
  457. url_dirty = false;
  458. }
  459. String URL::UrlEncode(const String &value)
  460. {
  461. String encoded;
  462. char hex[4] = {0,0,0,0};
  463. encoded.clear();
  464. const char *value_c = value.c_str();
  465. for (String::size_type i = 0; value_c[i]; i++)
  466. {
  467. char c = value_c[i];
  468. if (IsUnreservedChar(c))
  469. encoded += c;
  470. else
  471. {
  472. sprintf(hex, "%%%02X", c);
  473. encoded += hex;
  474. }
  475. }
  476. return encoded;
  477. }
  478. String URL::UrlDecode(const String &value)
  479. {
  480. String decoded;
  481. decoded.clear();
  482. const char *value_c = value.c_str();
  483. String::size_type value_len = value.size();
  484. for (String::size_type i = 0; i < value_len; i++)
  485. {
  486. char c = value_c[i];
  487. if (c == '+')
  488. {
  489. decoded += ' ';
  490. }
  491. else if (c == '%')
  492. {
  493. char *endp;
  494. String t = value.substr(i+1, 2);
  495. int ch = strtol(t.c_str(), &endp, 16);
  496. if (*endp == '\0')
  497. decoded += char(ch);
  498. else
  499. decoded += t;
  500. i += 2;
  501. }
  502. else
  503. {
  504. decoded += c;
  505. }
  506. }
  507. return decoded;
  508. }
  509. bool URL::IsUnreservedChar(const char in)
  510. {
  511. switch (in)
  512. {
  513. case '0': case '1': case '2': case '3': case '4':
  514. case '5': case '6': case '7': case '8': case '9':
  515. case 'a': case 'b': case 'c': case 'd': case 'e':
  516. case 'f': case 'g': case 'h': case 'i': case 'j':
  517. case 'k': case 'l': case 'm': case 'n': case 'o':
  518. case 'p': case 'q': case 'r': case 's': case 't':
  519. case 'u': case 'v': case 'w': case 'x': case 'y': case 'z':
  520. case 'A': case 'B': case 'C': case 'D': case 'E':
  521. case 'F': case 'G': case 'H': case 'I': case 'J':
  522. case 'K': case 'L': case 'M': case 'N': case 'O':
  523. case 'P': case 'Q': case 'R': case 'S': case 'T':
  524. case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z':
  525. case '-': case '.': case '_': case '~':
  526. return true;
  527. default:
  528. break;
  529. }
  530. return false;
  531. }
  532. }
  533. }