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.
5 #include "android_webview/native/cookie_manager.h"
7 #include "android_webview/browser/aw_browser_context.h"
8 #include "android_webview/browser/aw_cookie_access_policy.h"
9 #include "android_webview/browser/net/init_native_callback.h"
10 #include "android_webview/browser/scoped_allow_wait_for_legacy_web_view_api.h"
11 #include "android_webview/native/aw_browser_dependency_factory.h"
12 #include "base/android/jni_string.h"
13 #include "base/android/path_utils.h"
14 #include "base/bind.h"
15 #include "base/bind_helpers.h"
16 #include "base/files/file_path.h"
17 #include "base/files/file_util.h"
18 #include "base/lazy_instance.h"
19 #include "base/location.h"
20 #include "base/path_service.h"
21 #include "base/single_thread_task_runner.h"
22 #include "base/synchronization/lock.h"
23 #include "base/synchronization/waitable_event.h"
24 #include "base/threading/sequenced_worker_pool.h"
25 #include "base/threading/thread.h"
26 #include "base/threading/thread_restrictions.h"
27 #include "content/public/browser/browser_context.h"
28 #include "content/public/browser/browser_thread.h"
29 #include "content/public/browser/cookie_store_factory.h"
30 #include "jni/AwCookieManager_jni.h"
31 #include "net/cookies/cookie_monster.h"
32 #include "net/cookies/cookie_options.h"
33 #include "net/extras/sqlite/cookie_crypto_delegate.h"
34 #include "net/url_request/url_request_context.h"
35 #include "url/url_constants.h"
38 using base::WaitableEvent
;
39 using base::android::ConvertJavaStringToUTF8
;
40 using base::android::ConvertJavaStringToUTF16
;
41 using base::android::ScopedJavaGlobalRef
;
42 using content::BrowserThread
;
43 using net::CookieList
;
44 using net::CookieMonster
;
46 // In the future, we may instead want to inject an explicit CookieStore
47 // dependency into this object during process initialization to avoid
48 // depending on the URLRequestContext.
49 // See issue http://crbug.com/157683
51 // On the CookieManager methods without a callback and methods with a callback
52 // when that callback is null can be called from any thread, including threads
53 // without a message loop. Methods with a non-null callback must be called on
54 // a thread with a running message loop.
56 namespace android_webview
{
60 typedef base::Callback
<void(bool)> BoolCallback
;
61 typedef base::Callback
<void(int)> IntCallback
;
63 // Holds a Java BooleanCookieCallback, knows how to invoke it and turn it
64 // into a base callback.
65 class BoolCookieCallbackHolder
{
67 BoolCookieCallbackHolder(JNIEnv
* env
, jobject callback
) {
68 callback_
.Reset(env
, callback
);
71 void Invoke(bool result
) {
72 if (!callback_
.is_null()) {
73 JNIEnv
* env
= base::android::AttachCurrentThread();
74 Java_AwCookieManager_invokeBooleanCookieCallback(
75 env
, callback_
.obj(), result
);
79 static BoolCallback
ConvertToCallback(
80 scoped_ptr
<BoolCookieCallbackHolder
> me
) {
81 return base::Bind(&BoolCookieCallbackHolder::Invoke
,
82 base::Owned(me
.release()));
86 ScopedJavaGlobalRef
<jobject
> callback_
;
87 DISALLOW_COPY_AND_ASSIGN(BoolCookieCallbackHolder
);
90 // Construct a closure which signals a waitable event if and when the closure
91 // is called the waitable event must still exist.
92 static base::Closure
SignalEventClosure(WaitableEvent
* completion
) {
93 return base::Bind(&WaitableEvent::Signal
, base::Unretained(completion
));
96 static void DiscardBool(const base::Closure
& f
, bool b
) {
100 static BoolCallback
BoolCallbackAdapter(const base::Closure
& f
) {
101 return base::Bind(&DiscardBool
, f
);
104 static void DiscardInt(const base::Closure
& f
, int i
) {
108 static IntCallback
IntCallbackAdapter(const base::Closure
& f
) {
109 return base::Bind(&DiscardInt
, f
);
112 // Are cookies allowed for file:// URLs by default?
113 const bool kDefaultFileSchemeAllowed
= false;
115 void ImportLegacyCookieStore(const FilePath
& cookie_store_path
) {
116 // We use the old cookie store to create the new cookie store only if the
117 // new cookie store does not exist.
118 if (base::PathExists(cookie_store_path
))
121 // WebViewClassic gets the database path from Context and appends a
122 // hardcoded name. See:
123 // https://android.googlesource.com/platform/frameworks/base/+/bf6f6f9d/core/java/android/webkit/JniUtil.java
124 // https://android.googlesource.com/platform/external/webkit/+/7151e/
125 // Source/WebKit/android/WebCoreSupport/WebCookieJar.cpp
126 FilePath old_cookie_store_path
;
127 base::android::GetDatabaseDirectory(&old_cookie_store_path
);
128 old_cookie_store_path
= old_cookie_store_path
.Append(
129 FILE_PATH_LITERAL("webviewCookiesChromium.db"));
130 if (base::PathExists(old_cookie_store_path
) &&
131 !base::Move(old_cookie_store_path
, cookie_store_path
)) {
132 LOG(WARNING
) << "Failed to move old cookie store path from "
133 << old_cookie_store_path
.AsUTF8Unsafe() << " to "
134 << cookie_store_path
.AsUTF8Unsafe();
138 void GetUserDataDir(FilePath
* user_data_dir
) {
139 if (!PathService::Get(base::DIR_ANDROID_APP_DATA
, user_data_dir
)) {
140 NOTREACHED() << "Failed to get app data directory for Android WebView";
144 class CookieManager
{
146 static CookieManager
* GetInstance();
148 scoped_refptr
<net::CookieStore
> GetCookieStore();
150 void SetShouldAcceptCookies(bool accept
);
151 bool GetShouldAcceptCookies();
152 void SetCookie(const GURL
& host
,
153 const std::string
& cookie_value
,
154 scoped_ptr
<BoolCookieCallbackHolder
> callback
);
155 void SetCookieSync(const GURL
& host
,
156 const std::string
& cookie_value
);
157 std::string
GetCookie(const GURL
& host
);
158 void RemoveSessionCookies(scoped_ptr
<BoolCookieCallbackHolder
> callback
);
159 void RemoveAllCookies(scoped_ptr
<BoolCookieCallbackHolder
> callback
);
160 void RemoveAllCookiesSync();
161 void RemoveSessionCookiesSync();
162 void RemoveExpiredCookies();
163 void FlushCookieStore();
165 bool AllowFileSchemeCookies();
166 void SetAcceptFileSchemeCookies(bool accept
);
169 friend struct base::DefaultLazyInstanceTraits
<CookieManager
>;
174 void ExecCookieTaskSync(const base::Callback
<void(BoolCallback
)>& task
);
175 void ExecCookieTaskSync(const base::Callback
<void(IntCallback
)>& task
);
176 void ExecCookieTaskSync(const base::Callback
<void(base::Closure
)>& task
);
177 void ExecCookieTask(const base::Closure
& task
);
179 void SetCookieHelper(
181 const std::string
& value
,
182 BoolCallback callback
);
184 void GetCookieValueAsyncHelper(const GURL
& host
,
186 base::Closure complete
);
187 void GetCookieValueCompleted(base::Closure complete
,
189 const std::string
& value
);
191 void RemoveSessionCookiesHelper(BoolCallback callback
);
192 void RemoveAllCookiesHelper(BoolCallback callback
);
193 void RemoveCookiesCompleted(BoolCallback callback
, int num_deleted
);
195 void FlushCookieStoreAsyncHelper(base::Closure complete
);
197 void HasCookiesAsyncHelper(bool* result
, base::Closure complete
);
198 void HasCookiesCompleted(base::Closure complete
,
200 const CookieList
& cookies
);
202 void CreateCookieMonster(
203 const FilePath
& user_data_dir
,
204 const scoped_refptr
<base::SequencedTaskRunner
>& client_task_runner
,
205 const scoped_refptr
<base::SequencedTaskRunner
>& background_task_runner
);
206 void EnsureCookieMonsterExistsLocked();
207 bool AllowFileSchemeCookiesLocked();
208 void SetAcceptFileSchemeCookiesLocked(bool accept
);
210 scoped_refptr
<net::CookieMonster
> cookie_monster_
;
211 scoped_refptr
<base::SingleThreadTaskRunner
> cookie_monster_task_runner_
;
212 base::Lock cookie_monster_lock_
;
214 scoped_ptr
<base::Thread
> cookie_monster_client_thread_
;
215 scoped_ptr
<base::Thread
> cookie_monster_backend_thread_
;
217 DISALLOW_COPY_AND_ASSIGN(CookieManager
);
220 base::LazyInstance
<CookieManager
>::Leaky g_lazy_instance
;
223 CookieManager
* CookieManager::GetInstance() {
224 return g_lazy_instance
.Pointer();
227 CookieManager::CookieManager() {
230 CookieManager::~CookieManager() {
233 void CookieManager::CreateCookieMonster(
234 const FilePath
& user_data_dir
,
235 const scoped_refptr
<base::SequencedTaskRunner
>& client_task_runner
,
236 const scoped_refptr
<base::SequencedTaskRunner
>& background_task_runner
) {
237 FilePath cookie_store_path
=
238 user_data_dir
.Append(FILE_PATH_LITERAL("Cookies"));
240 background_task_runner
->PostTask(
242 base::Bind(ImportLegacyCookieStore
, cookie_store_path
));
244 content::CookieStoreConfig
cookie_config(
246 content::CookieStoreConfig::RESTORED_SESSION_COOKIES
,
248 cookie_config
.client_task_runner
= client_task_runner
;
249 cookie_config
.background_task_runner
= background_task_runner
;
250 net::CookieStore
* cookie_store
= content::CreateCookieStore(cookie_config
);
251 cookie_monster_
= cookie_store
->GetCookieMonster();
252 SetAcceptFileSchemeCookiesLocked(kDefaultFileSchemeAllowed
);
255 void CookieManager::EnsureCookieMonsterExistsLocked() {
256 cookie_monster_lock_
.AssertAcquired();
257 if (cookie_monster_
.get()) {
261 // Create cookie monster using WebView-specific threads, as the rest of the
262 // browser has not been started yet.
263 FilePath user_data_dir
;
264 GetUserDataDir(&user_data_dir
);
265 cookie_monster_client_thread_
.reset(
266 new base::Thread("CookieMonsterClient"));
267 cookie_monster_client_thread_
->Start();
268 cookie_monster_task_runner_
= cookie_monster_client_thread_
->task_runner();
269 cookie_monster_backend_thread_
.reset(
270 new base::Thread("CookieMonsterBackend"));
271 cookie_monster_backend_thread_
->Start();
273 CreateCookieMonster(user_data_dir
, cookie_monster_task_runner_
,
274 cookie_monster_backend_thread_
->task_runner());
277 // Executes the |task| on the |cookie_monster_proxy_| message loop and
278 // waits for it to complete before returning.
280 // To execute a CookieTask synchronously you must arrange for Signal to be
281 // called on the waitable event at some point. You can call the bool or int
282 // versions of ExecCookieTaskSync, these will supply the caller with a dummy
283 // callback which takes an int/bool, throws it away and calls Signal.
284 // Alternatively you can call the version which supplies a Closure in which
285 // case you must call Run on it when you want the unblock the calling code.
287 // Ignore a bool callback.
288 void CookieManager::ExecCookieTaskSync(
289 const base::Callback
<void(BoolCallback
)>& task
) {
290 WaitableEvent
completion(false, false);
292 base::Bind(task
, BoolCallbackAdapter(SignalEventClosure(&completion
))));
293 ScopedAllowWaitForLegacyWebViewApi wait
;
297 // Ignore an int callback.
298 void CookieManager::ExecCookieTaskSync(
299 const base::Callback
<void(IntCallback
)>& task
) {
300 WaitableEvent
completion(false, false);
302 base::Bind(task
, IntCallbackAdapter(SignalEventClosure(&completion
))));
303 ScopedAllowWaitForLegacyWebViewApi wait
;
307 // Call the supplied closure when you want to signal that the blocked code can
309 void CookieManager::ExecCookieTaskSync(
310 const base::Callback
<void(base::Closure
)>& task
) {
311 WaitableEvent
completion(false, false);
312 ExecCookieTask(base::Bind(task
, SignalEventClosure(&completion
)));
313 ScopedAllowWaitForLegacyWebViewApi wait
;
317 // Executes the |task| on the |cookie_monster_proxy_| message loop.
318 void CookieManager::ExecCookieTask(const base::Closure
& task
) {
319 base::AutoLock
lock(cookie_monster_lock_
);
320 EnsureCookieMonsterExistsLocked();
321 cookie_monster_task_runner_
->PostTask(FROM_HERE
, task
);
324 scoped_refptr
<net::CookieStore
> CookieManager::GetCookieStore() {
325 base::AutoLock
lock(cookie_monster_lock_
);
326 EnsureCookieMonsterExistsLocked();
327 return cookie_monster_
;
330 void CookieManager::SetShouldAcceptCookies(bool accept
) {
331 AwCookieAccessPolicy::GetInstance()->SetShouldAcceptCookies(accept
);
334 bool CookieManager::GetShouldAcceptCookies() {
335 return AwCookieAccessPolicy::GetInstance()->GetShouldAcceptCookies();
338 void CookieManager::SetCookie(
340 const std::string
& cookie_value
,
341 scoped_ptr
<BoolCookieCallbackHolder
> callback_holder
) {
342 BoolCallback callback
=
343 BoolCookieCallbackHolder::ConvertToCallback(callback_holder
.Pass());
344 ExecCookieTask(base::Bind(&CookieManager::SetCookieHelper
,
345 base::Unretained(this),
351 void CookieManager::SetCookieSync(const GURL
& host
,
352 const std::string
& cookie_value
) {
353 ExecCookieTaskSync(base::Bind(&CookieManager::SetCookieHelper
,
354 base::Unretained(this),
359 void CookieManager::SetCookieHelper(
361 const std::string
& value
,
362 const BoolCallback callback
) {
363 net::CookieOptions options
;
364 options
.set_include_httponly();
366 cookie_monster_
->SetCookieWithOptionsAsync(
367 host
, value
, options
, callback
);
370 std::string
CookieManager::GetCookie(const GURL
& host
) {
371 std::string cookie_value
;
372 ExecCookieTaskSync(base::Bind(&CookieManager::GetCookieValueAsyncHelper
,
373 base::Unretained(this),
379 void CookieManager::GetCookieValueAsyncHelper(
382 base::Closure complete
) {
383 net::CookieOptions options
;
384 options
.set_include_httponly();
386 cookie_monster_
->GetCookiesWithOptionsAsync(
389 base::Bind(&CookieManager::GetCookieValueCompleted
,
390 base::Unretained(this),
395 void CookieManager::GetCookieValueCompleted(base::Closure complete
,
397 const std::string
& value
) {
402 void CookieManager::RemoveSessionCookies(
403 scoped_ptr
<BoolCookieCallbackHolder
> callback_holder
) {
404 BoolCallback callback
=
405 BoolCookieCallbackHolder::ConvertToCallback(callback_holder
.Pass());
406 ExecCookieTask(base::Bind(&CookieManager::RemoveSessionCookiesHelper
,
407 base::Unretained(this),
411 void CookieManager::RemoveSessionCookiesSync() {
412 ExecCookieTaskSync(base::Bind(&CookieManager::RemoveSessionCookiesHelper
,
413 base::Unretained(this)));
416 void CookieManager::RemoveSessionCookiesHelper(
417 BoolCallback callback
) {
418 cookie_monster_
->DeleteSessionCookiesAsync(
419 base::Bind(&CookieManager::RemoveCookiesCompleted
,
420 base::Unretained(this),
424 void CookieManager::RemoveCookiesCompleted(
425 BoolCallback callback
,
427 callback
.Run(num_deleted
> 0);
430 void CookieManager::RemoveAllCookies(
431 scoped_ptr
<BoolCookieCallbackHolder
> callback_holder
) {
432 BoolCallback callback
=
433 BoolCookieCallbackHolder::ConvertToCallback(callback_holder
.Pass());
434 ExecCookieTask(base::Bind(&CookieManager::RemoveAllCookiesHelper
,
435 base::Unretained(this),
439 void CookieManager::RemoveAllCookiesSync() {
440 ExecCookieTaskSync(base::Bind(&CookieManager::RemoveAllCookiesHelper
,
441 base::Unretained(this)));
444 void CookieManager::RemoveAllCookiesHelper(
445 const BoolCallback callback
) {
446 cookie_monster_
->DeleteAllAsync(
447 base::Bind(&CookieManager::RemoveCookiesCompleted
,
448 base::Unretained(this),
452 void CookieManager::RemoveExpiredCookies() {
453 // HasCookies will call GetAllCookiesAsync, which in turn will force a GC.
457 void CookieManager::FlushCookieStore() {
458 ExecCookieTaskSync(base::Bind(&CookieManager::FlushCookieStoreAsyncHelper
,
459 base::Unretained(this)));
462 void CookieManager::FlushCookieStoreAsyncHelper(
463 base::Closure complete
) {
464 cookie_monster_
->FlushStore(complete
);
467 bool CookieManager::HasCookies() {
469 ExecCookieTaskSync(base::Bind(&CookieManager::HasCookiesAsyncHelper
,
470 base::Unretained(this),
475 // TODO(kristianm): Simplify this, copying the entire list around
476 // should not be needed.
477 void CookieManager::HasCookiesAsyncHelper(bool* result
,
478 base::Closure complete
) {
479 cookie_monster_
->GetAllCookiesAsync(
480 base::Bind(&CookieManager::HasCookiesCompleted
,
481 base::Unretained(this),
486 void CookieManager::HasCookiesCompleted(base::Closure complete
,
488 const CookieList
& cookies
) {
489 *result
= cookies
.size() != 0;
493 bool CookieManager::AllowFileSchemeCookies() {
494 base::AutoLock
lock(cookie_monster_lock_
);
495 EnsureCookieMonsterExistsLocked();
496 return AllowFileSchemeCookiesLocked();
499 bool CookieManager::AllowFileSchemeCookiesLocked() {
500 return cookie_monster_
->IsCookieableScheme(url::kFileScheme
);
503 void CookieManager::SetAcceptFileSchemeCookies(bool accept
) {
504 base::AutoLock
lock(cookie_monster_lock_
);
505 EnsureCookieMonsterExistsLocked();
506 SetAcceptFileSchemeCookiesLocked(accept
);
509 void CookieManager::SetAcceptFileSchemeCookiesLocked(bool accept
) {
510 cookie_monster_
->SetEnableFileScheme(accept
);
515 static void SetShouldAcceptCookies(JNIEnv
* env
,
516 const JavaParamRef
<jobject
>& obj
,
518 CookieManager::GetInstance()->SetShouldAcceptCookies(accept
);
521 static jboolean
GetShouldAcceptCookies(JNIEnv
* env
,
522 const JavaParamRef
<jobject
>& obj
) {
523 return CookieManager::GetInstance()->GetShouldAcceptCookies();
526 static void SetCookie(JNIEnv
* env
,
527 const JavaParamRef
<jobject
>& obj
,
528 const JavaParamRef
<jstring
>& url
,
529 const JavaParamRef
<jstring
>& value
,
530 const JavaParamRef
<jobject
>& java_callback
) {
531 GURL
host(ConvertJavaStringToUTF16(env
, url
));
532 std::string
cookie_value(ConvertJavaStringToUTF8(env
, value
));
533 scoped_ptr
<BoolCookieCallbackHolder
> callback(
534 new BoolCookieCallbackHolder(env
, java_callback
));
535 CookieManager::GetInstance()->SetCookie(host
, cookie_value
, callback
.Pass());
538 static void SetCookieSync(JNIEnv
* env
,
539 const JavaParamRef
<jobject
>& obj
,
540 const JavaParamRef
<jstring
>& url
,
541 const JavaParamRef
<jstring
>& value
) {
542 GURL
host(ConvertJavaStringToUTF16(env
, url
));
543 std::string
cookie_value(ConvertJavaStringToUTF8(env
, value
));
545 CookieManager::GetInstance()->SetCookieSync(host
, cookie_value
);
548 static ScopedJavaLocalRef
<jstring
> GetCookie(JNIEnv
* env
,
549 const JavaParamRef
<jobject
>& obj
,
550 const JavaParamRef
<jstring
>& url
) {
551 GURL
host(ConvertJavaStringToUTF16(env
, url
));
553 return base::android::ConvertUTF8ToJavaString(
554 env
, CookieManager::GetInstance()->GetCookie(host
));
557 static void RemoveSessionCookies(JNIEnv
* env
,
558 const JavaParamRef
<jobject
>& obj
,
559 const JavaParamRef
<jobject
>& java_callback
) {
560 scoped_ptr
<BoolCookieCallbackHolder
> callback(
561 new BoolCookieCallbackHolder(env
, java_callback
));
562 CookieManager::GetInstance()->RemoveSessionCookies(callback
.Pass());
565 static void RemoveSessionCookiesSync(JNIEnv
* env
,
566 const JavaParamRef
<jobject
>& obj
) {
567 CookieManager::GetInstance()->RemoveSessionCookiesSync();
570 static void RemoveAllCookies(JNIEnv
* env
,
571 const JavaParamRef
<jobject
>& obj
,
572 const JavaParamRef
<jobject
>& java_callback
) {
573 scoped_ptr
<BoolCookieCallbackHolder
> callback(
574 new BoolCookieCallbackHolder(env
, java_callback
));
575 CookieManager::GetInstance()->RemoveAllCookies(callback
.Pass());
578 static void RemoveAllCookiesSync(JNIEnv
* env
,
579 const JavaParamRef
<jobject
>& obj
) {
580 CookieManager::GetInstance()->RemoveAllCookiesSync();
583 static void RemoveExpiredCookies(JNIEnv
* env
,
584 const JavaParamRef
<jobject
>& obj
) {
585 CookieManager::GetInstance()->RemoveExpiredCookies();
588 static void FlushCookieStore(JNIEnv
* env
, const JavaParamRef
<jobject
>& obj
) {
589 CookieManager::GetInstance()->FlushCookieStore();
592 static jboolean
HasCookies(JNIEnv
* env
, const JavaParamRef
<jobject
>& obj
) {
593 return CookieManager::GetInstance()->HasCookies();
596 static jboolean
AllowFileSchemeCookies(JNIEnv
* env
,
597 const JavaParamRef
<jobject
>& obj
) {
598 return CookieManager::GetInstance()->AllowFileSchemeCookies();
601 static void SetAcceptFileSchemeCookies(JNIEnv
* env
,
602 const JavaParamRef
<jobject
>& obj
,
604 return CookieManager::GetInstance()->SetAcceptFileSchemeCookies(accept
);
607 scoped_refptr
<net::CookieStore
> CreateCookieStore(
608 AwBrowserContext
* browser_context
) {
609 return CookieManager::GetInstance()->GetCookieStore();
612 bool RegisterCookieManager(JNIEnv
* env
) {
613 return RegisterNativesImpl(env
);
616 } // android_webview namespace