Commit message: None
CVE: None
Vulnerability description: None

Project: Chrome

  DownloadManagerTest() {
    download_manager_ = new DownloadManager();
  }

Project: Chrome

  void GetGeneratedFilename(const std::string& content_disposition,
                            const std::string& url,
                            const std::string& mime_type,
                            const std::string& referrer_charset,
                            std::wstring* generated_name_string) {
    DownloadCreateInfo info;
    info.content_disposition = content_disposition;
    info.url = GURL(url);
    info.mime_type = mime_type;
    info.referrer_charset = referrer_charset;
    FilePath generated_name;
    DownloadManager::GenerateFileNameFromInfo(&info, &generated_name);
    *generated_name_string = generated_name.ToWStringHack();
  }

Project: Chrome

void AppendFormattedComponent(const std::string& spec,
                              const url_parse::Component& in_component,
                              UnescapeRule::Type unescape_rules,
                              std::wstring* output,
                              url_parse::Component* out_component,
                              size_t* offset_for_adjustment) {
  DCHECK(output);
  DCHECK(offset_for_adjustment);
  if (in_component.is_nonempty()) {
    out_component->begin = static_cast<int>(output->length());
    size_t offset_past_current_output =
        ((*offset_for_adjustment == std::wstring::npos) ||
         (*offset_for_adjustment < output->length())) ?
            std::wstring::npos : (*offset_for_adjustment - output->length());
    size_t* offset_into_component =
        (offset_past_current_output >= static_cast<size_t>(in_component.len)) ?
            NULL : &offset_past_current_output;
    if (unescape_rules == UnescapeRule::NONE) {
      output->append(UTF8ToWideAndAdjustOffset(
          spec.substr(in_component.begin, in_component.len),
          offset_into_component));
    } else {
      output->append(UTF16ToWideHack(UnescapeAndDecodeUTF8URLComponent(
          spec.substr(in_component.begin, in_component.len), unescape_rules,
          offset_into_component)));
    }
    out_component->len =
        static_cast<int>(output->length()) - out_component->begin;
    if (offset_into_component) {
      *offset_for_adjustment = (*offset_into_component == std::wstring::npos) ?
          std::wstring::npos : (out_component->begin + *offset_into_component);
    } else if (offset_past_current_output != std::wstring::npos) {
      *offset_for_adjustment += out_component->len - in_component.len;
    }
  } else {
    out_component->reset();
  }
}

Project: Chrome

void AppendFormattedHost(const GURL& url,
                         const std::wstring& languages,
                         std::wstring* output,
                         url_parse::Parsed* new_parsed,
                         size_t* offset_for_adjustment) {
  DCHECK(output);
  const url_parse::Component& host =
      url.parsed_for_possibly_invalid_spec().host;

  if (host.is_nonempty()) {
    int new_host_begin = static_cast<int>(output->length());
    if (new_parsed)
      new_parsed->host.begin = new_host_begin;
    size_t offset_past_current_output =
        (!offset_for_adjustment ||
         (*offset_for_adjustment == std::wstring::npos) ||
         (*offset_for_adjustment < output->length())) ?
            std::wstring::npos : (*offset_for_adjustment - output->length());
    size_t* offset_into_host =
        (offset_past_current_output >= static_cast<size_t>(host.len)) ?
            NULL : &offset_past_current_output;

    const std::string& spec = url.possibly_invalid_spec();
    DCHECK(host.begin >= 0 &&
           ((spec.length() == 0 && host.begin == 0) ||
            host.begin < static_cast<int>(spec.length())));
    output->append(net::IDNToUnicode(&spec[host.begin],
                   static_cast<size_t>(host.len), languages, offset_into_host));

    int new_host_len = static_cast<int>(output->length()) - new_host_begin;
    if (new_parsed)
      new_parsed->host.len = new_host_len;
    if (offset_into_host) {
      *offset_for_adjustment = (*offset_into_host == std::wstring::npos) ?
          std::wstring::npos : (new_host_begin + *offset_into_host);
    } else if (offset_past_current_output != std::wstring::npos) {
      *offset_for_adjustment += new_host_len - host.len;
    }
  } else if (new_parsed) {
    new_parsed->host.reset();
  }
}

Project: Chrome

std::string CanonicalizeHost(const std::wstring& host,
                             url_canon::CanonHostInfo* host_info) {
  std::string converted_host;
  WideToUTF8(host.c_str(), host.length(), &converted_host);
  return CanonicalizeHost(converted_host, host_info);
}

Project: Chrome

