Home | History | Annotate | Download | only in browser
      1 // Copyright (c) 2011 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 "chrome/browser/intranet_redirect_detector.h"
      6 
      7 #include "base/command_line.h"
      8 #include "base/rand_util.h"
      9 #include "base/stl_util-inl.h"
     10 #include "base/utf_string_conversions.h"
     11 #include "chrome/browser/browser_process.h"
     12 #include "chrome/browser/prefs/pref_service.h"
     13 #include "chrome/common/chrome_switches.h"
     14 #include "chrome/common/pref_names.h"
     15 #include "content/common/notification_service.h"
     16 #include "net/base/load_flags.h"
     17 #include "net/base/net_errors.h"
     18 #include "net/base/registry_controlled_domain.h"
     19 #include "net/url_request/url_request_context_getter.h"
     20 #include "net/url_request/url_request_status.h"
     21 
     22 const size_t IntranetRedirectDetector::kNumCharsInHostnames = 10;
     23 
     24 IntranetRedirectDetector::IntranetRedirectDetector()
     25     : redirect_origin_(g_browser_process->local_state()->GetString(
     26           prefs::kLastKnownIntranetRedirectOrigin)),
     27       ALLOW_THIS_IN_INITIALIZER_LIST(fetcher_factory_(this)),
     28       in_sleep_(true) {
     29   // Because this function can be called during startup, when kicking off a URL
     30   // fetch can eat up 20 ms of time, we delay seven seconds, which is hopefully
     31   // long enough to be after startup, but still get results back quickly.
     32   // Ideally, instead of this timer, we'd do something like "check if the
     33   // browser is starting up, and if so, come back later", but there is currently
     34   // no function to do this.
     35   static const int kStartFetchDelayMS = 7000;
     36   MessageLoop::current()->PostDelayedTask(FROM_HERE,
     37       fetcher_factory_.NewRunnableMethod(
     38           &IntranetRedirectDetector::FinishSleep),
     39       kStartFetchDelayMS);
     40 
     41   net::NetworkChangeNotifier::AddIPAddressObserver(this);
     42 }
     43 
     44 IntranetRedirectDetector::~IntranetRedirectDetector() {
     45   net::NetworkChangeNotifier::RemoveIPAddressObserver(this);
     46   STLDeleteElements(&fetchers_);
     47 }
     48 
     49 // static
     50 GURL IntranetRedirectDetector::RedirectOrigin() {
     51   const IntranetRedirectDetector* const detector =
     52       g_browser_process->intranet_redirect_detector();
     53   return detector ? detector->redirect_origin_ : GURL();
     54 }
     55 
     56 // static
     57 void IntranetRedirectDetector::RegisterPrefs(PrefService* prefs) {
     58   prefs->RegisterStringPref(prefs::kLastKnownIntranetRedirectOrigin,
     59                             std::string());
     60 }
     61 
     62 void IntranetRedirectDetector::FinishSleep() {
     63   in_sleep_ = false;
     64 
     65   // If another fetch operation is still running, cancel it.
     66   STLDeleteElements(&fetchers_);
     67   resulting_origins_.clear();
     68 
     69   // The detector is not needed in Chrome Frame since we have no omnibox there.
     70   const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
     71   if (cmd_line->HasSwitch(switches::kDisableBackgroundNetworking) ||
     72       cmd_line->HasSwitch(switches::kChromeFrame))
     73     return;
     74 
     75   DCHECK(fetchers_.empty() && resulting_origins_.empty());
     76 
     77   // Start three fetchers on random hostnames.
     78   for (size_t i = 0; i < 3; ++i) {
     79     std::string url_string("http://");
     80     for (size_t j = 0; j < kNumCharsInHostnames; ++j)
     81       url_string += ('a' + base::RandInt(0, 'z' - 'a'));
     82     GURL random_url(url_string + '/');
     83     URLFetcher* fetcher = new URLFetcher(random_url, URLFetcher::HEAD, this);
     84     // We don't want these fetches to affect existing state in the profile.
     85     fetcher->set_load_flags(net::LOAD_DISABLE_CACHE |
     86                             net::LOAD_DO_NOT_SAVE_COOKIES);
     87     fetcher->set_request_context(g_browser_process->system_request_context());
     88     fetcher->Start();
     89     fetchers_.insert(fetcher);
     90   }
     91 }
     92 
     93 void IntranetRedirectDetector::OnURLFetchComplete(
     94     const URLFetcher* source,
     95     const GURL& url,
     96     const net::URLRequestStatus& status,
     97     int response_code,
     98     const ResponseCookies& cookies,
     99     const std::string& data) {
    100   // Delete the fetcher on this function's exit.
    101   Fetchers::iterator fetcher = fetchers_.find(const_cast<URLFetcher*>(source));
    102   DCHECK(fetcher != fetchers_.end());
    103   scoped_ptr<URLFetcher> clean_up_fetcher(*fetcher);
    104   fetchers_.erase(fetcher);
    105 
    106   // If any two fetches result in the same domain/host, we set the redirect
    107   // origin to that; otherwise we set it to nothing.
    108   if (!status.is_success() || (response_code != 200)) {
    109     if ((resulting_origins_.empty()) ||
    110         ((resulting_origins_.size() == 1) &&
    111          resulting_origins_.front().is_valid())) {
    112       resulting_origins_.push_back(GURL());
    113       return;
    114     }
    115     redirect_origin_ = GURL();
    116   } else {
    117     DCHECK(url.is_valid());
    118     GURL origin(url.GetOrigin());
    119     if (resulting_origins_.empty()) {
    120       resulting_origins_.push_back(origin);
    121       return;
    122     }
    123     if (net::RegistryControlledDomainService::SameDomainOrHost(
    124         resulting_origins_.front(), origin)) {
    125       redirect_origin_ = origin;
    126       if (!fetchers_.empty()) {
    127         // Cancel remaining fetch, we don't need it.
    128         DCHECK(fetchers_.size() == 1);
    129         delete (*fetchers_.begin());
    130         fetchers_.clear();
    131       }
    132     }
    133     if (resulting_origins_.size() == 1) {
    134       resulting_origins_.push_back(origin);
    135       return;
    136     }
    137     DCHECK(resulting_origins_.size() == 2);
    138     redirect_origin_ = net::RegistryControlledDomainService::SameDomainOrHost(
    139         resulting_origins_.back(), origin) ? origin : GURL();
    140   }
    141 
    142   g_browser_process->local_state()->SetString(
    143       prefs::kLastKnownIntranetRedirectOrigin, redirect_origin_.is_valid() ?
    144           redirect_origin_.spec() : std::string());
    145 }
    146 
    147 void IntranetRedirectDetector::OnIPAddressChanged() {
    148   // If a request is already scheduled, do not scheduled yet another one.
    149   if (in_sleep_)
    150     return;
    151 
    152   // Since presumably many programs open connections after network changes,
    153   // delay this a little bit.
    154   in_sleep_ = true;
    155   static const int kNetworkSwitchDelayMS = 1000;
    156   MessageLoop::current()->PostDelayedTask(FROM_HERE,
    157       fetcher_factory_.NewRunnableMethod(
    158           &IntranetRedirectDetector::FinishSleep),
    159       kNetworkSwitchDelayMS);
    160 }
    161 
    162 IntranetRedirectHostResolverProc::IntranetRedirectHostResolverProc(
    163     net::HostResolverProc* previous)
    164     : net::HostResolverProc(previous) {
    165 }
    166 
    167 int IntranetRedirectHostResolverProc::Resolve(
    168     const std::string& host,
    169     net::AddressFamily address_family,
    170     net::HostResolverFlags host_resolver_flags,
    171     net::AddressList* addrlist,
    172     int* os_error) {
    173   // We'd love to just ask the IntranetRedirectDetector, but we may not be on
    174   // the same thread.  So just use the heuristic that any all-lowercase a-z
    175   // hostname with the right number of characters is likely from the detector
    176   // (and thus should be blocked).
    177   return ((host.length() == IntranetRedirectDetector::kNumCharsInHostnames) &&
    178       (host.find_first_not_of("abcdefghijklmnopqrstuvwxyz") ==
    179           std::string::npos)) ?
    180       net::ERR_NAME_NOT_RESOLVED :
    181       ResolveUsingPrevious(host, address_family, host_resolver_flags, addrlist,
    182                            os_error);
    183 }
    184