最近換了份工作泥栖,開(kāi)始做一些項(xiàng)目了簇宽;在小米的時(shí)候沒(méi)怎么寫(xiě)代碼,這猛然一寫(xiě)感覺(jué)還是有點(diǎn)陌生呢吧享;
好了魏割,閑扯一句之后我們進(jìn)入今天的話題;
問(wèn)題背景
當(dāng)我們登陸一個(gè)賬號(hào)钢颂,然后立即將我們的進(jìn)程殺掉钞它,然后會(huì)發(fā)現(xiàn)再次自動(dòng)登錄的時(shí)候無(wú)法登上;經(jīng)過(guò)服務(wù)端查詢后臺(tái)代碼殊鞭,發(fā)現(xiàn)登不上是因?yàn)楸4娴馁~號(hào)與Cookie對(duì)不上導(dǎo)致的問(wèn)題遭垛;這個(gè)就需要調(diào)查原因了;
問(wèn)題分析
我們用的是公司的網(wǎng)絡(luò)框架钱豁,但是基本原理一般應(yīng)該都相同耻卡,如果需要對(duì)Cookie進(jìn)行保存,最終應(yīng)該都是利用默認(rèn)的或者自己實(shí)現(xiàn)的CookieManager進(jìn)行處理牲尺,主要的方法也就是getCookie和setCookie卵酪;
公司的網(wǎng)絡(luò)框架中加了一個(gè)對(duì)于Cookie處理的攔截器;其中定義了兩個(gè)CookieManager谤碳,有一個(gè)作為backup溃卡;具體涉及到內(nèi)部邏輯,不能多說(shuō)蜒简;但是用的其實(shí)還是AwCookManager瘸羡;即webkit cookiemanager;在其中完成了Cookie的設(shè)置和讀取
Cookie的保存
那么首先看下Cookie是如何保存的搓茬;如果服務(wù)器返回的header中有Set-Cookie的字段犹赖,那么我們就調(diào)用AwCookieManager的setCookie來(lái)將Cookie進(jìn)行保存
/**
* Set cookie for a given url. The old cookie with same host/path/name will
* be removed. The new cookie will be added if it is not expired or it does
* not have expiration which implies it is session cookie.
* @param url The url which cookie is set for
* @param value The value for set-cookie: in http response header
*/
public void setCookie(final String url, final String value) {
nativeSetCookie(url, value);
}
從注釋也可以看出队他;其實(shí)url就相當(dāng)于是一個(gè)key;而要存的Cookie值相當(dāng)于是value峻村;當(dāng)新的Cookie進(jìn)來(lái)時(shí)麸折,舊的Cookie將被覆蓋;那么對(duì)于我們的賬號(hào)登錄來(lái)說(shuō)粘昨;應(yīng)該保存的是最新的登錄態(tài)垢啼;這個(gè)后續(xù)可以實(shí)測(cè)驗(yàn)證下;下面繼續(xù)分析代碼张肾;
這里會(huì)調(diào)用到CookieManager.cpp中的setCookie
static void setCookie(JNIEnv* env, jobject, jstring url, jstring value, jboolean privateBrowsing)
{
GURL gurl(jstringToStdString(env, url));
std::string line(jstringToStdString(env, value));
CookieOptions options;
options.set_include_httponly();
WebCookieJar::get(privateBrowsing)->cookieStore()->GetCookieMonster()->SetCookieWithOptions(gurl, line, options);
}
這一場(chǎng)長(zhǎng)串代碼最終應(yīng)該會(huì)走到cookie_monster.cc中的SetCookieWithOptions
bool CookieMonster::SetCookieWithOptions(const GURL& url,
const std::string& cookie_line,
const CookieOptions& options) {
base::AutoLock autolock(lock_);
if (!HasCookieableScheme(url)) {
return false;
}
return SetCookieWithCreationTimeAndOptions(url, cookie_line, Time(), options);
}
bool CookieMonster::SetCookieWithCreationTimeAndOptions(
const GURL& url,
const std::string& cookie_line,
const Time& creation_time_or_null,
const CookieOptions& options) {
lock_.AssertAcquired();
VLOG(kVlogSetCookies) << "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);
if (!pc.IsValid()) {
VLOG(kVlogSetCookies) << "WARNING: Couldn't parse cookie";
return false;
}
if (options.exclude_httponly() && pc.IsHttpOnly()) {
VLOG(kVlogSetCookies) << "SetCookie() not setting httponly cookie";
return false;
}
std::string cookie_domain;
if (!GetCookieDomain(url, pc, &cookie_domain)) {
return false;
}
std::string cookie_path = CanonPath(url, pc);
std::string mac_key = pc.HasMACKey() ? pc.MACKey() : std::string();
std::string mac_algorithm = pc.HasMACAlgorithm() ?
pc.MACAlgorithm() : std::string();
scoped_ptr<CanonicalCookie> cc;
Time cookie_expires = CanonExpiration(pc, creation_time);
bool session_only = options.force_session() || cookie_expires.is_null();
cc.reset(new CanonicalCookie(url, pc.Name(), pc.Value(), cookie_domain,
cookie_path, mac_key, mac_algorithm,
creation_time, cookie_expires,
creation_time, pc.IsSecure(), pc.IsHttpOnly(),
!cookie_expires.is_null(),
!session_only));
if (!cc.get()) {
VLOG(kVlogSetCookies) << "WARNING: Failed to allocate CanonicalCookie";
return false;
}
return SetCanonicalCookie(&cc, creation_time, options);
}
bool CookieMonster::SetCanonicalCookie(scoped_ptr<CanonicalCookie>* cc,
const Time& creation_time,
const CookieOptions& options) {
const std::string key(GetKey((*cc)->Domain()));
bool already_expired = (*cc)->IsExpired(creation_time);
if (DeleteAnyEquivalentCookie(key, **cc, options.exclude_httponly(),
already_expired)) {
VLOG(kVlogSetCookies) << "SetCookie() not clobbering httponly cookie";
return false;
}
VLOG(kVlogSetCookies) << "SetCookie() key: " << key << " cc: "
<< (*cc)->DebugString();
// Realize that we might be setting an expired cookie, and the only point
// was to delete the cookie which we've already done.
if (!already_expired || keep_expired_cookies_) {
// See InitializeHistograms() for details.
if ((*cc)->DoesExpire()) {
histogram_expiration_duration_minutes_->Add(
((*cc)->ExpiryDate() - creation_time).InMinutes());
}
InternalInsertCookie(key, cc->release(), true);
}
// We assume that hopefully setting a cookie will be less common than
// querying a cookie. Since setting a cookie can put us over our limits,
// make sure that we garbage collect... We can also make the assumption that
// if a cookie was set, in the common case it will be used soon after,
// and we will purge the expired cookies in GetCookies().
GarbageCollect(creation_time, key);
return true;
}
經(jīng)過(guò)上面對(duì)Cookie的處理芭析,最終調(diào)到:
void CookieMonster::InternalInsertCookie(const std::string& key,
CanonicalCookie* cc,
bool sync_to_store) {
lock_.AssertAcquired();
if ((cc->IsPersistent() || persist_session_cookies_) &&
store_ && sync_to_store)
store_->AddCookie(*cc);
cookies_.insert(CookieMap::value_type(key, cc));
if (delegate_.get()) {
delegate_->OnCookieChanged(
*cc, false, CookieMonster::Delegate::CHANGE_COOKIE_EXPLICIT);
}
}
可以看到其實(shí)這里有兩個(gè)保存的地方
cookies_.insert(CookieMap::value_type(key, cc)); 以及store_->AddCookie(*cc);
這里其實(shí)就可以想到了;一個(gè)是將Cookie的內(nèi)容保存在進(jìn)程的內(nèi)存中吞瞪,一個(gè)是將Cookie保存文件中馁启,也就是我們常說(shuō)的Cookie持久化
放到內(nèi)存中的其實(shí)沒(méi)什么好看的了;就是CookieMap cookies_; 這里講我們要保存的Cookie組織成CookieMap的形式尸饺,然后保存下进统;重點(diǎn)看下持久化的部分;
大體的邏輯在
https://github.com/adobe/chromium/blob/master/chrome/browser/net/sqlite_persistent_cookie_store.cc
Cookie持久化邏輯
void SQLitePersistentCookieStore::Backend::AddCookie(
const net::CookieMonster::CanonicalCookie& cc) {
BatchOperation(PendingOperation::COOKIE_ADD, cc);
}
相當(dāng)于30s才會(huì)觸發(fā)commit 浪听,也就是從setCookie到真正持久化螟碎,需要30s的時(shí)間
void SQLitePersistentCookieStore::Backend::BatchOperation(
PendingOperation::OperationType op,
const net::CookieMonster::CanonicalCookie& cc) {
// Commit every 30 seconds.
static const int kCommitIntervalMs = 30 * 1000;
// Commit right away if we have more than 512 outstanding operations.
static const size_t kCommitAfterBatchSize = 512;
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::DB));
// We do a full copy of the cookie here, and hopefully just here.
scoped_ptr<PendingOperation> po(new PendingOperation(op, cc));
PendingOperationsList::size_type num_pending;
{
base::AutoLock locked(lock_);
pending_.push_back(po.release());
num_pending = ++num_pending_;
}
if (num_pending == 1) {
// We've gotten our first entry for this batch, fire off the timer.
BrowserThread::PostDelayedTask(
BrowserThread::DB, FROM_HERE,
base::Bind(&Backend::Commit, this),
base::TimeDelta::FromMilliseconds(kCommitIntervalMs));
} else if (num_pending == kCommitAfterBatchSize) {
// We've reached a big enough batch, fire off a commit now.
BrowserThread::PostTask(
BrowserThread::DB, FROM_HERE,
base::Bind(&Backend::Commit, this));
}
}
到了這里,其實(shí)已經(jīng)可以確認(rèn)了迹栓;這是因?yàn)橄到y(tǒng)設(shè)計(jì)的原因造成的我們的問(wèn)題掉分;進(jìn)程被殺時(shí)使用了持久化的Cookie;但是由于這個(gè)kCommitIntervalMs 時(shí)延克伊;導(dǎo)致沒(méi)有及時(shí)更新酥郭;
這個(gè)設(shè)計(jì)應(yīng)該是為了節(jié)省IO資源吧;但是這也造成了我們這里的問(wèn)題愿吹;那么很明顯我們登陸之后殺掉進(jìn)程不从,就相當(dāng)于用這次賬號(hào)的信息和原來(lái)保存的Cookie共同登陸,所以會(huì)產(chǎn)生問(wèn)題
不過(guò)為了完整性犁跪,我們?cè)俅_認(rèn)下取Cookie的流程
Cookie的讀取
也是先通過(guò)AwCookieManager 先從內(nèi)存中取Cookie
std::string CookieMonster::GetCookiesWithOptions(const GURL& url,
const CookieOptions& options) {
base::AutoLock autolock(lock_);
if (!HasCookieableScheme(url))
return std::string();
TimeTicks start_time(TimeTicks::Now());
std::vector<CanonicalCookie*> cookies;
FindCookiesForHostAndDomain(url, options, true, &cookies); //
std::sort(cookies.begin(), cookies.end(), CookieSorter);
std::string cookie_line = BuildCookieLine(cookies);
histogram_time_get_->AddTime(TimeTicks::Now() - start_time);
VLOG(kVlogGetCookies) << "GetCookies() result: " << cookie_line;
return cookie_line;
}
std::string BuildCookieLine(const CanonicalCookieVector& cookies) {
std::string cookie_line;
for (CanonicalCookieVector::const_iterator it = cookies.begin();
it != cookies.end(); ++it) {
if (it != cookies.begin())
cookie_line += "; ";
// In Mozilla if you set a cookie like AAAA, it will have an empty token
// and a value of AAAA. When it sends the cookie back, it will send AAAA,
// so we need to avoid sending =AAAA for a blank token value.
if (!(*it)->Name().empty())
cookie_line += (*it)->Name() + "=";
cookie_line += (*it)->Value();
}
return cookie_line;
}
那么進(jìn)程被殺之后再次啟動(dòng)椿息,內(nèi)存中的Cookie沒(méi)了;就會(huì)取出持久化的Cookie 坷衍;其位置在
data/data/package_name/app_WebView/Cookies;
問(wèn)題驗(yàn)證
剛剛只是通過(guò)代碼分析寝优,那么如何驗(yàn)證我們的分析是正確的呢?
第一次登錄一個(gè)賬號(hào)然后快殺枫耳,只要app_webview存了上次登錄態(tài)的賬號(hào)就能復(fù)現(xiàn)
Set_Cookie
自動(dòng)登錄得到的Cookie
確實(shí)是app_webview中得到的Cookie(將文件pull出來(lái)乏矾,加個(gè)后綴db;然后用sqliteStudio可以查看)
可以看出確實(shí)是持久化位置的Cookie沒(méi)有及時(shí)更新造成的影響
問(wèn)題結(jié)束
確認(rèn)了這個(gè)之后;我前面也說(shuō)道公司的網(wǎng)絡(luò)框架還自己實(shí)現(xiàn)了CookieManager钻心,通過(guò)自定義PersistentCookieStore來(lái)保存Cookie凄硼;那么是否可以利用這個(gè)來(lái)避免webkit的設(shè)計(jì)造成的漏洞呢;同事將這個(gè)需求列入計(jì)劃了扔役,后續(xù)希望能看到好的結(jié)果帆喇;哈哈