bool DecodeBQEncoding(const std::string& part, RFC2047EncodingType enc_type,
                       const std::string& charset, std::string* output) {
  std::string decoded;
  if (enc_type == B_ENCODING) {
    if (!base::Base64Decode(part, &decoded)) {
      return false;
    }
  } else {
    if (!QPDecode(part, &decoded)) {
      return false;
    }
  }

  UErrorCode err = U_ZERO_ERROR;
  UConverter* converter(ucnv_open(charset.c_str(), &err));
  if (U_FAILURE(err)) {
    return false;
  }

  int length = static_cast<int>(decoded.length());
  char* buf = WriteInto(output, length * 3);
  length = ucnv_toAlgorithmic(UCNV_UTF8, converter, buf, length * 3,
      decoded.data(), length, &err);
  ucnv_close(converter);
  if (U_FAILURE(err)) {
    return false;
  }
  output->resize(length);
  return true;
}

Project: Chrome

bool DecodeParamValue(const std::string& input,
                      const std::string& referrer_charset,
                      std::string* output) {
  std::string tmp;
  StringTokenizer t(input, " \t\n\r");
  t.set_options(StringTokenizer::RETURN_DELIMS);
  bool is_previous_token_rfc2047 = true;
  while (t.GetNext()) {
    if (t.token_is_delim()) {
      if (!is_previous_token_rfc2047) {
        tmp.push_back(' ');
      }
      continue;
    }
    std::string decoded;
    if (!DecodeWord(t.token(), referrer_charset, &is_previous_token_rfc2047,
                    &decoded))
      return false;
    tmp.append(decoded);
  }
  output->swap(tmp);
  return true;
}

Project: Chrome

GURL FilePathToFileURL(const FilePath& path) {
  FilePath::StringType url_string(kFileURLPrefix);
  url_string.append(path.value());


  ReplaceSubstringsAfterOffset(&url_string, 0,
      FILE_PATH_LITERAL("%"), FILE_PATH_LITERAL("%25"));

  ReplaceSubstringsAfterOffset(&url_string, 0,
      FILE_PATH_LITERAL(";"), FILE_PATH_LITERAL("%3B"));

  ReplaceSubstringsAfterOffset(&url_string, 0,
      FILE_PATH_LITERAL("#"), FILE_PATH_LITERAL("%23"));

#if defined(OS_POSIX)
  ReplaceSubstringsAfterOffset(&url_string, 0,
      FILE_PATH_LITERAL("\\"), FILE_PATH_LITERAL("%5C"));
#endif

  return GURL(url_string);
}

Project: Chrome

