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.h"
10 #include "base/metrics/histogram.h"
11 #include "components/autofill/content/renderer/form_autofill_util.h"
12 #include "components/autofill/core/common/autofill_messages.h"
13 #include "components/autofill/core/common/form_field_data.h"
14 #include "components/autofill/core/common/password_form_fill_data.h"
15 #include "content/public/common/password_form.h"
16 #include "content/public/renderer/password_form_conversion_utils.h"
17 #include "content/public/renderer/render_view.h"
18 #include "third_party/WebKit/public/platform/WebVector.h"
19 #include "third_party/WebKit/public/web/WebAutofillClient.h"
20 #include "third_party/WebKit/public/web/WebDocument.h"
21 #include "third_party/WebKit/public/web/WebElement.h"
22 #include "third_party/WebKit/public/web/WebFormElement.h"
23 #include "third_party/WebKit/public/web/WebFrame.h"
24 #include "third_party/WebKit/public/web/WebInputEvent.h"
25 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
26 #include "third_party/WebKit/public/web/WebView.h"
27 #include "ui/base/keycodes/keyboard_codes.h"
32 // The size above which we stop triggering autocomplete.
33 static const size_t kMaximumTextSizeForAutocomplete
= 1000;
35 // Maps element names to the actual elements to simplify form filling.
36 typedef std::map
<base::string16
, WebKit::WebInputElement
>
39 // Utility struct for form lookup and autofill. When we parse the DOM to look up
40 // a form, in addition to action and origin URL's we have to compare all
41 // necessary form elements. To avoid having to look these up again when we want
42 // to fill the form, the FindFormElements function stores the pointers
43 // in a FormElements* result, referenced to ensure they are safe to use.
45 WebKit::WebFormElement form_element
;
46 FormInputElementMap input_elements
;
49 typedef std::vector
<FormElements
*> FormElementsList
;
51 // Helper to search the given form element for the specified input elements
52 // in |data|, and add results to |result|.
53 static bool FindFormInputElements(WebKit::WebFormElement
* fe
,
55 FormElements
* result
) {
56 // Loop through the list of elements we need to find on the form in order to
57 // autofill it. If we don't find any one of them, abort processing this
58 // form; it can't be the right one.
59 for (size_t j
= 0; j
< data
.fields
.size(); j
++) {
60 WebKit::WebVector
<WebKit::WebNode
> temp_elements
;
61 fe
->getNamedElements(data
.fields
[j
].name
, temp_elements
);
63 // Match the first input element, if any.
64 // |getNamedElements| may return non-input elements where the names match,
65 // so the results are filtered for input elements.
66 // If more than one match is made, then we have ambiguity (due to misuse
67 // of "name" attribute) so is it considered not found.
68 bool found_input
= false;
69 for (size_t i
= 0; i
< temp_elements
.size(); ++i
) {
70 if (temp_elements
[i
].to
<WebKit::WebElement
>().hasTagName("input")) {
71 // Check for a non-unique match.
77 // Only fill saved passwords into password fields and usernames into
79 WebKit::WebInputElement input_element
=
80 temp_elements
[i
].to
<WebKit::WebInputElement
>();
81 if (input_element
.isPasswordField() !=
82 (data
.fields
[j
].form_control_type
== "password"))
85 // This element matched, add it to our temporary result. It's possible
86 // there are multiple matches, but for purposes of identifying the form
87 // one suffices and if some function needs to deal with multiple
88 // matching elements it can get at them through the FormElement*.
89 // Note: This assignment adds a reference to the InputElement.
90 result
->input_elements
[data
.fields
[j
].name
] = input_element
;
95 // A required element was not found. This is not the right form.
96 // Make sure no input elements from a partially matched form in this
97 // iteration remain in the result set.
98 // Note: clear will remove a reference from each InputElement.
100 result
->input_elements
.clear();
107 // Helper to locate form elements identified by |data|.
108 void FindFormElements(WebKit::WebView
* view
,
109 const FormData
& data
,
110 FormElementsList
* results
) {
113 WebKit::WebFrame
* main_frame
= view
->mainFrame();
117 GURL::Replacements rep
;
121 // Loop through each frame.
122 for (WebKit::WebFrame
* f
= main_frame
; f
; f
= f
->traverseNext(false)) {
123 WebKit::WebDocument doc
= f
->document();
124 if (!doc
.isHTMLDocument())
127 GURL
full_origin(doc
.url());
128 if (data
.origin
!= full_origin
.ReplaceComponents(rep
))
131 WebKit::WebVector
<WebKit::WebFormElement
> forms
;
134 for (size_t i
= 0; i
< forms
.size(); ++i
) {
135 WebKit::WebFormElement fe
= forms
[i
];
137 GURL
full_action(f
->document().completeURL(fe
.action()));
138 if (full_action
.is_empty()) {
139 // The default action URL is the form's origin.
140 full_action
= full_origin
;
143 // Action URL must match.
144 if (data
.action
!= full_action
.ReplaceComponents(rep
))
147 scoped_ptr
<FormElements
> curr_elements(new FormElements
);
148 if (!FindFormInputElements(&fe
, data
, curr_elements
.get()))
151 // We found the right element.
152 // Note: this assignment adds a reference to |fe|.
153 curr_elements
->form_element
= fe
;
154 results
->push_back(curr_elements
.release());
159 bool IsElementEditable(const WebKit::WebInputElement
& element
) {
160 return element
.isEnabled() && !element
.isReadOnly();
163 void FillForm(FormElements
* fe
, const FormData
& data
) {
164 if (!fe
->form_element
.autoComplete())
167 std::map
<base::string16
, base::string16
> data_map
;
168 for (size_t i
= 0; i
< data
.fields
.size(); i
++)
169 data_map
[data
.fields
[i
].name
] = data
.fields
[i
].value
;
171 for (FormInputElementMap::iterator it
= fe
->input_elements
.begin();
172 it
!= fe
->input_elements
.end(); ++it
) {
173 WebKit::WebInputElement element
= it
->second
;
174 // Don't fill a form that has pre-filled values distinct from the ones we
175 // want to fill with.
176 if (!element
.value().isEmpty() && element
.value() != data_map
[it
->first
])
180 for (FormInputElementMap::iterator it
= fe
->input_elements
.begin();
181 it
!= fe
->input_elements
.end(); ++it
) {
182 WebKit::WebInputElement element
= it
->second
;
184 // Don't fill uneditable fields or fields with autocomplete disabled.
185 if (!IsElementEditable(element
) || !element
.autoComplete())
188 // TODO(tkent): Check maxlength and pattern.
189 element
.setValue(data_map
[it
->first
]);
190 element
.setAutofilled(true);
191 element
.dispatchFormControlChangeEvent();
195 void SetElementAutofilled(WebKit::WebInputElement
* element
, bool autofilled
) {
196 if (element
->isAutofilled() == autofilled
)
198 element
->setAutofilled(autofilled
);
199 // Notify any changeEvent listeners.
200 element
->dispatchFormControlChangeEvent();
203 bool DoUsernamesMatch(const base::string16
& username1
,
204 const base::string16
& username2
,
207 return username1
== username2
;
208 return StartsWith(username1
, username2
, true);
213 ////////////////////////////////////////////////////////////////////////////////
214 // PasswordAutofillAgent, public:
216 PasswordAutofillAgent::PasswordAutofillAgent(content::RenderView
* render_view
)
217 : content::RenderViewObserver(render_view
),
218 disable_popup_(false),
219 usernames_usage_(NOTHING_TO_AUTOFILL
),
220 web_view_(render_view
->GetWebView()),
221 weak_ptr_factory_(this) {
224 PasswordAutofillAgent::~PasswordAutofillAgent() {
227 bool PasswordAutofillAgent::TextFieldDidEndEditing(
228 const WebKit::WebInputElement
& element
) {
229 LoginToPasswordInfoMap::const_iterator iter
=
230 login_to_password_info_
.find(element
);
231 if (iter
== login_to_password_info_
.end())
234 const PasswordFormFillData
& fill_data
=
235 iter
->second
.fill_data
;
237 // If wait_for_username is false, we should have filled when the text changed.
238 if (!fill_data
.wait_for_username
)
241 WebKit::WebInputElement password
= iter
->second
.password_field
;
242 if (!IsElementEditable(password
))
245 WebKit::WebInputElement username
= element
; // We need a non-const.
247 // Do not set selection when ending an editing session, otherwise it can
249 FillUserNameAndPassword(&username
, &password
, fill_data
, true, false);
253 bool PasswordAutofillAgent::TextDidChangeInTextField(
254 const WebKit::WebInputElement
& element
) {
255 LoginToPasswordInfoMap::const_iterator iter
=
256 login_to_password_info_
.find(element
);
257 if (iter
== login_to_password_info_
.end())
260 // The input text is being changed, so any autofilled password is now
262 WebKit::WebInputElement username
= element
; // We need a non-const.
263 WebKit::WebInputElement password
= iter
->second
.password_field
;
264 SetElementAutofilled(&username
, false);
265 if (password
.isAutofilled()) {
266 password
.setValue(base::string16());
267 SetElementAutofilled(&password
, false);
270 // If wait_for_username is true we will fill when the username loses focus.
271 if (iter
->second
.fill_data
.wait_for_username
)
274 if (!IsElementEditable(element
) ||
276 !element
.autoComplete()) {
280 // Don't inline autocomplete if the user is deleting, that would be confusing.
281 // But refresh the popup. Note, since this is ours, return true to signal
282 // no further processing is required.
283 if (iter
->second
.backspace_pressed_last
) {
284 ShowSuggestionPopup(iter
->second
.fill_data
, username
);
288 WebKit::WebString name
= element
.nameForAutofill();
290 return false; // If the field has no name, then we won't have values.
292 // Don't attempt to autofill with values that are too large.
293 if (element
.value().length() > kMaximumTextSizeForAutocomplete
)
296 // The caret position should have already been updated.
297 PerformInlineAutocomplete(element
, password
, iter
->second
.fill_data
);
301 bool PasswordAutofillAgent::TextFieldHandlingKeyDown(
302 const WebKit::WebInputElement
& element
,
303 const WebKit::WebKeyboardEvent
& event
) {
304 // If using the new Autofill UI that lives in the browser, it will handle
305 // keypresses before this function. This is not currently an issue but if
306 // the keys handled there or here change, this issue may appear.
308 LoginToPasswordInfoMap::iterator iter
= login_to_password_info_
.find(element
);
309 if (iter
== login_to_password_info_
.end())
312 int win_key_code
= event
.windowsKeyCode
;
313 iter
->second
.backspace_pressed_last
=
314 (win_key_code
== ui::VKEY_BACK
|| win_key_code
== ui::VKEY_DELETE
);
318 bool PasswordAutofillAgent::DidAcceptAutofillSuggestion(
319 const WebKit::WebNode
& node
,
320 const WebKit::WebString
& value
) {
321 WebKit::WebInputElement input
;
322 PasswordInfo password
;
323 if (!FindLoginInfo(node
, &input
, &password
))
326 // Set the incoming |value| in the text field and |FillUserNameAndPassword|
328 input
.setValue(value
, true);
329 return FillUserNameAndPassword(&input
, &password
.password_field
,
330 password
.fill_data
, true, true);
333 bool PasswordAutofillAgent::DidSelectAutofillSuggestion(
334 const WebKit::WebNode
& node
) {
335 WebKit::WebInputElement input
;
336 PasswordInfo password
;
337 return FindLoginInfo(node
, &input
, &password
);
340 bool PasswordAutofillAgent::DidClearAutofillSelection(
341 const WebKit::WebNode
& node
) {
342 WebKit::WebInputElement input
;
343 PasswordInfo password
;
344 return FindLoginInfo(node
, &input
, &password
);
347 bool PasswordAutofillAgent::ShowSuggestions(
348 const WebKit::WebInputElement
& element
) {
349 LoginToPasswordInfoMap::const_iterator iter
=
350 login_to_password_info_
.find(element
);
351 if (iter
== login_to_password_info_
.end())
354 return ShowSuggestionPopup(iter
->second
.fill_data
, element
);
357 void PasswordAutofillAgent::SendPasswordForms(WebKit::WebFrame
* frame
,
359 // Make sure that this security origin is allowed to use password manager.
360 WebKit::WebSecurityOrigin origin
= frame
->document().securityOrigin();
361 if (!origin
.canAccessPasswordManager())
364 WebKit::WebVector
<WebKit::WebFormElement
> forms
;
365 frame
->document().forms(forms
);
367 std::vector
<content::PasswordForm
> password_forms
;
368 for (size_t i
= 0; i
< forms
.size(); ++i
) {
369 const WebKit::WebFormElement
& form
= forms
[i
];
371 // If requested, ignore non-rendered forms, e.g. those styled with
373 if (only_visible
&& !form
.hasNonEmptyBoundingBox())
376 scoped_ptr
<content::PasswordForm
> password_form(
377 content::CreatePasswordForm(form
));
378 if (password_form
.get())
379 password_forms
.push_back(*password_form
);
382 if (password_forms
.empty() && !only_visible
) {
383 // We need to send the PasswordFormsRendered message regardless of whether
384 // there are any forms visible, as this is also the code path that triggers
385 // showing the infobar.
390 Send(new AutofillHostMsg_PasswordFormsRendered(
391 routing_id(), password_forms
));
393 Send(new AutofillHostMsg_PasswordFormsParsed(routing_id(), password_forms
));
397 bool PasswordAutofillAgent::OnMessageReceived(const IPC::Message
& message
) {
399 IPC_BEGIN_MESSAGE_MAP(PasswordAutofillAgent
, message
)
400 IPC_MESSAGE_HANDLER(AutofillMsg_FillPasswordForm
, OnFillPasswordForm
)
401 IPC_MESSAGE_UNHANDLED(handled
= false)
402 IPC_END_MESSAGE_MAP()
406 void PasswordAutofillAgent::DidStartLoading() {
407 if (usernames_usage_
!= NOTHING_TO_AUTOFILL
) {
408 UMA_HISTOGRAM_ENUMERATION("PasswordManager.OtherPossibleUsernamesUsage",
409 usernames_usage_
, OTHER_POSSIBLE_USERNAMES_MAX
);
410 usernames_usage_
= NOTHING_TO_AUTOFILL
;
414 void PasswordAutofillAgent::DidFinishDocumentLoad(WebKit::WebFrame
* frame
) {
415 // The |frame| contents have been parsed, but not yet rendered. Let the
416 // PasswordManager know that forms are loaded, even though we can't yet tell
417 // whether they're visible.
418 SendPasswordForms(frame
, false);
421 void PasswordAutofillAgent::DidFinishLoad(WebKit::WebFrame
* frame
) {
422 // The |frame| contents have been rendered. Let the PasswordManager know
423 // which of the loaded frames are actually visible to the user. This also
424 // triggers the "Save password?" infobar if the user just submitted a password
426 SendPasswordForms(frame
, true);
429 void PasswordAutofillAgent::FrameDetached(WebKit::WebFrame
* frame
) {
433 void PasswordAutofillAgent::FrameWillClose(WebKit::WebFrame
* frame
) {
437 void PasswordAutofillAgent::OnFillPasswordForm(
438 const PasswordFormFillData
& form_data
,
439 bool disable_popup
) {
440 disable_popup_
= disable_popup
;
441 if (usernames_usage_
== NOTHING_TO_AUTOFILL
) {
442 if (form_data
.other_possible_usernames
.size())
443 usernames_usage_
= OTHER_POSSIBLE_USERNAMES_PRESENT
;
444 else if (usernames_usage_
== NOTHING_TO_AUTOFILL
)
445 usernames_usage_
= OTHER_POSSIBLE_USERNAMES_ABSENT
;
448 FormElementsList forms
;
449 // We own the FormElements* in forms.
450 FindFormElements(render_view()->GetWebView(), form_data
.basic_data
, &forms
);
451 FormElementsList::iterator iter
;
452 for (iter
= forms
.begin(); iter
!= forms
.end(); ++iter
) {
453 scoped_ptr
<FormElements
> form_elements(*iter
);
455 // If wait_for_username is true, we don't want to initially fill the form
456 // until the user types in a valid username.
457 if (!form_data
.wait_for_username
)
458 FillForm(form_elements
.get(), form_data
.basic_data
);
460 // Attach autocomplete listener to enable selecting alternate logins.
461 // First, get pointers to username element.
462 WebKit::WebInputElement username_element
=
463 form_elements
->input_elements
[form_data
.basic_data
.fields
[0].name
];
465 // Get pointer to password element. (We currently only support single
467 WebKit::WebInputElement password_element
=
468 form_elements
->input_elements
[form_data
.basic_data
.fields
[1].name
];
470 // We might have already filled this form if there are two <form> elements
471 // with identical markup.
472 if (login_to_password_info_
.find(username_element
) !=
473 login_to_password_info_
.end())
476 PasswordInfo password_info
;
477 password_info
.fill_data
= form_data
;
478 password_info
.password_field
= password_element
;
479 login_to_password_info_
[username_element
] = password_info
;
483 FindFormAndFieldForInputElement(
484 username_element
, &form
, &field
, REQUIRE_NONE
);
485 Send(new AutofillHostMsg_AddPasswordFormMapping(
492 ////////////////////////////////////////////////////////////////////////////////
493 // PasswordAutofillAgent, private:
495 void PasswordAutofillAgent::GetSuggestions(
496 const PasswordFormFillData
& fill_data
,
497 const base::string16
& input
,
498 std::vector
<base::string16
>* suggestions
) {
499 if (StartsWith(fill_data
.basic_data
.fields
[0].value
, input
, false))
500 suggestions
->push_back(fill_data
.basic_data
.fields
[0].value
);
502 for (PasswordFormFillData::LoginCollection::const_iterator iter
=
503 fill_data
.additional_logins
.begin();
504 iter
!= fill_data
.additional_logins
.end(); ++iter
) {
505 if (StartsWith(iter
->first
, input
, false))
506 suggestions
->push_back(iter
->first
);
509 for (PasswordFormFillData::UsernamesCollection::const_iterator iter
=
510 fill_data
.other_possible_usernames
.begin();
511 iter
!= fill_data
.other_possible_usernames
.end(); ++iter
) {
512 for (size_t i
= 0; i
< iter
->second
.size(); ++i
) {
513 if (StartsWith(iter
->second
[i
], input
, false)) {
514 usernames_usage_
= OTHER_POSSIBLE_USERNAME_SHOWN
;
515 suggestions
->push_back(iter
->second
[i
]);
521 bool PasswordAutofillAgent::ShowSuggestionPopup(
522 const PasswordFormFillData
& fill_data
,
523 const WebKit::WebInputElement
& user_input
) {
524 WebKit::WebFrame
* frame
= user_input
.document().frame();
528 WebKit::WebView
* webview
= frame
->view();
532 std::vector
<base::string16
> suggestions
;
533 GetSuggestions(fill_data
, user_input
.value(), &suggestions
);
535 if (disable_popup_
) {
538 FindFormAndFieldForInputElement(
539 user_input
, &form
, &field
, REQUIRE_NONE
);
541 WebKit::WebInputElement selected_element
= user_input
;
542 gfx::Rect
bounding_box(selected_element
.boundsInViewportSpace());
544 float scale
= web_view_
->pageScaleFactor();
545 gfx::RectF
bounding_box_scaled(bounding_box
.x() * scale
,
546 bounding_box
.y() * scale
,
547 bounding_box
.width() * scale
,
548 bounding_box
.height() * scale
);
549 Send(new AutofillHostMsg_ShowPasswordSuggestions(routing_id(),
553 return !suggestions
.empty();
557 if (suggestions
.empty()) {
558 webview
->hidePopups();
562 std::vector
<base::string16
> labels(suggestions
.size());
563 std::vector
<base::string16
> icons(suggestions
.size());
564 std::vector
<int> ids(suggestions
.size(),
565 WebKit::WebAutofillClient::MenuItemIDPasswordEntry
);
566 webview
->applyAutofillSuggestions(
567 user_input
, suggestions
, labels
, icons
, ids
);
571 bool PasswordAutofillAgent::FillUserNameAndPassword(
572 WebKit::WebInputElement
* username_element
,
573 WebKit::WebInputElement
* password_element
,
574 const PasswordFormFillData
& fill_data
,
575 bool exact_username_match
,
576 bool set_selection
) {
577 base::string16 current_username
= username_element
->value();
578 // username and password will contain the match found if any.
579 base::string16 username
;
580 base::string16 password
;
582 // Look for any suitable matches to current field text.
583 if (DoUsernamesMatch(fill_data
.basic_data
.fields
[0].value
, current_username
,
584 exact_username_match
)) {
585 username
= fill_data
.basic_data
.fields
[0].value
;
586 password
= fill_data
.basic_data
.fields
[1].value
;
588 // Scan additional logins for a match.
589 PasswordFormFillData::LoginCollection::const_iterator iter
;
590 for (iter
= fill_data
.additional_logins
.begin();
591 iter
!= fill_data
.additional_logins
.end(); ++iter
) {
592 if (DoUsernamesMatch(iter
->first
, current_username
,
593 exact_username_match
)) {
594 username
= iter
->first
;
595 password
= iter
->second
;
600 // Check possible usernames.
601 if (username
.empty() && password
.empty()) {
602 for (PasswordFormFillData::UsernamesCollection::const_iterator iter
=
603 fill_data
.other_possible_usernames
.begin();
604 iter
!= fill_data
.other_possible_usernames
.end(); ++iter
) {
605 for (size_t i
= 0; i
< iter
->second
.size(); ++i
) {
606 if (DoUsernamesMatch(iter
->second
[i
], current_username
,
607 exact_username_match
)) {
608 usernames_usage_
= OTHER_POSSIBLE_USERNAME_SELECTED
;
609 username
= iter
->second
[i
];
610 password
= iter
->first
.password
;
614 if (!username
.empty() && !password
.empty())
619 if (password
.empty())
620 return false; // No match was found.
622 // Input matches the username, fill in required values.
623 username_element
->setValue(username
);
626 username_element
->setSelectionRange(current_username
.length(),
630 SetElementAutofilled(username_element
, true);
631 if (IsElementEditable(*password_element
))
632 password_element
->setValue(password
);
633 SetElementAutofilled(password_element
, true);
637 void PasswordAutofillAgent::PerformInlineAutocomplete(
638 const WebKit::WebInputElement
& username_input
,
639 const WebKit::WebInputElement
& password_input
,
640 const PasswordFormFillData
& fill_data
) {
641 DCHECK(!fill_data
.wait_for_username
);
643 // We need non-const versions of the username and password inputs.
644 WebKit::WebInputElement username
= username_input
;
645 WebKit::WebInputElement password
= password_input
;
647 // Don't inline autocomplete if the caret is not at the end.
648 // TODO(jcivelli): is there a better way to test the caret location?
649 if (username
.selectionStart() != username
.selectionEnd() ||
650 username
.selectionEnd() != static_cast<int>(username
.value().length())) {
654 // Show the popup with the list of available usernames.
655 ShowSuggestionPopup(fill_data
, username
);
658 #if !defined(OS_ANDROID)
659 // Fill the user and password field with the most relevant match. Android
660 // only fills in the fields after the user clicks on the suggestion popup.
661 FillUserNameAndPassword(&username
, &password
, fill_data
, false, true);
665 void PasswordAutofillAgent::FrameClosing(const WebKit::WebFrame
* frame
) {
666 for (LoginToPasswordInfoMap::iterator iter
= login_to_password_info_
.begin();
667 iter
!= login_to_password_info_
.end();) {
668 if (iter
->first
.document().frame() == frame
)
669 login_to_password_info_
.erase(iter
++);
675 bool PasswordAutofillAgent::FindLoginInfo(const WebKit::WebNode
& node
,
676 WebKit::WebInputElement
* found_input
,
677 PasswordInfo
* found_password
) {
678 if (!node
.isElementNode())
681 WebKit::WebElement element
= node
.toConst
<WebKit::WebElement
>();
682 if (!element
.hasTagName("input"))
685 WebKit::WebInputElement input
= element
.to
<WebKit::WebInputElement
>();
686 LoginToPasswordInfoMap::iterator iter
= login_to_password_info_
.find(input
);
687 if (iter
== login_to_password_info_
.end())
690 *found_input
= input
;
691 *found_password
= iter
->second
;
695 } // namespace autofill