xref: /aosp_15_r20/external/cronet/base/strings/escape.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2020 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_STRINGS_ESCAPE_H_
6 #define BASE_STRINGS_ESCAPE_H_
7 
8 #include <stdint.h>
9 
10 #include <set>
11 #include <string>
12 
13 #include "base/base_export.h"
14 #include "base/strings/string_piece.h"
15 #include "base/strings/utf_offset_string_conversions.h"
16 #include "build/build_config.h"
17 
18 namespace base {
19 
20 // Escaping --------------------------------------------------------------------
21 
22 // Escapes all characters except unreserved characters. Unreserved characters,
23 // as defined in RFC 3986, include alphanumerics and -._~
24 BASE_EXPORT std::string EscapeAllExceptUnreserved(StringPiece text);
25 
26 // Escapes characters in text suitable for use as a query parameter value.
27 // We %XX everything except alphanumerics and -_.!~*'()
28 // Spaces change to "+" unless you pass usePlus=false.
29 // This is basically the same as encodeURIComponent in javascript.
30 BASE_EXPORT std::string EscapeQueryParamValue(StringPiece text, bool use_plus);
31 
32 // Escapes a partial or complete file/pathname.  This includes:
33 // non-printable, non-7bit, and (including space)  "#%:<>?[\]^`{|}
34 BASE_EXPORT std::string EscapePath(StringPiece path);
35 
36 #if BUILDFLAG(IS_APPLE)
37 // Escapes characters as per expectations of NSURL. This includes:
38 // non-printable, non-7bit, and (including space)  "#%<>[\]^`{|}
39 BASE_EXPORT std::string EscapeNSURLPrecursor(StringPiece precursor);
40 #endif  // BUILDFLAG(IS_APPLE)
41 
42 // Escapes application/x-www-form-urlencoded content.  This includes:
43 // non-printable, non-7bit, and (including space)  ?>=<;+'&%$#"![\]^`{|}
44 // Space is escaped as + (if use_plus is true) and other special characters
45 // as %XX (hex).
46 BASE_EXPORT std::string EscapeUrlEncodedData(StringPiece path, bool use_plus);
47 
48 // Escapes all non-ASCII input, as well as escaping % to %25.
49 BASE_EXPORT std::string EscapeNonASCIIAndPercent(StringPiece input);
50 
51 // Escapes all non-ASCII input. Note this function leaves % unescaped, which
52 // means the unescaping the resulting string will not give back the original
53 // input.
54 BASE_EXPORT std::string EscapeNonASCII(StringPiece input);
55 
56 // Escapes characters in text suitable for use as an external protocol handler
57 // command.
58 // We %XX everything except alphanumerics and -_.!~*'() and the restricted
59 // characters (;/?:@&=+$,#[]) and a valid percent escape sequence (%XX).
60 BASE_EXPORT std::string EscapeExternalHandlerValue(StringPiece text);
61 
62 // Appends the given character to the output string, escaping the character if
63 // the character would be interpreted as an HTML delimiter.
64 BASE_EXPORT void AppendEscapedCharForHTML(char c, std::string* output);
65 
66 // Escapes chars that might cause this text to be interpreted as HTML tags.
67 BASE_EXPORT std::string EscapeForHTML(StringPiece text);
68 BASE_EXPORT std::u16string EscapeForHTML(StringPiece16 text);
69 
70 // Unescaping ------------------------------------------------------------------
71 
72 class UnescapeRule {
73  public:
74   // A combination of the following flags that is passed to the unescaping
75   // functions.
76   typedef uint32_t Type;
77 
78   // Don't unescape anything at all.
79   static constexpr Type NONE = 0;
80 
81   // Don't unescape anything special, but all normal unescaping will happen.
82   // This is a placeholder and can't be combined with other flags (since it's
83   // just the absence of them). All other unescape rules imply "normal" in
84   // addition to their special meaning. Things like escaped letters, digits,
85   // and most symbols will get unescaped with this mode.
86   static constexpr Type NORMAL = 1 << 0;
87 
88   // Convert %20 to spaces. In some places where we're showing URLs, we may
89   // want this. In places where the URL may be copied and pasted out, then
90   // you wouldn't want this since it might not be interpreted in one piece
91   // by other applications.  Other UTF-8 spaces will not be unescaped.
92   static constexpr Type SPACES = 1 << 1;
93 
94   // Unescapes '/' and '\\'. If these characters were unescaped, the resulting
95   // URL won't be the same as the source one. Moreover, they are dangerous to
96   // unescape in strings that will be used as file paths or names. This value
97   // should only be used when slashes don't have special meaning, like data
98   // URLs.
99   static constexpr Type PATH_SEPARATORS = 1 << 2;
100 
101   // Unescapes various characters that will change the meaning of URLs,
102   // including '%', '+', '&', '#'. Does not unescape path separators.
103   // If these characters were unescaped, the resulting URL won't be the same
104   // as the source one. This flag is used when generating final output like
105   // filenames for URLs where we won't be interpreting as a URL and want to do
106   // as much unescaping as possible.
107   static constexpr Type URL_SPECIAL_CHARS_EXCEPT_PATH_SEPARATORS = 1 << 3;
108 
109   // URL queries use "+" for space. This flag controls that replacement.
110   static constexpr Type REPLACE_PLUS_WITH_SPACE = 1 << 4;
111 };
112 
113 // Unescapes |escaped_text| and returns the result.
114 // Unescaping consists of looking for the exact pattern "%XX", where each X is
115 // a hex digit, and converting to the character with the numerical value of
116 // those digits. Thus "i%20=%203%3b" unescapes to "i = 3;", if the
117 // "UnescapeRule::SPACES" used.
118 //
119 // This method does not ensure that the output is a valid string using any
120 // character encoding. However, it does leave escaped certain byte sequences
121 // that would be dangerous to display to the user, because if interpreted as
122 // UTF-8, they could be used to mislead the user. Callers that want to
123 // unconditionally unescape everything for uses other than displaying data to
124 // the user should use UnescapeBinaryURLComponent().
125 BASE_EXPORT std::string UnescapeURLComponent(StringPiece escaped_text,
126                                              UnescapeRule::Type rules);
127 
128 // Unescapes the given substring as a URL, and then tries to interpret the
129 // result as being encoded as UTF-8. If the result is convertible into UTF-8, it
130 // will be returned as converted. If it is not, the original escaped string will
131 // be converted into a std::u16string and returned.  |adjustments| provides
132 // information on how the original string was adjusted to get the string
133 // returned.
134 BASE_EXPORT std::u16string UnescapeAndDecodeUTF8URLComponentWithAdjustments(
135     StringPiece text,
136     UnescapeRule::Type rules,
137     OffsetAdjuster::Adjustments* adjustments);
138 
139 // Unescapes a component of a URL for use as binary data. Unlike
140 // UnescapeURLComponent, leaves nothing unescaped, including nulls, invalid
141 // characters, characters that are unsafe to display, etc. This should *not*
142 // be used when displaying the decoded data to the user.
143 //
144 // Only the NORMAL and REPLACE_PLUS_WITH_SPACE rules are allowed.
145 BASE_EXPORT std::string UnescapeBinaryURLComponent(
146     StringPiece escaped_text,
147     UnescapeRule::Type rules = UnescapeRule::NORMAL);
148 
149 // Variant of UnescapeBinaryURLComponent().  Writes output to |unescaped_text|.
150 // Returns true on success, returns false and clears |unescaped_text| on
151 // failure. Fails on characters escaped that are unsafe to unescape in some
152 // contexts, which are defined as characters "\0" through "\x1F" (Which includes
153 // CRLF but not space), and optionally path separators. Path separators include
154 // both forward and backward slashes on all platforms. Does not fail if any of
155 // those characters appear unescaped in the input string.
156 BASE_EXPORT bool UnescapeBinaryURLComponentSafe(StringPiece escaped_text,
157                                                 bool fail_on_path_separators,
158                                                 std::string* unescaped_text);
159 
160 // Returns true if |escaped_text| contains any element of |bytes| in
161 // percent-encoded form.
162 //
163 // For example, if |bytes| is {'%', '/'}, returns true if |escaped_text|
164 // contains "%25" or "%2F", but not if it just contains bare '%' or '/'
165 // characters.
166 BASE_EXPORT bool ContainsEncodedBytes(StringPiece escaped_text,
167                                       const std::set<unsigned char>& bytes);
168 
169 // Unescapes the following ampersand character codes from |text|:
170 // &lt; &gt; &amp; &quot; &#39;
171 BASE_EXPORT std::u16string UnescapeForHTML(StringPiece16 text);
172 
173 }  // namespace base
174 
175 #endif  // BASE_STRINGS_ESCAPE_H_
176