std::wstring FormatUrl(const GURL& url,
                       const std::wstring& languages,
                       bool omit_username_password,
                       UnescapeRule::Type unescape_rules,
                       url_parse::Parsed* new_parsed,
                       size_t* prefix_end,
                       size_t* offset_for_adjustment) {
  url_parse::Parsed parsed_temp;
  if (!new_parsed)
    new_parsed = &parsed_temp;
  size_t offset_temp = std::wstring::npos;
  if (!offset_for_adjustment)
    offset_for_adjustment = &offset_temp;

  std::wstring url_string;

  if (url.is_empty()) {
    if (prefix_end)
      *prefix_end = 0;
    *offset_for_adjustment = std::wstring::npos;
    return url_string;
  }

  const char* const kViewSource = "view-source";
  const char* const kViewSourceTwice = "view-source:view-source:";
  if (url.SchemeIs(kViewSource) &&
      !StartsWithASCII(url.possibly_invalid_spec(), kViewSourceTwice, false)) {
    return FormatViewSourceUrl(url, languages, omit_username_password,
        unescape_rules, new_parsed, prefix_end, offset_for_adjustment);
  }

  const std::string& spec = url.possibly_invalid_spec();
  const url_parse::Parsed& parsed = url.parsed_for_possibly_invalid_spec();
  if (*offset_for_adjustment >= spec.length())
    *offset_for_adjustment = std::wstring::npos;

  std::copy(spec.begin(),
      spec.begin() + parsed.CountCharactersBefore(url_parse::Parsed::USERNAME,
                                                  true),
      std::back_inserter(url_string));
  new_parsed->scheme = parsed.scheme;

  if (omit_username_password) {
    new_parsed->username.reset();
    new_parsed->password.reset();
    if ((*offset_for_adjustment != std::wstring::npos) &&
        (parsed.username.is_nonempty() || parsed.password.is_nonempty())) {
      if (parsed.username.is_nonempty() && parsed.password.is_nonempty()) {
        if (*offset_for_adjustment >
            static_cast<size_t>(parsed.password.end())) {
          *offset_for_adjustment -=
              (parsed.username.len + parsed.password.len + 2);
        } else if (*offset_for_adjustment >
                   static_cast<size_t>(parsed.username.begin)) {
          *offset_for_adjustment = std::wstring::npos;
        }
      } else {
        const url_parse::Component* nonempty_component =
            parsed.username.is_nonempty() ? &parsed.username : &parsed.password;
        if (*offset_for_adjustment >
            static_cast<size_t>(nonempty_component->end())) {
          *offset_for_adjustment -= (nonempty_component->len + 1);
        } else if (*offset_for_adjustment >
                   static_cast<size_t>(nonempty_component->begin)) {
          *offset_for_adjustment = std::wstring::npos;
        }
      }
    }
  } else {
    AppendFormattedComponent(spec, parsed.username, unescape_rules, &url_string,
                             &new_parsed->username, offset_for_adjustment);
    if (parsed.password.is_valid()) {
      url_string.push_back(':');
    }
    AppendFormattedComponent(spec, parsed.password, unescape_rules, &url_string,
                             &new_parsed->password, offset_for_adjustment);
    if (parsed.username.is_valid() || parsed.password.is_valid()) {
      url_string.push_back('@');
    }
  }
  if (prefix_end)
    *prefix_end = static_cast<size_t>(url_string.length());

  AppendFormattedHost(url, languages, &url_string, new_parsed,
                      offset_for_adjustment);

  if (parsed.port.is_nonempty()) {
    url_string.push_back(':');
    new_parsed->port.begin = url_string.length();
    std::copy(spec.begin() + parsed.port.begin,
              spec.begin() + parsed.port.end(), std::back_inserter(url_string));
    new_parsed->port.len = url_string.length() - new_parsed->port.begin;
  } else {
    new_parsed->port.reset();
  }

  AppendFormattedComponent(spec, parsed.path, unescape_rules, &url_string,
                           &new_parsed->path, offset_for_adjustment);
  if (parsed.query.is_valid())
    url_string.push_back('?');
  AppendFormattedComponent(spec, parsed.query, unescape_rules, &url_string,
                           &new_parsed->query, offset_for_adjustment);

  if (parsed.ref.is_valid()) {
    url_string.push_back('#');
    new_parsed->ref.begin = url_string.length();
    size_t offset_past_current_output =
        ((*offset_for_adjustment == std::wstring::npos) ||
         (*offset_for_adjustment < url_string.length())) ?
            std::wstring::npos : (*offset_for_adjustment - url_string.length());
    size_t* offset_into_ref =
        (offset_past_current_output >= static_cast<size_t>(parsed.ref.len)) ?
            NULL : &offset_past_current_output;
    if (parsed.ref.len > 0) {
      url_string.append(UTF8ToWideAndAdjustOffset(spec.substr(parsed.ref.begin,
                                                              parsed.ref.len),
                                                  offset_into_ref));
    }
    new_parsed->ref.len = url_string.length() - new_parsed->ref.begin;
    if (offset_into_ref) {
      *offset_for_adjustment = (*offset_into_ref == std::wstring::npos) ?
          std::wstring::npos : (new_parsed->ref.begin + *offset_into_ref);
    } else if (offset_past_current_output != std::wstring::npos) {
      *offset_for_adjustment = std::wstring::npos;
    }
  }

  return url_string;
}

Project: Chrome

