diff options
author | darin@chromium.org <darin@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2010-02-03 19:19:15 +0000 |
---|---|---|
committer | darin@chromium.org <darin@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2010-02-03 19:19:15 +0000 |
commit | c7a90eab2f4a045fee103dbfa18710918b368476 (patch) | |
tree | e12ebddacb41a61bb804deff42a504b0361f5544 /net | |
parent | 97cdd4667b961cf865047d0bc764764a7c199ce7 (diff) | |
download | chromium_src-c7a90eab2f4a045fee103dbfa18710918b368476.zip chromium_src-c7a90eab2f4a045fee103dbfa18710918b368476.tar.gz chromium_src-c7a90eab2f4a045fee103dbfa18710918b368476.tar.bz2 |
Modify CookiePolicy to work asynchronously
This change will enable us to prompt the user before setting a cookie. While we only need to prompt before setting, we actually need to make both CanSetCookie and CanGetCookies asynchronous. This is necessary in order to preserve FIFO ordering since the value returned by GetCookies depends on the changes made to the cookie DB by SetCookie.
This change also includes some simplification of CookieStore. Instead of N virtual functions, I distilled it down to only 4. The remaining functions are instead expressed in terms of those.
While studying all the places where we currently use CookiePolicy, I found that some of them were not appropriate. After discussing with Amit, I decided to remove the policy checks in URLRequestAutomationJob. See the comments in the code regarding this.
I changed the signature of CookieMonster::GetRawCookies to GetAllCookiesForURL to better match GetAllCookies. I also filed a bug about making it even closer in functionality. Related to this change webkit/glue/webcookie.h grows a constructor that takes a CanonicalCookie to help clean up some code.
On the Chrome side, ChromeURLRequestContext now has a ChromeCookiePolicy object. That object is thread-safe ref counted because it is passed between the UI and IO threads. It is responsible for implementing the queuing logic described above. It will also in the future trigger the Chrome UI code to actually show the set-cookie prompt.
Please review the state machinery changes in URLRequestHttpJob carefully.
R=eroman
BUG=34331
TEST=no tests yet for prompting.
Review URL: http://codereview.chromium.org/567015
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@37998 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'net')
-rw-r--r-- | net/base/cookie_monster.cc | 77 | ||||
-rw-r--r-- | net/base/cookie_monster.h | 33 | ||||
-rw-r--r-- | net/base/cookie_monster_unittest.cc | 7 | ||||
-rw-r--r-- | net/base/cookie_policy.h | 27 | ||||
-rw-r--r-- | net/base/cookie_store.h | 58 | ||||
-rw-r--r-- | net/base/static_cookie_policy.cc | 32 | ||||
-rw-r--r-- | net/base/static_cookie_policy.h | 40 | ||||
-rw-r--r-- | net/base/static_cookie_policy_unittest.cc | 104 | ||||
-rw-r--r-- | net/url_request/url_request_http_job.cc | 228 | ||||
-rw-r--r-- | net/url_request/url_request_http_job.h | 16 | ||||
-rw-r--r-- | net/url_request/url_request_unittest.cc | 212 | ||||
-rw-r--r-- | net/url_request/url_request_unittest.h | 92 |
12 files changed, 647 insertions, 279 deletions
diff --git a/net/base/cookie_monster.cc b/net/base/cookie_monster.cc index 992191c..805bfc1 100644 --- a/net/base/cookie_monster.cc +++ b/net/base/cookie_monster.cc @@ -404,44 +404,11 @@ void CookieMonster::SetCookieableSchemes( schemes, schemes + num_schemes); } -bool CookieMonster::SetCookie(const GURL& url, - const std::string& cookie_line) { - CookieOptions options; - return SetCookieWithOptions(url, cookie_line, options); -} - -bool CookieMonster::SetCookieWithOptions(const GURL& url, - const std::string& cookie_line, - const CookieOptions& options) { - Time creation_date; - { - AutoLock autolock(lock_); - creation_date = CurrentTime(); - last_time_seen_ = creation_date; - } - return SetCookieWithCreationTimeWithOptions(url, - cookie_line, - creation_date, - options); -} - -bool CookieMonster::SetCookieWithCreationTime(const GURL& url, - const std::string& cookie_line, - const Time& creation_time) { - CookieOptions options; - return SetCookieWithCreationTimeWithOptions(url, - cookie_line, - creation_time, - options); -} - -bool CookieMonster::SetCookieWithCreationTimeWithOptions( - const GURL& url, - const std::string& cookie_line, - const Time& creation_time, - const CookieOptions& options) { - DCHECK(!creation_time.is_null()); - +bool CookieMonster::SetCookieWithCreationTimeAndOptions( + const GURL& url, + const std::string& cookie_line, + const Time& creation_time_or_null, + const CookieOptions& options) { if (!HasCookieableScheme(url)) { return false; } @@ -451,6 +418,12 @@ bool CookieMonster::SetCookieWithCreationTimeWithOptions( COOKIE_DLOG(INFO) << "SetCookie() line: " << cookie_line; + Time creation_time = creation_time_or_null; + if (creation_time.is_null()) { + creation_time = CurrentTime(); + last_time_seen_ = creation_time; + } + // Parse the cookie. ParsedCookie pc(cookie_line); @@ -508,21 +481,6 @@ bool CookieMonster::SetCookieWithCreationTimeWithOptions( return true; } -void CookieMonster::SetCookies(const GURL& url, - const std::vector<std::string>& cookies) { - CookieOptions options; - SetCookiesWithOptions(url, cookies, options); -} - -void CookieMonster::SetCookiesWithOptions( - const GURL& url, - const std::vector<std::string>& cookies, - const CookieOptions& options) { - for (std::vector<std::string>::const_iterator iter = cookies.begin(); - iter != cookies.end(); ++iter) - SetCookieWithOptions(url, *iter, options); -} - void CookieMonster::InternalInsertCookie(const std::string& key, CanonicalCookie* cc, bool sync_to_store) { @@ -736,6 +694,12 @@ static bool CookieSorter(CookieMonster::CanonicalCookie* cc1, return cc1->Path().length() > cc2->Path().length(); } +bool CookieMonster::SetCookieWithOptions(const GURL& url, + const std::string& cookie_line, + const CookieOptions& options) { + return SetCookieWithCreationTimeAndOptions(url, cookie_line, Time(), options); +} + // Currently our cookie datastructure is based on Mozilla's approach. We have a // hash keyed on the cookie's domain, and for any query we walk down the domain // components and probe for cookies until we reach the TLD, where we stop. @@ -748,11 +712,6 @@ static bool CookieSorter(CookieMonster::CanonicalCookie* cc1, // search/prefix trie, where we reverse the hostname and query for all // keys that are a prefix of our hostname. I think the hash probing // should be fast and simple enough for now. -std::string CookieMonster::GetCookies(const GURL& url) { - CookieOptions options; - return GetCookiesWithOptions(url, options); -} - std::string CookieMonster::GetCookiesWithOptions(const GURL& url, const CookieOptions& options) { if (!HasCookieableScheme(url)) { @@ -834,7 +793,7 @@ CookieMonster::CookieList CookieMonster::GetAllCookies() { return cookie_list; } -CookieMonster::CookieList CookieMonster::GetRawCookies(const GURL& url) { +CookieMonster::CookieList CookieMonster::GetAllCookiesForURL(const GURL& url) { AutoLock autolock(lock_); InitIfNecessary(); diff --git a/net/base/cookie_monster.h b/net/base/cookie_monster.h index 6976f7f..7578c46 100644 --- a/net/base/cookie_monster.h +++ b/net/base/cookie_monster.h @@ -73,30 +73,25 @@ class CookieMonster : public CookieStore { static base::Time ParseCookieTime(const std::string& time_string); // CookieStore implementation. - virtual bool SetCookie(const GURL& url, const std::string& cookie_line); virtual bool SetCookieWithOptions(const GURL& url, const std::string& cookie_line, const CookieOptions& options); - virtual bool SetCookieWithCreationTime(const GURL& url, - const std::string& cookie_line, - const base::Time& creation_time); - virtual bool SetCookieWithCreationTimeWithOptions( - const GURL& url, - const std::string& cookie_line, - const base::Time& creation_time, - const CookieOptions& options); - virtual void SetCookies(const GURL& url, - const std::vector<std::string>& cookies); - virtual void SetCookiesWithOptions(const GURL& url, - const std::vector<std::string>& cookies, - const CookieOptions& options); - virtual std::string GetCookies(const GURL& url); virtual std::string GetCookiesWithOptions(const GURL& url, const CookieOptions& options); virtual void DeleteCookie(const GURL& url, const std::string& cookie_name); - - virtual CookieMonster* GetCookieMonster() { - return this; + virtual CookieMonster* GetCookieMonster() { return this; } + + + // Exposed for unit testing. + bool SetCookieWithCreationTimeAndOptions(const GURL& url, + const std::string& cookie_line, + const base::Time& creation_time, + const CookieOptions& options); + bool SetCookieWithCreationTime(const GURL& url, + const std::string& cookie_line, + const base::Time& creation_time) { + return SetCookieWithCreationTimeAndOptions(url, cookie_line, creation_time, + CookieOptions()); } // Returns all the cookies, for use in management UI, etc. This does not mark @@ -106,7 +101,7 @@ class CookieMonster : public CookieStore { // Returns all the cookies, for use in management UI, etc. Filters results // using given url scheme and host / domain. This does not mark the cookies // as having been accessed. - CookieList GetRawCookies(const GURL& url); + CookieList GetAllCookiesForURL(const GURL& url); // Delete all of the cookies. int DeleteAll(bool sync_to_store); diff --git a/net/base/cookie_monster_unittest.cc b/net/base/cookie_monster_unittest.cc index ba645ee..cdbf869 100644 --- a/net/base/cookie_monster_unittest.cc +++ b/net/base/cookie_monster_unittest.cc @@ -961,7 +961,7 @@ TEST(CookieMonsterTest, SetCookieableSchemes) { EXPECT_FALSE(cm_foo->SetCookie(http_url, "x=1")); } -TEST(CookieMonsterTest, GetRawCookies) { +TEST(CookieMonsterTest, GetAllCookiesForURL) { GURL url_google(kUrlGoogle); GURL url_google_secure(kUrlGoogleSecure); @@ -985,7 +985,8 @@ TEST(CookieMonsterTest, GetRawCookies) { PlatformThread::Sleep(kLastAccessThresholdMilliseconds + 20); // Check raw cookies. - net::CookieMonster::CookieList raw_cookies = cm->GetRawCookies(url_google); + net::CookieMonster::CookieList raw_cookies = + cm->GetAllCookiesForURL(url_google); net::CookieMonster::CookieList::iterator it = raw_cookies.begin(); ASSERT_TRUE(it != raw_cookies.end()); @@ -999,7 +1000,7 @@ TEST(CookieMonsterTest, GetRawCookies) { ASSERT_TRUE(++it == raw_cookies.end()); // Test secure cookies. - raw_cookies = cm->GetRawCookies(url_google_secure); + raw_cookies = cm->GetAllCookiesForURL(url_google_secure); it = raw_cookies.begin(); ASSERT_TRUE(it != raw_cookies.end()); diff --git a/net/base/cookie_policy.h b/net/base/cookie_policy.h index 91bbfb9..d2df2f5 100644 --- a/net/base/cookie_policy.h +++ b/net/base/cookie_policy.h @@ -5,19 +5,32 @@ #ifndef NET_BASE_COOKIE_POLICY_H_ #define NET_BASE_COOKIE_POLICY_H_ +#include "net/base/completion_callback.h" + class GURL; namespace net { class CookiePolicy { public: - // Determine if the URL's cookies may be read. - virtual bool CanGetCookies(const GURL& url, - const GURL& first_party_for_cookies) = 0; - - // Determine if the URL's cookies may be written. - virtual bool CanSetCookie(const GURL& url, - const GURL& first_party_for_cookies) = 0; + // Determines if the URL's cookies may be read. Returns OK if allowed to + // read cookies for the given URL. Returns ERR_IO_PENDING to indicate that + // the completion callback will be notified (asynchronously and on the + // current thread) of the final result. Note: The completion callback must + // remain valid until notified. + virtual int CanGetCookies(const GURL& url, + const GURL& first_party_for_cookies, + CompletionCallback* callback) = 0; + + // Determines if the URL's cookies may be written. Returns OK if allowed to + // write a cookie for the given URL. Returns ERR_IO_PENDING to indicate that + // the completion callback will be notified (asynchronously and on the + // current thread) of the final result. Note: The completion callback must + // remain valid until notified. + virtual int CanSetCookie(const GURL& url, + const GURL& first_party_for_cookies, + const std::string& cookie_line, + CompletionCallback* callback) = 0; protected: virtual ~CookiePolicy() {} diff --git a/net/base/cookie_store.h b/net/base/cookie_store.h index 1ea3fa2..2fbe1d8 100644 --- a/net/base/cookie_store.h +++ b/net/base/cookie_store.h @@ -24,45 +24,51 @@ class CookieMonster; // be thread safe as its methods can be accessed from IO as well as UI threads. class CookieStore : public base::RefCountedThreadSafe<CookieStore> { public: - // Set a single cookie. Expects a cookie line, like "a=1; domain=b.com". - virtual bool SetCookie(const GURL& url, const std::string& cookie_line) = 0; + // Sets a single cookie. Expects a cookie line, like "a=1; domain=b.com". virtual bool SetCookieWithOptions(const GURL& url, const std::string& cookie_line, const CookieOptions& options) = 0; - // Sets a single cookie with a specific creation date. To set a cookie with - // a creation date of Now() use SetCookie() instead (it calls this function - // internally). - virtual bool SetCookieWithCreationTime(const GURL& url, - const std::string& cookie_line, - const base::Time& creation_time) = 0; - virtual bool SetCookieWithCreationTimeWithOptions( - const GURL& url, - const std::string& cookie_line, - const base::Time& creation_time, - const CookieOptions& options) = 0; - // Set a vector of response cookie values for the same URL. - virtual void SetCookies(const GURL& url, - const std::vector<std::string>& cookies) = 0; - virtual void SetCookiesWithOptions(const GURL& url, - const std::vector<std::string>& cookies, - const CookieOptions& options) = 0; // TODO what if the total size of all the cookies >4k, can we have a header // that big or do we need multiple Cookie: headers? - // Simple interface, get a cookie string "a=b; c=d" for the given URL. - // It will _not_ return httponly cookies, see CookieOptions. - virtual std::string GetCookies(const GURL& url) = 0; + // Simple interface, gets a cookie string "a=b; c=d" for the given URL. + // Use options to access httponly cookies. virtual std::string GetCookiesWithOptions(const GURL& url, const CookieOptions& options) = 0; - virtual CookieMonster* GetCookieMonster() { - return NULL; - }; - // Deletes the passed in cookie for the specified URL. virtual void DeleteCookie(const GURL& url, const std::string& cookie_name) = 0; + // Returns the underlying CookieMonster. + virtual CookieMonster* GetCookieMonster() = 0; + + + // -------------------------------------------------------------------------- + // Helpers to make the above interface simpler for some cases. + + // Sets a cookie for the given URL using default options. + bool SetCookie(const GURL& url, const std::string& cookie_line) { + return SetCookieWithOptions(url, cookie_line, CookieOptions()); + } + + // Gets cookies for the given URL using default options. + std::string GetCookies(const GURL& url) { + return GetCookiesWithOptions(url, CookieOptions()); + } + + // Sets a vector of response cookie values for the same URL. + void SetCookiesWithOptions(const GURL& url, + const std::vector<std::string>& cookie_lines, + const CookieOptions& options) { + for (size_t i = 0; i < cookie_lines.size(); ++i) + SetCookieWithOptions(url, cookie_lines[i], options); + } + void SetCookies(const GURL& url, + const std::vector<std::string>& cookie_lines) { + SetCookiesWithOptions(url, cookie_lines, CookieOptions()); + } + protected: friend class base::RefCountedThreadSafe<CookieStore>; virtual ~CookieStore() {} diff --git a/net/base/static_cookie_policy.cc b/net/base/static_cookie_policy.cc index 25d58bc..0ff6ead 100644 --- a/net/base/static_cookie_policy.cc +++ b/net/base/static_cookie_policy.cc @@ -6,40 +6,44 @@ #include "base/logging.h" #include "googleurl/src/gurl.h" +#include "net/base/net_errors.h" #include "net/base/registry_controlled_domain.h" namespace net { -bool StaticCookiePolicy::CanGetCookies(const GURL& url, - const GURL& first_party_for_cookies) { +int StaticCookiePolicy::CanGetCookies(const GURL& url, + const GURL& first_party_for_cookies, + CompletionCallback* callback) { switch (type_) { case StaticCookiePolicy::ALLOW_ALL_COOKIES: - return true; + return OK; case StaticCookiePolicy::BLOCK_THIRD_PARTY_COOKIES: - return true; + return OK; case StaticCookiePolicy::BLOCK_ALL_COOKIES: - return false; + return ERR_ACCESS_DENIED; default: NOTREACHED(); - return false; + return ERR_ACCESS_DENIED; } } -bool StaticCookiePolicy::CanSetCookie(const GURL& url, - const GURL& first_party_for_cookies) { +int StaticCookiePolicy::CanSetCookie(const GURL& url, + const GURL& first_party_for_cookies, + const std::string& cookie_line, + CompletionCallback* callback) { switch (type_) { case StaticCookiePolicy::ALLOW_ALL_COOKIES: - return true; + return OK; case StaticCookiePolicy::BLOCK_THIRD_PARTY_COOKIES: if (first_party_for_cookies.is_empty()) - return true; // Empty first-party URL indicates a first-party request. - return net::RegistryControlledDomainService::SameDomainOrHost( - url, first_party_for_cookies); + return OK; // Empty first-party URL indicates a first-party request. + return RegistryControlledDomainService::SameDomainOrHost( + url, first_party_for_cookies) ? OK : ERR_ACCESS_DENIED; case StaticCookiePolicy::BLOCK_ALL_COOKIES: - return false; + return ERR_ACCESS_DENIED; default: NOTREACHED(); - return false; + return ERR_ACCESS_DENIED; } } diff --git a/net/base/static_cookie_policy.h b/net/base/static_cookie_policy.h index a16fd0c..4734d33 100644 --- a/net/base/static_cookie_policy.h +++ b/net/base/static_cookie_policy.h @@ -14,30 +14,18 @@ namespace net { // The StaticCookiePolicy class implements a static cookie policy that supports // three modes: allow all, deny all, or block third-party cookies. +// +// NOTE: This CookiePolicy implementation always completes synchronously. The +// callback parameter will be ignored if specified. Just pass NULL. +// class StaticCookiePolicy : public CookiePolicy { public: - // Consult the user's third-party cookie blocking preferences to determine - // whether the URL's cookies can be read. - bool CanGetCookies(const GURL& url, const GURL& first_party_for_cookies); - - // Consult the user's third-party cookie blocking preferences to determine - // whether the URL's cookies can be set. - bool CanSetCookie(const GURL& url, const GURL& first_party_for_cookies); - enum Type { ALLOW_ALL_COOKIES = 0, // Do not perform any cookie blocking. BLOCK_THIRD_PARTY_COOKIES, // Prevent third-party cookies from being set. BLOCK_ALL_COOKIES // Disable cookies. }; - // Sets the current policy to enforce. This should be called when the user's - // preferences change. - void set_type(Type type) { type_ = type; } - - Type type() const { - return type_; - } - StaticCookiePolicy() : type_(StaticCookiePolicy::ALLOW_ALL_COOKIES) { } @@ -46,6 +34,26 @@ class StaticCookiePolicy : public CookiePolicy { : type_(type) { } + // Sets the current policy to enforce. This should be called when the user's + // preferences change. + void set_type(Type type) { type_ = type; } + Type type() const { return type_; } + + // CookiePolicy methods: + + // Consults the user's third-party cookie blocking preferences to determine + // whether the URL's cookies can be read. + virtual int CanGetCookies(const GURL& url, + const GURL& first_party_for_cookies, + CompletionCallback* callback); + + // Consults the user's third-party cookie blocking preferences to determine + // whether the URL's cookies can be set. + virtual int CanSetCookie(const GURL& url, + const GURL& first_party_for_cookies, + const std::string& cookie_line, + CompletionCallback* callback); + private: Type type_; diff --git a/net/base/static_cookie_policy_unittest.cc b/net/base/static_cookie_policy_unittest.cc index 35af0fc..35c1a82 100644 --- a/net/base/static_cookie_policy_unittest.cc +++ b/net/base/static_cookie_policy_unittest.cc @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "net/base/net_errors.h" #include "net/base/static_cookie_policy.h" #include "testing/gtest/include/gtest/gtest.h" #include "googleurl/src/gurl.h" @@ -12,8 +13,19 @@ class StaticCookiePolicyTest : public testing::Test { : url_google_("http://www.google.izzle"), url_google_secure_("https://www.google.izzle"), url_google_mail_("http://mail.google.izzle"), - url_google_analytics_("http://www.googleanalytics.izzle") { } + url_google_analytics_("http://www.googleanalytics.izzle") { + } + void SetPolicyType(net::StaticCookiePolicy::Type type) { + policy_.set_type(type); + } + int CanGetCookies(const GURL& url, const GURL& first_party) { + return policy_.CanGetCookies(url, first_party, NULL); + } + int CanSetCookie(const GURL& url, const GURL& first_party) { + return policy_.CanSetCookie(url, first_party, std::string(), NULL); + } protected: + net::StaticCookiePolicy policy_; GURL url_google_; GURL url_google_secure_; GURL url_google_mail_; @@ -21,67 +33,63 @@ class StaticCookiePolicyTest : public testing::Test { }; TEST_F(StaticCookiePolicyTest, DefaultPolicyTest) { - net::StaticCookiePolicy cp; - EXPECT_TRUE(cp.CanGetCookies(url_google_, url_google_)); - EXPECT_TRUE(cp.CanGetCookies(url_google_, url_google_secure_)); - EXPECT_TRUE(cp.CanGetCookies(url_google_, url_google_mail_)); - EXPECT_TRUE(cp.CanGetCookies(url_google_, url_google_analytics_)); - EXPECT_TRUE(cp.CanGetCookies(url_google_, GURL())); + EXPECT_EQ(net::OK, CanGetCookies(url_google_, url_google_)); + EXPECT_EQ(net::OK, CanGetCookies(url_google_, url_google_secure_)); + EXPECT_EQ(net::OK, CanGetCookies(url_google_, url_google_mail_)); + EXPECT_EQ(net::OK, CanGetCookies(url_google_, url_google_analytics_)); + EXPECT_EQ(net::OK, CanGetCookies(url_google_, GURL())); - EXPECT_TRUE(cp.CanSetCookie(url_google_, url_google_)); - EXPECT_TRUE(cp.CanSetCookie(url_google_, url_google_secure_)); - EXPECT_TRUE(cp.CanSetCookie(url_google_, url_google_mail_)); - EXPECT_TRUE(cp.CanSetCookie(url_google_, url_google_analytics_)); - EXPECT_TRUE(cp.CanSetCookie(url_google_, GURL())); + EXPECT_EQ(net::OK, CanSetCookie(url_google_, url_google_)); + EXPECT_EQ(net::OK, CanSetCookie(url_google_, url_google_secure_)); + EXPECT_EQ(net::OK, CanSetCookie(url_google_, url_google_mail_)); + EXPECT_EQ(net::OK, CanSetCookie(url_google_, url_google_analytics_)); + EXPECT_EQ(net::OK, CanSetCookie(url_google_, GURL())); } TEST_F(StaticCookiePolicyTest, AllowAllCookiesTest) { - net::StaticCookiePolicy cp; - cp.set_type(net::StaticCookiePolicy::ALLOW_ALL_COOKIES); + SetPolicyType(net::StaticCookiePolicy::ALLOW_ALL_COOKIES); - EXPECT_TRUE(cp.CanGetCookies(url_google_, url_google_)); - EXPECT_TRUE(cp.CanGetCookies(url_google_, url_google_secure_)); - EXPECT_TRUE(cp.CanGetCookies(url_google_, url_google_mail_)); - EXPECT_TRUE(cp.CanGetCookies(url_google_, url_google_analytics_)); - EXPECT_TRUE(cp.CanGetCookies(url_google_, GURL())); + EXPECT_EQ(net::OK, CanGetCookies(url_google_, url_google_)); + EXPECT_EQ(net::OK, CanGetCookies(url_google_, url_google_secure_)); + EXPECT_EQ(net::OK, CanGetCookies(url_google_, url_google_mail_)); + EXPECT_EQ(net::OK, CanGetCookies(url_google_, url_google_analytics_)); + EXPECT_EQ(net::OK, CanGetCookies(url_google_, GURL())); - EXPECT_TRUE(cp.CanSetCookie(url_google_, url_google_)); - EXPECT_TRUE(cp.CanSetCookie(url_google_, url_google_secure_)); - EXPECT_TRUE(cp.CanSetCookie(url_google_, url_google_mail_)); - EXPECT_TRUE(cp.CanSetCookie(url_google_, url_google_analytics_)); - EXPECT_TRUE(cp.CanSetCookie(url_google_, GURL())); + EXPECT_EQ(net::OK, CanSetCookie(url_google_, url_google_)); + EXPECT_EQ(net::OK, CanSetCookie(url_google_, url_google_secure_)); + EXPECT_EQ(net::OK, CanSetCookie(url_google_, url_google_mail_)); + EXPECT_EQ(net::OK, CanSetCookie(url_google_, url_google_analytics_)); + EXPECT_EQ(net::OK, CanSetCookie(url_google_, GURL())); } TEST_F(StaticCookiePolicyTest, BlockThirdPartyCookiesTest) { - net::StaticCookiePolicy cp; - cp.set_type(net::StaticCookiePolicy::BLOCK_THIRD_PARTY_COOKIES); + SetPolicyType(net::StaticCookiePolicy::BLOCK_THIRD_PARTY_COOKIES); - EXPECT_TRUE(cp.CanGetCookies(url_google_, url_google_)); - EXPECT_TRUE(cp.CanGetCookies(url_google_, url_google_secure_)); - EXPECT_TRUE(cp.CanGetCookies(url_google_, url_google_mail_)); - EXPECT_TRUE(cp.CanGetCookies(url_google_, url_google_analytics_)); - EXPECT_TRUE(cp.CanGetCookies(url_google_, GURL())); + EXPECT_EQ(net::OK, CanGetCookies(url_google_, url_google_)); + EXPECT_EQ(net::OK, CanGetCookies(url_google_, url_google_secure_)); + EXPECT_EQ(net::OK, CanGetCookies(url_google_, url_google_mail_)); + EXPECT_EQ(net::OK, CanGetCookies(url_google_, url_google_analytics_)); + EXPECT_EQ(net::OK, CanGetCookies(url_google_, GURL())); - EXPECT_TRUE(cp.CanSetCookie(url_google_, url_google_)); - EXPECT_TRUE(cp.CanSetCookie(url_google_, url_google_secure_)); - EXPECT_TRUE(cp.CanSetCookie(url_google_, url_google_mail_)); - EXPECT_FALSE(cp.CanSetCookie(url_google_, url_google_analytics_)); - EXPECT_TRUE(cp.CanSetCookie(url_google_, GURL())); + EXPECT_EQ(net::OK, CanSetCookie(url_google_, url_google_)); + EXPECT_EQ(net::OK, CanSetCookie(url_google_, url_google_secure_)); + EXPECT_EQ(net::OK, CanSetCookie(url_google_, url_google_mail_)); + EXPECT_NE(net::OK, CanSetCookie(url_google_, url_google_analytics_)); + EXPECT_EQ(net::OK, CanSetCookie(url_google_, GURL())); } TEST_F(StaticCookiePolicyTest, BlockAllCookiesTest) { - net::StaticCookiePolicy cp; - cp.set_type(net::StaticCookiePolicy::BLOCK_ALL_COOKIES); + SetPolicyType(net::StaticCookiePolicy::BLOCK_ALL_COOKIES); - EXPECT_FALSE(cp.CanGetCookies(url_google_, url_google_)); - EXPECT_FALSE(cp.CanGetCookies(url_google_, url_google_secure_)); - EXPECT_FALSE(cp.CanGetCookies(url_google_, url_google_mail_)); - EXPECT_FALSE(cp.CanGetCookies(url_google_, url_google_analytics_)); - EXPECT_FALSE(cp.CanGetCookies(url_google_, GURL())); + EXPECT_NE(net::OK, CanGetCookies(url_google_, url_google_)); + EXPECT_NE(net::OK, CanGetCookies(url_google_, url_google_secure_)); + EXPECT_NE(net::OK, CanGetCookies(url_google_, url_google_mail_)); + EXPECT_NE(net::OK, CanGetCookies(url_google_, url_google_analytics_)); + EXPECT_NE(net::OK, CanGetCookies(url_google_, GURL())); - EXPECT_FALSE(cp.CanSetCookie(url_google_, url_google_)); - EXPECT_FALSE(cp.CanSetCookie(url_google_, url_google_secure_)); - EXPECT_FALSE(cp.CanSetCookie(url_google_, url_google_mail_)); - EXPECT_FALSE(cp.CanSetCookie(url_google_, url_google_analytics_)); - EXPECT_FALSE(cp.CanSetCookie(url_google_, GURL())); + EXPECT_NE(net::OK, CanSetCookie(url_google_, url_google_)); + EXPECT_NE(net::OK, CanSetCookie(url_google_, url_google_secure_)); + EXPECT_NE(net::OK, CanSetCookie(url_google_, url_google_mail_)); + EXPECT_NE(net::OK, CanSetCookie(url_google_, url_google_analytics_)); + EXPECT_NE(net::OK, CanSetCookie(url_google_, GURL())); } diff --git a/net/url_request/url_request_http_job.cc b/net/url_request/url_request_http_job.cc index 4b08c64..15b3373 100644 --- a/net/url_request/url_request_http_job.cc +++ b/net/url_request/url_request_http_job.cc @@ -75,12 +75,17 @@ URLRequestHttpJob::URLRequestHttpJob(URLRequest* request) : URLRequestJob(request), context_(request->context()), response_info_(NULL), + response_cookies_save_index_(0), proxy_auth_state_(net::AUTH_STATE_DONT_NEED_AUTH), server_auth_state_(net::AUTH_STATE_DONT_NEED_AUTH), - ALLOW_THIS_IN_INITIALIZER_LIST( - start_callback_(this, &URLRequestHttpJob::OnStartCompleted)), - ALLOW_THIS_IN_INITIALIZER_LIST( - read_callback_(this, &URLRequestHttpJob::OnReadCompleted)), + ALLOW_THIS_IN_INITIALIZER_LIST(can_get_cookies_callback_( + this, &URLRequestHttpJob::OnCanGetCookiesCompleted)), + ALLOW_THIS_IN_INITIALIZER_LIST(can_set_cookie_callback_( + this, &URLRequestHttpJob::OnCanSetCookieCompleted)), + ALLOW_THIS_IN_INITIALIZER_LIST(start_callback_( + this, &URLRequestHttpJob::OnStartCompleted)), + ALLOW_THIS_IN_INITIALIZER_LIST(read_callback_( + this, &URLRequestHttpJob::OnReadCompleted)), read_in_progress_(false), transaction_(NULL), sdch_dictionary_advertised_(false), @@ -146,8 +151,7 @@ void URLRequestHttpJob::Start() { } AddExtraHeaders(); - - StartTransaction(); + AddCookieHeaderAndStart(); } void URLRequestHttpJob::Kill() { @@ -200,11 +204,11 @@ bool URLRequestHttpJob::GetResponseCookies( if (!response_info_) return false; - if (response_cookies_.empty()) - FetchResponseCookies(); + // TODO(darin): Why are we extracting response cookies again? Perhaps we + // should just leverage response_cookies_. cookies->clear(); - cookies->swap(response_cookies_); + FetchResponseCookies(response_info_, cookies); return true; } @@ -320,6 +324,8 @@ void URLRequestHttpJob::SetAuth(const std::wstring& username, void URLRequestHttpJob::RestartTransactionWithAuth( const std::wstring& username, const std::wstring& password) { + username_ = username; + password_ = password; // These will be reset in OnStartCompleted. response_info_ = NULL; @@ -327,27 +333,12 @@ void URLRequestHttpJob::RestartTransactionWithAuth( // Update the cookies, since the cookie store may have been updated from the // headers in the 401/407. Since cookies were already appended to - // extra_headers by AddExtraHeaders(), we need to strip them out. + // extra_headers, we need to strip them out before adding them again. static const char* const cookie_name[] = { "cookie" }; request_info_.extra_headers = net::HttpUtil::StripHeaders( request_info_.extra_headers, cookie_name, arraysize(cookie_name)); - // TODO(eroman): this ordering is inconsistent with non-restarted request, - // where cookies header appears second from the bottom. - request_info_.extra_headers += AssembleRequestCookies(); - - // No matter what, we want to report our status as IO pending since we will - // be notifying our consumer asynchronously via OnStartCompleted. - SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0)); - int rv = transaction_->RestartWithAuth(username, password, - &start_callback_); - if (rv == net::ERR_IO_PENDING) - return; - - // The transaction started synchronously, but we need to notify the - // URLRequest delegate via the message loop. - MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod( - this, &URLRequestHttpJob::OnStartCompleted, rv)); + AddCookieHeaderAndStart(); } void URLRequestHttpJob::CancelAuth() { @@ -438,6 +429,41 @@ bool URLRequestHttpJob::ReadRawData(net::IOBuffer* buf, int buf_size, return false; } +void URLRequestHttpJob::OnCanGetCookiesCompleted(int policy) { + // If the request was destroyed, then there is no more work to do. + if (request_ && request_->delegate()) { + if (policy == net::OK && request_->context()->cookie_store()) { + net::CookieOptions options; + options.set_include_httponly(); + std::string cookies = + request_->context()->cookie_store()->GetCookiesWithOptions( + request_->url(), options); + if (request_->context()->InterceptRequestCookies(request_, cookies) && + !cookies.empty()) + request_info_.extra_headers += "Cookie: " + cookies + "\r\n"; + } + StartTransaction(); + } + Release(); // Balance AddRef taken in AddCookieHeaderAndStart +} + +void URLRequestHttpJob::OnCanSetCookieCompleted(int policy) { + // If the request was destroyed, then there is no more work to do. + if (request_ && request_->delegate()) { + if (policy == net::OK && request_->context()->cookie_store()) { + // OK to save the current response cookie now. + net::CookieOptions options; + options.set_include_httponly(); + request_->context()->cookie_store()->SetCookieWithOptions( + request_->url(), response_cookies_[response_cookies_save_index_], + options); + } + response_cookies_save_index_++; + SaveNextCookie(); + } + Release(); // Balance AddRef taken in SaveNextCookie +} + void URLRequestHttpJob::OnStartCompleted(int result) { // If the request was destroyed, then there is no more work to do. if (!request_ || !request_->delegate()) @@ -452,7 +478,7 @@ void URLRequestHttpJob::OnStartCompleted(int result) { SetStatus(URLRequestStatus()); if (result == net::OK) { - NotifyHeadersComplete(); + SaveCookiesAndNotifyHeadersComplete(); } else if (ShouldTreatAsCertificateError(result)) { // We encountered an SSL certificate error. Ask our delegate to decide // what we should do. @@ -509,21 +535,6 @@ void URLRequestHttpJob::NotifyHeadersComplete() { // also need this info. is_cached_content_ = response_info_->was_cached; - // Get the Set-Cookie values, and send them to our cookie database. - if (!(request_info_.load_flags & net::LOAD_DO_NOT_SAVE_COOKIES)) { - URLRequestContext* ctx = request_->context(); - if (ctx && ctx->cookie_store() && (!ctx->cookie_policy() || - ctx->cookie_policy()->CanSetCookie( - request_->url(), request_->first_party_for_cookies()))) { - FetchResponseCookies(); - net::CookieOptions options; - options.set_include_httponly(); - ctx->cookie_store()->SetCookiesWithOptions(request_->url(), - response_cookies_, - options); - } - } - ProcessStrictTransportSecurityHeader(); if (SdchManager::Global() && @@ -568,26 +579,29 @@ void URLRequestHttpJob::DestroyTransaction() { void URLRequestHttpJob::StartTransaction() { // NOTE: This method assumes that request_info_ is already setup properly. - // Create a transaction. - DCHECK(!transaction_.get()); - - DCHECK(request_->context()); - DCHECK(request_->context()->http_transaction_factory()); - - // No matter what, we want to report our status as IO pending since we will - // be notifying our consumer asynchronously via OnStartCompleted. - SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0)); + // If we already have a transaction, then we should restart the transaction + // with auth provided by username_ and password_. - int rv = request_->context()->http_transaction_factory()->CreateTransaction( - &transaction_); - - if (rv == net::OK) { - rv = transaction_->Start( - &request_info_, &start_callback_, request_->load_log()); - if (rv == net::ERR_IO_PENDING) - return; + int rv; + if (transaction_.get()) { + rv = transaction_->RestartWithAuth(username_, password_, &start_callback_); + username_.clear(); + password_.clear(); + } else { + DCHECK(request_->context()); + DCHECK(request_->context()->http_transaction_factory()); + + rv = request_->context()->http_transaction_factory()->CreateTransaction( + &transaction_); + if (rv == net::OK) { + rv = transaction_->Start( + &request_info_, &start_callback_, request_->load_log()); + } } + if (rv == net::ERR_IO_PENDING) + return; + // The transaction started synchronously, but we need to notify the // URLRequest delegate via the message loop. MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod( @@ -648,8 +662,6 @@ void URLRequestHttpJob::AddExtraHeaders() { URLRequestContext* context = request_->context(); if (context) { - request_info_.extra_headers += AssembleRequestCookies(); - // Only add default Accept-Language and Accept-Charset if the request // didn't have them specified. net::HttpUtil::AppendHeaderIfMissing("Accept-Language", @@ -661,39 +673,87 @@ void URLRequestHttpJob::AddExtraHeaders() { } } -std::string URLRequestHttpJob::AssembleRequestCookies() { - if (request_info_.load_flags & net::LOAD_DO_NOT_SEND_COOKIES) - return std::string(); +void URLRequestHttpJob::AddCookieHeaderAndStart() { + // No matter what, we want to report our status as IO pending since we will + // be notifying our consumer asynchronously via OnStartCompleted. + SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0)); - URLRequestContext* context = request_->context(); - if (context) { - // Add in the cookie header. TODO might we need more than one header? - if (context->cookie_store() && (!context->cookie_policy() || - context->cookie_policy()->CanGetCookies( - request_->url(), request_->first_party_for_cookies()))) { - net::CookieOptions options; - options.set_include_httponly(); - std::string cookies = request_->context()->cookie_store()-> - GetCookiesWithOptions(request_->url(), options); - if (context->InterceptRequestCookies(request_, cookies) && - !cookies.empty()) - return "Cookie: " + cookies + "\r\n"; - } + AddRef(); // Balanced in OnCanGetCookiesCompleted + + int policy = net::OK; + + if (request_info_.load_flags & net::LOAD_DO_NOT_SEND_COOKIES) { + policy = net::ERR_ACCESS_DENIED; + } else if (request_->context()->cookie_policy()) { + policy = request_->context()->cookie_policy()->CanGetCookies( + request_->url(), + request_->first_party_for_cookies(), + &can_get_cookies_callback_); + if (policy == net::ERR_IO_PENDING) + return; // Wait for completion callback } - return std::string(); + + OnCanGetCookiesCompleted(policy); } -void URLRequestHttpJob::FetchResponseCookies() { - DCHECK(response_info_); - DCHECK(response_cookies_.empty()); +void URLRequestHttpJob::SaveCookiesAndNotifyHeadersComplete() { + DCHECK(transaction_.get()); + const net::HttpResponseInfo* response_info = transaction_->GetResponseInfo(); + DCHECK(response_info); + + response_cookies_.clear(); + response_cookies_save_index_ = 0; + + FetchResponseCookies(response_info, &response_cookies_); + + // Now, loop over the response cookies, and attempt to persist each. + SaveNextCookie(); +} + +void URLRequestHttpJob::SaveNextCookie() { + if (response_cookies_save_index_ == response_cookies_.size()) { + response_cookies_.clear(); + response_cookies_save_index_ = 0; + SetStatus(URLRequestStatus()); // Clear the IO_PENDING status + NotifyHeadersComplete(); + return; + } + + // No matter what, we want to report our status as IO pending since we will + // be notifying our consumer asynchronously via OnStartCompleted. + SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0)); + + AddRef(); // Balanced in OnCanSetCookieCompleted + + int policy = net::OK; + + if (request_info_.load_flags & net::LOAD_DO_NOT_SAVE_COOKIES) { + policy = net::ERR_ACCESS_DENIED; + } else if (request_->context()->cookie_policy()) { + policy = request_->context()->cookie_policy()->CanSetCookie( + request_->url(), + request_->first_party_for_cookies(), + response_cookies_[response_cookies_save_index_], + &can_set_cookie_callback_); + if (policy == net::ERR_IO_PENDING) + return; // Wait for completion callback + } + + OnCanSetCookieCompleted(policy); +} + +void URLRequestHttpJob::FetchResponseCookies( + const net::HttpResponseInfo* response_info, + std::vector<std::string>* cookies) { std::string name = "Set-Cookie"; std::string value; void* iter = NULL; - while (response_info_->headers->EnumerateHeader(&iter, name, &value)) + while (response_info->headers->EnumerateHeader(&iter, name, &value)) { if (request_->context()->InterceptResponseCookie(request_, value)) - response_cookies_.push_back(value); + cookies->push_back(value); + } } class HTTPSProberDelegate : public net::HTTPSProberDelegate { diff --git a/net/url_request/url_request_http_job.h b/net/url_request/url_request_http_job.h index 383bae1..e00e3c4 100644 --- a/net/url_request/url_request_http_job.h +++ b/net/url_request/url_request_http_job.h @@ -62,12 +62,17 @@ class URLRequestHttpJob : public URLRequestJob { void DestroyTransaction(); void StartTransaction(); void AddExtraHeaders(); - std::string AssembleRequestCookies(); - void FetchResponseCookies(); + void AddCookieHeaderAndStart(); + void SaveCookiesAndNotifyHeadersComplete(); + void SaveNextCookie(); + void FetchResponseCookies(const net::HttpResponseInfo* response_info, + std::vector<std::string>* cookies); // Process the Strict-Transport-Security header, if one exists. void ProcessStrictTransportSecurityHeader(); + void OnCanGetCookiesCompleted(int result); + void OnCanSetCookieCompleted(int result); void OnStartCompleted(int result); void OnReadCompleted(int result); @@ -82,12 +87,19 @@ class URLRequestHttpJob : public URLRequestJob { net::HttpRequestInfo request_info_; const net::HttpResponseInfo* response_info_; + std::vector<std::string> response_cookies_; + size_t response_cookies_save_index_; // Auth states for proxy and origin server. net::AuthState proxy_auth_state_; net::AuthState server_auth_state_; + std::wstring username_; + std::wstring password_; + + net::CompletionCallbackImpl<URLRequestHttpJob> can_get_cookies_callback_; + net::CompletionCallbackImpl<URLRequestHttpJob> can_set_cookie_callback_; net::CompletionCallbackImpl<URLRequestHttpJob> start_callback_; net::CompletionCallbackImpl<URLRequestHttpJob> read_callback_; diff --git a/net/url_request/url_request_unittest.cc b/net/url_request/url_request_unittest.cc index 48cfd35..56901fc 100644 --- a/net/url_request/url_request_unittest.cc +++ b/net/url_request/url_request_unittest.cc @@ -24,6 +24,7 @@ #include "base/string_piece.h" #include "base/string_util.h" #include "net/base/cookie_monster.h" +#include "net/base/cookie_policy.h" #include "net/base/load_flags.h" #include "net/base/load_log.h" #include "net/base/load_log_unittest.h" @@ -1286,7 +1287,6 @@ TEST_F(URLRequestTest, DoNotSaveCookies) { // Try to set-up another cookie and update the previous cookie. { - scoped_refptr<URLRequestContext> context = new URLRequestTestContext(); TestDelegate d; URLRequest req(server->TestServerPage( "set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"), &d); @@ -1312,6 +1312,216 @@ TEST_F(URLRequestTest, DoNotSaveCookies) { } } +TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) { + scoped_refptr<HTTPTestServer> server = + HTTPTestServer::CreateServer(L"", NULL); + ASSERT_TRUE(NULL != server.get()); + scoped_refptr<URLRequestTestContext> context = new URLRequestTestContext(); + + // Set up a cookie. + { + TestDelegate d; + URLRequest req(server->TestServerPage("set-cookie?CookieToNotSend=1"), &d); + req.set_context(context); + req.Start(); + MessageLoop::current()->Run(); + } + + // Verify that the cookie is set. + { + TestDelegate d; + TestURLRequest req(server->TestServerPage("echoheader?Cookie"), &d); + req.set_context(context); + req.Start(); + MessageLoop::current()->Run(); + + EXPECT_TRUE(d.data_received().find("CookieToNotSend=1") + != std::string::npos); + } + + // Verify that the cookie isn't sent. + { + TestCookiePolicy cookie_policy(TestCookiePolicy::NO_GET_COOKIES); + context->set_cookie_policy(&cookie_policy); + + TestDelegate d; + TestURLRequest req(server->TestServerPage("echoheader?Cookie"), &d); + req.set_context(context); + req.Start(); + MessageLoop::current()->Run(); + + EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1") + == std::string::npos); + + context->set_cookie_policy(NULL); + } +} + +TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) { + scoped_refptr<HTTPTestServer> server = + HTTPTestServer::CreateServer(L"", NULL); + ASSERT_TRUE(NULL != server.get()); + scoped_refptr<URLRequestTestContext> context = new URLRequestTestContext(); + + // Set up a cookie. + { + TestDelegate d; + URLRequest req(server->TestServerPage("set-cookie?CookieToNotUpdate=2"), + &d); + req.set_context(context); + req.Start(); + MessageLoop::current()->Run(); + } + + // Try to set-up another cookie and update the previous cookie. + { + TestCookiePolicy cookie_policy(TestCookiePolicy::NO_SET_COOKIE); + context->set_cookie_policy(&cookie_policy); + + TestDelegate d; + URLRequest req(server->TestServerPage( + "set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"), &d); + req.set_context(context); + req.Start(); + + MessageLoop::current()->Run(); + + context->set_cookie_policy(NULL); + } + + + // Verify the cookies weren't saved or updated. + { + TestDelegate d; + TestURLRequest req(server->TestServerPage("echoheader?Cookie"), &d); + req.set_context(context); + req.Start(); + MessageLoop::current()->Run(); + + EXPECT_TRUE(d.data_received().find("CookieToNotSave=1") + == std::string::npos); + EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2") + != std::string::npos); + } +} + +TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) { + scoped_refptr<HTTPTestServer> server = + HTTPTestServer::CreateServer(L"", NULL); + ASSERT_TRUE(NULL != server.get()); + scoped_refptr<URLRequestTestContext> context = new URLRequestTestContext(); + + // Set up a cookie. + { + TestDelegate d; + URLRequest req(server->TestServerPage("set-cookie?CookieToNotSend=1"), &d); + req.set_context(context); + req.Start(); + MessageLoop::current()->Run(); + } + + // Verify that the cookie is set. + { + TestDelegate d; + TestURLRequest req(server->TestServerPage("echoheader?Cookie"), &d); + req.set_context(context); + req.Start(); + MessageLoop::current()->Run(); + + EXPECT_TRUE(d.data_received().find("CookieToNotSend=1") + != std::string::npos); + } + + // Verify that the cookie isn't sent. + { + TestCookiePolicy cookie_policy(TestCookiePolicy::NO_GET_COOKIES | + TestCookiePolicy::ASYNC); + context->set_cookie_policy(&cookie_policy); + + TestDelegate d; + TestURLRequest req(server->TestServerPage("echoheader?Cookie"), &d); + req.set_context(context); + req.Start(); + MessageLoop::current()->Run(); + + EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1") + == std::string::npos); + + context->set_cookie_policy(NULL); + } +} + +TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) { + scoped_refptr<HTTPTestServer> server = + HTTPTestServer::CreateServer(L"", NULL); + ASSERT_TRUE(NULL != server.get()); + scoped_refptr<URLRequestTestContext> context = new URLRequestTestContext(); + + // Set up a cookie. + { + TestDelegate d; + URLRequest req(server->TestServerPage("set-cookie?CookieToNotUpdate=2"), + &d); + req.set_context(context); + req.Start(); + MessageLoop::current()->Run(); + } + + // Try to set-up another cookie and update the previous cookie. + { + TestCookiePolicy cookie_policy(TestCookiePolicy::NO_SET_COOKIE | + TestCookiePolicy::ASYNC); + context->set_cookie_policy(&cookie_policy); + + TestDelegate d; + URLRequest req(server->TestServerPage( + "set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"), &d); + req.set_context(context); + req.Start(); + + MessageLoop::current()->Run(); + + context->set_cookie_policy(NULL); + } + + // Verify the cookies weren't saved or updated. + { + TestDelegate d; + TestURLRequest req(server->TestServerPage("echoheader?Cookie"), &d); + req.set_context(context); + req.Start(); + MessageLoop::current()->Run(); + + EXPECT_TRUE(d.data_received().find("CookieToNotSave=1") + == std::string::npos); + EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2") + != std::string::npos); + } +} + +TEST_F(URLRequestTest, CancelTest_DuringCookiePolicy) { + scoped_refptr<HTTPTestServer> server = + HTTPTestServer::CreateServer(L"", NULL); + ASSERT_TRUE(NULL != server.get()); + scoped_refptr<URLRequestTestContext> context = new URLRequestTestContext(); + + TestCookiePolicy cookie_policy(TestCookiePolicy::ASYNC); + context->set_cookie_policy(&cookie_policy); + + // Set up a cookie. + { + TestDelegate d; + URLRequest req(server->TestServerPage("set-cookie?A=1&B=2&C=3"), + &d); + req.set_context(context); + req.Start(); // Triggers an asynchronous cookie policy check. + + // But, now we cancel the request. This should not cause a crash. + } + + context->set_cookie_policy(NULL); +} + // In this test, we do a POST which the server will 302 redirect. // The subsequent transaction should use GET, and should not send the // Content-Type header. diff --git a/net/url_request/url_request_unittest.h b/net/url_request/url_request_unittest.h index abd94aa..e912ab9 100644 --- a/net/url_request/url_request_unittest.h +++ b/net/url_request/url_request_unittest.h @@ -22,6 +22,7 @@ #include "base/time.h" #include "base/waitable_event.h" #include "net/base/cookie_monster.h" +#include "net/base/cookie_policy.h" #include "net/base/host_resolver.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" @@ -45,6 +46,83 @@ const std::string kDefaultHostName("localhost"); using base::TimeDelta; +//----------------------------------------------------------------------------- + +class TestCookiePolicy : public net::CookiePolicy { + public: + enum Options { + NO_GET_COOKIES = 1 << 0, + NO_SET_COOKIE = 1 << 1, + ASYNC = 1 << 2 + }; + + explicit TestCookiePolicy(int options_bit_mask) + : ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)), + options_(options_bit_mask), + callback_(NULL) { + } + + virtual int CanGetCookies(const GURL& url, const GURL& first_party, + net::CompletionCallback* callback) { + if ((options_ & ASYNC) && callback) { + callback_ = callback; + MessageLoop::current()->PostTask(FROM_HERE, + method_factory_.NewRunnableMethod( + &TestCookiePolicy::DoGetCookiesPolicy, url, first_party)); + return net::ERR_IO_PENDING; + } + + if (options_ & NO_GET_COOKIES) + return net::ERR_ACCESS_DENIED; + + return net::OK; + } + + virtual int CanSetCookie(const GURL& url, const GURL& first_party, + const std::string& cookie_line, + net::CompletionCallback* callback) { + if ((options_ & ASYNC) && callback) { + callback_ = callback; + MessageLoop::current()->PostTask(FROM_HERE, + method_factory_.NewRunnableMethod( + &TestCookiePolicy::DoSetCookiePolicy, url, first_party, + cookie_line)); + return net::ERR_IO_PENDING; + } + + if (options_ & NO_SET_COOKIE) + return net::ERR_ACCESS_DENIED; + + return net::OK; + } + + private: + void DoGetCookiesPolicy(const GURL& url, const GURL& first_party) { + int policy = CanGetCookies(url, first_party, NULL); + + DCHECK(callback_); + net::CompletionCallback* callback = callback_; + callback_ = NULL; + callback->Run(policy); + } + + void DoSetCookiePolicy(const GURL& url, const GURL& first_party, + const std::string& cookie_line) { + int policy = CanSetCookie(url, first_party, cookie_line, NULL); + + DCHECK(callback_); + net::CompletionCallback* callback = callback_; + callback_ = NULL; + callback->Run(policy); + } + + ScopedRunnableMethodFactory<TestCookiePolicy> method_factory_; + int options_; + net::CompletionCallback* callback_; +}; + +//----------------------------------------------------------------------------- + class TestURLRequestContext : public URLRequestContext { public: TestURLRequestContext() { @@ -61,6 +139,10 @@ class TestURLRequestContext : public URLRequestContext { Init(); } + void set_cookie_policy(net::CookiePolicy* policy) { + cookie_policy_ = policy; + } + protected: virtual ~TestURLRequestContext() { delete ftp_transaction_factory_; @@ -86,6 +168,8 @@ class TestURLRequestContext : public URLRequestContext { // TODO(phajdan.jr): Migrate callers to the new name and remove the typedef. typedef TestURLRequestContext URLRequestTestContext; +//----------------------------------------------------------------------------- + class TestURLRequest : public URLRequest { public: TestURLRequest(const GURL& url, Delegate* delegate) @@ -94,6 +178,8 @@ class TestURLRequest : public URLRequest { } }; +//----------------------------------------------------------------------------- + class TestDelegate : public URLRequest::Delegate { public: TestDelegate() @@ -261,6 +347,8 @@ class TestDelegate : public URLRequest::Delegate { scoped_refptr<net::IOBuffer> buf_; }; +//----------------------------------------------------------------------------- + // This object bounds the lifetime of an external python-based HTTP/FTP server // that can provide various responses useful for testing. class BaseTestServer : public base::RefCounted<BaseTestServer> { @@ -372,6 +460,7 @@ class BaseTestServer : public base::RefCounted<BaseTestServer> { std::string port_str_; }; +//----------------------------------------------------------------------------- // HTTP class HTTPTestServer : public BaseTestServer { @@ -522,6 +611,8 @@ class HTTPTestServer : public BaseTestServer { MessageLoop* loop_; }; +//----------------------------------------------------------------------------- + class HTTPSTestServer : public HTTPTestServer { protected: explicit HTTPSTestServer() { @@ -598,6 +689,7 @@ class HTTPSTestServer : public HTTPTestServer { virtual ~HTTPSTestServer() {} }; +//----------------------------------------------------------------------------- class FTPTestServer : public BaseTestServer { public: |