1 // Copyright 2014 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.
5 #include "components/omnibox/autocomplete_input.h"
7 #include "base/strings/string_util.h"
8 #include "base/strings/utf_string_conversions.h"
9 #include "components/metrics/proto/omnibox_event.pb.h"
10 #include "components/omnibox/autocomplete_scheme_classifier.h"
11 #include "components/omnibox/omnibox_field_trial.h"
12 #include "components/url_fixer/url_fixer.h"
13 #include "net/base/net_util.h"
14 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
15 #include "url/url_canon_ip.h"
16 #include "url/url_util.h"
20 // Hardcode constant to avoid any dependencies on content/.
21 const char kViewSourceScheme
[] = "view-source";
23 void AdjustCursorPositionIfNecessary(size_t num_leading_chars_removed
,
24 size_t* cursor_position
) {
25 if (*cursor_position
== base::string16::npos
)
27 if (num_leading_chars_removed
< *cursor_position
)
28 *cursor_position
-= num_leading_chars_removed
;
35 AutocompleteInput::AutocompleteInput()
36 : cursor_position_(base::string16::npos
),
37 current_page_classification_(metrics::OmniboxEventProto::INVALID_SPEC
),
38 type_(metrics::OmniboxInputType::INVALID
),
39 prevent_inline_autocomplete_(false),
40 prefer_keyword_(false),
41 allow_exact_keyword_match_(true),
42 want_asynchronous_matches_(true),
43 from_omnibox_focus_(false) {
46 AutocompleteInput::AutocompleteInput(
47 const base::string16
& text
,
48 size_t cursor_position
,
49 const std::string
& desired_tld
,
50 const GURL
& current_url
,
51 metrics::OmniboxEventProto::PageClassification current_page_classification
,
52 bool prevent_inline_autocomplete
,
54 bool allow_exact_keyword_match
,
55 bool want_asynchronous_matches
,
56 bool from_omnibox_focus
,
57 const AutocompleteSchemeClassifier
& scheme_classifier
)
58 : cursor_position_(cursor_position
),
59 current_url_(current_url
),
60 current_page_classification_(current_page_classification
),
61 prevent_inline_autocomplete_(prevent_inline_autocomplete
),
62 prefer_keyword_(prefer_keyword
),
63 allow_exact_keyword_match_(allow_exact_keyword_match
),
64 want_asynchronous_matches_(want_asynchronous_matches
),
65 from_omnibox_focus_(from_omnibox_focus
) {
66 DCHECK(cursor_position
<= text
.length() ||
67 cursor_position
== base::string16::npos
)
68 << "Text: '" << text
<< "', cp: " << cursor_position
;
69 // None of the providers care about leading white space so we always trim it.
70 // Providers that care about trailing white space handle trimming themselves.
71 if ((base::TrimWhitespace(text
, base::TRIM_LEADING
, &text_
) &
72 base::TRIM_LEADING
) != 0)
73 AdjustCursorPositionIfNecessary(text
.length() - text_
.length(),
76 GURL canonicalized_url
;
77 type_
= Parse(text_
, desired_tld
, scheme_classifier
, &parts_
, &scheme_
,
80 if (type_
== metrics::OmniboxInputType::INVALID
)
83 if (((type_
== metrics::OmniboxInputType::UNKNOWN
) ||
84 (type_
== metrics::OmniboxInputType::URL
)) &&
85 canonicalized_url
.is_valid() &&
86 (!canonicalized_url
.IsStandard() || canonicalized_url
.SchemeIsFile() ||
87 canonicalized_url
.SchemeIsFileSystem() ||
88 !canonicalized_url
.host().empty()))
89 canonicalized_url_
= canonicalized_url
;
91 size_t chars_removed
= RemoveForcedQueryStringIfNecessary(type_
, &text_
);
92 AdjustCursorPositionIfNecessary(chars_removed
, &cursor_position_
);
94 // Remove spaces between opening question mark and first actual character.
95 base::string16 trimmed_text
;
96 if ((base::TrimWhitespace(text_
, base::TRIM_LEADING
, &trimmed_text
) &
97 base::TRIM_LEADING
) != 0) {
98 AdjustCursorPositionIfNecessary(text_
.length() - trimmed_text
.length(),
100 text_
= trimmed_text
;
105 AutocompleteInput::~AutocompleteInput() {
109 size_t AutocompleteInput::RemoveForcedQueryStringIfNecessary(
110 metrics::OmniboxInputType::Type type
,
111 base::string16
* text
) {
112 if ((type
!= metrics::OmniboxInputType::FORCED_QUERY
) || text
->empty() ||
115 // Drop the leading '?'.
121 std::string
AutocompleteInput::TypeToString(
122 metrics::OmniboxInputType::Type type
) {
124 case metrics::OmniboxInputType::INVALID
: return "invalid";
125 case metrics::OmniboxInputType::UNKNOWN
: return "unknown";
126 case metrics::OmniboxInputType::DEPRECATED_REQUESTED_URL
:
127 return "deprecated-requested-url";
128 case metrics::OmniboxInputType::URL
: return "url";
129 case metrics::OmniboxInputType::QUERY
: return "query";
130 case metrics::OmniboxInputType::FORCED_QUERY
: return "forced-query";
132 return std::string();
136 metrics::OmniboxInputType::Type
AutocompleteInput::Parse(
137 const base::string16
& text
,
138 const std::string
& desired_tld
,
139 const AutocompleteSchemeClassifier
& scheme_classifier
,
141 base::string16
* scheme
,
142 GURL
* canonicalized_url
) {
143 size_t first_non_white
= text
.find_first_not_of(base::kWhitespaceUTF16
, 0);
144 if (first_non_white
== base::string16::npos
)
145 return metrics::OmniboxInputType::INVALID
; // All whitespace.
147 if (text
[first_non_white
] == L
'?') {
148 // If the first non-whitespace character is a '?', we magically treat this
150 return metrics::OmniboxInputType::FORCED_QUERY
;
153 // Ask our parsing back-end to help us understand what the user typed. We
154 // use the URLFixerUpper here because we want to be smart about what we
155 // consider a scheme. For example, we shouldn't consider www.google.com:80
157 url::Parsed local_parts
;
159 parts
= &local_parts
;
160 const base::string16
parsed_scheme(url_fixer::SegmentURL(text
, parts
));
162 *scheme
= parsed_scheme
;
163 const std::string
parsed_scheme_utf8(base::UTF16ToUTF8(parsed_scheme
));
165 // If we can't canonicalize the user's input, the rest of the autocomplete
166 // system isn't going to be able to produce a navigable URL match for it.
167 // So we just return QUERY immediately in these cases.
168 GURL placeholder_canonicalized_url
;
169 if (!canonicalized_url
)
170 canonicalized_url
= &placeholder_canonicalized_url
;
172 url_fixer::FixupURL(base::UTF16ToUTF8(text
), desired_tld
);
173 if (!canonicalized_url
->is_valid())
174 return metrics::OmniboxInputType::QUERY
;
176 if (base::LowerCaseEqualsASCII(parsed_scheme_utf8
, url::kFileScheme
)) {
177 // A user might or might not type a scheme when entering a file URL. In
178 // either case, |parsed_scheme_utf8| will tell us that this is a file URL,
179 // but |parts->scheme| might be empty, e.g. if the user typed "C:\foo".
180 return metrics::OmniboxInputType::URL
;
183 // If the user typed a scheme, and it's HTTP or HTTPS, we know how to parse it
184 // well enough that we can fall through to the heuristics below. If it's
185 // something else, we can just determine our action based on what we do with
186 // any input of this scheme. In theory we could do better with some schemes
187 // (e.g. "ftp" or "view-source") but I'll wait to spend the effort on that
188 // until I run into some cases that really need it.
189 if (parts
->scheme
.is_nonempty() &&
190 !base::LowerCaseEqualsASCII(parsed_scheme_utf8
, url::kHttpScheme
) &&
191 !base::LowerCaseEqualsASCII(parsed_scheme_utf8
, url::kHttpsScheme
)) {
192 metrics::OmniboxInputType::Type type
=
193 scheme_classifier
.GetInputTypeForScheme(parsed_scheme_utf8
);
194 if (type
!= metrics::OmniboxInputType::INVALID
)
197 // We don't know about this scheme. It might be that the user typed a
198 // URL of the form "username:password@foo.com".
199 const base::string16 http_scheme_prefix
=
200 base::ASCIIToUTF16(std::string(url::kHttpScheme
) +
201 url::kStandardSchemeSeparator
);
202 url::Parsed http_parts
;
203 base::string16 http_scheme
;
204 GURL http_canonicalized_url
;
205 metrics::OmniboxInputType::Type http_type
=
206 Parse(http_scheme_prefix
+ text
, desired_tld
, scheme_classifier
,
207 &http_parts
, &http_scheme
, &http_canonicalized_url
);
208 DCHECK_EQ(std::string(url::kHttpScheme
),
209 base::UTF16ToUTF8(http_scheme
));
211 if ((http_type
== metrics::OmniboxInputType::URL
) &&
212 http_parts
.username
.is_nonempty() &&
213 http_parts
.password
.is_nonempty()) {
214 // Manually re-jigger the parsed parts to match |text| (without the
215 // http scheme added).
216 http_parts
.scheme
.reset();
217 url::Component
* components
[] = {
218 &http_parts
.username
,
219 &http_parts
.password
,
226 for (size_t i
= 0; i
< arraysize(components
); ++i
) {
227 url_fixer::OffsetComponent(
228 -static_cast<int>(http_scheme_prefix
.length()), components
[i
]);
234 *canonicalized_url
= http_canonicalized_url
;
236 return metrics::OmniboxInputType::URL
;
239 // We don't know about this scheme and it doesn't look like the user
240 // typed a username and password. It's likely to be a search operator
241 // like "site:" or "link:". We classify it as UNKNOWN so the user has
242 // the option of treating it as a URL if we're wrong.
243 // Note that SegmentURL() is smart so we aren't tricked by "c:\foo" or
244 // "www.example.com:81" in this case.
245 return metrics::OmniboxInputType::UNKNOWN
;
248 // Either the user didn't type a scheme, in which case we need to distinguish
249 // between an HTTP URL and a query, or the scheme is HTTP or HTTPS, in which
250 // case we should reject invalid formulations.
252 // If we have an empty host it can't be a valid HTTP[S] URL. (This should
253 // only trigger for input that begins with a colon, which GURL will parse as a
254 // valid, non-standard URL; for standard URLs, an empty host would have
255 // resulted in an invalid |canonicalized_url| above.)
256 if (!canonicalized_url
->has_host())
257 return metrics::OmniboxInputType::QUERY
;
259 // Determine the host family. We get this information by (re-)canonicalizing
260 // the already-canonicalized host rather than using the user's original input,
261 // in case fixup affected the result here (e.g. an input that looks like an
262 // IPv4 address but with a non-empty desired TLD would return IPV4 before
263 // fixup and NEUTRAL afterwards, and we want to treat it as NEUTRAL).
264 url::CanonHostInfo host_info
;
265 net::CanonicalizeHost(canonicalized_url
->host(), &host_info
);
267 // Check if the canonicalized host has a known TLD, which we'll want to know
269 const size_t registry_length
=
270 net::registry_controlled_domains::GetRegistryLength(
271 canonicalized_url
->host(),
272 net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES
,
273 net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES
);
274 DCHECK_NE(std::string::npos
, registry_length
);
275 const bool has_known_tld
= registry_length
!= 0;
277 // See if the hostname is valid. While IE and GURL allow hostnames to contain
278 // many other characters (perhaps for weird intranet machines), it's extremely
279 // unlikely that a user would be trying to type those in for anything other
280 // than a search query.
281 const base::string16
original_host(
282 text
.substr(parts
->host
.begin
, parts
->host
.len
));
283 if ((host_info
.family
== url::CanonHostInfo::NEUTRAL
) &&
284 !net::IsCanonicalizedHostCompliant(canonicalized_url
->host())) {
285 // Invalid hostname. There are several possible cases:
286 // * The user is typing a multi-word query. If we see a space anywhere in
287 // the input host we assume this is a search and return QUERY. (We check
288 // the input string instead of canonicalized_url->host() in case fixup
289 // escaped the space.)
290 // * The user is typing some garbage string. Return QUERY.
291 // * Our checker is too strict and the user is typing a real-world URL
292 // that's "invalid" but resolves. To catch these, we return UNKNOWN when
293 // the user explicitly typed a scheme or when the hostname has a known
294 // TLD, so we'll still search by default but we'll show the accidental
295 // search infobar if necessary.
297 // This means we would block the following kinds of navigation attempts:
298 // * Navigations to a hostname with spaces
299 // * Navigations to a hostname with invalid characters and an unknown TLD
300 // These might be possible in intranets, but we're not going to support them
301 // without concrete evidence that doing so is necessary.
302 return (parts
->scheme
.is_nonempty() ||
303 (has_known_tld
&& (original_host
.find(' ') == base::string16::npos
))) ?
304 metrics::OmniboxInputType::UNKNOWN
: metrics::OmniboxInputType::QUERY
;
307 // For hostnames that look like IP addresses, distinguish between IPv6
308 // addresses, which are basically guaranteed to be navigations, and IPv4
309 // addresses, which are much fuzzier.
310 if (host_info
.family
== url::CanonHostInfo::IPV6
)
311 return metrics::OmniboxInputType::URL
;
312 if (host_info
.family
== url::CanonHostInfo::IPV4
) {
313 // The host may be a real IP address, or something that looks a bit like it
314 // (e.g. "1.2" or "3232235521"). We check whether it was convertible to an
315 // IP with a non-zero first octet; IPs with first octet zero are "source
316 // IPs" and are almost never navigable as destination addresses.
318 // The one exception to this is 0.0.0.0; on many systems, attempting to
319 // navigate to this IP actually navigates to localhost. To support this
320 // case, when the converted IP is 0.0.0.0, we go ahead and run the "did the
321 // user actually type four components" test in the conditional below, so
322 // that we'll allow explicit attempts to navigate to "0.0.0.0". If the
323 // input was anything else (e.g. "0"), we'll fall through to returning QUERY
325 if ((host_info
.address
[0] != 0) ||
326 ((host_info
.address
[1] == 0) && (host_info
.address
[2] == 0) &&
327 (host_info
.address
[3] == 0))) {
328 // This is theoretically a navigable IP. We have four cases. The first
330 // * If the user typed four distinct components, this is an IP for sure.
331 // * If the user typed two or three components, this is almost certainly a
332 // query, especially for two components (as in "13.5/7.25"), but we'll
333 // allow navigation for an explicit scheme or trailing slash below.
334 // * If the user typed one component, this is likely a query, but could be
335 // a non-dotted-quad version of an IP address.
336 // Unfortunately, since we called CanonicalizeHost() on the
337 // already-canonicalized host, all of these cases will have been changed
338 // to have four components (e.g. 13.2 -> 13.0.0.2), so we have to call
339 // CanonicalizeHost() again, this time on the original input, so that we
340 // can get the correct number of IP components.
342 // The fourth case is that the user typed something ambiguous like ".1.2"
343 // that fixup converted to an IP address ("1.0.0.2"). In this case the
344 // call to CanonicalizeHost() will return NEUTRAL here. Since it's not
345 // clear what the user intended, we fall back to our other heuristics.
346 net::CanonicalizeHost(base::UTF16ToUTF8(original_host
), &host_info
);
347 if ((host_info
.family
== url::CanonHostInfo::IPV4
) &&
348 (host_info
.num_ipv4_components
== 4))
349 return metrics::OmniboxInputType::URL
;
352 // By this point, if we have an "IP" with first octet zero, we know it
353 // wasn't "0.0.0.0", so mark it as non-navigable.
354 if (host_info
.address
[0] == 0)
355 return metrics::OmniboxInputType::QUERY
;
358 // Now that we've ruled out all schemes other than http or https and done a
359 // little more sanity checking, the presence of a scheme means this is likely
361 if (parts
->scheme
.is_nonempty())
362 return metrics::OmniboxInputType::URL
;
364 // Trailing slashes force the input to be treated as a URL.
365 if (parts
->path
.is_nonempty()) {
366 base::char16 c
= text
[parts
->path
.end() - 1];
367 if ((c
== '\\') || (c
== '/'))
368 return metrics::OmniboxInputType::URL
;
371 // Handle the cases we detected in the IPv4 code above as "almost certainly a
372 // query" now that we know the user hasn't tried to force navigation via a
373 // scheme/trailing slash.
374 if ((host_info
.family
== url::CanonHostInfo::IPV4
) &&
375 (host_info
.num_ipv4_components
> 1))
376 return metrics::OmniboxInputType::QUERY
;
378 // If there is more than one recognized non-host component, this is likely to
379 // be a URL, even if the TLD is unknown (in which case this is likely an
381 if (NumNonHostComponents(*parts
) > 1)
382 return metrics::OmniboxInputType::URL
;
384 // If we reach here with a username, our input looks something like
385 // "user@host". Unless there is a desired TLD, we think this is more likely
386 // an email address than an HTTP auth attempt, so we search by default. (When
387 // there _is_ a desired TLD, the user hit ctrl-enter, and we assume that
388 // implies an attempted navigation.)
389 if (canonicalized_url
->has_username() && desired_tld
.empty())
390 return metrics::OmniboxInputType::UNKNOWN
;
392 // If the host has a known TLD or a port, it's probably a URL. Note that we
393 // special-case "localhost" as a known hostname.
394 if (has_known_tld
|| (canonicalized_url
->host() == "localhost") ||
395 canonicalized_url
->has_port())
396 return metrics::OmniboxInputType::URL
;
398 // If the input looks like a word followed by a pound sign and possibly more
399 // characters ("c#" or "c# foo"), this is almost certainly an attempt to
400 // search. We try to be conservative here by not firing on cases like "c/#"
401 // or "c?#" that might actually indicate some cryptic attempt to access an
402 // intranet host, and by placing this check late enough that other tests
403 // (e.g., for a non-empty TLD or a non-empty scheme) will have already
405 if (!OmniboxFieldTrial::PreventUWYTDefaultForNonURLInputs() &&
406 !parts
->path
.is_valid() && !canonicalized_url
->has_query() &&
407 canonicalized_url
->has_ref())
408 return metrics::OmniboxInputType::QUERY
;
410 // No scheme, username, port, and no known TLD on the host.
412 // * A single word "foo"; possibly an intranet site, but more likely a search.
413 // This is ideally an UNKNOWN, and we can let the Alternate Nav URL code
414 // catch our mistakes.
415 // * A URL with a valid TLD we don't know about yet. If e.g. a registrar adds
416 // "xxx" as a TLD, then until we add it to our data file, Chrome won't know
417 // "foo.xxx" is a real URL. So ideally this is a URL, but we can't really
418 // distinguish this case from:
419 // * A "URL-like" string that's not really a URL (like
420 // "browser.tabs.closeButtons" or "java.awt.event.*"). This is ideally a
421 // QUERY. Since this is indistinguishable from the case above, and this
422 // case is much more likely, claim these are UNKNOWN, which should default
423 // to the right thing and let users correct us on a case-by-case basis.
424 return metrics::OmniboxInputType::UNKNOWN
;
428 void AutocompleteInput::ParseForEmphasizeComponents(
429 const base::string16
& text
,
430 const AutocompleteSchemeClassifier
& scheme_classifier
,
431 url::Component
* scheme
,
432 url::Component
* host
) {
434 base::string16 scheme_str
;
435 Parse(text
, std::string(), scheme_classifier
, &parts
, &scheme_str
, NULL
);
437 *scheme
= parts
.scheme
;
440 int after_scheme_and_colon
= parts
.scheme
.end() + 1;
441 // For the view-source scheme, we should emphasize the scheme and host of the
442 // URL qualified by the view-source prefix.
443 if (base::LowerCaseEqualsASCII(scheme_str
, kViewSourceScheme
) &&
444 (static_cast<int>(text
.length()) > after_scheme_and_colon
)) {
445 // Obtain the URL prefixed by view-source and parse it.
446 base::string16
real_url(text
.substr(after_scheme_and_colon
));
447 url::Parsed real_parts
;
448 AutocompleteInput::Parse(real_url
, std::string(), scheme_classifier
,
449 &real_parts
, NULL
, NULL
);
450 if (real_parts
.scheme
.is_nonempty() || real_parts
.host
.is_nonempty()) {
451 if (real_parts
.scheme
.is_nonempty()) {
452 *scheme
= url::Component(
453 after_scheme_and_colon
+ real_parts
.scheme
.begin
,
454 real_parts
.scheme
.len
);
458 if (real_parts
.host
.is_nonempty()) {
459 *host
= url::Component(after_scheme_and_colon
+ real_parts
.host
.begin
,
460 real_parts
.host
.len
);
465 } else if (base::LowerCaseEqualsASCII(scheme_str
, url::kFileSystemScheme
) &&
466 parts
.inner_parsed() && parts
.inner_parsed()->scheme
.is_valid()) {
467 *host
= parts
.inner_parsed()->host
;
472 base::string16
AutocompleteInput::FormattedStringWithEquivalentMeaning(
474 const base::string16
& formatted_url
,
475 const AutocompleteSchemeClassifier
& scheme_classifier
) {
476 if (!net::CanStripTrailingSlash(url
))
477 return formatted_url
;
478 const base::string16
url_with_path(formatted_url
+ base::char16('/'));
479 return (AutocompleteInput::Parse(formatted_url
, std::string(),
480 scheme_classifier
, NULL
, NULL
, NULL
) ==
481 AutocompleteInput::Parse(url_with_path
, std::string(),
482 scheme_classifier
, NULL
, NULL
, NULL
)) ?
483 formatted_url
: url_with_path
;
487 int AutocompleteInput::NumNonHostComponents(const url::Parsed
& parts
) {
488 int num_nonhost_components
= 0;
489 if (parts
.scheme
.is_nonempty())
490 ++num_nonhost_components
;
491 if (parts
.username
.is_nonempty())
492 ++num_nonhost_components
;
493 if (parts
.password
.is_nonempty())
494 ++num_nonhost_components
;
495 if (parts
.port
.is_nonempty())
496 ++num_nonhost_components
;
497 if (parts
.path
.is_nonempty())
498 ++num_nonhost_components
;
499 if (parts
.query
.is_nonempty())
500 ++num_nonhost_components
;
501 if (parts
.ref
.is_nonempty())
502 ++num_nonhost_components
;
503 return num_nonhost_components
;
507 bool AutocompleteInput::HasHTTPScheme(const base::string16
& input
) {
508 std::string
utf8_input(base::UTF16ToUTF8(input
));
509 url::Component scheme
;
510 if (url::FindAndCompareScheme(utf8_input
, kViewSourceScheme
, &scheme
)) {
511 utf8_input
.erase(0, scheme
.end() + 1);
513 return url::FindAndCompareScheme(utf8_input
, url::kHttpScheme
, NULL
);
516 void AutocompleteInput::UpdateText(const base::string16
& text
,
517 size_t cursor_position
,
518 const url::Parsed
& parts
) {
519 DCHECK(cursor_position
<= text
.length() ||
520 cursor_position
== base::string16::npos
)
521 << "Text: '" << text
<< "', cp: " << cursor_position
;
523 cursor_position_
= cursor_position
;
527 void AutocompleteInput::Clear() {
529 cursor_position_
= base::string16::npos
;
530 current_url_
= GURL();
531 current_page_classification_
= metrics::OmniboxEventProto::INVALID_SPEC
;
532 type_
= metrics::OmniboxInputType::INVALID
;
533 parts_
= url::Parsed();
535 canonicalized_url_
= GURL();
536 prevent_inline_autocomplete_
= false;
537 prefer_keyword_
= false;
538 allow_exact_keyword_match_
= false;
539 want_asynchronous_matches_
= true;
540 from_omnibox_focus_
= false;