std::wstring FormatViewSourceUrl(const GURL& url,
                                 const std::wstring& languages,
                                 bool omit_username_password,
                                 UnescapeRule::Type unescape_rules,
                                 url_parse::Parsed* new_parsed,
                                 size_t* prefix_end,
                                 size_t* offset_for_adjustment) {
  DCHECK(new_parsed);
  const wchar_t* const kWideViewSource = L"view-source:";
  const size_t kViewSourceLengthPlus1 = 12;

  GURL real_url(url.possibly_invalid_spec().substr(kViewSourceLengthPlus1));
  size_t temp_offset = (*offset_for_adjustment == std::wstring::npos) ?
      std::wstring::npos : (*offset_for_adjustment - kViewSourceLengthPlus1);
  size_t* temp_offset_ptr = (*offset_for_adjustment < kViewSourceLengthPlus1) ?
      NULL : &temp_offset;
  std::wstring result = net::FormatUrl(real_url, languages,
      omit_username_password, unescape_rules, new_parsed, prefix_end,
      temp_offset_ptr);
  result.insert(0, kWideViewSource);

  if (new_parsed->scheme.is_nonempty()) {
    new_parsed->scheme.len += kViewSourceLengthPlus1;
  } else {
    new_parsed->scheme.begin = 0;
    new_parsed->scheme.len = kViewSourceLengthPlus1 - 1;
  }
  if (new_parsed->username.is_nonempty())
    new_parsed->username.begin += kViewSourceLengthPlus1;
  if (new_parsed->password.is_nonempty())
    new_parsed->password.begin += kViewSourceLengthPlus1;
  if (new_parsed->host.is_nonempty())
    new_parsed->host.begin += kViewSourceLengthPlus1;
  if (new_parsed->port.is_nonempty())
    new_parsed->port.begin += kViewSourceLengthPlus1;
  if (new_parsed->path.is_nonempty())
    new_parsed->path.begin += kViewSourceLengthPlus1;
  if (new_parsed->query.is_nonempty())
    new_parsed->query.begin += kViewSourceLengthPlus1;
  if (new_parsed->ref.is_nonempty())
    new_parsed->ref.begin += kViewSourceLengthPlus1;
  if (prefix_end)
    *prefix_end += kViewSourceLengthPlus1;
  if (temp_offset_ptr) {
    *offset_for_adjustment = (temp_offset == std::wstring::npos) ?
        std::wstring::npos : (temp_offset + kViewSourceLengthPlus1);
  }
  return result;
}

Project: Chrome

std::string GetDirectoryListingEntry(const string16& name,
                                     const std::string& raw_bytes,
                                     bool is_dir,
                                     int64 size,
                                     Time modified) {
  std::string result;
  result.append("<script>addRow(");
  base::JsonDoubleQuote(name, true, &result);
  result.append(",");
  if (raw_bytes.empty()) {
    base::JsonDoubleQuote(EscapePath(UTF16ToUTF8(name)),
                                   true, &result);
  } else {
    base::JsonDoubleQuote(EscapePath(raw_bytes), true, &result);
  }
  if (is_dir) {
    result.append(",1,");
  } else {
    result.append(",0,");
  }

  base::JsonDoubleQuote(
      WideToUTF16Hack(FormatBytes(size, GetByteDisplayUnits(size), true)), true,
      &result);

  result.append(",");

  string16 modified_str;
  if (!modified.is_null()) {
    modified_str = WideToUTF16Hack(base::TimeFormatShortDateAndTime(modified));
  }
  base::JsonDoubleQuote(modified_str, true, &result);

  result.append(");</script>\n");

  return result;
}

Project: Chrome

std::string GetDirectoryListingHeader(const string16& title) {
  static const base::StringPiece header(
      NetModule::GetResource(IDR_DIR_HEADER_HTML));
  DLOG_IF(WARNING, header.empty()) <<
      "Missing resource: directory listing header";

  std::string result;
  if (!header.empty())
    result.assign(header.data(), header.size());

  result.append("<script>start(");
  base::JsonDoubleQuote(title, true, &result);
  result.append(");</script>\n");

  return result;
}

Project: Chrome

std::string GetFileNameFromCD(const std::string& header,
                              const std::string& referrer_charset) {
  std::string param_value = GetHeaderParamValue(header, "filename");
  if (param_value.empty()) {
    param_value = GetHeaderParamValue(header, "name");
  }
  if (param_value.empty())
    return std::string();
  std::string decoded;
  if (DecodeParamValue(param_value, referrer_charset, &decoded))
    return decoded;
  return std::string();
}

Project: Chrome

std::wstring GetHeaderParamValue(const std::wstring& field,
                                 const std::wstring& param_name) {
  return GetHeaderParamValueT(field, param_name);
}

Project: Chrome

std::string GetHeaderParamValue(const std::string& field,
                                const std::string& param_name) {
  return GetHeaderParamValueT(field, param_name);
}

Project: Chrome

STR GetHeaderParamValueT(const STR& header, const STR& param_name) {
  typename STR::const_iterator param_begin =
      search(header.begin(), header.end(), param_name.begin(), param_name.end(),
             CaseInsensitiveCompareASCII<typename STR::value_type>());

  if (param_begin == header.end())
    return STR();
  param_begin += param_name.length();

  STR whitespace;
  whitespace.push_back(' ');
  whitespace.push_back('\t');
  const typename STR::size_type equals_offset =
      header.find_first_not_of(whitespace, param_begin - header.begin());
  if (equals_offset == STR::npos || header.at(equals_offset) != '=')
    return STR();

  param_begin = header.begin() + equals_offset + 1;
  if (param_begin == header.end())
    return STR();

  typename STR::const_iterator param_end;
  if (*param_begin == '"') {
    param_end = find(param_begin+1, header.end(), '"');
    if (param_end == header.end())
      return STR();  // poorly formatted param?

    ++param_begin;  // skip past the quote.
  } else {
    param_end = find(param_begin+1, header.end(), ';');
  }

  return STR(param_begin, param_end);
}

