url_canon_path.cc 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. // Copyright 2013 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include <limits.h>
  5. #include "base/check.h"
  6. #include "base/check_op.h"
  7. #include "third_party/abseil-cpp/absl/types/optional.h"
  8. #include "url/url_canon.h"
  9. #include "url/url_canon_internal.h"
  10. #include "url/url_parse_internal.h"
  11. namespace url {
  12. namespace {
  13. enum CharacterFlags {
  14. // Pass through unchanged, whether escaped or unescaped. This doesn't
  15. // actually set anything so you can't OR it to check, it's just to make the
  16. // table below more clear when neither ESCAPE or UNESCAPE is set.
  17. PASS = 0,
  18. // This character requires special handling in DoPartialPathInternal. Doing
  19. // this test
  20. // first allows us to filter out the common cases of regular characters that
  21. // can be directly copied.
  22. SPECIAL = 1,
  23. // This character must be escaped in the canonical output. Note that all
  24. // escaped chars also have the "special" bit set so that the code that looks
  25. // for this is triggered. Not valid with PASS or ESCAPE
  26. ESCAPE_BIT = 2,
  27. ESCAPE = ESCAPE_BIT | SPECIAL,
  28. // This character must be unescaped in canonical output. Not valid with
  29. // ESCAPE or PASS. We DON'T set the SPECIAL flag since if we encounter these
  30. // characters unescaped, they should just be copied.
  31. UNESCAPE = 4,
  32. // This character is disallowed in URLs. Note that the "special" bit is also
  33. // set to trigger handling.
  34. INVALID_BIT = 8,
  35. INVALID = INVALID_BIT | SPECIAL,
  36. };
  37. // This table contains one of the above flag values. Note some flags are more
  38. // than one bits because they also turn on the "special" flag. Special is the
  39. // only flag that may be combined with others.
  40. //
  41. // This table is designed to match exactly what IE does with the characters.
  42. //
  43. // Dot is even more special, and the escaped version is handled specially by
  44. // IsDot. Therefore, we don't need the "escape" flag, and even the "unescape"
  45. // bit is never handled (we just need the "special") bit.
  46. const unsigned char kPathCharLookup[0x100] = {
  47. // NULL control chars...
  48. INVALID, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
  49. // control chars...
  50. ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
  51. // ' ' ! " # $ % & ' ( ) * + , - . /
  52. ESCAPE, PASS, ESCAPE, ESCAPE, PASS, ESCAPE, PASS, PASS, PASS, PASS, PASS, PASS, PASS, UNESCAPE,SPECIAL, PASS,
  53. // 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
  54. UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,PASS, PASS, ESCAPE, PASS, ESCAPE, ESCAPE,
  55. // @ A B C D E F G H I J K L M N O
  56. PASS, UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,
  57. // P Q R S T U V W X Y Z [ \ ] ^ _
  58. UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,PASS, ESCAPE, PASS, ESCAPE, UNESCAPE,
  59. // ` a b c d e f g h i j k l m n o
  60. ESCAPE, UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,
  61. // p q r s t u v w x y z { | } ~ <NBSP>
  62. UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,ESCAPE, ESCAPE, ESCAPE, UNESCAPE,ESCAPE,
  63. // ...all the high-bit characters are escaped
  64. ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
  65. ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
  66. ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
  67. ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
  68. ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
  69. ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
  70. ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
  71. ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE};
  72. enum DotDisposition {
  73. // The given dot is just part of a filename and is not special.
  74. NOT_A_DIRECTORY,
  75. // The given dot is the current directory.
  76. DIRECTORY_CUR,
  77. // The given dot is the first of a double dot that should take us up one.
  78. DIRECTORY_UP
  79. };
  80. // When the path resolver finds a dot, this function is called with the
  81. // character following that dot to see what it is. The return value
  82. // indicates what type this dot is (see above). This code handles the case
  83. // where the dot is at the end of the input.
  84. //
  85. // |*consumed_len| will contain the number of characters in the input that
  86. // express what we found.
  87. //
  88. // If the input is "../foo", |after_dot| = 1, |end| = 6, and
  89. // at the end, |*consumed_len| = 2 for the "./" this function consumed. The
  90. // original dot length should be handled by the caller.
  91. template <typename CHAR>
  92. DotDisposition ClassifyAfterDot(const CHAR* spec,
  93. size_t after_dot,
  94. size_t end,
  95. size_t* consumed_len) {
  96. if (after_dot == end) {
  97. // Single dot at the end.
  98. *consumed_len = 0;
  99. return DIRECTORY_CUR;
  100. }
  101. if (IsURLSlash(spec[after_dot])) {
  102. // Single dot followed by a slash.
  103. *consumed_len = 1; // Consume the slash
  104. return DIRECTORY_CUR;
  105. }
  106. size_t second_dot_len = IsDot(spec, after_dot, end);
  107. if (second_dot_len) {
  108. size_t after_second_dot = after_dot + second_dot_len;
  109. if (after_second_dot == end) {
  110. // Double dot at the end.
  111. *consumed_len = second_dot_len;
  112. return DIRECTORY_UP;
  113. }
  114. if (IsURLSlash(spec[after_second_dot])) {
  115. // Double dot followed by a slash.
  116. *consumed_len = second_dot_len + 1;
  117. return DIRECTORY_UP;
  118. }
  119. }
  120. // The dots are followed by something else, not a directory.
  121. *consumed_len = 0;
  122. return NOT_A_DIRECTORY;
  123. }
  124. // Rewinds the output to the previous slash. It is assumed that the output
  125. // ends with a slash and this doesn't count (we call this when we are
  126. // appending directory paths, so the previous path component has and ending
  127. // slash).
  128. //
  129. // This will stop at the first slash (assumed to be at position
  130. // |path_begin_in_output| and not go any higher than that. Some web pages
  131. // do ".." too many times, so we need to handle that brokenness.
  132. //
  133. // It searches for a literal slash rather than including a backslash as well
  134. // because it is run only on the canonical output.
  135. //
  136. // The output is guaranteed to end in a slash when this function completes.
  137. void BackUpToPreviousSlash(size_t path_begin_in_output, CanonOutput* output) {
  138. CHECK(output->length() > 0);
  139. CHECK(path_begin_in_output < output->length());
  140. size_t i = output->length() - 1;
  141. DCHECK(output->at(i) == '/');
  142. if (i == path_begin_in_output)
  143. return; // We're at the first slash, nothing to do.
  144. // Now back up (skipping the trailing slash) until we find another slash.
  145. do {
  146. --i;
  147. } while (output->at(i) != '/' && i > path_begin_in_output);
  148. // Now shrink the output to just include that last slash we found.
  149. output->set_length(i + 1);
  150. }
  151. // Looks for problematic nested escape sequences and escapes the output as
  152. // needed to ensure they can't be misinterpreted.
  153. //
  154. // Our concern is that in input escape sequence that's invalid because it
  155. // contains nested escape sequences might look valid once those are unescaped.
  156. // For example, "%%300" is not a valid escape sequence, but after unescaping the
  157. // inner "%30" this becomes "%00" which is valid. Leaving this in the output
  158. // string can result in callers re-canonicalizing the string and unescaping this
  159. // sequence, thus resulting in something fundamentally different than the
  160. // original input here. This can cause a variety of problems.
  161. //
  162. // This function is called after we've just unescaped a sequence that's within
  163. // two output characters of a previous '%' that we know didn't begin a valid
  164. // escape sequence in the input string. We look for whether the output is going
  165. // to turn into a valid escape sequence, and if so, convert the initial '%' into
  166. // an escaped "%25" so the output can't be misinterpreted.
  167. //
  168. // |spec| is the input string we're canonicalizing.
  169. // |next_input_index| is the index of the next unprocessed character in |spec|.
  170. // |input_len| is the length of |spec|.
  171. // |last_invalid_percent_index| is the index in |output| of a previously-seen
  172. // '%' character. The caller knows this '%' character isn't followed by a valid
  173. // escape sequence in the input string.
  174. // |output| is the canonicalized output thus far. The caller guarantees this
  175. // ends with a '%' followed by one or two characters, and the '%' is the one
  176. // pointed to by |last_invalid_percent_index|. The last character in the string
  177. // was just unescaped.
  178. template <typename CHAR>
  179. void CheckForNestedEscapes(const CHAR* spec,
  180. size_t next_input_index,
  181. size_t input_len,
  182. size_t last_invalid_percent_index,
  183. CanonOutput* output) {
  184. const size_t length = output->length();
  185. const char last_unescaped_char = output->at(length - 1);
  186. // If |output| currently looks like "%c", we need to try appending the next
  187. // input character to see if this will result in a problematic escape
  188. // sequence. Note that this won't trigger on the first nested escape of a
  189. // two-escape sequence like "%%30%30" -- we'll allow the conversion to
  190. // "%0%30" -- but the second nested escape will be caught by this function
  191. // when it's called again in that case.
  192. const bool append_next_char = last_invalid_percent_index == length - 2;
  193. if (append_next_char) {
  194. // If the input doesn't contain a 7-bit character next, this case won't be a
  195. // problem.
  196. if ((next_input_index == input_len) || (spec[next_input_index] >= 0x80))
  197. return;
  198. output->push_back(static_cast<char>(spec[next_input_index]));
  199. }
  200. // Now output ends like "%cc". Try to unescape this.
  201. size_t begin = last_invalid_percent_index;
  202. unsigned char temp;
  203. if (DecodeEscaped(output->data(), &begin, output->length(), &temp)) {
  204. // New escape sequence found. Overwrite the characters following the '%'
  205. // with "25", and push_back() the one or two characters that were following
  206. // the '%' when we were called.
  207. if (!append_next_char)
  208. output->push_back(output->at(last_invalid_percent_index + 1));
  209. output->set(last_invalid_percent_index + 1, '2');
  210. output->set(last_invalid_percent_index + 2, '5');
  211. output->push_back(last_unescaped_char);
  212. } else if (append_next_char) {
  213. // Not a valid escape sequence, but we still need to undo appending the next
  214. // source character so the caller can process it normally.
  215. output->set_length(length);
  216. }
  217. }
  218. // Canonicalizes and appends the given path to the output. It assumes that if
  219. // the input path starts with a slash, it should be copied to the output.
  220. //
  221. // If there are already path components (this mode is used when appending
  222. // relative paths for resolving), it assumes that the output already has
  223. // a trailing slash and that if the input begins with a slash, it should be
  224. // copied to the output.
  225. //
  226. // We do not collapse multiple slashes in a row to a single slash. It seems
  227. // no web browsers do this, and we don't want incompatibilities, even though
  228. // it would be correct for most systems.
  229. template <typename CHAR, typename UCHAR>
  230. bool DoPartialPathInternal(const CHAR* spec,
  231. const Component& path,
  232. size_t path_begin_in_output,
  233. CanonOutput* output) {
  234. if (!path.is_nonempty())
  235. return true;
  236. size_t end = static_cast<size_t>(path.end());
  237. // We use this variable to minimize the amount of work done when unescaping --
  238. // we'll only call CheckForNestedEscapes() when this points at one of the last
  239. // couple of characters in |output|.
  240. absl::optional<size_t> last_invalid_percent_index;
  241. bool success = true;
  242. for (size_t i = static_cast<size_t>(path.begin); i < end; i++) {
  243. UCHAR uch = static_cast<UCHAR>(spec[i]);
  244. if (sizeof(CHAR) > 1 && uch >= 0x80) {
  245. // We only need to test wide input for having non-ASCII characters. For
  246. // narrow input, we'll always just use the lookup table. We don't try to
  247. // do anything tricky with decoding/validating UTF-8. This function will
  248. // read one or two UTF-16 characters and append the output as UTF-8. This
  249. // call will be removed in 8-bit mode.
  250. success &= AppendUTF8EscapedChar(spec, &i, end, output);
  251. } else {
  252. // Normal ASCII character or 8-bit input, use the lookup table.
  253. unsigned char out_ch = static_cast<unsigned char>(uch);
  254. unsigned char flags = kPathCharLookup[out_ch];
  255. if (flags & SPECIAL) {
  256. // Needs special handling of some sort.
  257. size_t dotlen;
  258. if ((dotlen = IsDot(spec, i, end)) > 0) {
  259. // See if this dot was preceded by a slash in the output.
  260. //
  261. // Note that we check this in the case of dots so we don't have to
  262. // special case slashes. Since slashes are much more common than
  263. // dots, this actually increases performance measurably (though
  264. // slightly).
  265. if (output->length() > path_begin_in_output &&
  266. output->at(output->length() - 1) == '/') {
  267. // Slash followed by a dot, check to see if this is means relative
  268. size_t consumed_len;
  269. switch (ClassifyAfterDot<CHAR>(spec, i + dotlen, end,
  270. &consumed_len)) {
  271. case NOT_A_DIRECTORY:
  272. // Copy the dot to the output, it means nothing special.
  273. output->push_back('.');
  274. i += dotlen - 1;
  275. break;
  276. case DIRECTORY_CUR: // Current directory, just skip the input.
  277. i += dotlen + consumed_len - 1;
  278. break;
  279. case DIRECTORY_UP:
  280. BackUpToPreviousSlash(path_begin_in_output, output);
  281. if (last_invalid_percent_index >= output->length()) {
  282. last_invalid_percent_index = absl::nullopt;
  283. }
  284. i += dotlen + consumed_len - 1;
  285. break;
  286. }
  287. } else {
  288. // This dot is not preceded by a slash, it is just part of some
  289. // file name.
  290. output->push_back('.');
  291. i += dotlen - 1;
  292. }
  293. } else if (out_ch == '\\') {
  294. // Convert backslashes to forward slashes
  295. output->push_back('/');
  296. } else if (out_ch == '%') {
  297. // Handle escape sequences.
  298. unsigned char unescaped_value;
  299. if (DecodeEscaped(spec, &i, end, &unescaped_value)) {
  300. // Valid escape sequence, see if we keep, reject, or unescape it.
  301. // Note that at this point DecodeEscape() will have advanced |i| to
  302. // the last character of the escape sequence.
  303. char unescaped_flags = kPathCharLookup[unescaped_value];
  304. if (unescaped_flags & UNESCAPE) {
  305. // This escaped value shouldn't be escaped. Try to copy it.
  306. output->push_back(unescaped_value);
  307. // If we just unescaped a value within 2 output characters of the
  308. // '%' from a previously-detected invalid escape sequence, we
  309. // might have an input string with problematic nested escape
  310. // sequences; detect and fix them.
  311. if (last_invalid_percent_index.has_value() &&
  312. ((last_invalid_percent_index.value() + 3) >=
  313. output->length())) {
  314. CheckForNestedEscapes(spec, i + 1, end,
  315. last_invalid_percent_index.value(),
  316. output);
  317. }
  318. } else {
  319. // Either this is an invalid escaped character, or it's a valid
  320. // escaped character we should keep escaped. In the first case we
  321. // should just copy it exactly and remember the error. In the
  322. // second we also copy exactly in case the server is sensitive to
  323. // changing the case of any hex letters.
  324. output->push_back('%');
  325. output->push_back(static_cast<char>(spec[i - 1]));
  326. output->push_back(static_cast<char>(spec[i]));
  327. if (unescaped_flags & INVALID_BIT)
  328. success = false;
  329. }
  330. } else {
  331. // Invalid escape sequence. IE7+ rejects any URLs with such
  332. // sequences, while other browsers pass them through unchanged. We
  333. // use the permissive behavior.
  334. // TODO(brettw): Consider testing IE's strict behavior, which would
  335. // allow removing the code to handle nested escapes above.
  336. last_invalid_percent_index = output->length();
  337. output->push_back('%');
  338. }
  339. } else if (flags & INVALID_BIT) {
  340. // For NULLs, etc. fail.
  341. AppendEscapedChar(out_ch, output);
  342. success = false;
  343. } else if (flags & ESCAPE_BIT) {
  344. // This character should be escaped.
  345. AppendEscapedChar(out_ch, output);
  346. }
  347. } else {
  348. // Nothing special about this character, just append it.
  349. output->push_back(out_ch);
  350. }
  351. }
  352. }
  353. return success;
  354. }
  355. // Perform the same logic as in DoPartialPathInternal(), but updates the
  356. // publicly exposed CanonOutput structure similar to DoPath(). Returns
  357. // true if successful.
  358. template <typename CHAR, typename UCHAR>
  359. bool DoPartialPath(const CHAR* spec,
  360. const Component& path,
  361. CanonOutput* output,
  362. Component* out_path) {
  363. out_path->begin = output->length();
  364. bool success =
  365. DoPartialPathInternal<CHAR, UCHAR>(spec, path, out_path->begin, output);
  366. out_path->len = output->length() - out_path->begin;
  367. return success;
  368. }
  369. template<typename CHAR, typename UCHAR>
  370. bool DoPath(const CHAR* spec,
  371. const Component& path,
  372. CanonOutput* output,
  373. Component* out_path) {
  374. bool success = true;
  375. out_path->begin = output->length();
  376. if (path.len > 0) {
  377. // Write out an initial slash if the input has none. If we just parse a URL
  378. // and then canonicalize it, it will of course have a slash already. This
  379. // check is for the replacement and relative URL resolving cases of file
  380. // URLs.
  381. if (!IsURLSlash(spec[path.begin]))
  382. output->push_back('/');
  383. success =
  384. DoPartialPathInternal<CHAR, UCHAR>(spec, path, out_path->begin, output);
  385. } else {
  386. // No input, canonical path is a slash.
  387. output->push_back('/');
  388. }
  389. out_path->len = output->length() - out_path->begin;
  390. return success;
  391. }
  392. } // namespace
  393. bool CanonicalizePath(const char* spec,
  394. const Component& path,
  395. CanonOutput* output,
  396. Component* out_path) {
  397. return DoPath<char, unsigned char>(spec, path, output, out_path);
  398. }
  399. bool CanonicalizePath(const char16_t* spec,
  400. const Component& path,
  401. CanonOutput* output,
  402. Component* out_path) {
  403. return DoPath<char16_t, char16_t>(spec, path, output, out_path);
  404. }
  405. bool CanonicalizePartialPath(const char* spec,
  406. const Component& path,
  407. CanonOutput* output,
  408. Component* out_path) {
  409. return DoPartialPath<char, unsigned char>(spec, path, output, out_path);
  410. }
  411. bool CanonicalizePartialPath(const char16_t* spec,
  412. const Component& path,
  413. CanonOutput* output,
  414. Component* out_path) {
  415. return DoPartialPath<char16_t, char16_t>(spec, path, output, out_path);
  416. }
  417. bool CanonicalizePartialPathInternal(const char* spec,
  418. const Component& path,
  419. size_t path_begin_in_output,
  420. CanonOutput* output) {
  421. return DoPartialPathInternal<char, unsigned char>(
  422. spec, path, path_begin_in_output, output);
  423. }
  424. bool CanonicalizePartialPathInternal(const char16_t* spec,
  425. const Component& path,
  426. size_t path_begin_in_output,
  427. CanonOutput* output) {
  428. return DoPartialPathInternal<char16_t, char16_t>(
  429. spec, path, path_begin_in_output, output);
  430. }
  431. } // namespace url