• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 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 // NOTE: based loosely on mozilla's nsDataChannel.cpp
6 
7 #include "net/base/data_url.h"
8 
9 #include <string>
10 #include <string_view>
11 
12 #include "base/base64.h"
13 #include "base/command_line.h"
14 #include "base/ranges/algorithm.h"
15 #include "base/strings/escape.h"
16 #include "base/strings/string_split.h"
17 #include "base/strings/string_util.h"
18 #include "net/base/features.h"
19 #include "net/base/mime_util.h"
20 #include "net/http/http_response_headers.h"
21 #include "net/http/http_util.h"
22 #include "url/gurl.h"
23 
24 namespace net {
25 
26 namespace {
27 
28 // Determine if we are in the deprecated mode of whitespace removal
29 // Enterprise policies can enable this command line flag to force
30 // the old (non-standard compliant) behavior.
HasRemoveWhitespaceCommandLineFlag()31 bool HasRemoveWhitespaceCommandLineFlag() {
32   const base::CommandLine* command_line =
33       base::CommandLine::ForCurrentProcess();
34   if (!command_line) {
35     return false;
36   }
37   return command_line->HasSwitch(kRemoveWhitespaceForDataURLs);
38 }
39 
40 // https://infra.spec.whatwg.org/#ascii-whitespace, which is referenced by
41 // https://infra.spec.whatwg.org/#forgiving-base64, does not include \v in the
42 // set of ASCII whitespace characters the way Unicode does.
IsBase64Whitespace(char c)43 bool IsBase64Whitespace(char c) {
44   return c != '\v' && base::IsAsciiWhitespace(c);
45 }
46 
47 // A data URL is ready for decode if it:
48 //   - Doesn't need any extra padding.
49 //   - Does not have any escaped characters.
50 //   - Does not have any whitespace.
IsDataURLReadyForDecode(std::string_view body)51 bool IsDataURLReadyForDecode(std::string_view body) {
52   return (body.length() % 4) == 0 && base::ranges::none_of(body, [](char c) {
53            return c == '%' || IsBase64Whitespace(c);
54          });
55 }
56 
57 }  // namespace
58 
Parse(const GURL & url,std::string * mime_type,std::string * charset,std::string * data)59 bool DataURL::Parse(const GURL& url,
60                     std::string* mime_type,
61                     std::string* charset,
62                     std::string* data) {
63   if (!url.is_valid() || !url.has_scheme())
64     return false;
65 
66   DCHECK(mime_type->empty());
67   DCHECK(charset->empty());
68   DCHECK(!data || data->empty());
69 
70   // Avoid copying the URL content which can be expensive for large URLs.
71   std::string_view content = url.GetContentPiece();
72 
73   std::string_view::const_iterator comma = base::ranges::find(content, ',');
74   if (comma == content.end())
75     return false;
76 
77   std::vector<std::string_view> meta_data =
78       base::SplitStringPiece(base::MakeStringPiece(content.begin(), comma), ";",
79                              base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
80 
81   // These are moved to |mime_type| and |charset| on success.
82   std::string mime_type_value;
83   std::string charset_value;
84   auto iter = meta_data.cbegin();
85   if (iter != meta_data.cend()) {
86     mime_type_value = base::ToLowerASCII(*iter);
87     ++iter;
88   }
89 
90   static constexpr std::string_view kBase64Tag("base64");
91   static constexpr std::string_view kCharsetTag("charset=");
92 
93   bool base64_encoded = false;
94   for (; iter != meta_data.cend(); ++iter) {
95     if (!base64_encoded &&
96         base::EqualsCaseInsensitiveASCII(*iter, kBase64Tag)) {
97       base64_encoded = true;
98     } else if (charset_value.empty() &&
99                base::StartsWith(*iter, kCharsetTag,
100                                 base::CompareCase::INSENSITIVE_ASCII)) {
101       charset_value = std::string(iter->substr(kCharsetTag.size()));
102       // The grammar for charset is not specially defined in RFC2045 and
103       // RFC2397. It just needs to be a token.
104       if (!HttpUtil::IsToken(charset_value))
105         return false;
106     }
107   }
108 
109   if (mime_type_value.empty()) {
110     // Fallback to the default if nothing specified in the mediatype part as
111     // specified in RFC2045. As specified in RFC2397, we use |charset| even if
112     // |mime_type| is empty.
113     mime_type_value = "text/plain";
114     if (charset_value.empty())
115       charset_value = "US-ASCII";
116   } else if (!ParseMimeTypeWithoutParameter(mime_type_value, nullptr,
117                                             nullptr)) {
118     // Fallback to the default as recommended in RFC2045 when the mediatype
119     // value is invalid. For this case, we don't respect |charset| but force it
120     // set to "US-ASCII".
121     mime_type_value = "text/plain";
122     charset_value = "US-ASCII";
123   }
124 
125   // The caller may not be interested in receiving the data.
126   if (data) {
127     // Preserve spaces if dealing with text or xml input, same as mozilla:
128     //   https://bugzilla.mozilla.org/show_bug.cgi?id=138052
129     // but strip them otherwise:
130     //   https://bugzilla.mozilla.org/show_bug.cgi?id=37200
131     // (Spaces in a data URL should be escaped, which is handled below, so any
132     // spaces now are wrong. People expect to be able to enter them in the URL
133     // bar for text, and it can't hurt, so we allow it.)
134     //
135     // TODO(mmenke): Is removing all spaces reasonable? GURL removes trailing
136     // spaces itself, anyways. Should we just trim leading spaces instead?
137     // Allowing random intermediary spaces seems unnecessary.
138 
139     auto raw_body = base::MakeStringPiece(comma + 1, content.end());
140 
141     // For base64, we may have url-escaped whitespace which is not part
142     // of the data, and should be stripped. Otherwise, the escaped whitespace
143     // could be part of the payload, so don't strip it.
144     if (base64_encoded) {
145       if (base::FeatureList::IsEnabled(features::kOptimizeParsingDataUrls)) {
146         // Since whitespace and invalid characters in input will always cause
147         // `Base64Decode` to fail, just handle unescaping the URL on failure.
148         // This is not much slower than scanning the URL for being well formed
149         // first, even for input with whitespace.
150         if (!base::Base64Decode(raw_body, data)) {
151           std::string unescaped_body =
152               base::UnescapeBinaryURLComponent(raw_body);
153           if (!base::Base64Decode(unescaped_body, data,
154                                   base::Base64DecodePolicy::kForgiving)) {
155             return false;
156           }
157         }
158       } else {
159         // If the data URL is well formed, we can decode it immediately.
160         if (IsDataURLReadyForDecode(raw_body)) {
161           if (!base::Base64Decode(raw_body, data)) {
162             return false;
163           }
164         } else {
165           std::string unescaped_body =
166               base::UnescapeBinaryURLComponent(raw_body);
167           if (!base::Base64Decode(unescaped_body, data,
168                                   base::Base64DecodePolicy::kForgiving)) {
169             return false;
170           }
171         }
172       }
173     } else {
174       // `temp`'s storage needs to be outside feature check since `raw_body` is
175       // a string_view.
176       std::string temp;
177       // Strip whitespace for non-text MIME types. This is controlled either by
178       // the feature (finch kill switch) or an enterprise policy which sets the
179       // command line flag.
180       if (!base::FeatureList::IsEnabled(features::kKeepWhitespaceForDataUrls) ||
181           HasRemoveWhitespaceCommandLineFlag()) {
182         if (!(mime_type_value.compare(0, 5, "text/") == 0 ||
183               mime_type_value.find("xml") != std::string::npos)) {
184           temp = std::string(raw_body);
185           std::erase_if(temp, base::IsAsciiWhitespace<char>);
186           raw_body = temp;
187         }
188       }
189 
190       *data = base::UnescapeBinaryURLComponent(raw_body);
191     }
192   }
193 
194   *mime_type = std::move(mime_type_value);
195   *charset = std::move(charset_value);
196   return true;
197 }
198 
BuildResponse(const GURL & url,std::string_view method,std::string * mime_type,std::string * charset,std::string * data,scoped_refptr<HttpResponseHeaders> * headers)199 Error DataURL::BuildResponse(const GURL& url,
200                              std::string_view method,
201                              std::string* mime_type,
202                              std::string* charset,
203                              std::string* data,
204                              scoped_refptr<HttpResponseHeaders>* headers) {
205   DCHECK(data);
206   DCHECK(!*headers);
207 
208   if (!DataURL::Parse(url, mime_type, charset, data))
209     return ERR_INVALID_URL;
210 
211   // |mime_type| set by DataURL::Parse() is guaranteed to be in
212   //     token "/" token
213   // form. |charset| can be an empty string.
214   DCHECK(!mime_type->empty());
215 
216   // "charset" in the Content-Type header is specified explicitly to follow
217   // the "token" ABNF in the HTTP spec. When the DataURL::Parse() call is
218   // successful, it's guaranteed that the string in |charset| follows the
219   // "token" ABNF.
220   std::string content_type = *mime_type;
221   if (!charset->empty())
222     content_type.append(";charset=" + *charset);
223   // The terminal double CRLF isn't needed by TryToCreate().
224   if (base::FeatureList::IsEnabled(features::kOptimizeParsingDataUrls)) {
225     *headers = HttpResponseHeaders::TryToCreateForDataURL(content_type);
226   } else {
227     *headers = HttpResponseHeaders::TryToCreate(
228         "HTTP/1.1 200 OK\r\n"
229         "Content-Type:" +
230         content_type);
231   }
232   // Above line should always succeed - TryToCreate() only fails when there are
233   // nulls in the string, and DataURL::Parse() can't return nulls in anything
234   // but the |data| argument.
235   DCHECK(*headers);
236 
237   if (base::EqualsCaseInsensitiveASCII(method, "HEAD"))
238     data->clear();
239 
240   return OK;
241 }
242 
243 }  // namespace net
244