Project: Chrome

std::string GetHostAndOptionalPort(const GURL& url) {
  if (url.has_port())
    return StringPrintf("%s:%s", url.host().c_str(), url.port().c_str());
  return url.host();
}

Project: Chrome

std::string GetHostAndPort(const GURL& url) {
  return StringPrintf("%s:%d", url.host().c_str(), url.EffectiveIntPort());
}

Project: Chrome

std::string GetHostName() {
#if defined(OS_WIN)
  EnsureWinsockInit();
#endif

  char buffer[256];
  int result = gethostname(buffer, sizeof(buffer));
  if (result != 0) {
    DLOG(INFO) << "gethostname() failed with " << result;
    buffer[0] = '\0';
  }
  return std::string(buffer);
}

Project: Chrome

void GetIdentityFromURL(const GURL& url,
                        std::wstring* username,
                        std::wstring* password) {
  UnescapeRule::Type flags = UnescapeRule::SPACES;
  *username = UTF16ToWideHack(UnescapeAndDecodeUTF8URLComponent(url.username(),
                                                                flags, NULL));
  *password = UTF16ToWideHack(UnescapeAndDecodeUTF8URLComponent(url.password(),
                                                                flags, NULL));
}

Project: Chrome

std::string GetSpecificHeader(const std::string& headers,
                               const std::string& name) {
  return GetSpecificHeaderT(headers, name);
}

Project: Chrome

STR GetSpecificHeaderT(const STR& headers, const STR& name) {
  if (headers.empty())
    return STR();

  STR match;
  match.push_back('\n');
  match.append(name);
  match.push_back(':');

  typename STR::const_iterator begin =
      search(headers.begin(), headers.end(), match.begin(), match.end(),
             CaseInsensitiveCompareASCII<typename STR::value_type>());

  if (begin == headers.end())
    return STR();

  begin += match.length();

  typename STR::const_iterator end = find(begin, headers.end(), '\n');

  STR ret;
  TrimWhitespace(STR(begin, end), TRIM_ALL, &ret);
  return ret;
}

Project: Chrome

std::wstring IDNToUnicode(const char* host,
                          size_t host_len,
                          const std::wstring& languages,
                          size_t* offset_for_adjustment) {
  string16 input16;
  input16.reserve(host_len);
  std::copy(host, host + host_len, std::back_inserter(input16));

  string16 out16;
  size_t output_offset = offset_for_adjustment ?
      *offset_for_adjustment : std::wstring::npos;

  for (size_t component_start = 0, component_end;
       component_start < input16.length();
       component_start = component_end + 1) {
    component_end = input16.find('.', component_start);
    if (component_end == string16::npos)
      component_end = input16.length();  // For getting the last component.
    size_t component_length = component_end - component_start;

    size_t output_component_start = out16.length();
    bool converted_idn = false;
    if (component_end > component_start) {
      converted_idn = IDNToUnicodeOneComponent(input16.data() + component_start,
          component_length, languages, &out16);
    }
    size_t output_component_length = out16.length() - output_component_start;

    if ((output_offset != std::wstring::npos) &&
        (*offset_for_adjustment > component_start)) {
      if ((*offset_for_adjustment < component_end) && converted_idn)
        output_offset = std::wstring::npos;
      else
        output_offset += output_component_length - component_length;
    }

    if (component_end < input16.length())
      out16.push_back('.');
  }

  if (offset_for_adjustment)
    *offset_for_adjustment = output_offset;

  return UTF16ToWideAndAdjustOffset(out16, offset_for_adjustment);
}

Project: Chrome

bool IDNToUnicodeOneComponent(const char16* comp,
                              size_t comp_len,
                              const std::wstring& languages,
                              string16* out) {
  DCHECK(out);
  if (comp_len == 0)
    return false;

  static const char16 kIdnPrefix[] = {'x', 'n', '-', '-'};
  if ((comp_len > arraysize(kIdnPrefix)) &&
      !memcmp(comp, kIdnPrefix, arraysize(kIdnPrefix) * sizeof(char16))) {
    size_t original_length = out->length();
    for (int extra_space = 64; ; extra_space *= 2) {
      UErrorCode status = U_ZERO_ERROR;
      out->resize(out->length() + extra_space);
      int output_chars = uidna_IDNToUnicode(comp,
          static_cast<int32_t>(comp_len), &(*out)[original_length], extra_space,
          UIDNA_DEFAULT, NULL, &status);
      if (status == U_ZERO_ERROR) {
        out->resize(original_length + output_chars);
        if (IsIDNComponentSafe(out->data() + original_length, output_chars,
                               languages))
          return true;
      }

      if (status != U_BUFFER_OVERFLOW_ERROR)
        break;
    }
    out->resize(original_length);
  }

  out->append(comp, comp_len);
  return false;
}

