1 // Copyright 2013 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/autofill/content/renderer/password_autofill_agent.h"
8 #include "base/memory/scoped_ptr.h"
9 #include "base/message_loop/message_loop.h"
10 #include "base/metrics/histogram.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "components/autofill/content/common/autofill_messages.h"
13 #include "components/autofill/content/renderer/form_autofill_util.h"
14 #include "components/autofill/content/renderer/password_form_conversion_utils.h"
15 #include "components/autofill/content/renderer/renderer_save_password_progress_logger.h"
16 #include "components/autofill/core/common/form_field_data.h"
17 #include "components/autofill/core/common/password_autofill_util.h"
18 #include "components/autofill/core/common/password_form.h"
19 #include "components/autofill/core/common/password_form_fill_data.h"
20 #include "content/public/renderer/document_state.h"
21 #include "content/public/renderer/navigation_state.h"
22 #include "content/public/renderer/render_view.h"
23 #include "third_party/WebKit/public/platform/WebVector.h"
24 #include "third_party/WebKit/public/web/WebAutofillClient.h"
25 #include "third_party/WebKit/public/web/WebDocument.h"
26 #include "third_party/WebKit/public/web/WebElement.h"
27 #include "third_party/WebKit/public/web/WebFormElement.h"
28 #include "third_party/WebKit/public/web/WebInputEvent.h"
29 #include "third_party/WebKit/public/web/WebLocalFrame.h"
30 #include "third_party/WebKit/public/web/WebNode.h"
31 #include "third_party/WebKit/public/web/WebNodeList.h"
32 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
33 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
34 #include "third_party/WebKit/public/web/WebView.h"
35 #include "ui/base/page_transition_types.h"
36 #include "ui/events/keycodes/keyboard_codes.h"
42 // The size above which we stop triggering autocomplete.
43 static const size_t kMaximumTextSizeForAutocomplete
= 1000;
45 // Maps element names to the actual elements to simplify form filling.
46 typedef std::map
<base::string16
, blink::WebInputElement
> FormInputElementMap
;
48 // Use the shorter name when referencing SavePasswordProgressLogger::StringID
49 // values to spare line breaks. The code provides enough context for that
51 typedef SavePasswordProgressLogger Logger
;
53 // Utility struct for form lookup and autofill. When we parse the DOM to look up
54 // a form, in addition to action and origin URL's we have to compare all
55 // necessary form elements. To avoid having to look these up again when we want
56 // to fill the form, the FindFormElements function stores the pointers
57 // in a FormElements* result, referenced to ensure they are safe to use.
59 blink::WebFormElement form_element
;
60 FormInputElementMap input_elements
;
63 typedef std::vector
<FormElements
*> FormElementsList
;
65 // Helper to search the given form element for the specified input elements
66 // in |data|, and add results to |result|.
67 static bool FindFormInputElements(blink::WebFormElement
* fe
,
69 FormElements
* result
) {
70 const bool username_is_present
= !data
.fields
[0].name
.empty();
72 // Loop through the list of elements we need to find on the form in order to
73 // autofill it. If we don't find any one of them, abort processing this
74 // form; it can't be the right one.
75 // First field is the username, skip it if not present.
76 for (size_t j
= (username_is_present
? 0 : 1); j
< data
.fields
.size(); ++j
) {
77 blink::WebVector
<blink::WebNode
> temp_elements
;
78 fe
->getNamedElements(data
.fields
[j
].name
, temp_elements
);
80 // Match the first input element, if any.
81 // |getNamedElements| may return non-input elements where the names match,
82 // so the results are filtered for input elements.
83 // If more than one match is made, then we have ambiguity (due to misuse
84 // of "name" attribute) so is it considered not found.
85 bool found_input
= false;
86 for (size_t i
= 0; i
< temp_elements
.size(); ++i
) {
87 if (temp_elements
[i
].to
<blink::WebElement
>().hasHTMLTagName("input")) {
88 // Check for a non-unique match.
94 // Only fill saved passwords into password fields and usernames into
96 blink::WebInputElement input_element
=
97 temp_elements
[i
].to
<blink::WebInputElement
>();
98 if (input_element
.isPasswordField() !=
99 (data
.fields
[j
].form_control_type
== "password"))
102 // This element matched, add it to our temporary result. It's possible
103 // there are multiple matches, but for purposes of identifying the form
104 // one suffices and if some function needs to deal with multiple
105 // matching elements it can get at them through the FormElement*.
106 // Note: This assignment adds a reference to the InputElement.
107 result
->input_elements
[data
.fields
[j
].name
] = input_element
;
112 // A required element was not found. This is not the right form.
113 // Make sure no input elements from a partially matched form in this
114 // iteration remain in the result set.
115 // Note: clear will remove a reference from each InputElement.
117 result
->input_elements
.clear();
124 // Helper to locate form elements identified by |data|.
125 void FindFormElements(blink::WebView
* view
,
126 const FormData
& data
,
127 FormElementsList
* results
) {
130 blink::WebFrame
* main_frame
= view
->mainFrame();
134 GURL::Replacements rep
;
138 // Loop through each frame.
139 for (blink::WebFrame
* f
= main_frame
; f
; f
= f
->traverseNext(false)) {
140 blink::WebDocument doc
= f
->document();
141 if (!doc
.isHTMLDocument())
144 GURL
full_origin(doc
.url());
145 if (data
.origin
!= full_origin
.ReplaceComponents(rep
))
148 blink::WebVector
<blink::WebFormElement
> forms
;
151 for (size_t i
= 0; i
< forms
.size(); ++i
) {
152 blink::WebFormElement fe
= forms
[i
];
154 GURL
full_action(f
->document().completeURL(fe
.action()));
155 if (full_action
.is_empty()) {
156 // The default action URL is the form's origin.
157 full_action
= full_origin
;
160 // Action URL must match.
161 if (data
.action
!= full_action
.ReplaceComponents(rep
))
164 scoped_ptr
<FormElements
> curr_elements(new FormElements
);
165 if (!FindFormInputElements(&fe
, data
, curr_elements
.get()))
168 // We found the right element.
169 // Note: this assignment adds a reference to |fe|.
170 curr_elements
->form_element
= fe
;
171 results
->push_back(curr_elements
.release());
176 bool IsElementEditable(const blink::WebInputElement
& element
) {
177 return element
.isEnabled() && !element
.isReadOnly();
180 bool DoUsernamesMatch(const base::string16
& username1
,
181 const base::string16
& username2
,
184 return username1
== username2
;
185 return StartsWith(username1
, username2
, true);
188 // Returns |true| if the given element is both editable and has permission to be
189 // autocompleted. The latter can be either because there is no
190 // autocomplete='off' set for the element, or because the flag is set to ignore
191 // autocomplete='off'. Otherwise, returns |false|.
192 bool IsElementAutocompletable(const blink::WebInputElement
& element
) {
193 return IsElementEditable(element
) &&
194 (ShouldIgnoreAutocompleteOffForPasswordFields() ||
195 element
.autoComplete());
198 // Returns true if the password specified in |form| is a default value.
199 bool PasswordValueIsDefault(const base::string16
& password_element
,
200 const base::string16
& password_value
,
201 blink::WebFormElement form_element
) {
202 blink::WebVector
<blink::WebNode
> temp_elements
;
203 form_element
.getNamedElements(password_element
, temp_elements
);
205 // We are loose in our definition here and will return true if any of the
206 // appropriately named elements match the element to be saved. Currently
207 // we ignore filling passwords where naming is ambigious anyway.
208 for (size_t i
= 0; i
< temp_elements
.size(); ++i
) {
209 if (temp_elements
[i
].to
<blink::WebElement
>().getAttribute("value") ==
216 // Return true if either password_value or new_password_value is not empty and
218 bool FormContainsNonDefaultPasswordValue(const PasswordForm
& password_form
,
219 blink::WebFormElement form_element
) {
220 return (!password_form
.password_value
.empty() &&
221 !PasswordValueIsDefault(password_form
.password_element
,
222 password_form
.password_value
,
224 (!password_form
.new_password_value
.empty() &&
225 !PasswordValueIsDefault(password_form
.new_password_element
,
226 password_form
.new_password_value
,
230 // Log a message including the name, method and action of |form|.
231 void LogHTMLForm(SavePasswordProgressLogger
* logger
,
232 SavePasswordProgressLogger::StringID message_id
,
233 const blink::WebFormElement
& form
) {
234 logger
->LogHTMLForm(message_id
,
236 GURL(form
.action().utf8()));
239 bool FillDataContainsUsername(const PasswordFormFillData
& fill_data
) {
240 return !fill_data
.basic_data
.fields
[0].name
.empty();
243 // This function attempts to fill |suggestions| and |realms| form |fill_data|
244 // based on |current_username|. Returns true when |suggestions| gets filled
245 // from |fill_data.other_possible_usernames|, else returns false.
246 bool GetSuggestions(const PasswordFormFillData
& fill_data
,
247 const base::string16
& current_username
,
248 std::vector
<base::string16
>* suggestions
,
249 std::vector
<base::string16
>* realms
,
251 bool other_possible_username_shown
= false;
254 fill_data
.basic_data
.fields
[0].value
, current_username
, false)) {
255 suggestions
->push_back(fill_data
.basic_data
.fields
[0].value
);
256 realms
->push_back(base::UTF8ToUTF16(fill_data
.preferred_realm
));
259 for (PasswordFormFillData::LoginCollection::const_iterator iter
=
260 fill_data
.additional_logins
.begin();
261 iter
!= fill_data
.additional_logins
.end();
263 if (show_all
|| StartsWith(iter
->first
, current_username
, false)) {
264 suggestions
->push_back(iter
->first
);
265 realms
->push_back(base::UTF8ToUTF16(iter
->second
.realm
));
269 for (PasswordFormFillData::UsernamesCollection::const_iterator iter
=
270 fill_data
.other_possible_usernames
.begin();
271 iter
!= fill_data
.other_possible_usernames
.end();
273 for (size_t i
= 0; i
< iter
->second
.size(); ++i
) {
274 if (show_all
|| StartsWith(iter
->second
[i
], current_username
, false)) {
275 other_possible_username_shown
= true;
276 suggestions
->push_back(iter
->second
[i
]);
277 realms
->push_back(base::UTF8ToUTF16(iter
->first
.realm
));
281 return other_possible_username_shown
;
284 // This function attempts to fill |username_element| and |password_element|
285 // with values from |fill_data|. The |password_element| will only have the
286 // |suggestedValue| set, and will be registered for copying that to the real
287 // value through |registration_callback|. The function returns true when
288 // selected username comes from |fill_data.other_possible_usernames|.
289 bool FillUserNameAndPassword(
290 blink::WebInputElement
* username_element
,
291 blink::WebInputElement
* password_element
,
292 const PasswordFormFillData
& fill_data
,
293 bool exact_username_match
,
295 base::Callback
<void(blink::WebInputElement
*)> registration_callback
) {
296 bool other_possible_username_selected
= false;
297 // Don't fill username if password can't be set.
298 if (!IsElementAutocompletable(*password_element
))
301 base::string16 current_username
;
302 if (!username_element
->isNull()) {
303 current_username
= username_element
->value();
306 // username and password will contain the match found if any.
307 base::string16 username
;
308 base::string16 password
;
310 // Look for any suitable matches to current field text.
311 if (DoUsernamesMatch(fill_data
.basic_data
.fields
[0].value
,
313 exact_username_match
)) {
314 username
= fill_data
.basic_data
.fields
[0].value
;
315 password
= fill_data
.basic_data
.fields
[1].value
;
317 // Scan additional logins for a match.
318 PasswordFormFillData::LoginCollection::const_iterator iter
;
319 for (iter
= fill_data
.additional_logins
.begin();
320 iter
!= fill_data
.additional_logins
.end();
322 if (DoUsernamesMatch(
323 iter
->first
, current_username
, exact_username_match
)) {
324 username
= iter
->first
;
325 password
= iter
->second
.password
;
330 // Check possible usernames.
331 if (username
.empty() && password
.empty()) {
332 for (PasswordFormFillData::UsernamesCollection::const_iterator iter
=
333 fill_data
.other_possible_usernames
.begin();
334 iter
!= fill_data
.other_possible_usernames
.end();
336 for (size_t i
= 0; i
< iter
->second
.size(); ++i
) {
337 if (DoUsernamesMatch(
338 iter
->second
[i
], current_username
, exact_username_match
)) {
339 other_possible_username_selected
= true;
340 username
= iter
->second
[i
];
341 password
= iter
->first
.password
;
345 if (!username
.empty() && !password
.empty())
350 if (password
.empty())
351 return other_possible_username_selected
; // No match was found.
353 // TODO(tkent): Check maxlength and pattern for both username and password
356 // Input matches the username, fill in required values.
357 if (!username_element
->isNull() &&
358 IsElementAutocompletable(*username_element
)) {
359 username_element
->setValue(username
, true);
360 username_element
->setAutofilled(true);
363 username_element
->setSelectionRange(current_username
.length(),
366 } else if (current_username
!= username
) {
367 // If the username can't be filled and it doesn't match a saved password
368 // as is, don't autofill a password.
369 return other_possible_username_selected
;
372 // Wait to fill in the password until a user gesture occurs. This is to make
373 // sure that we do not fill in the DOM with a password until we believe the
374 // user is intentionally interacting with the page.
375 password_element
->setSuggestedValue(password
);
376 registration_callback
.Run(password_element
);
378 password_element
->setAutofilled(true);
379 return other_possible_username_selected
;
382 // Attempts to fill |username_element| and |password_element| with the
383 // |fill_data|. Will use the data corresponding to the preferred username,
384 // unless the |username_element| already has a value set. In that case,
385 // attempts to fill the password matching the already filled username, if
386 // such a password exists. The |password_element| will have the
387 // |suggestedValue| set, and |suggestedValue| will be registered for copying to
388 // the real value through |registration_callback|. Returns true when the
389 // username gets selected from |other_possible_usernames|, else returns false.
390 bool FillFormOnPasswordRecieved(
391 const PasswordFormFillData
& fill_data
,
392 blink::WebInputElement username_element
,
393 blink::WebInputElement password_element
,
394 base::Callback
<void(blink::WebInputElement
*)> registration_callback
) {
395 // Do not fill if the password field is in an iframe.
396 DCHECK(password_element
.document().frame());
397 if (password_element
.document().frame()->parent())
400 bool form_contains_username_field
= FillDataContainsUsername(fill_data
);
401 if (!ShouldIgnoreAutocompleteOffForPasswordFields() &&
402 form_contains_username_field
&& !username_element
.form().autoComplete())
405 // If we can't modify the password, don't try to set the username
406 if (!IsElementAutocompletable(password_element
))
409 // Try to set the username to the preferred name, but only if the field
410 // can be set and isn't prefilled.
411 if (form_contains_username_field
&&
412 IsElementAutocompletable(username_element
) &&
413 username_element
.value().isEmpty()) {
414 // TODO(tkent): Check maxlength and pattern.
415 username_element
.setValue(fill_data
.basic_data
.fields
[0].value
, true);
418 // Fill if we have an exact match for the username. Note that this sets
419 // username to autofilled.
420 return FillUserNameAndPassword(&username_element
,
423 true /* exact_username_match */,
424 false /* set_selection */,
425 registration_callback
);
428 // Takes a |map| with pointers as keys and linked_ptr as values, and returns
429 // true if |key| is not NULL and |map| contains a non-NULL entry for |key|.
430 // Makes sure not to create an entry as a side effect of using the operator [].
431 template <class Key
, class Value
>
432 bool ContainsNonNullEntryForNonNullKey(
433 const std::map
<Key
*, linked_ptr
<Value
>>& map
,
437 auto it
= map
.find(key
);
438 return it
!= map
.end() && it
->second
.get();
443 ////////////////////////////////////////////////////////////////////////////////
444 // PasswordAutofillAgent, public:
446 PasswordAutofillAgent::PasswordAutofillAgent(content::RenderView
* render_view
)
447 : content::RenderViewObserver(render_view
),
448 usernames_usage_(NOTHING_TO_AUTOFILL
),
449 web_view_(render_view
->GetWebView()),
450 logging_state_active_(false),
451 was_username_autofilled_(false),
452 was_password_autofilled_(false),
453 username_selection_start_(0),
454 did_stop_loading_(false),
455 weak_ptr_factory_(this) {
456 Send(new AutofillHostMsg_PasswordAutofillAgentConstructed(routing_id()));
459 PasswordAutofillAgent::~PasswordAutofillAgent() {
462 PasswordAutofillAgent::PasswordValueGatekeeper::PasswordValueGatekeeper()
463 : was_user_gesture_seen_(false) {
466 PasswordAutofillAgent::PasswordValueGatekeeper::~PasswordValueGatekeeper() {
469 void PasswordAutofillAgent::PasswordValueGatekeeper::RegisterElement(
470 blink::WebInputElement
* element
) {
471 if (was_user_gesture_seen_
)
474 elements_
.push_back(*element
);
477 void PasswordAutofillAgent::PasswordValueGatekeeper::OnUserGesture() {
478 was_user_gesture_seen_
= true;
480 for (std::vector
<blink::WebInputElement
>::iterator it
= elements_
.begin();
481 it
!= elements_
.end();
489 void PasswordAutofillAgent::PasswordValueGatekeeper::Reset() {
490 was_user_gesture_seen_
= false;
494 void PasswordAutofillAgent::PasswordValueGatekeeper::ShowValue(
495 blink::WebInputElement
* element
) {
496 if (!element
->isNull() && !element
->suggestedValue().isEmpty())
497 element
->setValue(element
->suggestedValue(), true);
500 bool PasswordAutofillAgent::TextFieldDidEndEditing(
501 const blink::WebInputElement
& element
) {
502 LoginToPasswordInfoMap::const_iterator iter
=
503 login_to_password_info_
.find(element
);
504 if (iter
== login_to_password_info_
.end())
507 const PasswordInfo
& password_info
= iter
->second
;
508 // Don't let autofill overwrite an explicit change made by the user.
509 if (password_info
.password_was_edited_last
)
512 const PasswordFormFillData
& fill_data
= password_info
.fill_data
;
514 // If wait_for_username is false, we should have filled when the text changed.
515 if (!fill_data
.wait_for_username
)
518 blink::WebInputElement password
= password_info
.password_field
;
519 if (!IsElementEditable(password
))
522 blink::WebInputElement username
= element
; // We need a non-const.
524 // Do not set selection when ending an editing session, otherwise it can
526 if (FillUserNameAndPassword(
530 true /* exact_username_match */,
531 false /* set_selection */,
532 base::Bind(&PasswordValueGatekeeper::RegisterElement
,
533 base::Unretained(&gatekeeper_
)))) {
534 usernames_usage_
= OTHER_POSSIBLE_USERNAME_SELECTED
;
539 bool PasswordAutofillAgent::TextDidChangeInTextField(
540 const blink::WebInputElement
& element
) {
541 // TODO(vabr): Get a mutable argument instead. http://crbug.com/397083
542 blink::WebInputElement mutable_element
= element
; // We need a non-const.
544 if (element
.isPasswordField()) {
545 // Some login forms have event handlers that put a hash of the password into
546 // a hidden field and then clear the password (http://crbug.com/28910,
547 // http://crbug.com/391693). This method gets called before any of those
548 // handlers run, so save away a copy of the password in case it gets lost.
549 // To honor the user having explicitly cleared the password, even an empty
550 // password will be saved here.
551 if (blink::WebLocalFrame
* element_frame
= element
.document().frame()) {
552 ProvisionallySavePassword(
553 element_frame
, element
.form(), RESTRICTION_NONE
);
556 PasswordToLoginMap::iterator iter
= password_to_username_
.find(element
);
557 if (iter
!= password_to_username_
.end()) {
558 login_to_password_info_
[iter
->second
].password_was_edited_last
= true;
559 // Note that the suggested value of |mutable_element| was reset when its
561 mutable_element
.setAutofilled(false);
566 LoginToPasswordInfoMap::iterator iter
= login_to_password_info_
.find(element
);
567 if (iter
== login_to_password_info_
.end())
570 // The input text is being changed, so any autofilled password is now
572 mutable_element
.setAutofilled(false);
573 iter
->second
.password_was_edited_last
= false;
575 blink::WebInputElement password
= iter
->second
.password_field
;
576 if (password
.isAutofilled()) {
577 password
.setValue(base::string16(), true);
578 password
.setAutofilled(false);
581 // If wait_for_username is true we will fill when the username loses focus.
582 if (iter
->second
.fill_data
.wait_for_username
)
585 if (!element
.isText() || !IsElementAutocompletable(element
) ||
586 !IsElementAutocompletable(password
)) {
590 // Don't inline autocomplete if the user is deleting, that would be confusing.
591 // But refresh the popup. Note, since this is ours, return true to signal
592 // no further processing is required.
593 if (iter
->second
.backspace_pressed_last
) {
594 ShowSuggestionPopup(iter
->second
.fill_data
, element
, false);
598 blink::WebString name
= element
.nameForAutofill();
600 return false; // If the field has no name, then we won't have values.
602 // Don't attempt to autofill with values that are too large.
603 if (element
.value().length() > kMaximumTextSizeForAutocomplete
)
606 // The caret position should have already been updated.
607 PerformInlineAutocomplete(element
, password
, iter
->second
.fill_data
);
611 bool PasswordAutofillAgent::TextFieldHandlingKeyDown(
612 const blink::WebInputElement
& element
,
613 const blink::WebKeyboardEvent
& event
) {
614 // If using the new Autofill UI that lives in the browser, it will handle
615 // keypresses before this function. This is not currently an issue but if
616 // the keys handled there or here change, this issue may appear.
618 LoginToPasswordInfoMap::iterator iter
= login_to_password_info_
.find(element
);
619 if (iter
== login_to_password_info_
.end())
622 int win_key_code
= event
.windowsKeyCode
;
623 iter
->second
.backspace_pressed_last
=
624 (win_key_code
== ui::VKEY_BACK
|| win_key_code
== ui::VKEY_DELETE
);
628 bool PasswordAutofillAgent::FillSuggestion(
629 const blink::WebNode
& node
,
630 const blink::WebString
& username
,
631 const blink::WebString
& password
) {
632 blink::WebInputElement username_element
;
633 PasswordInfo
* password_info
;
635 if (!FindLoginInfo(node
, &username_element
, &password_info
) ||
636 !IsElementAutocompletable(username_element
) ||
637 !IsElementAutocompletable(password_info
->password_field
)) {
641 password_info
->password_was_edited_last
= false;
642 username_element
.setValue(username
, true);
643 username_element
.setAutofilled(true);
644 username_element
.setSelectionRange(username
.length(), username
.length());
646 password_info
->password_field
.setValue(password
, true);
647 password_info
->password_field
.setAutofilled(true);
652 bool PasswordAutofillAgent::PreviewSuggestion(
653 const blink::WebNode
& node
,
654 const blink::WebString
& username
,
655 const blink::WebString
& password
) {
656 blink::WebInputElement username_element
;
657 PasswordInfo
* password_info
;
659 if (!FindLoginInfo(node
, &username_element
, &password_info
) ||
660 !IsElementAutocompletable(username_element
) ||
661 !IsElementAutocompletable(password_info
->password_field
)) {
665 was_username_autofilled_
= username_element
.isAutofilled();
666 username_selection_start_
= username_element
.selectionStart();
667 username_element
.setSuggestedValue(username
);
668 username_element
.setAutofilled(true);
669 username_element
.setSelectionRange(
670 username_selection_start_
,
671 username_element
.suggestedValue().length());
673 was_password_autofilled_
= password_info
->password_field
.isAutofilled();
674 password_info
->password_field
.setSuggestedValue(password
);
675 password_info
->password_field
.setAutofilled(true);
680 bool PasswordAutofillAgent::DidClearAutofillSelection(
681 const blink::WebNode
& node
) {
682 blink::WebInputElement username_element
;
683 PasswordInfo
* password_info
;
684 if (!FindLoginInfo(node
, &username_element
, &password_info
))
687 ClearPreview(&username_element
, &password_info
->password_field
);
691 bool PasswordAutofillAgent::ShowSuggestions(
692 const blink::WebInputElement
& element
,
694 LoginToPasswordInfoMap::const_iterator iter
=
695 login_to_password_info_
.find(element
);
696 if (iter
== login_to_password_info_
.end())
699 // If autocomplete='off' is set on the form elements, no suggestion dialog
700 // should be shown. However, return |true| to indicate that this is a known
701 // password form and that the request to show suggestions has been handled (as
703 if (!IsElementAutocompletable(element
) ||
704 !IsElementAutocompletable(iter
->second
.password_field
))
707 return ShowSuggestionPopup(iter
->second
.fill_data
, element
, show_all
);
710 bool PasswordAutofillAgent::OriginCanAccessPasswordManager(
711 const blink::WebSecurityOrigin
& origin
) {
712 return origin
.canAccessPasswordManager();
715 void PasswordAutofillAgent::OnDynamicFormsSeen(blink::WebFrame
* frame
) {
716 SendPasswordForms(frame
, false /* only_visible */);
719 void PasswordAutofillAgent::FirstUserGestureObserved() {
720 gatekeeper_
.OnUserGesture();
723 void PasswordAutofillAgent::SendPasswordForms(blink::WebFrame
* frame
,
725 scoped_ptr
<RendererSavePasswordProgressLogger
> logger
;
726 if (logging_state_active_
) {
727 logger
.reset(new RendererSavePasswordProgressLogger(this, routing_id()));
728 logger
->LogMessage(Logger::STRING_SEND_PASSWORD_FORMS_METHOD
);
729 logger
->LogBoolean(Logger::STRING_ONLY_VISIBLE
, only_visible
);
732 // Make sure that this security origin is allowed to use password manager.
733 blink::WebSecurityOrigin origin
= frame
->document().securityOrigin();
735 logger
->LogURL(Logger::STRING_SECURITY_ORIGIN
,
736 GURL(origin
.toString().utf8()));
738 if (!OriginCanAccessPasswordManager(origin
)) {
740 logger
->LogMessage(Logger::STRING_SECURITY_ORIGIN_FAILURE
);
741 logger
->LogMessage(Logger::STRING_DECISION_DROP
);
746 // Checks whether the webpage is a redirect page or an empty page.
747 if (IsWebpageEmpty(frame
)) {
749 logger
->LogMessage(Logger::STRING_WEBPAGE_EMPTY
);
750 logger
->LogMessage(Logger::STRING_DECISION_DROP
);
755 blink::WebVector
<blink::WebFormElement
> forms
;
756 frame
->document().forms(forms
);
758 logger
->LogNumber(Logger::STRING_NUMBER_OF_ALL_FORMS
, forms
.size());
760 std::vector
<PasswordForm
> password_forms
;
761 for (size_t i
= 0; i
< forms
.size(); ++i
) {
762 const blink::WebFormElement
& form
= forms
[i
];
763 bool is_form_visible
= IsWebNodeVisible(form
);
765 LogHTMLForm(logger
.get(), Logger::STRING_FORM_FOUND_ON_PAGE
, form
);
766 logger
->LogBoolean(Logger::STRING_FORM_IS_VISIBLE
, is_form_visible
);
769 // If requested, ignore non-rendered forms, e.g. those styled with
771 if (only_visible
&& !is_form_visible
)
774 scoped_ptr
<PasswordForm
> password_form(CreatePasswordForm(form
));
775 if (password_form
.get()) {
777 logger
->LogPasswordForm(Logger::STRING_FORM_IS_PASSWORD
,
780 password_forms
.push_back(*password_form
);
784 if (password_forms
.empty() && !only_visible
) {
785 // We need to send the PasswordFormsRendered message regardless of whether
786 // there are any forms visible, as this is also the code path that triggers
787 // showing the infobar.
792 Send(new AutofillHostMsg_PasswordFormsRendered(routing_id(),
796 Send(new AutofillHostMsg_PasswordFormsParsed(routing_id(), password_forms
));
800 bool PasswordAutofillAgent::OnMessageReceived(const IPC::Message
& message
) {
802 IPC_BEGIN_MESSAGE_MAP(PasswordAutofillAgent
, message
)
803 IPC_MESSAGE_HANDLER(AutofillMsg_FillPasswordForm
, OnFillPasswordForm
)
804 IPC_MESSAGE_HANDLER(AutofillMsg_SetLoggingState
, OnSetLoggingState
)
805 IPC_MESSAGE_UNHANDLED(handled
= false)
806 IPC_END_MESSAGE_MAP()
810 void PasswordAutofillAgent::DidStartLoading() {
811 did_stop_loading_
= false;
812 if (usernames_usage_
!= NOTHING_TO_AUTOFILL
) {
813 UMA_HISTOGRAM_ENUMERATION("PasswordManager.OtherPossibleUsernamesUsage",
815 OTHER_POSSIBLE_USERNAMES_MAX
);
816 usernames_usage_
= NOTHING_TO_AUTOFILL
;
820 void PasswordAutofillAgent::DidFinishDocumentLoad(blink::WebLocalFrame
* frame
) {
821 // The |frame| contents have been parsed, but not yet rendered. Let the
822 // PasswordManager know that forms are loaded, even though we can't yet tell
823 // whether they're visible.
824 SendPasswordForms(frame
, false);
827 void PasswordAutofillAgent::DidFinishLoad(blink::WebLocalFrame
* frame
) {
828 // The |frame| contents have been rendered. Let the PasswordManager know
829 // which of the loaded frames are actually visible to the user. This also
830 // triggers the "Save password?" infobar if the user just submitted a password
832 SendPasswordForms(frame
, true);
835 void PasswordAutofillAgent::DidStopLoading() {
836 did_stop_loading_
= true;
839 void PasswordAutofillAgent::FrameDetached(blink::WebFrame
* frame
) {
843 void PasswordAutofillAgent::FrameWillClose(blink::WebFrame
* frame
) {
847 void PasswordAutofillAgent::WillSendSubmitEvent(
848 blink::WebLocalFrame
* frame
,
849 const blink::WebFormElement
& form
) {
850 // Forms submitted via XHR are not seen by WillSubmitForm if the default
851 // onsubmit handler is overridden. Such submission first gets detected in
852 // DidStartProvisionalLoad, which no longer knows about the particular form,
853 // and uses the candidate stored in |provisionally_saved_forms_|.
855 // User-typed password will get stored to |provisionally_saved_forms_| in
856 // TextDidChangeInTextField. Autofilled or JavaScript-copied passwords need to
859 // Only non-empty passwords are saved here. Empty passwords were likely
860 // cleared by some scripts (http://crbug.com/28910, http://crbug.com/391693).
861 // Had the user cleared the password, |provisionally_saved_forms_| would
862 // already have been updated in TextDidChangeInTextField.
863 ProvisionallySavePassword(frame
, form
, RESTRICTION_NON_EMPTY_PASSWORD
);
866 void PasswordAutofillAgent::WillSubmitForm(blink::WebLocalFrame
* frame
,
867 const blink::WebFormElement
& form
) {
869 scoped_ptr
<RendererSavePasswordProgressLogger
> logger
;
870 if (logging_state_active_
) {
871 logger
.reset(new RendererSavePasswordProgressLogger(this, routing_id()));
872 logger
->LogMessage(Logger::STRING_WILL_SUBMIT_FORM_METHOD
);
873 LogHTMLForm(logger
.get(), Logger::STRING_HTML_FORM_FOR_SUBMIT
, form
);
876 scoped_ptr
<PasswordForm
> submitted_form
= CreatePasswordForm(form
);
878 // If there is a provisionally saved password, copy over the previous
879 // password value so we get the user's typed password, not the value that
880 // may have been transformed for submit.
881 // TODO(gcasto): Do we need to have this action equality check? Is it trying
882 // to prevent accidentally copying over passwords from a different form?
883 if (submitted_form
) {
885 logger
->LogPasswordForm(Logger::STRING_CREATED_PASSWORD_FORM
,
888 if (ContainsNonNullEntryForNonNullKey(
889 provisionally_saved_forms_
, static_cast<blink::WebFrame
*>(frame
)) &&
890 submitted_form
->action
== provisionally_saved_forms_
[frame
]->action
) {
892 logger
->LogMessage(Logger::STRING_SUBMITTED_PASSWORD_REPLACED
);
893 submitted_form
->password_value
=
894 provisionally_saved_forms_
[frame
]->password_value
;
895 submitted_form
->new_password_value
=
896 provisionally_saved_forms_
[frame
]->new_password_value
;
899 // Some observers depend on sending this information now instead of when
900 // the frame starts loading. If there are redirects that cause a new
901 // RenderView to be instantiated (such as redirects to the WebStore)
902 // we will never get to finish the load.
903 Send(new AutofillHostMsg_PasswordFormSubmitted(routing_id(),
905 // Remove reference since we have already submitted this form.
906 provisionally_saved_forms_
.erase(frame
);
908 logger
->LogMessage(Logger::STRING_DECISION_DROP
);
912 blink::WebFrame
* PasswordAutofillAgent::CurrentOrChildFrameWithSavedForms(
913 const blink::WebFrame
* current_frame
) {
914 for (FrameToPasswordFormMap::const_iterator it
=
915 provisionally_saved_forms_
.begin();
916 it
!= provisionally_saved_forms_
.end();
918 blink::WebFrame
* form_frame
= it
->first
;
919 // The check that the returned frame is related to |current_frame| is mainly
920 // for double-checking. There should not be any unrelated frames in
921 // |provisionally_saved_forms_|, because the map is cleared after
922 // navigation. If there are reasons to remove this check in the future and
923 // keep just the first frame found, it might be a good idea to add a UMA
924 // statistic or a similar check on how many frames are here to choose from.
925 if (current_frame
== form_frame
||
926 current_frame
->findChildByName(form_frame
->assignedName())) {
933 void PasswordAutofillAgent::DidStartProvisionalLoad(
934 blink::WebLocalFrame
* frame
) {
935 scoped_ptr
<RendererSavePasswordProgressLogger
> logger
;
936 if (logging_state_active_
) {
937 logger
.reset(new RendererSavePasswordProgressLogger(this, routing_id()));
938 logger
->LogMessage(Logger::STRING_DID_START_PROVISIONAL_LOAD_METHOD
);
941 if (!frame
->parent()) {
942 // If the navigation is not triggered by a user gesture, e.g. by some ajax
943 // callback, then inherit the submitted password form from the previous
944 // state. This fixes the no password save issue for ajax login, tracked in
945 // [http://crbug/43219]. Note that this still fails for sites that use
946 // synchonous XHR as isProcessingUserGesture() will return true.
947 blink::WebFrame
* form_frame
= CurrentOrChildFrameWithSavedForms(frame
);
949 logger
->LogBoolean(Logger::STRING_FORM_FRAME_EQ_FRAME
,
950 form_frame
== frame
);
952 // Bug fix for crbug.com/368690. isProcessingUserGesture() is false when
953 // the user is performing actions outside the page (e.g. typed url,
954 // history navigation). We don't want to trigger saving in these cases.
955 content::DocumentState
* document_state
=
956 content::DocumentState::FromDataSource(
957 frame
->provisionalDataSource());
958 content::NavigationState
* navigation_state
=
959 document_state
->navigation_state();
960 if (ui::PageTransitionIsWebTriggerable(
961 navigation_state
->transition_type()) &&
962 !blink::WebUserGestureIndicator::isProcessingUserGesture()) {
963 // If onsubmit has been called, try and save that form.
964 if (ContainsNonNullEntryForNonNullKey(provisionally_saved_forms_
,
967 logger
->LogPasswordForm(
968 Logger::STRING_PROVISIONALLY_SAVED_FORM_FOR_FRAME
,
969 *provisionally_saved_forms_
[form_frame
]);
971 Send(new AutofillHostMsg_PasswordFormSubmitted(
972 routing_id(), *provisionally_saved_forms_
[form_frame
]));
973 provisionally_saved_forms_
.erase(form_frame
);
975 // Loop through the forms on the page looking for one that has been
976 // filled out. If one exists, try and save the credentials.
977 blink::WebVector
<blink::WebFormElement
> forms
;
978 frame
->document().forms(forms
);
980 bool password_forms_found
= false;
981 for (size_t i
= 0; i
< forms
.size(); ++i
) {
982 blink::WebFormElement form_element
= forms
[i
];
985 logger
.get(), Logger::STRING_FORM_FOUND_ON_PAGE
, form_element
);
987 scoped_ptr
<PasswordForm
> password_form(
988 CreatePasswordForm(form_element
));
989 if (password_form
.get() && !password_form
->username_value
.empty() &&
990 FormContainsNonDefaultPasswordValue(
991 *password_form
, form_element
)) {
992 password_forms_found
= true;
994 logger
->LogPasswordForm(
995 Logger::STRING_PASSWORD_FORM_FOUND_ON_PAGE
, *password_form
);
997 Send(new AutofillHostMsg_PasswordFormSubmitted(routing_id(),
1001 if (!password_forms_found
&& logger
) {
1002 logger
->LogMessage(Logger::STRING_DECISION_DROP
);
1006 // Clear the whole map during main frame navigation.
1007 provisionally_saved_forms_
.clear();
1009 // This is a new navigation, so require a new user gesture before filling in
1011 gatekeeper_
.Reset();
1014 logger
->LogMessage(Logger::STRING_DECISION_DROP
);
1018 void PasswordAutofillAgent::OnFillPasswordForm(
1019 const PasswordFormFillData
& form_data
) {
1020 if (usernames_usage_
== NOTHING_TO_AUTOFILL
) {
1021 if (form_data
.other_possible_usernames
.size())
1022 usernames_usage_
= OTHER_POSSIBLE_USERNAMES_PRESENT
;
1023 else if (usernames_usage_
== NOTHING_TO_AUTOFILL
)
1024 usernames_usage_
= OTHER_POSSIBLE_USERNAMES_ABSENT
;
1027 FormElementsList forms
;
1028 // We own the FormElements* in forms.
1029 FindFormElements(render_view()->GetWebView(), form_data
.basic_data
, &forms
);
1030 FormElementsList::iterator iter
;
1031 for (iter
= forms
.begin(); iter
!= forms
.end(); ++iter
) {
1032 scoped_ptr
<FormElements
> form_elements(*iter
);
1034 // Attach autocomplete listener to enable selecting alternate logins.
1035 blink::WebInputElement username_element
, password_element
;
1037 // Check whether the password form has a username input field.
1038 bool form_contains_username_field
= FillDataContainsUsername(form_data
);
1039 if (form_contains_username_field
) {
1041 form_elements
->input_elements
[form_data
.basic_data
.fields
[0].name
];
1044 // No password field, bail out.
1045 if (form_data
.basic_data
.fields
[1].name
.empty())
1048 // Get pointer to password element. (We currently only support single
1051 form_elements
->input_elements
[form_data
.basic_data
.fields
[1].name
];
1053 // If wait_for_username is true, we don't want to initially fill the form
1054 // until the user types in a valid username.
1055 if (!form_data
.wait_for_username
&&
1056 FillFormOnPasswordRecieved(
1060 base::Bind(&PasswordValueGatekeeper::RegisterElement
,
1061 base::Unretained(&gatekeeper_
)))) {
1062 usernames_usage_
= OTHER_POSSIBLE_USERNAME_SELECTED
;
1064 // We might have already filled this form if there are two <form> elements
1065 // with identical markup.
1066 if (login_to_password_info_
.find(username_element
) !=
1067 login_to_password_info_
.end())
1070 PasswordInfo password_info
;
1071 password_info
.fill_data
= form_data
;
1072 password_info
.password_field
= password_element
;
1073 login_to_password_info_
[username_element
] = password_info
;
1074 password_to_username_
[password_element
] = username_element
;
1077 FormFieldData field
;
1078 if (form_contains_username_field
) {
1079 FindFormAndFieldForFormControlElement(
1080 username_element
, &form
, &field
, REQUIRE_NONE
);
1083 Send(new AutofillHostMsg_AddPasswordFormMapping(
1084 routing_id(), field
, form_data
));
1088 void PasswordAutofillAgent::OnSetLoggingState(bool active
) {
1089 logging_state_active_
= active
;
1092 ////////////////////////////////////////////////////////////////////////////////
1093 // PasswordAutofillAgent, private:
1095 PasswordAutofillAgent::PasswordInfo::PasswordInfo()
1096 : backspace_pressed_last(false), password_was_edited_last(false) {
1099 bool PasswordAutofillAgent::ShowSuggestionPopup(
1100 const PasswordFormFillData
& fill_data
,
1101 const blink::WebInputElement
& user_input
,
1103 blink::WebFrame
* frame
= user_input
.document().frame();
1107 blink::WebView
* webview
= frame
->view();
1111 std::vector
<base::string16
> suggestions
;
1112 std::vector
<base::string16
> realms
;
1114 fill_data
, user_input
.value(), &suggestions
, &realms
, show_all
)) {
1115 usernames_usage_
= OTHER_POSSIBLE_USERNAME_SHOWN
;
1118 DCHECK_EQ(suggestions
.size(), realms
.size());
1121 FormFieldData field
;
1122 FindFormAndFieldForFormControlElement(
1123 user_input
, &form
, &field
, REQUIRE_NONE
);
1125 blink::WebInputElement selected_element
= user_input
;
1126 gfx::Rect
bounding_box(selected_element
.boundsInViewportSpace());
1128 float scale
= web_view_
->pageScaleFactor();
1129 gfx::RectF
bounding_box_scaled(bounding_box
.x() * scale
,
1130 bounding_box
.y() * scale
,
1131 bounding_box
.width() * scale
,
1132 bounding_box
.height() * scale
);
1133 Send(new AutofillHostMsg_ShowPasswordSuggestions(
1134 routing_id(), field
, bounding_box_scaled
, suggestions
, realms
));
1135 return !suggestions
.empty();
1138 void PasswordAutofillAgent::PerformInlineAutocomplete(
1139 const blink::WebInputElement
& username_input
,
1140 const blink::WebInputElement
& password_input
,
1141 const PasswordFormFillData
& fill_data
) {
1142 DCHECK(!fill_data
.wait_for_username
);
1144 // We need non-const versions of the username and password inputs.
1145 blink::WebInputElement username
= username_input
;
1146 blink::WebInputElement password
= password_input
;
1148 // Don't inline autocomplete if the caret is not at the end.
1149 // TODO(jcivelli): is there a better way to test the caret location?
1150 if (username
.selectionStart() != username
.selectionEnd() ||
1151 username
.selectionEnd() != static_cast<int>(username
.value().length())) {
1155 // Show the popup with the list of available usernames.
1156 ShowSuggestionPopup(fill_data
, username
, false);
1158 #if !defined(OS_ANDROID)
1159 // Fill the user and password field with the most relevant match. Android
1160 // only fills in the fields after the user clicks on the suggestion popup.
1161 if (FillUserNameAndPassword(
1165 false /* exact_username_match */,
1166 true /* set_selection */,
1167 base::Bind(&PasswordValueGatekeeper::RegisterElement
,
1168 base::Unretained(&gatekeeper_
)))) {
1169 usernames_usage_
= OTHER_POSSIBLE_USERNAME_SELECTED
;
1174 void PasswordAutofillAgent::FrameClosing(const blink::WebFrame
* frame
) {
1175 for (LoginToPasswordInfoMap::iterator iter
= login_to_password_info_
.begin();
1176 iter
!= login_to_password_info_
.end();) {
1177 // There may not be a username field, so get the frame from the password
1179 if (iter
->second
.password_field
.document().frame() == frame
) {
1180 password_to_username_
.erase(iter
->second
.password_field
);
1181 login_to_password_info_
.erase(iter
++);
1186 for (FrameToPasswordFormMap::iterator iter
=
1187 provisionally_saved_forms_
.begin();
1188 iter
!= provisionally_saved_forms_
.end();) {
1189 if (iter
->first
== frame
)
1190 provisionally_saved_forms_
.erase(iter
++);
1196 bool PasswordAutofillAgent::FindLoginInfo(const blink::WebNode
& node
,
1197 blink::WebInputElement
* found_input
,
1198 PasswordInfo
** found_password
) {
1199 if (!node
.isElementNode())
1202 blink::WebElement element
= node
.toConst
<blink::WebElement
>();
1203 if (!element
.hasHTMLTagName("input"))
1206 blink::WebInputElement input
= element
.to
<blink::WebInputElement
>();
1207 LoginToPasswordInfoMap::iterator iter
= login_to_password_info_
.find(input
);
1208 if (iter
== login_to_password_info_
.end())
1211 *found_input
= input
;
1212 *found_password
= &iter
->second
;
1216 void PasswordAutofillAgent::ClearPreview(
1217 blink::WebInputElement
* username
,
1218 blink::WebInputElement
* password
) {
1219 if (!username
->suggestedValue().isEmpty()) {
1220 username
->setSuggestedValue(blink::WebString());
1221 username
->setAutofilled(was_username_autofilled_
);
1222 username
->setSelectionRange(username_selection_start_
,
1223 username
->value().length());
1225 if (!password
->suggestedValue().isEmpty()) {
1226 password
->setSuggestedValue(blink::WebString());
1227 password
->setAutofilled(was_password_autofilled_
);
1231 void PasswordAutofillAgent::ProvisionallySavePassword(
1232 blink::WebLocalFrame
* frame
,
1233 const blink::WebFormElement
& form
,
1234 ProvisionallySaveRestriction restriction
) {
1235 // TODO(vabr): This is just to stop getting a NULL frame in
1236 // |provisionally_saved_forms_|. Cases where we try to save password for a
1237 // form in a NULL frame should not happen, and it's currently unclear how they
1238 // happen (http://crbug.com/420519). This thing will be hopefully solved by
1239 // migrating the PasswordAutofillAgent to observe frames directly
1240 // (http://crbug.com/400186).
1243 scoped_ptr
<PasswordForm
> password_form(CreatePasswordForm(form
));
1244 if (!password_form
|| (restriction
== RESTRICTION_NON_EMPTY_PASSWORD
&&
1245 password_form
->password_value
.empty() &&
1246 password_form
->new_password_value
.empty())) {
1249 provisionally_saved_forms_
[frame
].reset(password_form
.release());
1252 } // namespace autofill