form_structure.cc revision a1401311d1ab56c4ed0a474bd38c108f75cb0cd9
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.
4
5#include "components/autofill/core/browser/form_structure.h"
6
7#include <utility>
8
9#include "base/basictypes.h"
10#include "base/command_line.h"
11#include "base/i18n/case_conversion.h"
12#include "base/logging.h"
13#include "base/memory/scoped_ptr.h"
14#include "base/sha1.h"
15#include "base/strings/string_number_conversions.h"
16#include "base/strings/string_util.h"
17#include "base/strings/stringprintf.h"
18#include "base/strings/utf_string_conversions.h"
19#include "base/time/time.h"
20#include "components/autofill/core/browser/autofill_metrics.h"
21#include "components/autofill/core/browser/autofill_type.h"
22#include "components/autofill/core/browser/autofill_xml_parser.h"
23#include "components/autofill/core/browser/field_types.h"
24#include "components/autofill/core/browser/form_field.h"
25#include "components/autofill/core/common/autofill_constants.h"
26#include "components/autofill/core/common/form_data.h"
27#include "components/autofill/core/common/form_data_predictions.h"
28#include "components/autofill/core/common/form_field_data.h"
29#include "components/autofill/core/common/form_field_data_predictions.h"
30#include "third_party/icu/source/i18n/unicode/regex.h"
31#include "third_party/libjingle/source/talk/xmllite/xmlelement.h"
32
33namespace autofill {
34namespace {
35
36const char kFormMethodPost[] = "post";
37
38// XML elements and attributes.
39const char kAttributeAutofillUsed[] = "autofillused";
40const char kAttributeAutofillType[] = "autofilltype";
41const char kAttributeClientVersion[] = "clientversion";
42const char kAttributeDataPresent[] = "datapresent";
43const char kAttributeFieldID[] = "fieldid";
44const char kAttributeFieldType[] = "fieldtype";
45const char kAttributeFormSignature[] = "formsignature";
46const char kAttributeName[] = "name";
47const char kAttributeSignature[] = "signature";
48const char kClientVersion[] = "6.1.1715.1442/en (GGLL)";
49const char kXMLDeclaration[] = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
50const char kXMLElementAutofillQuery[] = "autofillquery";
51const char kXMLElementAutofillUpload[] = "autofillupload";
52const char kXMLElementFieldAssignments[] = "fieldassignments";
53const char kXMLElementField[] = "field";
54const char kXMLElementFields[] = "fields";
55const char kXMLElementForm[] = "form";
56const char kBillingMode[] = "billing";
57const char kShippingMode[] = "shipping";
58
59// Stip away >= 5 consecutive digits.
60const char kIgnorePatternInFieldName[] = "\\d{5,}+";
61
62// Helper for |EncodeUploadRequest()| that creates a bit field corresponding to
63// |available_field_types| and returns the hex representation as a string.
64std::string EncodeFieldTypes(const ServerFieldTypeSet& available_field_types) {
65  // There are |MAX_VALID_FIELD_TYPE| different field types and 8 bits per byte,
66  // so we need ceil(MAX_VALID_FIELD_TYPE / 8) bytes to encode the bit field.
67  const size_t kNumBytes = (MAX_VALID_FIELD_TYPE + 0x7) / 8;
68
69  // Pack the types in |available_field_types| into |bit_field|.
70  std::vector<uint8> bit_field(kNumBytes, 0);
71  for (ServerFieldTypeSet::const_iterator field_type =
72           available_field_types.begin();
73       field_type != available_field_types.end();
74       ++field_type) {
75    // Set the appropriate bit in the field.  The bit we set is the one
76    // |field_type| % 8 from the left of the byte.
77    const size_t byte = *field_type / 8;
78    const size_t bit = 0x80 >> (*field_type % 8);
79    DCHECK(byte < bit_field.size());
80    bit_field[byte] |= bit;
81  }
82
83  // Discard any trailing zeroes.
84  // If there are no available types, we return the empty string.
85  size_t data_end = bit_field.size();
86  for (; data_end > 0 && !bit_field[data_end - 1]; --data_end) {
87  }
88
89  // Print all meaningfull bytes into a string.
90  std::string data_presence;
91  data_presence.reserve(data_end * 2 + 1);
92  for (size_t i = 0; i < data_end; ++i) {
93    base::StringAppendF(&data_presence, "%02x", bit_field[i]);
94  }
95
96  return data_presence;
97}
98
99// Helper for |EncodeFormRequest()| that creates XmlElements for the given field
100// in upload xml, and also add them to the parent XmlElement.
101void EncodeFieldForUpload(const AutofillField& field,
102                          buzz::XmlElement* parent) {
103  // Don't upload checkable fields.
104  if (field.is_checkable)
105    return;
106
107  ServerFieldTypeSet types = field.possible_types();
108  // |types| could be empty in unit-tests only.
109  for (ServerFieldTypeSet::iterator field_type = types.begin();
110       field_type != types.end(); ++field_type) {
111    buzz::XmlElement *field_element = new buzz::XmlElement(
112        buzz::QName(kXMLElementField));
113
114    field_element->SetAttr(buzz::QName(kAttributeSignature),
115                           field.FieldSignature());
116    field_element->SetAttr(buzz::QName(kAttributeAutofillType),
117                           base::IntToString(*field_type));
118    parent->AddElement(field_element);
119  }
120}
121
122// Helper for |EncodeFormRequest()| that creates XmlElement for the given field
123// in query xml, and also add it to the parent XmlElement.
124void EncodeFieldForQuery(const AutofillField& field,
125                         buzz::XmlElement* parent) {
126  buzz::XmlElement *field_element = new buzz::XmlElement(
127      buzz::QName(kXMLElementField));
128  field_element->SetAttr(buzz::QName(kAttributeSignature),
129                         field.FieldSignature());
130  parent->AddElement(field_element);
131}
132
133// Helper for |EncodeFormRequest()| that creates XmlElements for the given field
134// in field assignments xml, and also add them to the parent XmlElement.
135void EncodeFieldForFieldAssignments(const AutofillField& field,
136                                    buzz::XmlElement* parent) {
137  ServerFieldTypeSet types = field.possible_types();
138  for (ServerFieldTypeSet::iterator field_type = types.begin();
139       field_type != types.end(); ++field_type) {
140    buzz::XmlElement *field_element = new buzz::XmlElement(
141        buzz::QName(kXMLElementFields));
142
143    field_element->SetAttr(buzz::QName(kAttributeFieldID),
144                           field.FieldSignature());
145    field_element->SetAttr(buzz::QName(kAttributeFieldType),
146                           base::IntToString(*field_type));
147    field_element->SetAttr(buzz::QName(kAttributeName),
148                           base::UTF16ToUTF8(field.name));
149    parent->AddElement(field_element);
150  }
151}
152
153// Returns |true| iff the |token| is a type hint for a contact field, as
154// specified in the implementation section of http://is.gd/whatwg_autocomplete
155// Note that "fax" and "pager" are intentionally ignored, as Chrome does not
156// support filling either type of information.
157bool IsContactTypeHint(const std::string& token) {
158  return token == "home" || token == "work" || token == "mobile";
159}
160
161// Returns |true| iff the |token| is a type hint appropriate for a field of the
162// given |field_type|, as specified in the implementation section of
163// http://is.gd/whatwg_autocomplete
164bool ContactTypeHintMatchesFieldType(const std::string& token,
165                                     HtmlFieldType field_type) {
166  // The "home" and "work" type hints are only appropriate for email and phone
167  // number field types.
168  if (token == "home" || token == "work") {
169    return field_type == HTML_TYPE_EMAIL ||
170        (field_type >= HTML_TYPE_TEL &&
171         field_type <= HTML_TYPE_TEL_LOCAL_SUFFIX);
172  }
173
174  // The "mobile" type hint is only appropriate for phone number field types.
175  // Note that "fax" and "pager" are intentionally ignored, as Chrome does not
176  // support filling either type of information.
177  if (token == "mobile") {
178    return field_type >= HTML_TYPE_TEL &&
179        field_type <= HTML_TYPE_TEL_LOCAL_SUFFIX;
180  }
181
182  return false;
183}
184
185// Returns the Chrome Autofill-supported field type corresponding to the given
186// |autocomplete_attribute_value|, if there is one, in the context of the given
187// |field|.  Chrome Autofill supports a subset of the field types listed at
188// http://is.gd/whatwg_autocomplete
189HtmlFieldType FieldTypeFromAutocompleteAttributeValue(
190    const std::string& autocomplete_attribute_value,
191    const AutofillField& field) {
192  if (autocomplete_attribute_value == "name")
193    return HTML_TYPE_NAME;
194
195  if (autocomplete_attribute_value == "given-name")
196    return HTML_TYPE_GIVEN_NAME;
197
198  if (autocomplete_attribute_value == "additional-name") {
199    if (field.max_length == 1)
200      return HTML_TYPE_ADDITIONAL_NAME_INITIAL;
201    else
202      return HTML_TYPE_ADDITIONAL_NAME;
203  }
204
205  if (autocomplete_attribute_value == "family-name")
206    return HTML_TYPE_FAMILY_NAME;
207
208  if (autocomplete_attribute_value == "organization")
209    return HTML_TYPE_ORGANIZATION;
210
211  if (autocomplete_attribute_value == "street-address")
212    return HTML_TYPE_STREET_ADDRESS;
213
214  if (autocomplete_attribute_value == "address-line1")
215    return HTML_TYPE_ADDRESS_LINE1;
216
217  if (autocomplete_attribute_value == "address-line2")
218    return HTML_TYPE_ADDRESS_LINE2;
219
220  if (autocomplete_attribute_value == "locality")
221    return HTML_TYPE_LOCALITY;
222
223  if (autocomplete_attribute_value == "region")
224    return HTML_TYPE_REGION;
225
226  if (autocomplete_attribute_value == "country")
227    return HTML_TYPE_COUNTRY_CODE;
228
229  if (autocomplete_attribute_value == "country-name")
230    return HTML_TYPE_COUNTRY_NAME;
231
232  if (autocomplete_attribute_value == "postal-code")
233    return HTML_TYPE_POSTAL_CODE;
234
235  if (autocomplete_attribute_value == "cc-name")
236    return HTML_TYPE_CREDIT_CARD_NAME;
237
238  if (autocomplete_attribute_value == "cc-number")
239    return HTML_TYPE_CREDIT_CARD_NUMBER;
240
241  if (autocomplete_attribute_value == "cc-exp") {
242    if (field.max_length == 5)
243      return HTML_TYPE_CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR;
244    else if (field.max_length == 7)
245      return HTML_TYPE_CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR;
246    else
247      return HTML_TYPE_CREDIT_CARD_EXP;
248  }
249
250  if (autocomplete_attribute_value == "cc-exp-month")
251    return HTML_TYPE_CREDIT_CARD_EXP_MONTH;
252
253  if (autocomplete_attribute_value == "cc-exp-year") {
254    if (field.max_length == 2)
255      return HTML_TYPE_CREDIT_CARD_EXP_2_DIGIT_YEAR;
256    else if (field.max_length == 4)
257      return HTML_TYPE_CREDIT_CARD_EXP_4_DIGIT_YEAR;
258    else
259      return HTML_TYPE_CREDIT_CARD_EXP_YEAR;
260  }
261
262  if (autocomplete_attribute_value == "cc-csc")
263    return HTML_TYPE_CREDIT_CARD_VERIFICATION_CODE;
264
265  if (autocomplete_attribute_value == "cc-type")
266    return HTML_TYPE_CREDIT_CARD_TYPE;
267
268  if (autocomplete_attribute_value == "tel")
269    return HTML_TYPE_TEL;
270
271  if (autocomplete_attribute_value == "tel-country-code")
272    return HTML_TYPE_TEL_COUNTRY_CODE;
273
274  if (autocomplete_attribute_value == "tel-national")
275    return HTML_TYPE_TEL_NATIONAL;
276
277  if (autocomplete_attribute_value == "tel-area-code")
278    return HTML_TYPE_TEL_AREA_CODE;
279
280  if (autocomplete_attribute_value == "tel-local")
281    return HTML_TYPE_TEL_LOCAL;
282
283  if (autocomplete_attribute_value == "tel-local-prefix")
284    return HTML_TYPE_TEL_LOCAL_PREFIX;
285
286  if (autocomplete_attribute_value == "tel-local-suffix")
287    return HTML_TYPE_TEL_LOCAL_SUFFIX;
288
289  if (autocomplete_attribute_value == "email")
290    return HTML_TYPE_EMAIL;
291
292  return HTML_TYPE_UNKNOWN;
293}
294
295std::string StripDigitsIfRequired(const base::string16& input) {
296  UErrorCode status = U_ZERO_ERROR;
297  CR_DEFINE_STATIC_LOCAL(icu::UnicodeString, icu_pattern,
298                         (kIgnorePatternInFieldName));
299  CR_DEFINE_STATIC_LOCAL(icu::RegexMatcher, matcher,
300                         (icu_pattern, UREGEX_CASE_INSENSITIVE, status));
301  DCHECK_EQ(status, U_ZERO_ERROR);
302
303  icu::UnicodeString icu_input(input.data(), input.length());
304  matcher.reset(icu_input);
305
306  icu::UnicodeString replaced_string = matcher.replaceAll("", status);
307
308  std::string return_string;
309  status = U_ZERO_ERROR;
310  base::UTF16ToUTF8(replaced_string.getBuffer(),
311                    static_cast<size_t>(replaced_string.length()),
312                    &return_string);
313  if (status != U_ZERO_ERROR) {
314    DVLOG(1) << "Couldn't strip digits in " << base::UTF16ToUTF8(input);
315    return base::UTF16ToUTF8(input);
316  }
317
318  return return_string;
319}
320
321}  // namespace
322
323FormStructure::FormStructure(const FormData& form)
324    : form_name_(form.name),
325      source_url_(form.origin),
326      target_url_(form.action),
327      autofill_count_(0),
328      active_field_count_(0),
329      upload_required_(USE_UPLOAD_RATES),
330      has_author_specified_types_(false) {
331  // Copy the form fields.
332  std::map<base::string16, size_t> unique_names;
333  for (std::vector<FormFieldData>::const_iterator field =
334           form.fields.begin();
335       field != form.fields.end(); ++field) {
336    if (!ShouldSkipField(*field)) {
337      // Add all supported form fields (including with empty names) to the
338      // signature.  This is a requirement for Autofill servers.
339      form_signature_field_names_.append("&");
340      form_signature_field_names_.append(StripDigitsIfRequired(field->name));
341
342      ++active_field_count_;
343    }
344
345    // Generate a unique name for this field by appending a counter to the name.
346    // Make sure to prepend the counter with a non-numeric digit so that we are
347    // guaranteed to avoid collisions.
348    if (!unique_names.count(field->name))
349      unique_names[field->name] = 1;
350    else
351      ++unique_names[field->name];
352    base::string16 unique_name = field->name + base::ASCIIToUTF16("_") +
353        base::IntToString16(unique_names[field->name]);
354    fields_.push_back(new AutofillField(*field, unique_name));
355  }
356
357  std::string method = base::UTF16ToUTF8(form.method);
358  if (StringToLowerASCII(method) == kFormMethodPost) {
359    method_ = POST;
360  } else {
361    // Either the method is 'get', or we don't know.  In this case we default
362    // to GET.
363    method_ = GET;
364  }
365}
366
367FormStructure::~FormStructure() {}
368
369void FormStructure::DetermineHeuristicTypes(
370    const AutofillMetrics& metric_logger) {
371  // First, try to detect field types based on each field's |autocomplete|
372  // attribute value.  If there is at least one form field that specifies an
373  // autocomplete type hint, don't try to apply other heuristics to match fields
374  // in this form.
375  bool has_author_specified_sections;
376  ParseFieldTypesFromAutocompleteAttributes(&has_author_specified_types_,
377                                            &has_author_specified_sections);
378
379  if (!has_author_specified_types_) {
380    ServerFieldTypeMap field_type_map;
381    FormField::ParseFormFields(fields_.get(), &field_type_map);
382    for (size_t i = 0; i < field_count(); ++i) {
383      AutofillField* field = fields_[i];
384      ServerFieldTypeMap::iterator iter =
385          field_type_map.find(field->unique_name());
386      if (iter != field_type_map.end())
387        field->set_heuristic_type(iter->second);
388    }
389  }
390
391  UpdateAutofillCount();
392  IdentifySections(has_author_specified_sections);
393
394  if (IsAutofillable(true)) {
395    metric_logger.LogDeveloperEngagementMetric(
396        AutofillMetrics::FILLABLE_FORM_PARSED);
397    if (has_author_specified_types_) {
398      metric_logger.LogDeveloperEngagementMetric(
399          AutofillMetrics::FILLABLE_FORM_CONTAINS_TYPE_HINTS);
400    }
401  }
402}
403
404bool FormStructure::EncodeUploadRequest(
405    const ServerFieldTypeSet& available_field_types,
406    bool form_was_autofilled,
407    std::string* encoded_xml) const {
408  DCHECK(ShouldBeCrowdsourced());
409
410  // Verify that |available_field_types| agrees with the possible field types we
411  // are uploading.
412  for (std::vector<AutofillField*>::const_iterator field = begin();
413       field != end();
414       ++field) {
415    for (ServerFieldTypeSet::const_iterator type =
416             (*field)->possible_types().begin();
417         type != (*field)->possible_types().end();
418         ++type) {
419      DCHECK(*type == UNKNOWN_TYPE ||
420             *type == EMPTY_TYPE ||
421             available_field_types.count(*type));
422    }
423  }
424
425  // Set up the <autofillupload> element and its attributes.
426  buzz::XmlElement autofill_request_xml(
427      (buzz::QName(kXMLElementAutofillUpload)));
428  autofill_request_xml.SetAttr(buzz::QName(kAttributeClientVersion),
429                               kClientVersion);
430  autofill_request_xml.SetAttr(buzz::QName(kAttributeFormSignature),
431                               FormSignature());
432  autofill_request_xml.SetAttr(buzz::QName(kAttributeAutofillUsed),
433                               form_was_autofilled ? "true" : "false");
434  autofill_request_xml.SetAttr(buzz::QName(kAttributeDataPresent),
435                               EncodeFieldTypes(available_field_types).c_str());
436
437  if (!EncodeFormRequest(FormStructure::UPLOAD, &autofill_request_xml))
438    return false;  // Malformed form, skip it.
439
440  // Obtain the XML structure as a string.
441  *encoded_xml = kXMLDeclaration;
442  *encoded_xml += autofill_request_xml.Str().c_str();
443
444  // To enable this logging, run with the flag --vmodule="form_structure=2".
445  VLOG(2) << "\n" << *encoded_xml;
446
447  return true;
448}
449
450bool FormStructure::EncodeFieldAssignments(
451    const ServerFieldTypeSet& available_field_types,
452    std::string* encoded_xml) const {
453  DCHECK(ShouldBeCrowdsourced());
454
455  // Set up the <fieldassignments> element and its attributes.
456  buzz::XmlElement autofill_request_xml(
457      (buzz::QName(kXMLElementFieldAssignments)));
458  autofill_request_xml.SetAttr(buzz::QName(kAttributeFormSignature),
459                               FormSignature());
460
461  if (!EncodeFormRequest(FormStructure::FIELD_ASSIGNMENTS,
462                         &autofill_request_xml))
463    return false;  // Malformed form, skip it.
464
465  // Obtain the XML structure as a string.
466  *encoded_xml = kXMLDeclaration;
467  *encoded_xml += autofill_request_xml.Str().c_str();
468
469  return true;
470}
471
472// static
473bool FormStructure::EncodeQueryRequest(
474    const std::vector<FormStructure*>& forms,
475    std::vector<std::string>* encoded_signatures,
476    std::string* encoded_xml) {
477  DCHECK(encoded_signatures);
478  DCHECK(encoded_xml);
479  encoded_xml->clear();
480  encoded_signatures->clear();
481  encoded_signatures->reserve(forms.size());
482
483  // Set up the <autofillquery> element and attributes.
484  buzz::XmlElement autofill_request_xml(
485      (buzz::QName(kXMLElementAutofillQuery)));
486  autofill_request_xml.SetAttr(buzz::QName(kAttributeClientVersion),
487                               kClientVersion);
488
489  // Some badly formatted web sites repeat forms - detect that and encode only
490  // one form as returned data would be the same for all the repeated forms.
491  std::set<std::string> processed_forms;
492  for (ScopedVector<FormStructure>::const_iterator it = forms.begin();
493       it != forms.end();
494       ++it) {
495    std::string signature((*it)->FormSignature());
496    if (processed_forms.find(signature) != processed_forms.end())
497      continue;
498    processed_forms.insert(signature);
499    scoped_ptr<buzz::XmlElement> encompassing_xml_element(
500        new buzz::XmlElement(buzz::QName(kXMLElementForm)));
501    encompassing_xml_element->SetAttr(buzz::QName(kAttributeSignature),
502                                      signature);
503
504    if (!(*it)->EncodeFormRequest(FormStructure::QUERY,
505                                  encompassing_xml_element.get()))
506      continue;  // Malformed form, skip it.
507
508    autofill_request_xml.AddElement(encompassing_xml_element.release());
509    encoded_signatures->push_back(signature);
510  }
511
512  if (!encoded_signatures->size())
513    return false;
514
515  // Note: Chrome used to also set 'accepts="e"' (where 'e' is for experiments),
516  // but no longer sets this because support for experiments is deprecated.  If
517  // it ever resurfaces, re-add code here to set the attribute accordingly.
518
519  // Obtain the XML structure as a string.
520  *encoded_xml = kXMLDeclaration;
521  *encoded_xml += autofill_request_xml.Str().c_str();
522
523  return true;
524}
525
526// static
527void FormStructure::ParseQueryResponse(
528    const std::string& response_xml,
529    const std::vector<FormStructure*>& forms,
530    const AutofillMetrics& metric_logger) {
531  metric_logger.LogServerQueryMetric(AutofillMetrics::QUERY_RESPONSE_RECEIVED);
532
533  // Parse the field types from the server response to the query.
534  std::vector<AutofillServerFieldInfo> field_infos;
535  UploadRequired upload_required;
536  AutofillQueryXmlParser parse_handler(&field_infos,
537                                       &upload_required);
538  buzz::XmlParser parser(&parse_handler);
539  parser.Parse(response_xml.c_str(), response_xml.length(), true);
540  if (!parse_handler.succeeded())
541    return;
542
543  metric_logger.LogServerQueryMetric(AutofillMetrics::QUERY_RESPONSE_PARSED);
544
545  bool heuristics_detected_fillable_field = false;
546  bool query_response_overrode_heuristics = false;
547
548  // Copy the field types into the actual form.
549  std::vector<AutofillServerFieldInfo>::iterator current_info =
550      field_infos.begin();
551  for (std::vector<FormStructure*>::const_iterator iter = forms.begin();
552       iter != forms.end(); ++iter) {
553    FormStructure* form = *iter;
554    form->upload_required_ = upload_required;
555
556    for (std::vector<AutofillField*>::iterator field = form->fields_.begin();
557         field != form->fields_.end(); ++field) {
558      if (form->ShouldSkipField(**field))
559        continue;
560
561      // In some cases *successful* response does not return all the fields.
562      // Quit the update of the types then.
563      if (current_info == field_infos.end())
564        break;
565
566      // UNKNOWN_TYPE is reserved for use by the client.
567      DCHECK_NE(current_info->field_type, UNKNOWN_TYPE);
568
569      ServerFieldType heuristic_type = (*field)->heuristic_type();
570      if (heuristic_type != UNKNOWN_TYPE)
571        heuristics_detected_fillable_field = true;
572
573      (*field)->set_server_type(current_info->field_type);
574      if (heuristic_type != (*field)->Type().GetStorableType())
575        query_response_overrode_heuristics = true;
576
577      // Copy default value into the field if available.
578      if (!current_info->default_value.empty())
579        (*field)->set_default_value(current_info->default_value);
580
581      ++current_info;
582    }
583
584    form->UpdateAutofillCount();
585    form->IdentifySections(false);
586  }
587
588  AutofillMetrics::ServerQueryMetric metric;
589  if (query_response_overrode_heuristics) {
590    if (heuristics_detected_fillable_field) {
591      metric = AutofillMetrics::QUERY_RESPONSE_OVERRODE_LOCAL_HEURISTICS;
592    } else {
593      metric = AutofillMetrics::QUERY_RESPONSE_WITH_NO_LOCAL_HEURISTICS;
594    }
595  } else {
596    metric = AutofillMetrics::QUERY_RESPONSE_MATCHED_LOCAL_HEURISTICS;
597  }
598  metric_logger.LogServerQueryMetric(metric);
599}
600
601// static
602void FormStructure::GetFieldTypePredictions(
603    const std::vector<FormStructure*>& form_structures,
604    std::vector<FormDataPredictions>* forms) {
605  forms->clear();
606  forms->reserve(form_structures.size());
607  for (size_t i = 0; i < form_structures.size(); ++i) {
608    FormStructure* form_structure = form_structures[i];
609    FormDataPredictions form;
610    form.data.name = form_structure->form_name_;
611    form.data.method =
612        base::ASCIIToUTF16((form_structure->method_ == POST) ? "POST" : "GET");
613    form.data.origin = form_structure->source_url_;
614    form.data.action = form_structure->target_url_;
615    form.signature = form_structure->FormSignature();
616
617    for (std::vector<AutofillField*>::const_iterator field =
618             form_structure->fields_.begin();
619         field != form_structure->fields_.end(); ++field) {
620      form.data.fields.push_back(FormFieldData(**field));
621
622      FormFieldDataPredictions annotated_field;
623      annotated_field.signature = (*field)->FieldSignature();
624      annotated_field.heuristic_type =
625          AutofillType((*field)->heuristic_type()).ToString();
626      annotated_field.server_type =
627          AutofillType((*field)->server_type()).ToString();
628      annotated_field.overall_type = (*field)->Type().ToString();
629      form.fields.push_back(annotated_field);
630    }
631
632    forms->push_back(form);
633  }
634}
635
636std::string FormStructure::FormSignature() const {
637  std::string scheme(target_url_.scheme());
638  std::string host(target_url_.host());
639
640  // If target host or scheme is empty, set scheme and host of source url.
641  // This is done to match the Toolbar's behavior.
642  if (scheme.empty() || host.empty()) {
643    scheme = source_url_.scheme();
644    host = source_url_.host();
645  }
646
647  std::string form_string = scheme + "://" + host + "&" +
648                            base::UTF16ToUTF8(form_name_) +
649                            form_signature_field_names_;
650
651  return Hash64Bit(form_string);
652}
653
654bool FormStructure::ShouldSkipField(const FormFieldData& field) const {
655  return field.is_checkable;
656}
657
658bool FormStructure::IsAutofillable(bool require_method_post) const {
659  if (autofill_count() < kRequiredAutofillFields)
660    return false;
661
662  return ShouldBeParsed(require_method_post);
663}
664
665void FormStructure::UpdateAutofillCount() {
666  autofill_count_ = 0;
667  for (std::vector<AutofillField*>::const_iterator iter = begin();
668       iter != end(); ++iter) {
669    AutofillField* field = *iter;
670    if (field && field->IsFieldFillable())
671      ++autofill_count_;
672  }
673}
674
675bool FormStructure::ShouldBeParsed(bool require_method_post) const {
676  if (active_field_count() < kRequiredAutofillFields)
677    return false;
678
679  // Rule out http(s)://*/search?...
680  //  e.g. http://www.google.com/search?q=...
681  //       http://search.yahoo.com/search?p=...
682  if (target_url_.path() == "/search")
683    return false;
684
685  bool has_text_field = false;
686  for (std::vector<AutofillField*>::const_iterator it = begin();
687       it != end() && !has_text_field; ++it) {
688    has_text_field |= (*it)->form_control_type != "select-one";
689  }
690  if (!has_text_field)
691    return false;
692
693  return !require_method_post || (method_ == POST);
694}
695
696bool FormStructure::ShouldBeCrowdsourced() const {
697  return !has_author_specified_types_ && ShouldBeParsed(true);
698}
699
700void FormStructure::UpdateFromCache(const FormStructure& cached_form) {
701  // Map from field signatures to cached fields.
702  std::map<std::string, const AutofillField*> cached_fields;
703  for (size_t i = 0; i < cached_form.field_count(); ++i) {
704    const AutofillField* field = cached_form.field(i);
705    cached_fields[field->FieldSignature()] = field;
706  }
707
708  for (std::vector<AutofillField*>::const_iterator iter = begin();
709       iter != end(); ++iter) {
710    AutofillField* field = *iter;
711
712    std::map<std::string, const AutofillField*>::const_iterator
713        cached_field = cached_fields.find(field->FieldSignature());
714    if (cached_field != cached_fields.end()) {
715      if (field->form_control_type != "select-one" &&
716          field->value == cached_field->second->value) {
717        // From the perspective of learning user data, text fields containing
718        // default values are equivalent to empty fields.
719        field->value = base::string16();
720      }
721
722      field->set_heuristic_type(cached_field->second->heuristic_type());
723      field->set_server_type(cached_field->second->server_type());
724    }
725  }
726
727  UpdateAutofillCount();
728
729  // The form signature should match between query and upload requests to the
730  // server. On many websites, form elements are dynamically added, removed, or
731  // rearranged via JavaScript between page load and form submission, so we
732  // copy over the |form_signature_field_names_| corresponding to the query
733  // request.
734  DCHECK_EQ(cached_form.form_name_, form_name_);
735  DCHECK_EQ(cached_form.source_url_, source_url_);
736  DCHECK_EQ(cached_form.target_url_, target_url_);
737  form_signature_field_names_ = cached_form.form_signature_field_names_;
738}
739
740void FormStructure::LogQualityMetrics(
741    const AutofillMetrics& metric_logger,
742    const base::TimeTicks& load_time,
743    const base::TimeTicks& interaction_time,
744    const base::TimeTicks& submission_time) const {
745  size_t num_detected_field_types = 0;
746  bool did_autofill_all_possible_fields = true;
747  bool did_autofill_some_possible_fields = false;
748  for (size_t i = 0; i < field_count(); ++i) {
749    const AutofillField* field = this->field(i);
750
751    // No further logging for empty fields nor for fields where the entered data
752    // does not appear to already exist in the user's stored Autofill data.
753    const ServerFieldTypeSet& field_types = field->possible_types();
754    DCHECK(!field_types.empty());
755    if (field_types.count(EMPTY_TYPE) || field_types.count(UNKNOWN_TYPE))
756      continue;
757
758    // Similarly, no further logging for password fields.  Those are primarily
759    // related to a different feature code path, and so make more sense to track
760    // outside of this metric.
761    if (field->form_control_type == "password")
762      continue;
763
764    ++num_detected_field_types;
765    if (field->is_autofilled)
766      did_autofill_some_possible_fields = true;
767    else
768      did_autofill_all_possible_fields = false;
769
770    // Collapse field types that Chrome treats as identical, e.g. home and
771    // billing address fields.
772    ServerFieldTypeSet collapsed_field_types;
773    for (ServerFieldTypeSet::const_iterator it = field_types.begin();
774         it != field_types.end();
775         ++it) {
776      // Since we currently only support US phone numbers, the (city code + main
777      // digits) number is almost always identical to the whole phone number.
778      // TODO(isherman): Improve this logic once we add support for
779      // international numbers.
780      if (*it == PHONE_HOME_CITY_AND_NUMBER)
781        collapsed_field_types.insert(PHONE_HOME_WHOLE_NUMBER);
782      else
783        collapsed_field_types.insert(AutofillType(*it).GetStorableType());
784    }
785
786    // Capture the field's type, if it is unambiguous.
787    ServerFieldType field_type = UNKNOWN_TYPE;
788    if (collapsed_field_types.size() == 1)
789      field_type = *collapsed_field_types.begin();
790
791    ServerFieldType heuristic_type =
792        AutofillType(field->heuristic_type()).GetStorableType();
793    ServerFieldType server_type =
794        AutofillType(field->server_type()).GetStorableType();
795    ServerFieldType predicted_type = field->Type().GetStorableType();
796
797    // Log heuristic, server, and overall type quality metrics, independently of
798    // whether the field was autofilled.
799    if (heuristic_type == UNKNOWN_TYPE) {
800      metric_logger.LogHeuristicTypePrediction(AutofillMetrics::TYPE_UNKNOWN,
801                                               field_type);
802    } else if (field_types.count(heuristic_type)) {
803      metric_logger.LogHeuristicTypePrediction(AutofillMetrics::TYPE_MATCH,
804                                               field_type);
805    } else {
806      metric_logger.LogHeuristicTypePrediction(AutofillMetrics::TYPE_MISMATCH,
807                                               field_type);
808    }
809
810    if (server_type == NO_SERVER_DATA) {
811      metric_logger.LogServerTypePrediction(AutofillMetrics::TYPE_UNKNOWN,
812                                            field_type);
813    } else if (field_types.count(server_type)) {
814      metric_logger.LogServerTypePrediction(AutofillMetrics::TYPE_MATCH,
815                                            field_type);
816    } else {
817      metric_logger.LogServerTypePrediction(AutofillMetrics::TYPE_MISMATCH,
818                                            field_type);
819    }
820
821    if (predicted_type == UNKNOWN_TYPE) {
822      metric_logger.LogOverallTypePrediction(AutofillMetrics::TYPE_UNKNOWN,
823                                             field_type);
824    } else if (field_types.count(predicted_type)) {
825      metric_logger.LogOverallTypePrediction(AutofillMetrics::TYPE_MATCH,
826                                             field_type);
827    } else {
828      metric_logger.LogOverallTypePrediction(AutofillMetrics::TYPE_MISMATCH,
829                                             field_type);
830    }
831  }
832
833  if (num_detected_field_types < kRequiredAutofillFields) {
834    metric_logger.LogUserHappinessMetric(
835        AutofillMetrics::SUBMITTED_NON_FILLABLE_FORM);
836  } else {
837    if (did_autofill_all_possible_fields) {
838      metric_logger.LogUserHappinessMetric(
839          AutofillMetrics::SUBMITTED_FILLABLE_FORM_AUTOFILLED_ALL);
840    } else if (did_autofill_some_possible_fields) {
841      metric_logger.LogUserHappinessMetric(
842          AutofillMetrics::SUBMITTED_FILLABLE_FORM_AUTOFILLED_SOME);
843    } else {
844      metric_logger.LogUserHappinessMetric(
845          AutofillMetrics::SUBMITTED_FILLABLE_FORM_AUTOFILLED_NONE);
846    }
847
848    // Unlike the other times, the |submission_time| should always be available.
849    DCHECK(!submission_time.is_null());
850
851    // The |load_time| might be unset, in the case that the form was dynamically
852    // added to the DOM.
853    if (!load_time.is_null()) {
854      // Submission should always chronologically follow form load.
855      DCHECK(submission_time > load_time);
856      base::TimeDelta elapsed = submission_time - load_time;
857      if (did_autofill_some_possible_fields)
858        metric_logger.LogFormFillDurationFromLoadWithAutofill(elapsed);
859      else
860        metric_logger.LogFormFillDurationFromLoadWithoutAutofill(elapsed);
861    }
862
863    // The |interaction_time| might be unset, in the case that the user
864    // submitted a blank form.
865    if (!interaction_time.is_null()) {
866      // Submission should always chronologically follow interaction.
867      DCHECK(submission_time > interaction_time);
868      base::TimeDelta elapsed = submission_time - interaction_time;
869      if (did_autofill_some_possible_fields) {
870        metric_logger.LogFormFillDurationFromInteractionWithAutofill(elapsed);
871      } else {
872        metric_logger.LogFormFillDurationFromInteractionWithoutAutofill(
873            elapsed);
874      }
875    }
876  }
877}
878
879const AutofillField* FormStructure::field(size_t index) const {
880  if (index >= fields_.size()) {
881    NOTREACHED();
882    return NULL;
883  }
884
885  return fields_[index];
886}
887
888AutofillField* FormStructure::field(size_t index) {
889  return const_cast<AutofillField*>(
890      static_cast<const FormStructure*>(this)->field(index));
891}
892
893size_t FormStructure::field_count() const {
894  return fields_.size();
895}
896
897size_t FormStructure::active_field_count() const {
898  return active_field_count_;
899}
900
901FormData FormStructure::ToFormData() const {
902  // |data.user_submitted| will always be false.
903  FormData data;
904  data.name = form_name_;
905  data.origin = source_url_;
906  data.action = target_url_;
907  data.method = base::ASCIIToUTF16(method_ == POST ? "POST" : "GET");
908
909  for (size_t i = 0; i < fields_.size(); ++i) {
910    data.fields.push_back(FormFieldData(*fields_[i]));
911  }
912
913  return data;
914}
915
916bool FormStructure::operator==(const FormData& form) const {
917  // TODO(jhawkins): Is this enough to differentiate a form?
918  if (form_name_ == form.name &&
919      source_url_ == form.origin &&
920      target_url_ == form.action) {
921    return true;
922  }
923
924  // TODO(jhawkins): Compare field names, IDs and labels once we have labels
925  // set up.
926
927  return false;
928}
929
930bool FormStructure::operator!=(const FormData& form) const {
931  return !operator==(form);
932}
933
934std::string FormStructure::Hash64Bit(const std::string& str) {
935  std::string hash_bin = base::SHA1HashString(str);
936  DCHECK_EQ(20U, hash_bin.length());
937
938  uint64 hash64 = (((static_cast<uint64>(hash_bin[0])) & 0xFF) << 56) |
939                  (((static_cast<uint64>(hash_bin[1])) & 0xFF) << 48) |
940                  (((static_cast<uint64>(hash_bin[2])) & 0xFF) << 40) |
941                  (((static_cast<uint64>(hash_bin[3])) & 0xFF) << 32) |
942                  (((static_cast<uint64>(hash_bin[4])) & 0xFF) << 24) |
943                  (((static_cast<uint64>(hash_bin[5])) & 0xFF) << 16) |
944                  (((static_cast<uint64>(hash_bin[6])) & 0xFF) << 8) |
945                   ((static_cast<uint64>(hash_bin[7])) & 0xFF);
946
947  return base::Uint64ToString(hash64);
948}
949
950bool FormStructure::EncodeFormRequest(
951    FormStructure::EncodeRequestType request_type,
952    buzz::XmlElement* encompassing_xml_element) const {
953  if (!field_count())  // Nothing to add.
954    return false;
955
956  // Some badly formatted web sites repeat fields - limit number of fields to
957  // 48, which is far larger than any valid form and XML still fits into 2K.
958  // Do not send requests for forms with more than this many fields, as they are
959  // near certainly not valid/auto-fillable.
960  const size_t kMaxFieldsOnTheForm = 48;
961  if (field_count() > kMaxFieldsOnTheForm)
962    return false;
963
964  // Add the child nodes for the form fields.
965  for (size_t index = 0; index < field_count(); ++index) {
966    const AutofillField* field = fields_[index];
967    switch (request_type) {
968      case FormStructure::UPLOAD:
969        EncodeFieldForUpload(*field, encompassing_xml_element);
970        break;
971      case FormStructure::QUERY:
972        if (ShouldSkipField(*field))
973          continue;
974        EncodeFieldForQuery(*field, encompassing_xml_element);
975        break;
976      case FormStructure::FIELD_ASSIGNMENTS:
977        EncodeFieldForFieldAssignments(*field, encompassing_xml_element);
978        break;
979    }
980  }
981  return true;
982}
983
984void FormStructure::ParseFieldTypesFromAutocompleteAttributes(
985    bool* found_types,
986    bool* found_sections) {
987  const std::string kDefaultSection = "-default";
988
989  *found_types = false;
990  *found_sections = false;
991  for (std::vector<AutofillField*>::iterator it = fields_.begin();
992       it != fields_.end(); ++it) {
993    AutofillField* field = *it;
994
995    // To prevent potential section name collisions, add a default suffix for
996    // other fields.  Without this, 'autocomplete' attribute values
997    // "section--shipping street-address" and "shipping street-address" would be
998    // parsed identically, given the section handling code below.  We do this
999    // before any validation so that fields with invalid attributes still end up
1000    // in the default section.  These default section names will be overridden
1001    // by subsequent heuristic parsing steps if there are no author-specified
1002    // section names.
1003    field->set_section(kDefaultSection);
1004
1005    // Canonicalize the attribute value by trimming whitespace, collapsing
1006    // non-space characters (e.g. tab) to spaces, and converting to lowercase.
1007    std::string autocomplete_attribute =
1008        base::CollapseWhitespaceASCII(field->autocomplete_attribute, false);
1009    autocomplete_attribute = StringToLowerASCII(autocomplete_attribute);
1010
1011    // The autocomplete attribute is overloaded: it can specify either a field
1012    // type hint or whether autocomplete should be enabled at all.  Ignore the
1013    // latter type of attribute value.
1014    if (autocomplete_attribute.empty() ||
1015        autocomplete_attribute == "on" ||
1016        autocomplete_attribute == "off") {
1017      continue;
1018    }
1019
1020    // Any other value, even it is invalid, is considered to be a type hint.
1021    // This allows a website's author to specify an attribute like
1022    // autocomplete="other" on a field to disable all Autofill heuristics for
1023    // the form.
1024    *found_types = true;
1025
1026    // Tokenize the attribute value.  Per the spec, the tokens are parsed in
1027    // reverse order.
1028    std::vector<std::string> tokens;
1029    Tokenize(autocomplete_attribute, " ", &tokens);
1030
1031    // The final token must be the field type.
1032    // If it is not one of the known types, abort.
1033    DCHECK(!tokens.empty());
1034    std::string field_type_token = tokens.back();
1035    tokens.pop_back();
1036    HtmlFieldType field_type =
1037        FieldTypeFromAutocompleteAttributeValue(field_type_token, *field);
1038    if (field_type == HTML_TYPE_UNKNOWN)
1039      continue;
1040
1041    // The preceding token, if any, may be a type hint.
1042    if (!tokens.empty() && IsContactTypeHint(tokens.back())) {
1043      // If it is, it must match the field type; otherwise, abort.
1044      // Note that an invalid token invalidates the entire attribute value, even
1045      // if the other tokens are valid.
1046      if (!ContactTypeHintMatchesFieldType(tokens.back(), field_type))
1047        continue;
1048
1049      // Chrome Autofill ignores these type hints.
1050      tokens.pop_back();
1051    }
1052
1053    // The preceding token, if any, may be a fixed string that is either
1054    // "shipping" or "billing".  Chrome Autofill treats these as implicit
1055    // section name suffixes.
1056    DCHECK_EQ(kDefaultSection, field->section());
1057    std::string section = field->section();
1058    HtmlFieldMode mode = HTML_MODE_NONE;
1059    if (!tokens.empty()) {
1060      if (tokens.back() == kShippingMode)
1061        mode = HTML_MODE_SHIPPING;
1062      else if (tokens.back() == kBillingMode)
1063        mode = HTML_MODE_BILLING;
1064    }
1065
1066    if (mode != HTML_MODE_NONE) {
1067      section = "-" + tokens.back();
1068      tokens.pop_back();
1069    }
1070
1071    // The preceding token, if any, may be a named section.
1072    const std::string kSectionPrefix = "section-";
1073    if (!tokens.empty() &&
1074        StartsWithASCII(tokens.back(), kSectionPrefix, true)) {
1075      // Prepend this section name to the suffix set in the preceding block.
1076      section = tokens.back().substr(kSectionPrefix.size()) + section;
1077      tokens.pop_back();
1078    }
1079
1080    // No other tokens are allowed.  If there are any remaining, abort.
1081    if (!tokens.empty())
1082      continue;
1083
1084    if (section != kDefaultSection) {
1085      *found_sections = true;
1086      field->set_section(section);
1087    }
1088
1089    // No errors encountered while parsing!
1090    // Update the |field|'s type based on what was parsed from the attribute.
1091    field->SetHtmlType(field_type, mode);
1092  }
1093}
1094
1095bool FormStructure::FillFields(
1096    const std::vector<ServerFieldType>& types,
1097    const InputFieldComparator& matches,
1098    const base::Callback<base::string16(const AutofillType&)>& get_info,
1099    const std::string& app_locale) {
1100  bool filled_something = false;
1101  for (size_t i = 0; i < field_count(); ++i) {
1102    for (size_t j = 0; j < types.size(); ++j) {
1103      if (matches.Run(types[j], *field(i))) {
1104        AutofillField::FillFormField(*field(i),
1105                                     get_info.Run(field(i)->Type()),
1106                                     app_locale,
1107                                     field(i));
1108        filled_something = true;
1109        break;
1110      }
1111    }
1112  }
1113  return filled_something;
1114}
1115
1116std::set<base::string16> FormStructure::PossibleValues(ServerFieldType type) {
1117  std::set<base::string16> values;
1118  AutofillType target_type(type);
1119  for (std::vector<AutofillField*>::iterator iter = fields_.begin();
1120       iter != fields_.end(); ++iter) {
1121    AutofillField* field = *iter;
1122    if (field->Type().GetStorableType() != target_type.GetStorableType() ||
1123        field->Type().group() != target_type.group()) {
1124      continue;
1125    }
1126
1127    // No option values; anything goes.
1128    if (field->option_values.empty())
1129      return std::set<base::string16>();
1130
1131    for (size_t i = 0; i < field->option_values.size(); ++i) {
1132      if (!field->option_values[i].empty())
1133        values.insert(base::i18n::ToUpper(field->option_values[i]));
1134    }
1135
1136    for (size_t i = 0; i < field->option_contents.size(); ++i) {
1137      if (!field->option_contents[i].empty())
1138        values.insert(base::i18n::ToUpper(field->option_contents[i]));
1139    }
1140  }
1141
1142  return values;
1143}
1144
1145void FormStructure::IdentifySections(bool has_author_specified_sections) {
1146  if (fields_.empty())
1147    return;
1148
1149  if (!has_author_specified_sections) {
1150    // Name sections after the first field in the section.
1151    base::string16 current_section = fields_.front()->unique_name();
1152
1153    // Keep track of the types we've seen in this section.
1154    std::set<ServerFieldType> seen_types;
1155    ServerFieldType previous_type = UNKNOWN_TYPE;
1156
1157    for (std::vector<AutofillField*>::iterator field = fields_.begin();
1158         field != fields_.end(); ++field) {
1159      const ServerFieldType current_type = (*field)->Type().GetStorableType();
1160
1161      bool already_saw_current_type = seen_types.count(current_type) > 0;
1162
1163      // Forms often ask for multiple phone numbers -- e.g. both a daytime and
1164      // evening phone number.  Our phone number detection is also generally a
1165      // little off.  Hence, ignore this field type as a signal here.
1166      if (AutofillType(current_type).group() == PHONE_HOME)
1167        already_saw_current_type = false;
1168
1169      // Some forms have adjacent fields of the same type.  Two common examples:
1170      //  * Forms with two email fields, where the second is meant to "confirm"
1171      //    the first.
1172      //  * Forms with a <select> menu for states in some countries, and a
1173      //    freeform <input> field for states in other countries.  (Usually,
1174      //    only one of these two will be visible for any given choice of
1175      //    country.)
1176      // Generally, adjacent fields of the same type belong in the same logical
1177      // section.
1178      if (current_type == previous_type)
1179        already_saw_current_type = false;
1180
1181      previous_type = current_type;
1182
1183      if (current_type != UNKNOWN_TYPE && already_saw_current_type) {
1184        // We reached the end of a section, so start a new section.
1185        seen_types.clear();
1186        current_section = (*field)->unique_name();
1187      }
1188
1189      seen_types.insert(current_type);
1190      (*field)->set_section(base::UTF16ToUTF8(current_section));
1191    }
1192  }
1193
1194  // Ensure that credit card and address fields are in separate sections.
1195  // This simplifies the section-aware logic in autofill_manager.cc.
1196  for (std::vector<AutofillField*>::iterator field = fields_.begin();
1197       field != fields_.end(); ++field) {
1198    FieldTypeGroup field_type_group = (*field)->Type().group();
1199    if (field_type_group == CREDIT_CARD)
1200      (*field)->set_section((*field)->section() + "-cc");
1201    else
1202      (*field)->set_section((*field)->section() + "-default");
1203  }
1204}
1205
1206}  // namespace autofill
1207