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_form.h"
18 #include "components/autofill/core/common/password_form_fill_data.h"
19 #include "content/public/renderer/document_state.h"
20 #include "content/public/renderer/navigation_state.h"
21 #include "content/public/renderer/render_view.h"
22 #include "third_party/WebKit/public/platform/WebVector.h"
23 #include "third_party/WebKit/public/web/WebAutofillClient.h"
24 #include "third_party/WebKit/public/web/WebDocument.h"
25 #include "third_party/WebKit/public/web/WebElement.h"
26 #include "third_party/WebKit/public/web/WebFormElement.h"
27 #include "third_party/WebKit/public/web/WebInputEvent.h"
28 #include "third_party/WebKit/public/web/WebLocalFrame.h"
29 #include "third_party/WebKit/public/web/WebNode.h"
30 #include "third_party/WebKit/public/web/WebNodeList.h"
31 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
32 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
33 #include "third_party/WebKit/public/web/WebView.h"
34 #include "ui/base/page_transition_types.h"
35 #include "ui/events/keycodes/keyboard_codes.h"
41 // The size above which we stop triggering autocomplete.
42 static const size_t kMaximumTextSizeForAutocomplete
= 1000;
44 // Maps element names to the actual elements to simplify form filling.
45 typedef std::map
<base::string16
, blink::WebInputElement
> FormInputElementMap
;
47 // Use the shorter name when referencing SavePasswordProgressLogger::StringID
48 // values to spare line breaks. The code provides enough context for that
50 typedef SavePasswordProgressLogger Logger
;
52 // Utility struct for form lookup and autofill. When we parse the DOM to look up
53 // a form, in addition to action and origin URL's we have to compare all
54 // necessary form elements. To avoid having to look these up again when we want
55 // to fill the form, the FindFormElements function stores the pointers
56 // in a FormElements* result, referenced to ensure they are safe to use.
58 blink::WebFormElement form_element
;
59 FormInputElementMap input_elements
;
62 typedef std::vector
<FormElements
*> FormElementsList
;
64 // Utility function to find the unique entry of the |form_element| for the
65 // specified input |field|. On successful find, adds it to |result| and returns
66 // |true|. Otherwise clears the references from each |HTMLInputElement| from
67 // |result| and returns |false|.
68 bool FindFormInputElement(blink::WebFormElement
* form_element
,
69 const FormFieldData
& field
,
70 FormElements
* result
) {
71 blink::WebVector
<blink::WebNode
> temp_elements
;
72 form_element
->getNamedElements(field
.name
, temp_elements
);
74 // Match the first input element, if any.
75 // |getNamedElements| may return non-input elements where the names match,
76 // so the results are filtered for input elements.
77 // If more than one match is made, then we have ambiguity (due to misuse
78 // of "name" attribute) so is it considered not found.
79 bool found_input
= false;
80 for (size_t i
= 0; i
< temp_elements
.size(); ++i
) {
81 if (temp_elements
[i
].to
<blink::WebElement
>().hasHTMLTagName("input")) {
82 // Check for a non-unique match.
88 // Only fill saved passwords into password fields and usernames into
90 blink::WebInputElement input_element
=
91 temp_elements
[i
].to
<blink::WebInputElement
>();
92 if (input_element
.isPasswordField() !=
93 (field
.form_control_type
== "password"))
96 // This element matched, add it to our temporary result. It's possible
97 // there are multiple matches, but for purposes of identifying the form
98 // one suffices and if some function needs to deal with multiple
99 // matching elements it can get at them through the FormElement*.
100 // Note: This assignment adds a reference to the InputElement.
101 result
->input_elements
[field
.name
] = input_element
;
106 // A required element was not found. This is not the right form.
107 // Make sure no input elements from a partially matched form in this
108 // iteration remain in the result set.
109 // Note: clear will remove a reference from each InputElement.
111 result
->input_elements
.clear();
118 // Helper to search the given form element for the specified input elements in
119 // |data|, and add results to |result|.
120 bool FindFormInputElements(blink::WebFormElement
* form_element
,
121 const FormData
& data
,
122 FormElements
* result
) {
123 const bool username_is_present
= !data
.fields
[0].name
.empty();
125 // Loop through the list of elements we need to find on the form in order to
126 // autofill it. If we don't find any one of them, abort processing this
127 // form; it can't be the right one.
128 // First field is the username, skip it if not present.
129 for (size_t j
= (username_is_present
? 0 : 1); j
< data
.fields
.size(); ++j
) {
130 if (!FindFormInputElement(form_element
, data
.fields
[j
], result
))
137 // Helper to locate form elements identified by |data|.
138 void FindFormElements(blink::WebView
* view
,
139 const FormData
& data
,
140 FormElementsList
* results
) {
143 blink::WebFrame
* main_frame
= view
->mainFrame();
147 GURL::Replacements rep
;
151 // Loop through each frame.
152 for (blink::WebFrame
* f
= main_frame
; f
; f
= f
->traverseNext(false)) {
153 blink::WebDocument doc
= f
->document();
154 if (!doc
.isHTMLDocument())
157 GURL
full_origin(doc
.url());
158 if (data
.origin
!= full_origin
.ReplaceComponents(rep
))
161 blink::WebVector
<blink::WebFormElement
> forms
;
164 for (size_t i
= 0; i
< forms
.size(); ++i
) {
165 blink::WebFormElement fe
= forms
[i
];
167 GURL
full_action(f
->document().completeURL(fe
.action()));
168 if (full_action
.is_empty()) {
169 // The default action URL is the form's origin.
170 full_action
= full_origin
;
173 // Action URL must match.
174 if (data
.action
!= full_action
.ReplaceComponents(rep
))
177 scoped_ptr
<FormElements
> curr_elements(new FormElements
);
178 if (!FindFormInputElements(&fe
, data
, curr_elements
.get()))
181 // We found the right element.
182 // Note: this assignment adds a reference to |fe|.
183 curr_elements
->form_element
= fe
;
184 results
->push_back(curr_elements
.release());
189 bool IsElementEditable(const blink::WebInputElement
& element
) {
190 return element
.isEnabled() && !element
.isReadOnly();
193 bool DoUsernamesMatch(const base::string16
& username1
,
194 const base::string16
& username2
,
197 return username1
== username2
;
198 return StartsWith(username1
, username2
, true);
201 // Returns |true| if the given element is editable. Otherwise, returns |false|.
202 bool IsElementAutocompletable(const blink::WebInputElement
& element
) {
203 return IsElementEditable(element
);
206 // Returns true if the password specified in |form| is a default value.
207 bool PasswordValueIsDefault(const base::string16
& password_element
,
208 const base::string16
& password_value
,
209 blink::WebFormElement form_element
) {
210 blink::WebVector
<blink::WebNode
> temp_elements
;
211 form_element
.getNamedElements(password_element
, temp_elements
);
213 // We are loose in our definition here and will return true if any of the
214 // appropriately named elements match the element to be saved. Currently
215 // we ignore filling passwords where naming is ambigious anyway.
216 for (size_t i
= 0; i
< temp_elements
.size(); ++i
) {
217 if (temp_elements
[i
].to
<blink::WebElement
>().getAttribute("value") ==
224 // Return true if either password_value or new_password_value is not empty and
226 bool FormContainsNonDefaultPasswordValue(const PasswordForm
& password_form
,
227 blink::WebFormElement form_element
) {
228 return (!password_form
.password_value
.empty() &&
229 !PasswordValueIsDefault(password_form
.password_element
,
230 password_form
.password_value
,
232 (!password_form
.new_password_value
.empty() &&
233 !PasswordValueIsDefault(password_form
.new_password_element
,
234 password_form
.new_password_value
,
238 // Log a message including the name, method and action of |form|.
239 void LogHTMLForm(SavePasswordProgressLogger
* logger
,
240 SavePasswordProgressLogger::StringID message_id
,
241 const blink::WebFormElement
& form
) {
242 logger
->LogHTMLForm(message_id
,
244 GURL(form
.action().utf8()));
247 bool FillDataContainsUsername(const PasswordFormFillData
& fill_data
) {
248 return !fill_data
.basic_data
.fields
[0].name
.empty();
251 // Sets |suggestions_present| to true if there are any suggestions to be derived
252 // from |fill_data|. Unless |show_all| is true, only considers suggestions with
253 // usernames having |current_username| as a prefix. Returns true if a username
254 // from the |fill_data.other_possible_usernames| would be included in the
256 bool GetSuggestionsStats(const PasswordFormFillData
& fill_data
,
257 const base::string16
& current_username
,
259 bool* suggestions_present
) {
260 *suggestions_present
= false;
262 for (const auto& usernames
: fill_data
.other_possible_usernames
) {
263 for (size_t i
= 0; i
< usernames
.second
.size(); ++i
) {
265 StartsWith(usernames
.second
[i
], current_username
, false)) {
266 *suggestions_present
= true;
272 if (show_all
|| StartsWith(fill_data
.basic_data
.fields
[0].value
,
273 current_username
, false)) {
274 *suggestions_present
= true;
278 for (const auto& login
: fill_data
.additional_logins
) {
279 if (show_all
|| StartsWith(login
.first
, current_username
, false)) {
280 *suggestions_present
= true;
288 // This function attempts to fill |username_element| and |password_element|
289 // with values from |fill_data|. The |password_element| will only have the
290 // |suggestedValue| set, and will be registered for copying that to the real
291 // value through |registration_callback|. The function returns true when
292 // selected username comes from |fill_data.other_possible_usernames|.
293 bool FillUserNameAndPassword(
294 blink::WebInputElement
* username_element
,
295 blink::WebInputElement
* password_element
,
296 const PasswordFormFillData
& fill_data
,
297 bool exact_username_match
,
299 base::Callback
<void(blink::WebInputElement
*)> registration_callback
) {
300 bool other_possible_username_selected
= false;
301 // Don't fill username if password can't be set.
302 if (!IsElementAutocompletable(*password_element
))
305 base::string16 current_username
;
306 if (!username_element
->isNull()) {
307 current_username
= username_element
->value();
310 // username and password will contain the match found if any.
311 base::string16 username
;
312 base::string16 password
;
314 // Look for any suitable matches to current field text.
315 if (DoUsernamesMatch(fill_data
.basic_data
.fields
[0].value
,
317 exact_username_match
)) {
318 username
= fill_data
.basic_data
.fields
[0].value
;
319 password
= fill_data
.basic_data
.fields
[1].value
;
321 // Scan additional logins for a match.
322 PasswordFormFillData::LoginCollection::const_iterator iter
;
323 for (iter
= fill_data
.additional_logins
.begin();
324 iter
!= fill_data
.additional_logins
.end();
326 if (DoUsernamesMatch(
327 iter
->first
, current_username
, exact_username_match
)) {
328 username
= iter
->first
;
329 password
= iter
->second
.password
;
334 // Check possible usernames.
335 if (username
.empty() && password
.empty()) {
336 for (PasswordFormFillData::UsernamesCollection::const_iterator iter
=
337 fill_data
.other_possible_usernames
.begin();
338 iter
!= fill_data
.other_possible_usernames
.end();
340 for (size_t i
= 0; i
< iter
->second
.size(); ++i
) {
341 if (DoUsernamesMatch(
342 iter
->second
[i
], current_username
, exact_username_match
)) {
343 other_possible_username_selected
= true;
344 username
= iter
->second
[i
];
345 password
= iter
->first
.password
;
349 if (!username
.empty() && !password
.empty())
354 if (password
.empty())
355 return other_possible_username_selected
; // No match was found.
357 // TODO(tkent): Check maxlength and pattern for both username and password
360 // Input matches the username, fill in required values.
361 if (!username_element
->isNull() &&
362 IsElementAutocompletable(*username_element
)) {
363 username_element
->setValue(username
, true);
364 username_element
->setAutofilled(true);
367 username_element
->setSelectionRange(current_username
.length(),
370 } else if (current_username
!= username
) {
371 // If the username can't be filled and it doesn't match a saved password
372 // as is, don't autofill a password.
373 return other_possible_username_selected
;
376 // Wait to fill in the password until a user gesture occurs. This is to make
377 // sure that we do not fill in the DOM with a password until we believe the
378 // user is intentionally interacting with the page.
379 password_element
->setSuggestedValue(password
);
380 registration_callback
.Run(password_element
);
382 password_element
->setAutofilled(true);
383 return other_possible_username_selected
;
386 // Attempts to fill |username_element| and |password_element| with the
387 // |fill_data|. Will use the data corresponding to the preferred username,
388 // unless the |username_element| already has a value set. In that case,
389 // attempts to fill the password matching the already filled username, if
390 // such a password exists. The |password_element| will have the
391 // |suggestedValue| set, and |suggestedValue| will be registered for copying to
392 // the real value through |registration_callback|. Returns true when the
393 // username gets selected from |other_possible_usernames|, else returns false.
394 bool FillFormOnPasswordRecieved(
395 const PasswordFormFillData
& fill_data
,
396 blink::WebInputElement username_element
,
397 blink::WebInputElement password_element
,
398 base::Callback
<void(blink::WebInputElement
*)> registration_callback
) {
399 // Do not fill if the password field is in an iframe.
400 DCHECK(password_element
.document().frame());
401 if (password_element
.document().frame()->parent())
404 // If we can't modify the password, don't try to set the username
405 if (!IsElementAutocompletable(password_element
))
408 bool form_contains_username_field
= FillDataContainsUsername(fill_data
);
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(
1020 const PasswordFormFillData
& form_data
) {
1021 if (usernames_usage_
== NOTHING_TO_AUTOFILL
) {
1022 if (form_data
.other_possible_usernames
.size())
1023 usernames_usage_
= OTHER_POSSIBLE_USERNAMES_PRESENT
;
1024 else if (usernames_usage_
== NOTHING_TO_AUTOFILL
)
1025 usernames_usage_
= OTHER_POSSIBLE_USERNAMES_ABSENT
;
1028 FormElementsList forms
;
1029 // We own the FormElements* in forms.
1030 FindFormElements(render_view()->GetWebView(), form_data
.basic_data
, &forms
);
1031 FormElementsList::iterator iter
;
1032 for (iter
= forms
.begin(); iter
!= forms
.end(); ++iter
) {
1033 scoped_ptr
<FormElements
> form_elements(*iter
);
1035 // Attach autocomplete listener to enable selecting alternate logins.
1036 blink::WebInputElement username_element
, password_element
;
1038 // Check whether the password form has a username input field.
1039 bool form_contains_username_field
= FillDataContainsUsername(form_data
);
1040 if (form_contains_username_field
) {
1042 form_elements
->input_elements
[form_data
.basic_data
.fields
[0].name
];
1045 // No password field, bail out.
1046 if (form_data
.basic_data
.fields
[1].name
.empty())
1049 // Get pointer to password element. (We currently only support single
1052 form_elements
->input_elements
[form_data
.basic_data
.fields
[1].name
];
1054 // If wait_for_username is true, we don't want to initially fill the form
1055 // until the user types in a valid username.
1056 if (!form_data
.wait_for_username
&&
1057 FillFormOnPasswordRecieved(
1061 base::Bind(&PasswordValueGatekeeper::RegisterElement
,
1062 base::Unretained(&gatekeeper_
)))) {
1063 usernames_usage_
= OTHER_POSSIBLE_USERNAME_SELECTED
;
1065 // We might have already filled this form if there are two <form> elements
1066 // with identical markup.
1067 if (login_to_password_info_
.find(username_element
) !=
1068 login_to_password_info_
.end())
1071 PasswordInfo password_info
;
1072 password_info
.fill_data
= form_data
;
1073 password_info
.password_field
= password_element
;
1074 login_to_password_info_
[username_element
] = password_info
;
1075 password_to_username_
[password_element
] = username_element
;
1076 login_to_password_info_key_
[username_element
] = key
;
1080 void PasswordAutofillAgent::OnSetLoggingState(bool active
) {
1081 logging_state_active_
= active
;
1084 ////////////////////////////////////////////////////////////////////////////////
1085 // PasswordAutofillAgent, private:
1087 PasswordAutofillAgent::PasswordInfo::PasswordInfo()
1088 : backspace_pressed_last(false), password_was_edited_last(false) {
1091 bool PasswordAutofillAgent::ShowSuggestionPopup(
1092 const PasswordFormFillData
& fill_data
,
1093 const blink::WebInputElement
& user_input
,
1095 blink::WebFrame
* frame
= user_input
.document().frame();
1099 blink::WebView
* webview
= frame
->view();
1104 FormFieldData field
;
1105 FindFormAndFieldForFormControlElement(
1106 user_input
, &form
, &field
, REQUIRE_NONE
);
1108 blink::WebInputElement selected_element
= user_input
;
1109 gfx::Rect
bounding_box(selected_element
.boundsInViewportSpace());
1111 LoginToPasswordInfoKeyMap::const_iterator key_it
=
1112 login_to_password_info_key_
.find(user_input
);
1113 DCHECK(key_it
!= login_to_password_info_key_
.end());
1115 float scale
= web_view_
->pageScaleFactor();
1116 gfx::RectF
bounding_box_scaled(bounding_box
.x() * scale
,
1117 bounding_box
.y() * scale
,
1118 bounding_box
.width() * scale
,
1119 bounding_box
.height() * scale
);
1120 Send(new AutofillHostMsg_ShowPasswordSuggestions(
1121 routing_id(), key_it
->second
, field
.text_direction
, user_input
.value(),
1122 show_all
, bounding_box_scaled
));
1124 bool suggestions_present
= false;
1125 if (GetSuggestionsStats(fill_data
, user_input
.value(), show_all
,
1126 &suggestions_present
)) {
1127 usernames_usage_
= OTHER_POSSIBLE_USERNAME_SHOWN
;
1129 return suggestions_present
;
1132 void PasswordAutofillAgent::PerformInlineAutocomplete(
1133 const blink::WebInputElement
& username_input
,
1134 const blink::WebInputElement
& password_input
,
1135 const PasswordFormFillData
& fill_data
) {
1136 DCHECK(!fill_data
.wait_for_username
);
1138 // We need non-const versions of the username and password inputs.
1139 blink::WebInputElement username
= username_input
;
1140 blink::WebInputElement password
= password_input
;
1142 // Don't inline autocomplete if the caret is not at the end.
1143 // TODO(jcivelli): is there a better way to test the caret location?
1144 if (username
.selectionStart() != username
.selectionEnd() ||
1145 username
.selectionEnd() != static_cast<int>(username
.value().length())) {
1149 // Show the popup with the list of available usernames.
1150 ShowSuggestionPopup(fill_data
, username
, false);
1152 #if !defined(OS_ANDROID)
1153 // Fill the user and password field with the most relevant match. Android
1154 // only fills in the fields after the user clicks on the suggestion popup.
1155 if (FillUserNameAndPassword(
1159 false /* exact_username_match */,
1160 true /* set_selection */,
1161 base::Bind(&PasswordValueGatekeeper::RegisterElement
,
1162 base::Unretained(&gatekeeper_
)))) {
1163 usernames_usage_
= OTHER_POSSIBLE_USERNAME_SELECTED
;
1168 void PasswordAutofillAgent::FrameClosing(const blink::WebFrame
* frame
) {
1169 for (LoginToPasswordInfoMap::iterator iter
= login_to_password_info_
.begin();
1170 iter
!= login_to_password_info_
.end();) {
1171 // There may not be a username field, so get the frame from the password
1173 if (iter
->second
.password_field
.document().frame() == frame
) {
1174 login_to_password_info_key_
.erase(iter
->first
);
1175 password_to_username_
.erase(iter
->second
.password_field
);
1176 login_to_password_info_
.erase(iter
++);
1181 for (FrameToPasswordFormMap::iterator iter
=
1182 provisionally_saved_forms_
.begin();
1183 iter
!= provisionally_saved_forms_
.end();) {
1184 if (iter
->first
== frame
)
1185 provisionally_saved_forms_
.erase(iter
++);
1191 bool PasswordAutofillAgent::FindLoginInfo(const blink::WebNode
& node
,
1192 blink::WebInputElement
* found_input
,
1193 PasswordInfo
** found_password
) {
1194 if (!node
.isElementNode())
1197 blink::WebElement element
= node
.toConst
<blink::WebElement
>();
1198 if (!element
.hasHTMLTagName("input"))
1201 blink::WebInputElement input
= element
.to
<blink::WebInputElement
>();
1202 LoginToPasswordInfoMap::iterator iter
= login_to_password_info_
.find(input
);
1203 if (iter
== login_to_password_info_
.end())
1206 *found_input
= input
;
1207 *found_password
= &iter
->second
;
1211 void PasswordAutofillAgent::ClearPreview(
1212 blink::WebInputElement
* username
,
1213 blink::WebInputElement
* password
) {
1214 if (!username
->suggestedValue().isEmpty()) {
1215 username
->setSuggestedValue(blink::WebString());
1216 username
->setAutofilled(was_username_autofilled_
);
1217 username
->setSelectionRange(username_selection_start_
,
1218 username
->value().length());
1220 if (!password
->suggestedValue().isEmpty()) {
1221 password
->setSuggestedValue(blink::WebString());
1222 password
->setAutofilled(was_password_autofilled_
);
1226 void PasswordAutofillAgent::ProvisionallySavePassword(
1227 blink::WebLocalFrame
* frame
,
1228 const blink::WebFormElement
& form
,
1229 ProvisionallySaveRestriction restriction
) {
1230 // TODO(vabr): This is just to stop getting a NULL frame in
1231 // |provisionally_saved_forms_|. Cases where we try to save password for a
1232 // form in a NULL frame should not happen, and it's currently unclear how they
1233 // happen (http://crbug.com/420519). This thing will be hopefully solved by
1234 // migrating the PasswordAutofillAgent to observe frames directly
1235 // (http://crbug.com/400186).
1238 scoped_ptr
<PasswordForm
> password_form(CreatePasswordForm(form
));
1239 if (!password_form
|| (restriction
== RESTRICTION_NON_EMPTY_PASSWORD
&&
1240 password_form
->password_value
.empty() &&
1241 password_form
->new_password_value
.empty())) {
1244 provisionally_saved_forms_
[frame
].reset(password_form
.release());
1247 } // namespace autofill