Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(850)

Side by Side Diff: components/url_formatter/url_formatter.cc

Issue 1171333003: Move net::FormatUrl and friends outside of //net and into //components (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Rebase again now that CQ is fixed Created 5 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « components/url_formatter/url_formatter.h ('k') | components/url_formatter/url_formatter.gyp » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "net/base/net_util.h" 5 #include "components/url_formatter/url_formatter.h"
6 6
7 #include <algorithm>
7 #include <map> 8 #include <map>
8 #include <vector> 9 #include <utility>
9 10
10 #include "base/i18n/time_formatting.h"
11 #include "base/json/string_escape.h"
12 #include "base/lazy_instance.h" 11 #include "base/lazy_instance.h"
13 #include "base/logging.h" 12 #include "base/logging.h"
13 #include "base/macros.h"
14 #include "base/memory/singleton.h" 14 #include "base/memory/singleton.h"
15 #include "base/stl_util.h" 15 #include "base/stl_util.h"
16 #include "base/strings/string_tokenizer.h" 16 #include "base/strings/string_tokenizer.h"
17 #include "base/strings/string_util.h" 17 #include "base/strings/string_util.h"
18 #include "base/strings/utf_offset_string_conversions.h" 18 #include "base/strings/utf_offset_string_conversions.h"
19 #include "base/strings/utf_string_conversions.h" 19 #include "base/strings/utf_string_conversions.h"
20 #include "base/time/time.h" 20 #include "base/synchronization/lock.h"
21 #include "url/gurl.h"
22 #include "third_party/icu/source/common/unicode/uidna.h" 21 #include "third_party/icu/source/common/unicode/uidna.h"
23 #include "third_party/icu/source/common/unicode/uniset.h" 22 #include "third_party/icu/source/common/unicode/uniset.h"
24 #include "third_party/icu/source/common/unicode/uscript.h" 23 #include "third_party/icu/source/common/unicode/uscript.h"
25 #include "third_party/icu/source/common/unicode/uset.h"
26 #include "third_party/icu/source/i18n/unicode/datefmt.h"
27 #include "third_party/icu/source/i18n/unicode/regex.h" 24 #include "third_party/icu/source/i18n/unicode/regex.h"
28 #include "third_party/icu/source/i18n/unicode/ulocdata.h" 25 #include "third_party/icu/source/i18n/unicode/ulocdata.h"
29 26 #include "url/gurl.h"
30 using base::Time; 27 #include "url/third_party/mozilla/url_parse.h"
31 28
32 namespace net { 29 namespace url_formatter {
33 30
34 namespace { 31 namespace {
35 32
36 typedef std::vector<size_t> Offsets; 33 base::string16 IDNToUnicodeWithAdjustments(
34 const std::string& host,
35 const std::string& languages,
36 base::OffsetAdjuster::Adjustments* adjustments);
37 bool IDNToUnicodeOneComponent(const base::char16* comp,
38 size_t comp_len,
39 const std::string& languages,
40 base::string16* out);
41
42 class AppendComponentTransform {
43 public:
44 AppendComponentTransform() {}
45 virtual ~AppendComponentTransform() {}
46
47 virtual base::string16 Execute(
48 const std::string& component_text,
49 base::OffsetAdjuster::Adjustments* adjustments) const = 0;
50
51 // NOTE: No DISALLOW_COPY_AND_ASSIGN here, since gcc < 4.3.0 requires an
52 // accessible copy constructor in order to call AppendFormattedComponent()
53 // with an inline temporary (see http://gcc.gnu.org/bugs/#cxx%5Frvalbind ).
54 };
55
56 class HostComponentTransform : public AppendComponentTransform {
57 public:
58 explicit HostComponentTransform(const std::string& languages)
59 : languages_(languages) {}
60
61 private:
62 base::string16 Execute(
63 const std::string& component_text,
64 base::OffsetAdjuster::Adjustments* adjustments) const override {
65 return IDNToUnicodeWithAdjustments(component_text, languages_, adjustments);
66 }
67
68 const std::string& languages_;
69 };
70
71 class NonHostComponentTransform : public AppendComponentTransform {
72 public:
73 explicit NonHostComponentTransform(net::UnescapeRule::Type unescape_rules)
74 : unescape_rules_(unescape_rules) {}
75
76 private:
77 base::string16 Execute(
78 const std::string& component_text,
79 base::OffsetAdjuster::Adjustments* adjustments) const override {
80 return (unescape_rules_ == net::UnescapeRule::NONE)
81 ? base::UTF8ToUTF16WithAdjustments(component_text, adjustments)
82 : net::UnescapeAndDecodeUTF8URLComponentWithAdjustments(
83 component_text, unescape_rules_, adjustments);
84 }
85
86 const net::UnescapeRule::Type unescape_rules_;
87 };
88
89 // Transforms the portion of |spec| covered by |original_component| according to
90 // |transform|. Appends the result to |output|. If |output_component| is
91 // non-NULL, its start and length are set to the transformed component's new
92 // start and length. If |adjustments| is non-NULL, appends adjustments (if
93 // any) that reflect the transformation the original component underwent to
94 // become the transformed value appended to |output|.
95 void AppendFormattedComponent(const std::string& spec,
96 const url::Component& original_component,
97 const AppendComponentTransform& transform,
98 base::string16* output,
99 url::Component* output_component,
100 base::OffsetAdjuster::Adjustments* adjustments) {
101 DCHECK(output);
102 if (original_component.is_nonempty()) {
103 size_t original_component_begin =
104 static_cast<size_t>(original_component.begin);
105 size_t output_component_begin = output->length();
106 std::string component_str(spec, original_component_begin,
107 static_cast<size_t>(original_component.len));
108
109 // Transform |component_str| and modify |adjustments| appropriately.
110 base::OffsetAdjuster::Adjustments component_transform_adjustments;
111 output->append(
112 transform.Execute(component_str, &component_transform_adjustments));
113
114 // Shift all the adjustments made for this component so the offsets are
115 // valid for the original string and add them to |adjustments|.
116 for (base::OffsetAdjuster::Adjustments::iterator comp_iter =
117 component_transform_adjustments.begin();
118 comp_iter != component_transform_adjustments.end(); ++comp_iter)
119 comp_iter->original_offset += original_component_begin;
120 if (adjustments) {
121 adjustments->insert(adjustments->end(),
122 component_transform_adjustments.begin(),
123 component_transform_adjustments.end());
124 }
125
126 // Set positions of the parsed component.
127 if (output_component) {
128 output_component->begin = static_cast<int>(output_component_begin);
129 output_component->len =
130 static_cast<int>(output->length() - output_component_begin);
131 }
132 } else if (output_component) {
133 output_component->reset();
134 }
135 }
136
137 // If |component| is valid, its begin is incremented by |delta|.
138 void AdjustComponent(int delta, url::Component* component) {
139 if (!component->is_valid())
140 return;
141
142 DCHECK(delta >= 0 || component->begin >= -delta);
143 component->begin += delta;
144 }
145
146 // Adjusts all the components of |parsed| by |delta|, except for the scheme.
147 void AdjustAllComponentsButScheme(int delta, url::Parsed* parsed) {
148 AdjustComponent(delta, &(parsed->username));
149 AdjustComponent(delta, &(parsed->password));
150 AdjustComponent(delta, &(parsed->host));
151 AdjustComponent(delta, &(parsed->port));
152 AdjustComponent(delta, &(parsed->path));
153 AdjustComponent(delta, &(parsed->query));
154 AdjustComponent(delta, &(parsed->ref));
155 }
156
157 // Helper for FormatUrlWithOffsets().
158 base::string16 FormatViewSourceUrl(
159 const GURL& url,
160 const std::string& languages,
161 FormatUrlTypes format_types,
162 net::UnescapeRule::Type unescape_rules,
163 url::Parsed* new_parsed,
164 size_t* prefix_end,
165 base::OffsetAdjuster::Adjustments* adjustments) {
166 DCHECK(new_parsed);
167 const char kViewSource[] = "view-source:";
168 const size_t kViewSourceLength = arraysize(kViewSource) - 1;
169
170 // Format the underlying URL and record adjustments.
171 const std::string& url_str(url.possibly_invalid_spec());
172 adjustments->clear();
173 base::string16 result(
174 base::ASCIIToUTF16(kViewSource) +
175 FormatUrlWithAdjustments(GURL(url_str.substr(kViewSourceLength)),
176 languages, format_types, unescape_rules,
177 new_parsed, prefix_end, adjustments));
178 // Revise |adjustments| by shifting to the offsets to prefix that the above
179 // call to FormatUrl didn't get to see.
180 for (base::OffsetAdjuster::Adjustments::iterator it = adjustments->begin();
181 it != adjustments->end(); ++it)
182 it->original_offset += kViewSourceLength;
183
184 // Adjust positions of the parsed components.
185 if (new_parsed->scheme.is_nonempty()) {
186 // Assume "view-source:real-scheme" as a scheme.
187 new_parsed->scheme.len += kViewSourceLength;
188 } else {
189 new_parsed->scheme.begin = 0;
190 new_parsed->scheme.len = kViewSourceLength - 1;
191 }
192 AdjustAllComponentsButScheme(kViewSourceLength, new_parsed);
193
194 if (prefix_end)
195 *prefix_end += kViewSourceLength;
196
197 return result;
198 }
199
200 // TODO(brettw) bug 734373: check the scripts for each host component and
201 // don't un-IDN-ize if there is more than one. Alternatively, only IDN for
202 // scripts that the user has installed. For now, just put the entire
203 // path through IDN. Maybe this feature can be implemented in ICU itself?
204 //
205 // We may want to skip this step in the case of file URLs to allow unicode
206 // UNC hostnames regardless of encodings.
207 base::string16 IDNToUnicodeWithAdjustments(
208 const std::string& host,
209 const std::string& languages,
210 base::OffsetAdjuster::Adjustments* adjustments) {
211 if (adjustments)
212 adjustments->clear();
213 // Convert the ASCII input to a base::string16 for ICU.
214 base::string16 input16;
215 input16.reserve(host.length());
216 input16.insert(input16.end(), host.begin(), host.end());
217
218 // Do each component of the host separately, since we enforce script matching
219 // on a per-component basis.
220 base::string16 out16;
221 for (size_t component_start = 0, component_end;
222 component_start < input16.length();
223 component_start = component_end + 1) {
224 // Find the end of the component.
225 component_end = input16.find('.', component_start);
226 if (component_end == base::string16::npos)
227 component_end = input16.length(); // For getting the last component.
228 size_t component_length = component_end - component_start;
229 size_t new_component_start = out16.length();
230 bool converted_idn = false;
231 if (component_end > component_start) {
232 // Add the substring that we just found.
233 converted_idn =
234 IDNToUnicodeOneComponent(input16.data() + component_start,
235 component_length, languages, &out16);
236 }
237 size_t new_component_length = out16.length() - new_component_start;
238
239 if (converted_idn && adjustments) {
240 adjustments->push_back(base::OffsetAdjuster::Adjustment(
241 component_start, component_length, new_component_length));
242 }
243
244 // Need to add the dot we just found (if we found one).
245 if (component_end < input16.length())
246 out16.push_back('.');
247 }
248 return out16;
249 }
37 250
38 // Does some simple normalization of scripts so we can allow certain scripts 251 // Does some simple normalization of scripts so we can allow certain scripts
39 // to exist together. 252 // to exist together.
40 // TODO(brettw) bug 880223: we should allow some other languages to be 253 // TODO(brettw) bug 880223: we should allow some other languages to be
41 // oombined such as Chinese and Latin. We will probably need a more 254 // oombined such as Chinese and Latin. We will probably need a more
42 // complicated system of language pairs to have more fine-grained control. 255 // complicated system of language pairs to have more fine-grained control.
43 UScriptCode NormalizeScript(UScriptCode code) { 256 UScriptCode NormalizeScript(UScriptCode code) {
44 switch (code) { 257 switch (code) {
45 case USCRIPT_KATAKANA: 258 case USCRIPT_KATAKANA:
46 case USCRIPT_HIRAGANA: 259 case USCRIPT_HIRAGANA:
(...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after
78 } 291 }
79 return true; 292 return true;
80 } 293 }
81 294
82 // Check if the script of a language can be 'safely' mixed with 295 // Check if the script of a language can be 'safely' mixed with
83 // Latin letters in the ASCII range. 296 // Latin letters in the ASCII range.
84 bool IsCompatibleWithASCIILetters(const std::string& lang) { 297 bool IsCompatibleWithASCIILetters(const std::string& lang) {
85 // For now, just list Chinese, Japanese and Korean (positive list). 298 // For now, just list Chinese, Japanese and Korean (positive list).
86 // An alternative is negative-listing (languages using Greek and 299 // An alternative is negative-listing (languages using Greek and
87 // Cyrillic letters), but it can be more dangerous. 300 // Cyrillic letters), but it can be more dangerous.
88 return !lang.substr(0, 2).compare("zh") || 301 return !lang.substr(0, 2).compare("zh") || !lang.substr(0, 2).compare("ja") ||
89 !lang.substr(0, 2).compare("ja") ||
90 !lang.substr(0, 2).compare("ko"); 302 !lang.substr(0, 2).compare("ko");
91 } 303 }
92 304
93 typedef std::map<std::string, icu::UnicodeSet*> LangToExemplarSetMap; 305 typedef std::map<std::string, icu::UnicodeSet*> LangToExemplarSetMap;
94 306
95 class LangToExemplarSet { 307 class LangToExemplarSet {
96 public: 308 public:
97 static LangToExemplarSet* GetInstance() { 309 static LangToExemplarSet* GetInstance() {
98 return Singleton<LangToExemplarSet>::get(); 310 return Singleton<LangToExemplarSet>::get();
99 } 311 }
100 312
101 private: 313 private:
102 LangToExemplarSetMap map; 314 LangToExemplarSetMap map;
103 LangToExemplarSet() { } 315 LangToExemplarSet() {}
104 ~LangToExemplarSet() { 316 ~LangToExemplarSet() {
105 STLDeleteContainerPairSecondPointers(map.begin(), map.end()); 317 STLDeleteContainerPairSecondPointers(map.begin(), map.end());
106 } 318 }
107 319
108 friend class Singleton<LangToExemplarSet>; 320 friend class Singleton<LangToExemplarSet>;
109 friend struct DefaultSingletonTraits<LangToExemplarSet>; 321 friend struct DefaultSingletonTraits<LangToExemplarSet>;
110 friend bool GetExemplarSetForLang(const std::string&, icu::UnicodeSet**); 322 friend bool GetExemplarSetForLang(const std::string&, icu::UnicodeSet**);
111 friend void SetExemplarSetForLang(const std::string&, icu::UnicodeSet*); 323 friend void SetExemplarSetForLang(const std::string&, icu::UnicodeSet*);
112 324
113 DISALLOW_COPY_AND_ASSIGN(LangToExemplarSet); 325 DISALLOW_COPY_AND_ASSIGN(LangToExemplarSet);
114 }; 326 };
115 327
116 bool GetExemplarSetForLang(const std::string& lang, 328 bool GetExemplarSetForLang(const std::string& lang,
117 icu::UnicodeSet** lang_set) { 329 icu::UnicodeSet** lang_set) {
118 const LangToExemplarSetMap& map = LangToExemplarSet::GetInstance()->map; 330 const LangToExemplarSetMap& map = LangToExemplarSet::GetInstance()->map;
119 LangToExemplarSetMap::const_iterator pos = map.find(lang); 331 LangToExemplarSetMap::const_iterator pos = map.find(lang);
120 if (pos != map.end()) { 332 if (pos != map.end()) {
121 *lang_set = pos->second; 333 *lang_set = pos->second;
122 return true; 334 return true;
123 } 335 }
124 return false; 336 return false;
125 } 337 }
126 338
127 void SetExemplarSetForLang(const std::string& lang, 339 void SetExemplarSetForLang(const std::string& lang, icu::UnicodeSet* lang_set) {
128 icu::UnicodeSet* lang_set) {
129 LangToExemplarSetMap& map = LangToExemplarSet::GetInstance()->map; 340 LangToExemplarSetMap& map = LangToExemplarSet::GetInstance()->map;
130 map.insert(std::make_pair(lang, lang_set)); 341 map.insert(std::make_pair(lang, lang_set));
131 } 342 }
132 343
133 static base::LazyInstance<base::Lock>::Leaky 344 static base::LazyInstance<base::Lock>::Leaky g_lang_set_lock =
134 g_lang_set_lock = LAZY_INSTANCE_INITIALIZER; 345 LAZY_INSTANCE_INITIALIZER;
135 346
136 // Returns true if all the characters in component_characters are used by 347 // Returns true if all the characters in component_characters are used by
137 // the language |lang|. 348 // the language |lang|.
138 bool IsComponentCoveredByLang(const icu::UnicodeSet& component_characters, 349 bool IsComponentCoveredByLang(const icu::UnicodeSet& component_characters,
139 const std::string& lang) { 350 const std::string& lang) {
140 CR_DEFINE_STATIC_LOCAL( 351 CR_DEFINE_STATIC_LOCAL(const icu::UnicodeSet, kASCIILetters, ('a', 'z'));
141 const icu::UnicodeSet, kASCIILetters, ('a', 'z'));
142 icu::UnicodeSet* lang_set = nullptr; 352 icu::UnicodeSet* lang_set = nullptr;
143 // We're called from both the UI thread and the history thread. 353 // We're called from both the UI thread and the history thread.
144 { 354 {
145 base::AutoLock lock(g_lang_set_lock.Get()); 355 base::AutoLock lock(g_lang_set_lock.Get());
146 if (!GetExemplarSetForLang(lang, &lang_set)) { 356 if (!GetExemplarSetForLang(lang, &lang_set)) {
147 UErrorCode status = U_ZERO_ERROR; 357 UErrorCode status = U_ZERO_ERROR;
148 ULocaleData* uld = ulocdata_open(lang.c_str(), &status); 358 ULocaleData* uld = ulocdata_open(lang.c_str(), &status);
149 // TODO(jungshik) Turn this check on when the ICU data file is 359 // TODO(jungshik) Turn this check on when the ICU data file is
150 // rebuilt with the minimal subset of locale data for languages 360 // rebuilt with the minimal subset of locale data for languages
151 // to which Chrome is not localized but which we offer in the list 361 // to which Chrome is not localized but which we offer in the list
(...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after
183 // TODO(jungshik) : Check if there's any character inappropriate 393 // TODO(jungshik) : Check if there's any character inappropriate
184 // (although allowed) for domain names. 394 // (although allowed) for domain names.
185 // See http://www.unicode.org/reports/tr39/#IDN_Security_Profiles and 395 // See http://www.unicode.org/reports/tr39/#IDN_Security_Profiles and
186 // http://www.unicode.org/reports/tr39/data/xidmodifications.txt 396 // http://www.unicode.org/reports/tr39/data/xidmodifications.txt
187 // For now, we borrow the list from Mozilla and tweaked it slightly. 397 // For now, we borrow the list from Mozilla and tweaked it slightly.
188 // (e.g. Characters like U+00A0, U+3000, U+3002 are omitted because 398 // (e.g. Characters like U+00A0, U+3000, U+3002 are omitted because
189 // they're gonna be canonicalized to U+0020 and full stop before 399 // they're gonna be canonicalized to U+0020 and full stop before
190 // reaching here.) 400 // reaching here.)
191 // The original list is available at 401 // The original list is available at
192 // http://kb.mozillazine.org/Network.IDN.blacklist_chars and 402 // http://kb.mozillazine.org/Network.IDN.blacklist_chars and
193 // at http://mxr.mozilla.org/seamonkey/source/modules/libpref/src/init/all.js# 703 403 // at
404 // http://mxr.mozilla.org/seamonkey/source/modules/libpref/src/init/all.js#703
194 405
195 UErrorCode status = U_ZERO_ERROR; 406 UErrorCode status = U_ZERO_ERROR;
196 #ifdef U_WCHAR_IS_UTF16 407 #ifdef U_WCHAR_IS_UTF16
197 icu::UnicodeSet dangerous_characters( 408 icu::UnicodeSet dangerous_characters(
198 icu::UnicodeString( 409 icu::UnicodeString(
199 L"[[\\ \u00ad\u00bc\u00bd\u01c3\u0337\u0338" 410 L"[[\\ \u00ad\u00bc\u00bd\u01c3\u0337\u0338"
200 L"\u05c3\u05f4\u06d4\u0702\u115f\u1160][\u2000-\u200b]" 411 L"\u05c3\u05f4\u06d4\u0702\u115f\u1160][\u2000-\u200b]"
201 L"[\u2024\u2027\u2028\u2029\u2039\u203a\u2044\u205f]" 412 L"[\u2024\u2027\u2028\u2029\u2039\u203a\u2044\u205f]"
202 L"[\u2154-\u2156][\u2159-\u215b][\u215f\u2215\u23ae" 413 L"[\u2154-\u2156][\u2159-\u215b][\u215f\u2215\u23ae"
203 L"\u29f6\u29f8\u2afb\u2afd][\u2ff0-\u2ffb][\u3014" 414 L"\u29f6\u29f8\u2afb\u2afd][\u2ff0-\u2ffb][\u3014"
204 L"\u3015\u3033\u3164\u321d\u321e\u33ae\u33af\u33c6\u33df\ufe14" 415 L"\u3015\u3033\u3164\u321d\u321e\u33ae\u33af\u33c6\u33df\ufe14"
205 L"\ufe15\ufe3f\ufe5d\ufe5e\ufeff\uff0e\uff06\uff61\uffa0\ufff9]" 416 L"\ufe15\ufe3f\ufe5d\ufe5e\ufeff\uff0e\uff06\uff61\uffa0\ufff9]"
206 L"[\ufffa-\ufffd]\U0001f50f\U0001f510\U0001f512\U0001f513]"), 417 L"[\ufffa-\ufffd]\U0001f50f\U0001f510\U0001f512\U0001f513]"),
207 status); 418 status);
208 DCHECK(U_SUCCESS(status)); 419 DCHECK(U_SUCCESS(status));
209 icu::RegexMatcher dangerous_patterns(icu::UnicodeString( 420 icu::RegexMatcher dangerous_patterns(
210 // Lone katakana no, so, or n 421 icu::UnicodeString(
211 L"[^\\p{Katakana}][\u30ce\u30f3\u30bd][^\\p{Katakana}]" 422 // Lone katakana no, so, or n
212 // Repeating Japanese accent characters 423 L"[^\\p{Katakana}][\u30ce\u30f3\u30bd][^\\p{Katakana}]"
213 L"|[\u3099\u309a\u309b\u309c][\u3099\u309a\u309b\u309c]"), 424 // Repeating Japanese accent characters
425 L"|[\u3099\u309a\u309b\u309c][\u3099\u309a\u309b\u309c]"),
214 0, status); 426 0, status);
215 #else 427 #else
216 icu::UnicodeSet dangerous_characters(icu::UnicodeString( 428 icu::UnicodeSet dangerous_characters(
217 "[[\\u0020\\u00ad\\u00bc\\u00bd\\u01c3\\u0337\\u0338" 429 icu::UnicodeString(
218 "\\u05c3\\u05f4\\u06d4\\u0702\\u115f\\u1160][\\u2000-\\u200b]" 430 "[[\\u0020\\u00ad\\u00bc\\u00bd\\u01c3\\u0337\\u0338"
219 "[\\u2024\\u2027\\u2028\\u2029\\u2039\\u203a\\u2044\\u205f]" 431 "\\u05c3\\u05f4\\u06d4\\u0702\\u115f\\u1160][\\u2000-\\u200b]"
220 "[\\u2154-\\u2156][\\u2159-\\u215b][\\u215f\\u2215\\u23ae" 432 "[\\u2024\\u2027\\u2028\\u2029\\u2039\\u203a\\u2044\\u205f]"
221 "\\u29f6\\u29f8\\u2afb\\u2afd][\\u2ff0-\\u2ffb][\\u3014" 433 "[\\u2154-\\u2156][\\u2159-\\u215b][\\u215f\\u2215\\u23ae"
222 "\\u3015\\u3033\\u3164\\u321d\\u321e\\u33ae\\u33af\\u33c6\\u33df\\ufe14" 434 "\\u29f6\\u29f8\\u2afb\\u2afd][\\u2ff0-\\u2ffb][\\u3014"
223 "\\ufe15\\ufe3f\\ufe5d\\ufe5e\\ufeff\\uff0e\\uff06\\uff61\\uffa0\\ufff9]" 435 "\\u3015\\u3033\\u3164\\u321d\\u321e\\u33ae\\u33af\\u33c6\\u33df\\ufe"
224 "[\\ufffa-\\ufffd]\\U0001f50f\\U0001f510\\U0001f512\\U0001f513]", -1, 436 "14"
225 US_INV), status); 437 "\\ufe15\\ufe3f\\ufe5d\\ufe5e\\ufeff\\uff0e\\uff06\\uff61\\uffa0\\uff"
438 "f9]"
439 "[\\ufffa-\\ufffd]\\U0001f50f\\U0001f510\\U0001f512\\U0001f513]",
440 -1, US_INV),
441 status);
226 DCHECK(U_SUCCESS(status)); 442 DCHECK(U_SUCCESS(status));
227 icu::RegexMatcher dangerous_patterns(icu::UnicodeString( 443 icu::RegexMatcher dangerous_patterns(
228 // Lone katakana no, so, or n 444 icu::UnicodeString(
229 "[^\\p{Katakana}][\\u30ce\\u30f3\\u30bd][^\\p{Katakana}]" 445 // Lone katakana no, so, or n
230 // Repeating Japanese accent characters 446 "[^\\p{Katakana}][\\u30ce\\u30f3\\u30bd][^\\p{Katakana}]"
231 "|[\\u3099\\u309a\\u309b\\u309c][\\u3099\\u309a\\u309b\\u309c]"), 447 // Repeating Japanese accent characters
448 "|[\\u3099\\u309a\\u309b\\u309c][\\u3099\\u309a\\u309b\\u309c]"),
232 0, status); 449 0, status);
233 #endif 450 #endif
234 DCHECK(U_SUCCESS(status)); 451 DCHECK(U_SUCCESS(status));
235 icu::UnicodeSet component_characters; 452 icu::UnicodeSet component_characters;
236 icu::UnicodeString component_string(str, str_len); 453 icu::UnicodeString component_string(str, str_len);
237 component_characters.addAll(component_string); 454 component_characters.addAll(component_string);
238 if (dangerous_characters.containsSome(component_characters)) 455 if (dangerous_characters.containsSome(component_characters))
239 return false; 456 return false;
240 457
241 DCHECK(U_SUCCESS(status)); 458 DCHECK(U_SUCCESS(status));
(...skipping 56 matching lines...) Expand 10 before | Expand all | Expand 10 after
298 // TODO(jungshik): Change options as different parties (browsers, 515 // TODO(jungshik): Change options as different parties (browsers,
299 // registrars, search engines) converge toward a consensus. 516 // registrars, search engines) converge toward a consensus.
300 value = uidna_openUTS46(UIDNA_CHECK_BIDI, &err); 517 value = uidna_openUTS46(UIDNA_CHECK_BIDI, &err);
301 if (U_FAILURE(err)) 518 if (U_FAILURE(err))
302 value = NULL; 519 value = NULL;
303 } 520 }
304 521
305 UIDNA* value; 522 UIDNA* value;
306 }; 523 };
307 524
308 static base::LazyInstance<UIDNAWrapper>::Leaky 525 static base::LazyInstance<UIDNAWrapper>::Leaky g_uidna =
309 g_uidna = LAZY_INSTANCE_INITIALIZER; 526 LAZY_INSTANCE_INITIALIZER;
310 527
311 // Converts one component of a host (between dots) to IDN if safe. The result 528 // Converts one component of a host (between dots) to IDN if safe. The result
312 // will be APPENDED to the given output string and will be the same as the input 529 // will be APPENDED to the given output string and will be the same as the input
313 // if it is not IDN or the IDN is unsafe to display. Returns whether any 530 // if it is not IDN or the IDN is unsafe to display. Returns whether any
314 // conversion was performed. 531 // conversion was performed.
315 bool IDNToUnicodeOneComponent(const base::char16* comp, 532 bool IDNToUnicodeOneComponent(const base::char16* comp,
316 size_t comp_len, 533 size_t comp_len,
317 const std::string& languages, 534 const std::string& languages,
318 base::string16* out) { 535 base::string16* out) {
319 DCHECK(out); 536 DCHECK(out);
(...skipping 33 matching lines...) Expand 10 before | Expand all | Expand 10 after
353 // Something went wrong. Revert to original string. 570 // Something went wrong. Revert to original string.
354 out->resize(original_length); 571 out->resize(original_length);
355 } 572 }
356 573
357 // We get here with no IDN or on error, in which case we just append the 574 // We get here with no IDN or on error, in which case we just append the
358 // literal input. 575 // literal input.
359 out->append(comp, comp_len); 576 out->append(comp, comp_len);
360 return false; 577 return false;
361 } 578 }
362 579
363 // TODO(brettw) bug 734373: check the scripts for each host component and
364 // don't un-IDN-ize if there is more than one. Alternatively, only IDN for
365 // scripts that the user has installed. For now, just put the entire
366 // path through IDN. Maybe this feature can be implemented in ICU itself?
367 //
368 // We may want to skip this step in the case of file URLs to allow unicode
369 // UNC hostnames regardless of encodings.
370 base::string16 IDNToUnicodeWithAdjustments(
371 const std::string& host,
372 const std::string& languages,
373 base::OffsetAdjuster::Adjustments* adjustments) {
374 if (adjustments)
375 adjustments->clear();
376 // Convert the ASCII input to a base::string16 for ICU.
377 base::string16 input16;
378 input16.reserve(host.length());
379 input16.insert(input16.end(), host.begin(), host.end());
380
381 // Do each component of the host separately, since we enforce script matching
382 // on a per-component basis.
383 base::string16 out16;
384 {
385 for (size_t component_start = 0, component_end;
386 component_start < input16.length();
387 component_start = component_end + 1) {
388 // Find the end of the component.
389 component_end = input16.find('.', component_start);
390 if (component_end == base::string16::npos)
391 component_end = input16.length(); // For getting the last component.
392 size_t component_length = component_end - component_start;
393 size_t new_component_start = out16.length();
394 bool converted_idn = false;
395 if (component_end > component_start) {
396 // Add the substring that we just found.
397 converted_idn = IDNToUnicodeOneComponent(
398 input16.data() + component_start, component_length, languages,
399 &out16);
400 }
401 size_t new_component_length = out16.length() - new_component_start;
402
403 if (converted_idn && adjustments) {
404 adjustments->push_back(base::OffsetAdjuster::Adjustment(
405 component_start, component_length, new_component_length));
406 }
407
408 // Need to add the dot we just found (if we found one).
409 if (component_end < input16.length())
410 out16.push_back('.');
411 }
412 }
413 return out16;
414 }
415
416 // If |component| is valid, its begin is incremented by |delta|.
417 void AdjustComponent(int delta, url::Component* component) {
418 if (!component->is_valid())
419 return;
420
421 DCHECK(delta >= 0 || component->begin >= -delta);
422 component->begin += delta;
423 }
424
425 // Adjusts all the components of |parsed| by |delta|, except for the scheme.
426 void AdjustAllComponentsButScheme(int delta, url::Parsed* parsed) {
427 AdjustComponent(delta, &(parsed->username));
428 AdjustComponent(delta, &(parsed->password));
429 AdjustComponent(delta, &(parsed->host));
430 AdjustComponent(delta, &(parsed->port));
431 AdjustComponent(delta, &(parsed->path));
432 AdjustComponent(delta, &(parsed->query));
433 AdjustComponent(delta, &(parsed->ref));
434 }
435
436 // Helper for FormatUrlWithOffsets().
437 base::string16 FormatViewSourceUrl(
438 const GURL& url,
439 const std::string& languages,
440 FormatUrlTypes format_types,
441 UnescapeRule::Type unescape_rules,
442 url::Parsed* new_parsed,
443 size_t* prefix_end,
444 base::OffsetAdjuster::Adjustments* adjustments) {
445 DCHECK(new_parsed);
446 const char kViewSource[] = "view-source:";
447 const size_t kViewSourceLength = arraysize(kViewSource) - 1;
448
449 // Format the underlying URL and record adjustments.
450 const std::string& url_str(url.possibly_invalid_spec());
451 adjustments->clear();
452 base::string16 result(base::ASCIIToUTF16(kViewSource) +
453 FormatUrlWithAdjustments(GURL(url_str.substr(kViewSourceLength)),
454 languages, format_types, unescape_rules,
455 new_parsed, prefix_end, adjustments));
456 // Revise |adjustments| by shifting to the offsets to prefix that the above
457 // call to FormatUrl didn't get to see.
458 for (base::OffsetAdjuster::Adjustments::iterator it = adjustments->begin();
459 it != adjustments->end(); ++it)
460 it->original_offset += kViewSourceLength;
461
462 // Adjust positions of the parsed components.
463 if (new_parsed->scheme.is_nonempty()) {
464 // Assume "view-source:real-scheme" as a scheme.
465 new_parsed->scheme.len += kViewSourceLength;
466 } else {
467 new_parsed->scheme.begin = 0;
468 new_parsed->scheme.len = kViewSourceLength - 1;
469 }
470 AdjustAllComponentsButScheme(kViewSourceLength, new_parsed);
471
472 if (prefix_end)
473 *prefix_end += kViewSourceLength;
474
475 return result;
476 }
477
478 class AppendComponentTransform {
479 public:
480 AppendComponentTransform() {}
481 virtual ~AppendComponentTransform() {}
482
483 virtual base::string16 Execute(
484 const std::string& component_text,
485 base::OffsetAdjuster::Adjustments* adjustments) const = 0;
486
487 // NOTE: No DISALLOW_COPY_AND_ASSIGN here, since gcc < 4.3.0 requires an
488 // accessible copy constructor in order to call AppendFormattedComponent()
489 // with an inline temporary (see http://gcc.gnu.org/bugs/#cxx%5Frvalbind ).
490 };
491
492 class HostComponentTransform : public AppendComponentTransform {
493 public:
494 explicit HostComponentTransform(const std::string& languages)
495 : languages_(languages) {
496 }
497
498 private:
499 base::string16 Execute(
500 const std::string& component_text,
501 base::OffsetAdjuster::Adjustments* adjustments) const override {
502 return IDNToUnicodeWithAdjustments(component_text, languages_,
503 adjustments);
504 }
505
506 const std::string& languages_;
507 };
508
509 class NonHostComponentTransform : public AppendComponentTransform {
510 public:
511 explicit NonHostComponentTransform(UnescapeRule::Type unescape_rules)
512 : unescape_rules_(unescape_rules) {
513 }
514
515 private:
516 base::string16 Execute(
517 const std::string& component_text,
518 base::OffsetAdjuster::Adjustments* adjustments) const override {
519 return (unescape_rules_ == UnescapeRule::NONE) ?
520 base::UTF8ToUTF16WithAdjustments(component_text, adjustments) :
521 UnescapeAndDecodeUTF8URLComponentWithAdjustments(component_text,
522 unescape_rules_, adjustments);
523 }
524
525 const UnescapeRule::Type unescape_rules_;
526 };
527
528 // Transforms the portion of |spec| covered by |original_component| according to
529 // |transform|. Appends the result to |output|. If |output_component| is
530 // non-NULL, its start and length are set to the transformed component's new
531 // start and length. If |adjustments| is non-NULL, appends adjustments (if
532 // any) that reflect the transformation the original component underwent to
533 // become the transformed value appended to |output|.
534 void AppendFormattedComponent(const std::string& spec,
535 const url::Component& original_component,
536 const AppendComponentTransform& transform,
537 base::string16* output,
538 url::Component* output_component,
539 base::OffsetAdjuster::Adjustments* adjustments) {
540 DCHECK(output);
541 if (original_component.is_nonempty()) {
542 size_t original_component_begin =
543 static_cast<size_t>(original_component.begin);
544 size_t output_component_begin = output->length();
545 std::string component_str(spec, original_component_begin,
546 static_cast<size_t>(original_component.len));
547
548 // Transform |component_str| and modify |adjustments| appropriately.
549 base::OffsetAdjuster::Adjustments component_transform_adjustments;
550 output->append(
551 transform.Execute(component_str, &component_transform_adjustments));
552
553 // Shift all the adjustments made for this component so the offsets are
554 // valid for the original string and add them to |adjustments|.
555 for (base::OffsetAdjuster::Adjustments::iterator comp_iter =
556 component_transform_adjustments.begin();
557 comp_iter != component_transform_adjustments.end(); ++comp_iter)
558 comp_iter->original_offset += original_component_begin;
559 if (adjustments) {
560 adjustments->insert(adjustments->end(),
561 component_transform_adjustments.begin(),
562 component_transform_adjustments.end());
563 }
564
565 // Set positions of the parsed component.
566 if (output_component) {
567 output_component->begin = static_cast<int>(output_component_begin);
568 output_component->len =
569 static_cast<int>(output->length() - output_component_begin);
570 }
571 } else if (output_component) {
572 output_component->reset();
573 }
574 }
575
576 } // namespace 580 } // namespace
577 581
578 const FormatUrlType kFormatUrlOmitNothing = 0; 582 const FormatUrlType kFormatUrlOmitNothing = 0;
579 const FormatUrlType kFormatUrlOmitUsernamePassword = 1 << 0; 583 const FormatUrlType kFormatUrlOmitUsernamePassword = 1 << 0;
580 const FormatUrlType kFormatUrlOmitHTTP = 1 << 1; 584 const FormatUrlType kFormatUrlOmitHTTP = 1 << 1;
581 const FormatUrlType kFormatUrlOmitTrailingSlashOnBareHostname = 1 << 2; 585 const FormatUrlType kFormatUrlOmitTrailingSlashOnBareHostname = 1 << 2;
582 const FormatUrlType kFormatUrlOmitAll = kFormatUrlOmitUsernamePassword | 586 const FormatUrlType kFormatUrlOmitAll =
583 kFormatUrlOmitHTTP | kFormatUrlOmitTrailingSlashOnBareHostname; 587 kFormatUrlOmitUsernamePassword | kFormatUrlOmitHTTP |
588 kFormatUrlOmitTrailingSlashOnBareHostname;
584 589
585 base::string16 IDNToUnicode(const std::string& host, 590 base::string16 FormatUrl(const GURL& url,
586 const std::string& languages) { 591 const std::string& languages,
587 return IDNToUnicodeWithAdjustments(host, languages, NULL); 592 FormatUrlTypes format_types,
588 } 593 net::UnescapeRule::Type unescape_rules,
589 594 url::Parsed* new_parsed,
590 std::string GetDirectoryListingEntry(const base::string16& name, 595 size_t* prefix_end,
591 const std::string& raw_bytes, 596 size_t* offset_for_adjustment) {
592 bool is_dir, 597 std::vector<size_t> offsets;
593 int64_t size, 598 if (offset_for_adjustment)
594 Time modified) { 599 offsets.push_back(*offset_for_adjustment);
595 std::string result; 600 base::string16 result =
596 result.append("<script>addRow("); 601 FormatUrlWithOffsets(url, languages, format_types, unescape_rules,
597 base::EscapeJSONString(name, true, &result); 602 new_parsed, prefix_end, &offsets);
598 result.append(","); 603 if (offset_for_adjustment)
599 if (raw_bytes.empty()) { 604 *offset_for_adjustment = offsets[0];
600 base::EscapeJSONString(EscapePath(base::UTF16ToUTF8(name)), true, &result);
601 } else {
602 base::EscapeJSONString(EscapePath(raw_bytes), true, &result);
603 }
604 if (is_dir) {
605 result.append(",1,");
606 } else {
607 result.append(",0,");
608 }
609
610 // Negative size means unknown or not applicable (e.g. directory).
611 base::string16 size_string;
612 if (size >= 0)
613 size_string = base::FormatBytesUnlocalized(size);
614 base::EscapeJSONString(size_string, true, &result);
615
616 result.append(",");
617
618 base::string16 modified_str;
619 // |modified| can be NULL in FTP listings.
620 if (!modified.is_null()) {
621 modified_str = base::TimeFormatShortDateAndTime(modified);
622 }
623 base::EscapeJSONString(modified_str, true, &result);
624
625 result.append(");</script>\n");
626
627 return result; 605 return result;
628 } 606 }
629 607
630 void AppendFormattedHost(const GURL& url,
631 const std::string& languages,
632 base::string16* output) {
633 AppendFormattedComponent(url.possibly_invalid_spec(),
634 url.parsed_for_possibly_invalid_spec().host,
635 HostComponentTransform(languages), output, NULL, NULL);
636 }
637
638 base::string16 FormatUrlWithOffsets( 608 base::string16 FormatUrlWithOffsets(
639 const GURL& url, 609 const GURL& url,
640 const std::string& languages, 610 const std::string& languages,
641 FormatUrlTypes format_types, 611 FormatUrlTypes format_types,
642 UnescapeRule::Type unescape_rules, 612 net::UnescapeRule::Type unescape_rules,
643 url::Parsed* new_parsed, 613 url::Parsed* new_parsed,
644 size_t* prefix_end, 614 size_t* prefix_end,
645 std::vector<size_t>* offsets_for_adjustment) { 615 std::vector<size_t>* offsets_for_adjustment) {
646 base::OffsetAdjuster::Adjustments adjustments; 616 base::OffsetAdjuster::Adjustments adjustments;
647 const base::string16& format_url_return_value = 617 const base::string16& format_url_return_value =
648 FormatUrlWithAdjustments(url, languages, format_types, unescape_rules, 618 FormatUrlWithAdjustments(url, languages, format_types, unescape_rules,
649 new_parsed, prefix_end, &adjustments); 619 new_parsed, prefix_end, &adjustments);
650 base::OffsetAdjuster::AdjustOffsets(adjustments, offsets_for_adjustment); 620 base::OffsetAdjuster::AdjustOffsets(adjustments, offsets_for_adjustment);
651 if (offsets_for_adjustment) { 621 if (offsets_for_adjustment) {
652 std::for_each( 622 std::for_each(
653 offsets_for_adjustment->begin(), 623 offsets_for_adjustment->begin(), offsets_for_adjustment->end(),
654 offsets_for_adjustment->end(),
655 base::LimitOffset<std::string>(format_url_return_value.length())); 624 base::LimitOffset<std::string>(format_url_return_value.length()));
656 } 625 }
657 return format_url_return_value; 626 return format_url_return_value;
658 } 627 }
659 628
660 base::string16 FormatUrlWithAdjustments( 629 base::string16 FormatUrlWithAdjustments(
661 const GURL& url, 630 const GURL& url,
662 const std::string& languages, 631 const std::string& languages,
663 FormatUrlTypes format_types, 632 FormatUrlTypes format_types,
664 UnescapeRule::Type unescape_rules, 633 net::UnescapeRule::Type unescape_rules,
665 url::Parsed* new_parsed, 634 url::Parsed* new_parsed,
666 size_t* prefix_end, 635 size_t* prefix_end,
667 base::OffsetAdjuster::Adjustments* adjustments) { 636 base::OffsetAdjuster::Adjustments* adjustments) {
668 DCHECK(adjustments != NULL); 637 DCHECK(adjustments != NULL);
669 adjustments->clear(); 638 adjustments->clear();
670 url::Parsed parsed_temp; 639 url::Parsed parsed_temp;
671 if (!new_parsed) 640 if (!new_parsed)
672 new_parsed = &parsed_temp; 641 new_parsed = &parsed_temp;
673 else 642 else
674 *new_parsed = url::Parsed(); 643 *new_parsed = url::Parsed();
675 644
676 // Special handling for view-source:. Don't use content::kViewSourceScheme 645 // Special handling for view-source:. Don't use content::kViewSourceScheme
677 // because this library shouldn't depend on chrome. 646 // because this library shouldn't depend on chrome.
678 const char kViewSource[] = "view-source"; 647 const char kViewSource[] = "view-source";
679 // Reject "view-source:view-source:..." to avoid deep recursion. 648 // Reject "view-source:view-source:..." to avoid deep recursion.
680 const char kViewSourceTwice[] = "view-source:view-source:"; 649 const char kViewSourceTwice[] = "view-source:view-source:";
681 if (url.SchemeIs(kViewSource) && 650 if (url.SchemeIs(kViewSource) &&
682 !base::StartsWith(url.possibly_invalid_spec(), kViewSourceTwice, 651 !base::StartsWith(url.possibly_invalid_spec(), kViewSourceTwice,
683 base::CompareCase::INSENSITIVE_ASCII)) { 652 base::CompareCase::INSENSITIVE_ASCII)) {
684 return FormatViewSourceUrl(url, languages, format_types, 653 return FormatViewSourceUrl(url, languages, format_types, unescape_rules,
685 unescape_rules, new_parsed, prefix_end, 654 new_parsed, prefix_end, adjustments);
686 adjustments);
687 } 655 }
688 656
689 // We handle both valid and invalid URLs (this will give us the spec 657 // We handle both valid and invalid URLs (this will give us the spec
690 // regardless of validity). 658 // regardless of validity).
691 const std::string& spec = url.possibly_invalid_spec(); 659 const std::string& spec = url.possibly_invalid_spec();
692 const url::Parsed& parsed = url.parsed_for_possibly_invalid_spec(); 660 const url::Parsed& parsed = url.parsed_for_possibly_invalid_spec();
693 661
694 // Scheme & separators. These are ASCII. 662 // Scheme & separators. These are ASCII.
695 base::string16 url_string; 663 base::string16 url_string;
696 url_string.insert( 664 url_string.insert(
697 url_string.end(), spec.begin(), 665 url_string.end(), spec.begin(),
698 spec.begin() + parsed.CountCharactersBefore(url::Parsed::USERNAME, true)); 666 spec.begin() + parsed.CountCharactersBefore(url::Parsed::USERNAME, true));
699 const char kHTTP[] = "http://"; 667 const char kHTTP[] = "http://";
700 const char kFTP[] = "ftp."; 668 const char kFTP[] = "ftp.";
701 // url_fixer::FixupURL() treats "ftp.foo.com" as ftp://ftp.foo.com. This 669 // url_formatter::FixupURL() treats "ftp.foo.com" as ftp://ftp.foo.com. This
702 // means that if we trim "http://" off a URL whose host starts with "ftp." and 670 // means that if we trim "http://" off a URL whose host starts with "ftp." and
703 // the user inputs this into any field subject to fixup (which is basically 671 // the user inputs this into any field subject to fixup (which is basically
704 // all input fields), the meaning would be changed. (In fact, often the 672 // all input fields), the meaning would be changed. (In fact, often the
705 // formatted URL is directly pre-filled into an input field.) For this reason 673 // formatted URL is directly pre-filled into an input field.) For this reason
706 // we avoid stripping "http://" in this case. 674 // we avoid stripping "http://" in this case.
707 bool omit_http = 675 bool omit_http =
708 (format_types & kFormatUrlOmitHTTP) && 676 (format_types & kFormatUrlOmitHTTP) &&
709 base::EqualsASCII(url_string, kHTTP) && 677 base::EqualsASCII(url_string, kHTTP) &&
710 !base::StartsWith(url.host(), kFTP, base::CompareCase::SENSITIVE); 678 !base::StartsWith(url.host(), kFTP, base::CompareCase::SENSITIVE);
711 new_parsed->scheme = parsed.scheme; 679 new_parsed->scheme = parsed.scheme;
(...skipping 14 matching lines...) Expand all
726 static_cast<size_t>(parsed.username.begin), 694 static_cast<size_t>(parsed.username.begin),
727 static_cast<size_t>(parsed.username.len + parsed.password.len + 2), 695 static_cast<size_t>(parsed.username.len + parsed.password.len + 2),
728 0)); 696 0));
729 } else { 697 } else {
730 const url::Component* nonempty_component = 698 const url::Component* nonempty_component =
731 parsed.username.is_nonempty() ? &parsed.username : &parsed.password; 699 parsed.username.is_nonempty() ? &parsed.username : &parsed.password;
732 // The seeming off-by-one is to account for the '@' after the 700 // The seeming off-by-one is to account for the '@' after the
733 // username/password. 701 // username/password.
734 adjustments->push_back(base::OffsetAdjuster::Adjustment( 702 adjustments->push_back(base::OffsetAdjuster::Adjustment(
735 static_cast<size_t>(nonempty_component->begin), 703 static_cast<size_t>(nonempty_component->begin),
736 static_cast<size_t>(nonempty_component->len + 1), 704 static_cast<size_t>(nonempty_component->len + 1), 0));
737 0));
738 } 705 }
739 } 706 }
740 } else { 707 } else {
741 AppendFormattedComponent(spec, parsed.username, 708 AppendFormattedComponent(spec, parsed.username,
742 NonHostComponentTransform(unescape_rules), 709 NonHostComponentTransform(unescape_rules),
743 &url_string, &new_parsed->username, adjustments); 710 &url_string, &new_parsed->username, adjustments);
744 if (parsed.password.is_valid()) 711 if (parsed.password.is_valid())
745 url_string.push_back(':'); 712 url_string.push_back(':');
746 AppendFormattedComponent(spec, parsed.password, 713 AppendFormattedComponent(spec, parsed.password,
747 NonHostComponentTransform(unescape_rules), 714 NonHostComponentTransform(unescape_rules),
748 &url_string, &new_parsed->password, adjustments); 715 &url_string, &new_parsed->password, adjustments);
749 if (parsed.username.is_valid() || parsed.password.is_valid()) 716 if (parsed.username.is_valid() || parsed.password.is_valid())
750 url_string.push_back('@'); 717 url_string.push_back('@');
751 } 718 }
752 if (prefix_end) 719 if (prefix_end)
753 *prefix_end = static_cast<size_t>(url_string.length()); 720 *prefix_end = static_cast<size_t>(url_string.length());
754 721
755 // Host. 722 // Host.
756 AppendFormattedComponent(spec, parsed.host, HostComponentTransform(languages), 723 AppendFormattedComponent(spec, parsed.host, HostComponentTransform(languages),
757 &url_string, &new_parsed->host, adjustments); 724 &url_string, &new_parsed->host, adjustments);
758 725
759 // Port. 726 // Port.
760 if (parsed.port.is_nonempty()) { 727 if (parsed.port.is_nonempty()) {
761 url_string.push_back(':'); 728 url_string.push_back(':');
762 new_parsed->port.begin = url_string.length(); 729 new_parsed->port.begin = url_string.length();
763 url_string.insert(url_string.end(), 730 url_string.insert(url_string.end(), spec.begin() + parsed.port.begin,
764 spec.begin() + parsed.port.begin,
765 spec.begin() + parsed.port.end()); 731 spec.begin() + parsed.port.end());
766 new_parsed->port.len = url_string.length() - new_parsed->port.begin; 732 new_parsed->port.len = url_string.length() - new_parsed->port.begin;
767 } else { 733 } else {
768 new_parsed->port.reset(); 734 new_parsed->port.reset();
769 } 735 }
770 736
771 // Path & query. Both get the same general unescape & convert treatment. 737 // Path & query. Both get the same general unescape & convert treatment.
772 if (!(format_types & kFormatUrlOmitTrailingSlashOnBareHostname) || 738 if (!(format_types & kFormatUrlOmitTrailingSlashOnBareHostname) ||
773 !CanStripTrailingSlash(url)) { 739 !CanStripTrailingSlash(url)) {
774 AppendFormattedComponent(spec, parsed.path, 740 AppendFormattedComponent(spec, parsed.path,
775 NonHostComponentTransform(unescape_rules), 741 NonHostComponentTransform(unescape_rules),
776 &url_string, &new_parsed->path, adjustments); 742 &url_string, &new_parsed->path, adjustments);
777 } else { 743 } else {
778 if (parsed.path.len > 0) { 744 if (parsed.path.len > 0) {
779 adjustments->push_back(base::OffsetAdjuster::Adjustment( 745 adjustments->push_back(base::OffsetAdjuster::Adjustment(
780 parsed.path.begin, parsed.path.len, 0)); 746 parsed.path.begin, parsed.path.len, 0));
781 } 747 }
782 } 748 }
783 if (parsed.query.is_valid()) 749 if (parsed.query.is_valid())
784 url_string.push_back('?'); 750 url_string.push_back('?');
785 AppendFormattedComponent(spec, parsed.query, 751 AppendFormattedComponent(spec, parsed.query,
786 NonHostComponentTransform(unescape_rules), 752 NonHostComponentTransform(unescape_rules),
787 &url_string, &new_parsed->query, adjustments); 753 &url_string, &new_parsed->query, adjustments);
788 754
789 // Ref. This is valid, unescaped UTF-8, so we can just convert. 755 // Ref. This is valid, unescaped UTF-8, so we can just convert.
790 if (parsed.ref.is_valid()) 756 if (parsed.ref.is_valid())
791 url_string.push_back('#'); 757 url_string.push_back('#');
792 AppendFormattedComponent(spec, parsed.ref, 758 AppendFormattedComponent(spec, parsed.ref,
793 NonHostComponentTransform(UnescapeRule::NONE), 759 NonHostComponentTransform(net::UnescapeRule::NONE),
794 &url_string, &new_parsed->ref, adjustments); 760 &url_string, &new_parsed->ref, adjustments);
795 761
796 // If we need to strip out http do it after the fact. 762 // If we need to strip out http do it after the fact.
797 if (omit_http && 763 if (omit_http && base::StartsWith(url_string, base::ASCIIToUTF16(kHTTP),
798 base::StartsWith(url_string, base::ASCIIToUTF16(kHTTP), 764 base::CompareCase::SENSITIVE)) {
799 base::CompareCase::SENSITIVE)) {
800 const size_t kHTTPSize = arraysize(kHTTP) - 1; 765 const size_t kHTTPSize = arraysize(kHTTP) - 1;
801 url_string = url_string.substr(kHTTPSize); 766 url_string = url_string.substr(kHTTPSize);
802 // Because offsets in the |adjustments| are already calculated with respect 767 // Because offsets in the |adjustments| are already calculated with respect
803 // to the string with the http:// prefix in it, those offsets remain correct 768 // to the string with the http:// prefix in it, those offsets remain correct
804 // after stripping the prefix. The only thing necessary is to add an 769 // after stripping the prefix. The only thing necessary is to add an
805 // adjustment to reflect the stripped prefix. 770 // adjustment to reflect the stripped prefix.
806 adjustments->insert(adjustments->begin(), 771 adjustments->insert(adjustments->begin(),
807 base::OffsetAdjuster::Adjustment(0, kHTTPSize, 0)); 772 base::OffsetAdjuster::Adjustment(0, kHTTPSize, 0));
808 773
809 if (prefix_end) 774 if (prefix_end)
810 *prefix_end -= kHTTPSize; 775 *prefix_end -= kHTTPSize;
811 776
812 // Adjust new_parsed. 777 // Adjust new_parsed.
813 DCHECK(new_parsed->scheme.is_valid()); 778 DCHECK(new_parsed->scheme.is_valid());
814 int delta = -(new_parsed->scheme.len + 3); // +3 for ://. 779 int delta = -(new_parsed->scheme.len + 3); // +3 for ://.
815 new_parsed->scheme.reset(); 780 new_parsed->scheme.reset();
816 AdjustAllComponentsButScheme(delta, new_parsed); 781 AdjustAllComponentsButScheme(delta, new_parsed);
817 } 782 }
818 783
819 return url_string; 784 return url_string;
820 } 785 }
821 786
822 base::string16 FormatUrl(const GURL& url, 787 bool CanStripTrailingSlash(const GURL& url) {
823 const std::string& languages, 788 // Omit the path only for standard, non-file URLs with nothing but "/" after
824 FormatUrlTypes format_types, 789 // the hostname.
825 UnescapeRule::Type unescape_rules, 790 return url.IsStandard() && !url.SchemeIsFile() && !url.SchemeIsFileSystem() &&
826 url::Parsed* new_parsed, 791 !url.has_query() && !url.has_ref() && url.path() == "/";
827 size_t* prefix_end,
828 size_t* offset_for_adjustment) {
829 Offsets offsets;
830 if (offset_for_adjustment)
831 offsets.push_back(*offset_for_adjustment);
832 base::string16 result = FormatUrlWithOffsets(url, languages, format_types,
833 unescape_rules, new_parsed, prefix_end, &offsets);
834 if (offset_for_adjustment)
835 *offset_for_adjustment = offsets[0];
836 return result;
837 } 792 }
838 793
839 } // namespace net 794 void AppendFormattedHost(const GURL& url,
795 const std::string& languages,
796 base::string16* output) {
797 AppendFormattedComponent(
798 url.possibly_invalid_spec(), url.parsed_for_possibly_invalid_spec().host,
799 HostComponentTransform(languages), output, NULL, NULL);
800 }
801
802 base::string16 IDNToUnicode(const std::string& host,
803 const std::string& languages) {
804 return IDNToUnicodeWithAdjustments(host, languages, NULL);
805 }
806
807 } // url_formatter
OLDNEW
« no previous file with comments | « components/url_formatter/url_formatter.h ('k') | components/url_formatter/url_formatter.gyp » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698