Project: Chrome

static void IPv6SupportResults(IPv6SupportStatus result) {
  static bool run_once = false;
  if (run_once)
    return;
  run_once = true;
  UMA_HISTOGRAM_ENUMERATION("Net.IPv6Status", result, IPV6_SUPPORT_MAX);
}

Project: Chrome

bool IPv6Supported() {
#if defined(OS_POSIX)
  int test_socket;

  test_socket = socket(AF_INET6, SOCK_STREAM, 0);
  if (test_socket == -1) {
    IPv6SupportResults(IPV6_CANNOT_CREATE_SOCKETS);
    return false;
  }

  close(test_socket);
  IPv6SupportResults(IPV6_CAN_CREATE_SOCKETS);
  return true;
#elif defined(OS_WIN)
  EnsureWinsockInit();
  SOCKET test_socket;

  test_socket = socket(AF_INET6, SOCK_STREAM, 0);
  if (test_socket == INVALID_SOCKET) {
    IPv6SupportResults(IPV6_CANNOT_CREATE_SOCKETS);
    return false;
  }

  closesocket(test_socket);
  IPv6SupportResults(IPV6_CAN_CREATE_SOCKETS);
  return true;
#else
  NOTIMPLEMENTED();
  return true;
#endif  // defined(various platforms)
}

Project: Chrome

bool IsCanonicalizedHostCompliant(const std::string& host) {
  if (host.empty())
    return false;

  bool in_component = false;
  bool most_recent_component_started_alpha = false;
  bool last_char_was_hyphen_or_underscore = false;

  for (std::string::const_iterator i(host.begin()); i != host.end(); ++i) {
    const char c = *i;
    if (!in_component) {
      most_recent_component_started_alpha = IsHostCharAlpha(c);
      if (!most_recent_component_started_alpha && !IsHostCharDigit(c))
        return false;
      in_component = true;
    } else {
      if (c == '.') {
        if (last_char_was_hyphen_or_underscore)
          return false;
        in_component = false;
      } else if (IsHostCharAlpha(c) || IsHostCharDigit(c)) {
        last_char_was_hyphen_or_underscore = false;
      } else if ((c == '-') || (c == '_')) {
        last_char_was_hyphen_or_underscore = true;
      } else {
        return false;
      }
    }
  }

  return most_recent_component_started_alpha;
}

Project: Chrome

bool IsCompatibleWithASCIILetters(const std::string& lang) {
  return !lang.substr(0, 2).compare("zh") ||
         !lang.substr(0, 2).compare("ja") ||
         !lang.substr(0, 2).compare("ko");
}

Project: Chrome

bool IsComponentCoveredByLang(const icu::UnicodeSet& component_characters,
                              const std::string& lang) {
  static const icu::UnicodeSet kASCIILetters(0x61, 0x7a);  // [a-z]
  icu::UnicodeSet* lang_set;
  {
    AutoLock lock(lang_set_lock);
    if (!GetExemplarSetForLang(lang, &lang_set)) {
      UErrorCode status = U_ZERO_ERROR;
      ULocaleData* uld = ulocdata_open(lang.c_str(), &status);
      if (U_SUCCESS(status) && status != U_USING_DEFAULT_WARNING) {
        lang_set = reinterpret_cast<icu::UnicodeSet *>(
            ulocdata_getExemplarSet(uld, NULL, 0,
                                    ULOCDATA_ES_STANDARD, &status));
        if (IsCompatibleWithASCIILetters(lang))
          lang_set->addAll(kASCIILetters);
      } else {
        lang_set = new icu::UnicodeSet(1, 0);
      }
      lang_set->freeze();
      SetExemplarSetForLang(lang, lang_set);
      ulocdata_close(uld);
    }
  }
  return !lang_set->isEmpty() && lang_set->containsAll(component_characters);
}

Project: Chrome

inline bool IsHexDigit(unsigned char c) {
  return (('0' <= c && c <= '9') || ('A' <= c && c <= 'F') ||
          ('a' <= c && c <= 'f'));
}

Project: Chrome

