1// Copyright (c) 2012 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
5// NOTE: based loosely on mozilla's nsDataChannel.cpp
6
7#include <algorithm>
8
9#include "net/base/data_url.h"
10
11#include "base/base64.h"
12#include "base/basictypes.h"
13#include "base/strings/string_split.h"
14#include "base/strings/string_util.h"
15#include "net/base/escape.h"
16#include "net/base/mime_util.h"
17#include "net/http/http_util.h"
18#include "url/gurl.h"
19
20namespace net {
21
22// static
23bool DataURL::Parse(const GURL& url, std::string* mime_type,
24                    std::string* charset, std::string* data) {
25  DCHECK(mime_type->empty());
26  DCHECK(charset->empty());
27  std::string::const_iterator begin = url.spec().begin();
28  std::string::const_iterator end = url.spec().end();
29
30  std::string::const_iterator after_colon = std::find(begin, end, ':');
31  if (after_colon == end)
32    return false;
33  ++after_colon;
34
35  std::string::const_iterator comma = std::find(after_colon, end, ',');
36  if (comma == end)
37    return false;
38
39  std::vector<std::string> meta_data;
40  std::string unparsed_meta_data(after_colon, comma);
41  base::SplitString(unparsed_meta_data, ';', &meta_data);
42
43  std::vector<std::string>::iterator iter = meta_data.begin();
44  if (iter != meta_data.end()) {
45    mime_type->swap(*iter);
46    base::StringToLowerASCII(mime_type);
47    ++iter;
48  }
49
50  static const char kBase64Tag[] = "base64";
51  static const char kCharsetTag[] = "charset=";
52  const size_t kCharsetTagLength = arraysize(kCharsetTag) - 1;
53
54  bool base64_encoded = false;
55  for (; iter != meta_data.end(); ++iter) {
56    if (!base64_encoded && *iter == kBase64Tag) {
57      base64_encoded = true;
58    } else if (charset->empty() &&
59               iter->compare(0, kCharsetTagLength, kCharsetTag) == 0) {
60      charset->assign(iter->substr(kCharsetTagLength));
61      // The grammar for charset is not specially defined in RFC2045 and
62      // RFC2397. It just needs to be a token.
63      if (!net::HttpUtil::IsToken(*charset))
64        return false;
65    }
66  }
67
68  if (mime_type->empty()) {
69    // Fallback to the default if nothing specified in the mediatype part as
70    // specified in RFC2045. As specified in RFC2397, we use |charset| even if
71    // |mime_type| is empty.
72    mime_type->assign("text/plain");
73  } else if (!ParseMimeTypeWithoutParameter(*mime_type, NULL, NULL)) {
74    // Fallback to the default as recommended in RFC2045 when the mediatype
75    // value is invalid. For this case, we don't respect |charset| but force it
76    // set to "US-ASCII".
77    mime_type->assign("text/plain");
78    charset->assign("US-ASCII");
79  }
80  if (charset->empty())
81    charset->assign("US-ASCII");
82
83  // The caller may not be interested in receiving the data.
84  if (!data)
85    return true;
86
87  // Preserve spaces if dealing with text or xml input, same as mozilla:
88  //   https://bugzilla.mozilla.org/show_bug.cgi?id=138052
89  // but strip them otherwise:
90  //   https://bugzilla.mozilla.org/show_bug.cgi?id=37200
91  // (Spaces in a data URL should be escaped, which is handled below, so any
92  // spaces now are wrong. People expect to be able to enter them in the URL
93  // bar for text, and it can't hurt, so we allow it.)
94  std::string temp_data = std::string(comma + 1, end);
95
96  // For base64, we may have url-escaped whitespace which is not part
97  // of the data, and should be stripped. Otherwise, the escaped whitespace
98  // could be part of the payload, so don't strip it.
99  if (base64_encoded) {
100    temp_data = UnescapeURLComponent(temp_data,
101        UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS |
102        UnescapeRule::CONTROL_CHARS);
103  }
104
105  // Strip whitespace.
106  if (base64_encoded || !(mime_type->compare(0, 5, "text/") == 0 ||
107                          mime_type->find("xml") != std::string::npos)) {
108    temp_data.erase(std::remove_if(temp_data.begin(), temp_data.end(),
109                                   IsAsciiWhitespace<wchar_t>),
110                    temp_data.end());
111  }
112
113  if (!base64_encoded) {
114    temp_data = UnescapeURLComponent(temp_data,
115        UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS |
116        UnescapeRule::CONTROL_CHARS);
117  }
118
119  if (base64_encoded) {
120    size_t length = temp_data.length();
121    size_t padding_needed = 4 - (length % 4);
122    // If the input wasn't padded, then we pad it as necessary until we have a
123    // length that is a multiple of 4 as required by our decoder. We don't
124    // correct if the input was incorrectly padded. If |padding_needed| == 3,
125    // then the input isn't well formed and decoding will fail with or without
126    // padding.
127    if ((padding_needed == 1 || padding_needed == 2) &&
128        temp_data[length - 1] != '=') {
129      temp_data.resize(length + padding_needed, '=');
130    }
131    return base::Base64Decode(temp_data, data);
132  }
133
134  temp_data.swap(*data);
135  return true;
136}
137
138}  // namespace net
139