URL.cpp 13 KB

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