inline bool IsHostCharAlpha(char c) {
  return (c >= 'a') && (c <= 'z');
}

Project: Chrome

inline bool IsHostCharDigit(char c) {
  return (c >= '0') && (c <= '9');
}

Project: Chrome

bool IsIDNComponentInSingleScript(const char16* str, int str_len) {
  UScriptCode first_script = USCRIPT_INVALID_CODE;
  bool is_first = true;

  int i = 0;
  while (i < str_len) {
    unsigned code_point;
    U16_NEXT(str, i, str_len, code_point);

    UErrorCode err = U_ZERO_ERROR;
    UScriptCode cur_script = uscript_getScript(code_point, &err);
    if (err != U_ZERO_ERROR)
      return false;  // Report mixed on error.
    cur_script = NormalizeScript(cur_script);

    if (is_first && cur_script != USCRIPT_COMMON) {
      first_script = cur_script;
      is_first = false;
    } else {
      if (cur_script != USCRIPT_COMMON && cur_script != first_script)
        return false;
    }
  }
  return true;
}

Project: Chrome

bool IsIDNComponentSafe(const char16* str,
                        int str_len,
                        const std::wstring& languages) {

  UErrorCode status = U_ZERO_ERROR;
#ifdef U_WCHAR_IS_UTF16
  icu::UnicodeSet dangerous_characters(icu::UnicodeString(
      L"[[\\ \u00bc\u00bd\u01c3\u0337\u0338"
      L"\u05c3\u05f4\u06d4\u0702\u115f\u1160][\u2000-\u200b]"
      L"[\u2024\u2027\u2028\u2029\u2039\u203a\u2044\u205f]"
      L"[\u2154-\u2156][\u2159-\u215b][\u215f\u2215\u23ae"
      L"\u29f6\u29f8\u2afb\u2afd][\u2ff0-\u2ffb][\u3014"
      L"\u3015\u3033\u3164\u321d\u321e\u33ae\u33af\u33c6\u33df\ufe14"
      L"\ufe15\ufe3f\ufe5d\ufe5e\ufeff\uff0e\uff06\uff61\uffa0\ufff9]"
      L"[\ufffa-\ufffd]]"), status);
#else
  icu::UnicodeSet dangerous_characters(icu::UnicodeString(
      "[[\\u0020\\u00bc\\u00bd\\u01c3\\u0337\\u0338"
      "\\u05c3\\u05f4\\u06d4\\u0702\\u115f\\u1160][\\u2000-\\u200b]"
      "[\\u2024\\u2027\\u2028\\u2029\\u2039\\u203a\\u2044\\u205f]"
      "[\\u2154-\\u2156][\\u2159-\\u215b][\\u215f\\u2215\\u23ae"
      "\\u29f6\\u29f8\\u2afb\\u2afd][\\u2ff0-\\u2ffb][\\u3014"
      "\\u3015\\u3033\\u3164\\u321d\\u321e\\u33ae\\u33af\\u33c6\\u33df\\ufe14"
      "\\ufe15\\ufe3f\\ufe5d\\ufe5e\\ufeff\\uff0e\\uff06\\uff61\\uffa0\\ufff9]"
      "[\\ufffa-\\ufffd]]", -1, US_INV), status);
#endif
  DCHECK(U_SUCCESS(status));
  icu::UnicodeSet component_characters;
  component_characters.addAll(icu::UnicodeString(str, str_len));
  if (dangerous_characters.containsSome(component_characters))
    return false;

  if (languages.empty())
    return IsIDNComponentInSingleScript(str, str_len);

  icu::UnicodeSet common_characters(UNICODE_STRING_SIMPLE("[[0-9]\\-_+\\ ]"),
                                    status);
  DCHECK(U_SUCCESS(status));
  component_characters.removeAll(common_characters);

  std::string languages_list(WideToASCII(languages));
  StringTokenizer t(languages_list, ",");
  while (t.GetNext()) {
    if (IsComponentCoveredByLang(component_characters, t.token()))
      return true;
  }
  return false;
}

Project: Chrome

bool IsPortAllowedByFtp(int port) {
  int array_size = arraysize(kAllowedFtpPorts);
  for (int i = 0; i < array_size; i++) {
    if (kAllowedFtpPorts[i] == port) {
        return true;
    }
  }
  return IsPortAllowedByDefault(port);
}

Project: Chrome

bool IsPortAllowedByOverride(int port) {
  if (explicitly_allowed_ports.empty())
    return false;

  std::set<int>::const_iterator it =
      std::find(explicitly_allowed_ports.begin(),
                explicitly_allowed_ports.end(),
                port);

  return it != explicitly_allowed_ports.end();
}

Project: Chrome

  LangToExemplarSet() { }

Project: Chrome

std::string NetAddressToString(const struct addrinfo* net_address) {
#if defined(OS_WIN)
  EnsureWinsockInit();
#endif

  char buffer[INET6_ADDRSTRLEN];

  int result = getnameinfo(net_address->ai_addr,
      net_address->ai_addrlen, buffer, sizeof(buffer), NULL, 0, NI_NUMERICHOST);

  if (result != 0) {
    DLOG(INFO) << "getnameinfo() failed with " << result;
    buffer[0] = '\0';
  }
  return std::string(buffer);
}

Project: Chrome

UScriptCode NormalizeScript(UScriptCode code) {
  switch (code) {
    case USCRIPT_KATAKANA:
    case USCRIPT_HIRAGANA:
    case USCRIPT_KATAKANA_OR_HIRAGANA:
    case USCRIPT_HANGUL:  // This one is arguable.
      return USCRIPT_HAN;
    default:
      return code;
  }
}

Project: Chrome

bool ParseHostAndPort(std::string::const_iterator host_and_port_begin,
                      std::string::const_iterator host_and_port_end,
                      std::string* host,
                      int* port) {
  if (host_and_port_begin >= host_and_port_end)
    return false;

  const char* auth_begin = &(*host_and_port_begin);
  int auth_len = host_and_port_end - host_and_port_begin;

  url_parse::Component auth_component(0, auth_len);
  url_parse::Component username_component;
  url_parse::Component password_component;
  url_parse::Component hostname_component;
  url_parse::Component port_component;

  url_parse::ParseAuthority(auth_begin, auth_component, &username_component,
      &password_component, &hostname_component, &port_component);

  if (username_component.is_valid() || password_component.is_valid())
    return false;

  if (!hostname_component.is_nonempty())
    return false;  // Failed parsing.

  int parsed_port_number = -1;
  if (port_component.is_nonempty()) {
    parsed_port_number = url_parse::ParsePort(auth_begin, port_component);

    if (parsed_port_number < 0)
      return false;  // Failed parsing the port number.
  }

  if (port_component.len == 0)
    return false;  // Reject inputs like "foo:"

  host->assign(auth_begin + hostname_component.begin, hostname_component.len);
  *port = parsed_port_number;

  return true;  // Success.
}

Project: Chrome

bool QPDecode(const std::string& input, std::string* output) {
  std::string temp;
  temp.reserve(input.size());
  std::string::const_iterator it = input.begin();
  while (it != input.end()) {
    if (*it == '_') {
      temp.push_back(' ');
    } else if (*it == '=') {
      if (input.end() - it < 3) {
        return false;
      }
      if (IsHexDigit(static_cast<unsigned char>(*(it + 1))) &&
          IsHexDigit(static_cast<unsigned char>(*(it + 2)))) {
        unsigned char ch = HexToInt(*(it + 1)) * 16 + HexToInt(*(it + 2));
        temp.push_back(static_cast<char>(ch));
        ++it;
        ++it;
      } else {
        return false;
      }
    } else if (0x20 < *it && *it < 0x7F) {
      DCHECK(*it != 0x3D && *it != 0x5F && *it != 0x3F);
      temp.push_back(*it);
    } else {
      return false;
    }
    ++it;
  }
  output->swap(temp);
  return true;
}

Project: Chrome

void SetExemplarSetForLang(const std::string& lang,
                           icu::UnicodeSet* lang_set) {
  LangToExemplarSetMap& map = Singleton<LangToExemplarSet>()->map;
  map.insert(std::make_pair(lang, lang_set));
}

Project: Chrome

void SetExplicitlyAllowedPorts(const std::wstring& allowed_ports) {
  if (allowed_ports.empty())
    return;

  std::set<int> ports;
  size_t last = 0;
  size_t size = allowed_ports.size();
  const std::wstring::value_type kComma = L',';

  for (size_t i = 0; i <= size; ++i) {
    if (i != size && !IsAsciiDigit(allowed_ports[i]) &&
        (allowed_ports[i] != kComma))
      return;
    if (i == size || allowed_ports[i] == kComma) {
      size_t length = i - last;
      if (length > 0)
        ports.insert(StringToInt(WideToASCII(
            allowed_ports.substr(last, length))));
      last = i + 1;
    }
  }
  explicitly_allowed_ports = ports;
}

Project: Chrome

  ~LangToExemplarSet() {
    STLDeleteContainerPairSecondPointers(map.begin(), map.end());
  }