Пример #1
0
void ResourceHandle::setCookies()
{
    KURL url = getInternal()->m_request.url();
    if ((cookieManager().cookiePolicy() == CookieStorageAcceptPolicyOnlyFromMainDocumentDomain) 
      && (getInternal()->m_request.firstPartyForCookies() != url)
      && cookieManager().getCookie(url, WithHttpOnlyCookies).isEmpty())
        return;
    cookieManager().setCookies(url, getInternal()->m_response.httpHeaderField("Set-Cookie"));
    checkAndSendCookies(url);
}
Пример #2
0
bool CookieMap::addOrReplaceCookie(PassRefPtr<ParsedCookie> prpCandidateCookie, RefPtr<ParsedCookie>& replacedCookie, CookieFilter filter)
{
    RefPtr<ParsedCookie> candidateCookie = prpCandidateCookie;
    CookieLog("CookieMap - Attempting to add cookie - %s", cookie->name().utf8().data());

    size_t cookieCount = m_cookieVector.size();
    for (size_t i = 0; i < cookieCount; i++) {
        if (m_cookieVector[i]->name() == candidateCookie->name() && m_cookieVector[i]->path() == candidateCookie->path()) {

            if (filter == NoHttpOnlyCookie && m_cookieVector[i]->isHttpOnly())
                return false;

            replacedCookie = m_cookieVector[i];
            m_cookieVector[i] = candidateCookie;
            if (replacedCookie == m_oldestCookie)
                updateOldestCookie();
            return true;
        }
    }

    m_cookieVector.append(candidateCookie);
    if (!candidateCookie->isSession())
        cookieManager().addedCookie();
    if (!m_oldestCookie || m_oldestCookie->lastAccessed() > candidateCookie->lastAccessed())
        m_oldestCookie = candidateCookie;
    return true;
}
Пример #3
0
nsresult
nsDogbertProfileMigrator::CopyCookies(PRBool aReplace)
{
  nsresult rv;
  if (aReplace) {
#ifdef NEED_TO_FIX_4X_COOKIES
    rv = CopyFile(COOKIES_FILE_NAME_IN_4x, COOKIES_FILE_NAME_IN_5x);
    if (NS_FAILED(rv)) return rv;

    rv = FixDogbertCookies();
#else
    rv = CopyFile(COOKIES_FILE_NAME_IN_4x, COOKIES_FILE_NAME_IN_5x);
#endif
  }
  else {
    nsCOMPtr<nsICookieManager2> cookieManager(do_GetService(NS_COOKIEMANAGER_CONTRACTID));
    if (!cookieManager)
      return NS_ERROR_OUT_OF_MEMORY;

    nsCOMPtr<nsIFile> dogbertCookiesFile;
    mSourceProfile->Clone(getter_AddRefs(dogbertCookiesFile));
    dogbertCookiesFile->Append(COOKIES_FILE_NAME_IN_4x);

    rv = ImportNetscapeCookies(dogbertCookiesFile);
  }
  return rv;
}
Пример #4
0
void deleteCookie(const Document*, const KURL& url, const String& cookieName)
{
    // Cookies are not bound to the document. Therefore, we don't need to pass
    // in the document object to find the targeted cookies in cookie manager.
    // Note: this method is called by inspector only. No need to check if cookie is enabled.
    cookieManager().removeCookieWithName(url, cookieName);
}
nsresult
nsNetscapeProfileMigratorBase::CopyCookies(bool aReplace)
{
  if (aReplace) {
    // can't start the cookieservice, so just push files around:
    // 1) remove target cookies.sqlite file if it exists, to force import
    // 2) copy source cookies.txt file, which will be imported on startup
    nsCOMPtr<nsIFile> targetFile;
    mTargetProfile->Clone(getter_AddRefs(targetFile));
    targetFile->AppendNative(NS_LITERAL_CSTRING(FILE_NAME_COOKIES_SQLITE));
    targetFile->Remove(false);

    return CopyFile(FILE_NAME_COOKIES, FILE_NAME_COOKIES);
  }

  nsresult rv;
  nsCOMPtr<nsICookieManager2> cookieManager(do_GetService(NS_COOKIEMANAGER_CONTRACTID, &rv));
  if (NS_FAILED(rv)) 
    return rv;

  nsCOMPtr<nsIFile> seamonkeyCookiesFile;
  mSourceProfile->Clone(getter_AddRefs(seamonkeyCookiesFile));
  seamonkeyCookiesFile->AppendNative(NS_LITERAL_CSTRING(FILE_NAME_COOKIES));

  return cookieManager->ImportCookies(seamonkeyCookiesFile);
}
Пример #6
0
void WebCookieJar::setCookies(const BlackBerry::Platform::String& url, const std::vector<BlackBerry::Platform::String>& cookies)
{
    KURL kurl = KURL(KURL(), url);
    Vector<String> coreCookies;
    for (size_t i = 0; i < cookies.size(); ++i)
        coreCookies.append(cookies[i]);
    cookieManager().setCookies(kurl, coreCookies, WithHttpOnlyCookies);
}
Пример #7
0
String cookies(Document const* document, KURL const& url)
{
    // 'HttpOnly' cookies should no be accessible from scripts, so we filter them out here
    if (cookiesEnabled(document))
        return cookieManager().getCookie(url, NoHttpOnlyCookie);
    return String();

}
Пример #8
0
void WebCookieJar::setCookies(const char* url, const std::vector<WebString>& cookies)
{
    KURL kurl = KURL(KURL(), String(url));
    Vector<String> coreCookies;
    for (size_t i = 0; i < cookies.size(); ++i)
        coreCookies.append(String(cookies[i].impl()));
    cookieManager().setCookies(kurl, coreCookies, WithHttpOnlyCookies);
}
Пример #9
0
bool getRawCookies(const Document*, const KURL& url, Vector<Cookie>& rawCookies)
{
    // Note: this method is called by inspector only. No need to check if cookie is enabled.
    Vector<RefPtr<ParsedCookie> > result;
    cookieManager().getRawCookies(result, url, WithHttpOnlyCookies);
    for (size_t i = 0; i < result.size(); i++)
        result[i]->appendWebCoreCookie(rawCookies);
    return true;
}
Пример #10
0
void NetworkJob::handleSetCookieHeader(const String& value)
{
    KURL url = m_response.url();
    CookieManager& manager = cookieManager();
    if ((manager.cookiePolicy() == CookieStorageAcceptPolicyOnlyFromMainDocumentDomain)
      && (m_handle->firstRequest().firstPartyForCookies() != url)
      && manager.getCookie(url, WithHttpOnlyCookies).isEmpty())
        return;
    manager.setCookies(url, value);
}
Пример #11
0
std::vector<WebString> WebCookieJar::cookies(const char* url)
{
    KURL kurl = KURL(KURL(), String(url));

    Vector<ParsedCookie*> rawCookies;
    cookieManager().getRawCookies(rawCookies, kurl, WithHttpOnlyCookies);

    std::vector<WebString> result;
    for (size_t i = 0; i < rawCookies.size(); ++i)
        result.push_back(WebString(rawCookies[i]->toNameValuePair().impl()));

    return result;
}
Пример #12
0
std::vector<BlackBerry::Platform::String> WebCookieJar::cookies(const BlackBerry::Platform::String& url)
{
    KURL kurl = KURL(KURL(), url);

    Vector<ParsedCookie*> rawCookies;
    cookieManager().getRawCookies(rawCookies, kurl, WithHttpOnlyCookies);

    std::vector<BlackBerry::Platform::String> result;
    for (size_t i = 0; i < rawCookies.size(); ++i)
        result.push_back(rawCookies[i]->toNameValuePair());

    return result;
}
void CookieDatabaseBackingStore::openAndLoadDatabaseSynchronously(const String& cookieJar)
{
    CookieLog("CookieBackingStore - loading database into CookieManager immediately");

    if (m_db.isOpen()) {
        if (isCurrentThread())
            BlackBerry::Platform::webKitThreadMessageClient()->dispatchSyncMessage(createMethodCallMessage(&CookieManager::getBackingStoreCookies, &cookieManager()));
        else
            cookieManager().getBackingStoreCookies();
    } else {
        if (isCurrentThread())
            invokeOpen(cookieJar);
        else
            dispatchSyncMessage(createMethodCallMessage(&CookieDatabaseBackingStore::invokeOpen, this, cookieJar));
    }
}
nsresult
nsSafariProfileMigrator::CopyCookies(bool aReplace)
{
  nsCOMPtr<nsIProperties> fileLocator(do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID));
  nsCOMPtr<nsILocalFile> safariCookiesFile;
  fileLocator->Get(NS_MAC_USER_LIB_DIR,
                   NS_GET_IID(nsILocalFile),
                   getter_AddRefs(safariCookiesFile));
  safariCookiesFile->Append(NS_LITERAL_STRING("Cookies"));
  safariCookiesFile->Append(SAFARI_COOKIES_FILE_NAME);

  CFArrayRef safariCookies = (CFArrayRef)CopyPListFromFile(safariCookiesFile);
  if (!safariCookies)
    return NS_OK;

  nsCOMPtr<nsICookieManager2> cookieManager(do_GetService(NS_COOKIEMANAGER_CONTRACTID));
  CFIndex count = ::CFArrayGetCount(safariCookies);
  for (PRInt32 i = 0; i < count; ++i) {
    CFDictionaryRef entry = (CFDictionaryRef)::CFArrayGetValueAtIndex(safariCookies, i);

    CFDateRef date = (CFDateRef)::CFDictionaryGetValue(entry, CFSTR("Expires"));

    nsCAutoString domain, path, name, value;
    if (date &&
        GetDictionaryCStringValue(entry, CFSTR("Domain"), domain,
                                  kCFStringEncodingUTF8) &&
        GetDictionaryCStringValue(entry, CFSTR("Path"), path,
                                  kCFStringEncodingUTF8) &&
        GetDictionaryCStringValue(entry, CFSTR("Name"), name,
                                  kCFStringEncodingASCII) &&
        GetDictionaryCStringValue(entry, CFSTR("Value"), value,
                                  kCFStringEncodingASCII)) {
      PRInt64 expiryTime;
      LL_D2L(expiryTime, (double)::CFDateGetAbsoluteTime(date));

      expiryTime += SAFARI_DATE_OFFSET;
      cookieManager->Add(domain, path, name, value,
                         false, // isSecure
                         false, // isHttpOnly
                         false, // isSession
                         expiryTime);
    }
  }
  ::CFRelease(safariCookies);

  return NS_OK;
}
Пример #15
0
void ResourceHandle::checkAndSendCookies(KURL& url)
{
    // Cookies are a part of the http protocol only
    if (!String(d->m_url).startsWith("http"))
        return;

    if (url.isEmpty())
        url = KURL(ParsedURLString, d->m_url);

    // Prepare a cookie header if there are cookies related to this url.
    String cookiePairs = cookieManager().getCookie(url, WithHttpOnlyCookies);
    if (!cookiePairs.isEmpty() && d->m_handle) {
        Vector<char> cookieChar = cookiePairs.impl()->ascii();
        LOG(Network, "CURL POST Cookie : %s \n", cookieChar.data());
        curl_easy_setopt(d->m_handle, CURLOPT_COOKIE, cookieChar.data());
    }
}
Пример #16
0
PassRefPtr<ParsedCookie> CookieMap::removeCookieAtIndex(int position, const PassRefPtr<ParsedCookie> cookie)
{
    ASSERT(0 <= position && static_cast<unsigned>(position) < m_cookieVector.size());
    RefPtr<ParsedCookie> prevCookie = m_cookieVector[position];
    m_cookieVector.remove(position);

    if (prevCookie == m_oldestCookie)
        updateOldestCookie();
    else if (prevCookie != cookie) {
        // The cookie we used to search is force expired, we must do the same
        // to the cookie in memory too.
        if (cookie->isForceExpired())
            prevCookie->forceExpire();
    }

    if (!prevCookie->isSession())
        cookieManager().removedCookie();
    return prevCookie;
}
Пример #17
0
String cookieRequestHeaderFieldValue(const Document* document, const KURL &url)
{
    if (cookiesEnabled(document))
        return cookieManager().getCookie(url, WithHttpOnlyCookies);
    return String();
}
Пример #18
0
static void flushCookiesOnExit(void)
{
    cookieManager().flushCookiesToBackingStore();
}
Пример #19
0
void setCookies(Document* document, KURL const& url, String const& value)
{
    if (cookiesEnabled(document))
        cookieManager().setCookies(url, value, NoHttpOnlyCookie);
}
Пример #20
0
void ResourceRequest::initializePlatformRequest(NetworkRequest& platformRequest, bool cookiesEnabled, bool isInitial, bool isRedirect) const
{
    // If this is the initial load, skip the request body and headers.
    if (isInitial)
        platformRequest.setRequestInitial(timeoutInterval());
    else {
        ReadOnlyLatin1String latin1URL(url().string());
        ReadOnlyLatin1String latin1HttpMethod(httpMethod());
        platformRequest.setRequestUrl(latin1URL.data(), latin1URL.length(),
                latin1HttpMethod.data(), latin1HttpMethod.length(),
                platformCachePolicyForRequest(*this),
                platformTargetTypeForRequest(*this),
                timeoutInterval());

        platformRequest.setConditional(isConditional());
        platformRequest.setSuggestedSaveName(suggestedSaveName().utf8().data());

        if (httpBody() && !httpBody()->isEmpty()) {
            const Vector<FormDataElement>& elements = httpBody()->elements();
            // Use setData for simple forms because it is slightly more efficient.
            if (elements.size() == 1 && elements[0].m_type == FormDataElement::data)
                platformRequest.setData(elements[0].m_data.data(), elements[0].m_data.size());
            else {
                for (unsigned i = 0; i < elements.size(); ++i) {
                    const FormDataElement& element = elements[i];
                    if (element.m_type == FormDataElement::data)
                        platformRequest.addMultipartData(element.m_data.data(), element.m_data.size());
                    else if (element.m_type == FormDataElement::encodedFile)
                        platformRequest.addMultipartFilename(element.m_filename.characters(), element.m_filename.length());
#if ENABLE(BLOB)
                    else if (element.m_type == FormDataElement::encodedBlob) {
                        RefPtr<BlobStorageData> blobData = static_cast<BlobRegistryImpl&>(blobRegistry()).getBlobDataFromURL(KURL(ParsedURLString, element.m_url));
                        if (blobData) {
                            for (size_t j = 0; j < blobData->items().size(); ++j) {
                                const BlobDataItem& blobItem = blobData->items()[j];
                                if (blobItem.type == BlobDataItem::Data)
                                    platformRequest.addMultipartData(blobItem.data->data() + static_cast<int>(blobItem.offset), static_cast<int>(blobItem.length));
                                else {
                                    ASSERT(blobItem.type == BlobDataItem::File);
                                    platformRequest.addMultipartFilename(blobItem.path.characters(), blobItem.path.length(), blobItem.offset, blobItem.length, blobItem.expectedModificationTime);
                                }
                            }
                        }
                    }
#endif
                    else
                        ASSERT_NOT_REACHED(); // unknown type
                }
            }
        }

        // When ResourceRequest is reused by CacheResourceLoader, page refreshing or redirection, its cookies may be dirtied. We won't use these cookies any more.
        bool cookieHeaderMayBeDirty = isRedirect || cachePolicy() == WebCore::ReloadIgnoringCacheData || cachePolicy() == WebCore::ReturnCacheDataElseLoad;

        for (HTTPHeaderMap::const_iterator it = httpHeaderFields().begin(); it != httpHeaderFields().end(); ++it) {
            String key = it->first;
            String value = it->second;
            if (!key.isEmpty()) {
                if (equalIgnoringCase(key, "Cookie")) {
                    // We won't use the old cookies of resourceRequest for new location because these cookies may be changed by redirection.
                    if (cookieHeaderMayBeDirty)
                        continue;
                    // We need to check the encoding and encode the cookie's value using latin1 or utf8 to support unicode data.
                    if (!value.containsOnlyLatin1()) {
                        platformRequest.addHeader("Cookie", value.utf8().data());
                        continue;
                    }
                }
                ReadOnlyLatin1String latin1Key(key);
                ReadOnlyLatin1String latin1Value(value);
                platformRequest.addHeader(latin1Key.data(), latin1Key.length(), latin1Value.data(), latin1Value.length());
            }
        }

        // If request's cookies may be dirty, they must be set again.
        // If there aren't cookies in the header list, we need trying to add cookies.
        if (cookiesEnabled && (cookieHeaderMayBeDirty || !httpHeaderFields().contains("Cookie")) && !url().isNull()) {
            // Prepare a cookie header if there are cookies related to this url.
            String cookiePairs = cookieManager().getCookie(url(), WithHttpOnlyCookies);
            if (!cookiePairs.isEmpty())
                platformRequest.addHeader("Cookie", cookiePairs.containsOnlyLatin1() ? cookiePairs.latin1().data() : cookiePairs.utf8().data());
        }

        if (!httpHeaderFields().contains("Accept-Language"))
            platformRequest.addAcceptLanguageHeader();
    }
}
Пример #21
0
void ResourceRequest::initializePlatformRequest(NetworkRequest& platformRequest, bool cookiesEnabled, bool isInitial, bool isRedirect) const
{
    // If this is the initial load, skip the request body and headers.
    if (isInitial)
        platformRequest.setRequestInitial(timeoutInterval());
    else {
        platformRequest.setRequestUrl(url().string().utf8().data(),
                httpMethod().latin1().data(),
                platformCachePolicyForRequest(*this),
                platformTargetTypeForRequest(*this),
                timeoutInterval());

        platformRequest.setConditional(isConditional());

        if (httpBody() && !httpBody()->isEmpty()) {
            const Vector<FormDataElement>& elements = httpBody()->elements();
            // Use setData for simple forms because it is slightly more efficient.
            if (elements.size() == 1 && elements[0].m_type == FormDataElement::data)
                platformRequest.setData(elements[0].m_data.data(), elements[0].m_data.size());
            else {
                for (unsigned i = 0; i < elements.size(); ++i) {
                    const FormDataElement& element = elements[i];
                    if (element.m_type == FormDataElement::data)
                        platformRequest.addMultipartData(element.m_data.data(), element.m_data.size());
                    else if (element.m_type == FormDataElement::encodedFile)
                        platformRequest.addMultipartFilename(element.m_filename.characters(), element.m_filename.length());
#if ENABLE(BLOB)
                    else if (element.m_type == FormDataElement::encodedBlob) {
                        RefPtr<BlobStorageData> blobData = static_cast<BlobRegistryImpl&>(blobRegistry()).getBlobDataFromURL(KURL(ParsedURLString, element.m_blobURL));
                        if (blobData) {
                            for (size_t j = 0; j < blobData->items().size(); ++j) {
                                const BlobDataItem& blobItem = blobData->items()[j];
                                if (blobItem.type == BlobDataItem::Data)
                                    platformRequest.addMultipartData(blobItem.data->data() + static_cast<int>(blobItem.offset), static_cast<int>(blobItem.length));
                                else {
                                    ASSERT(blobItem.type == BlobDataItem::File);
                                    platformRequest.addMultipartFilename(blobItem.path.characters(), blobItem.path.length(), blobItem.offset, blobItem.length, blobItem.expectedModificationTime);
                                }
                            }
                        }
                    }
#endif
                    else
                        ASSERT_NOT_REACHED(); // unknown type
                }
            }
        }

        for (HTTPHeaderMap::const_iterator it = httpHeaderFields().begin(); it != httpHeaderFields().end(); ++it) {
            String key = it->first;
            String value = it->second;
            if (!key.isEmpty() && !value.isEmpty()) {
                // We need to check the encoding and encode the cookie's value using latin1 or utf8 to support unicode characters.
                if (equalIgnoringCase(key, "Cookie"))
                    platformRequest.addHeader(key.latin1().data(), value.containsOnlyLatin1() ? value.latin1().data() : value.utf8().data());
                else
                    platformRequest.addHeader(key.latin1().data(), value.latin1().data());
            }
        }
       
        // Redirection's response may contain new cookies, so add cookies again.
        // If there aren't cookies in the header list, we need trying to add cookies.
        if (cookiesEnabled && (isRedirect || !httpHeaderFields().contains("Cookie")) && !url().isNull()) {
            // Prepare a cookie header if there are cookies related to this url.
            String cookiePairs = cookieManager().getCookie(url(), WithHttpOnlyCookies);
            if (!cookiePairs.isEmpty())
                platformRequest.addHeader("Cookie", cookiePairs.containsOnlyLatin1() ? cookiePairs.latin1().data() : cookiePairs.utf8().data());
        }

        // Locale has the form "en-US". Construct accept language like "en-US, en;q=0.8".
        std::string locale = BlackBerry::Platform::Client::get()->getLocale();
        // POSIX locale has '_' instead of '-'.
        // Replace to conform to HTTP spec.
        size_t underscore = locale.find('_');
        if (underscore != std::string::npos)
            locale.replace(underscore, 1, "-");
        std::string acceptLanguage = locale + ", " + locale.substr(0, 2) + ";q=0.8";
        platformRequest.addHeader("Accept-Language", acceptLanguage.c_str());
    }
}
void CookieDatabaseBackingStore::invokeOpen(const String& cookieJar)
{
    ASSERT(isCurrentThread());
    if (m_db.isOpen())
        close();

    if (!m_db.open(cookieJar)) {
        LOG_ERROR("Could not open the cookie database. No cookie will be stored!");
        LOG_ERROR("SQLite Error Message: %s", m_db.lastErrorMsg());
        return;
    }

    m_db.executeCommand("PRAGMA locking_mode=EXCLUSIVE;");
    m_db.executeCommand("PRAGMA journal_mode=WAL;");

    const String primaryKeyFields("PRIMARY KEY (protocol, host, path, name)");
    const String databaseFields("name TEXT, value TEXT, host TEXT, path TEXT, expiry DOUBLE, lastAccessed DOUBLE, isSecure INTEGER, isHttpOnly INTEGER, creationTime DOUBLE, protocol TEXT");

    StringBuilder createTableQuery;
    createTableQuery.append("CREATE TABLE IF NOT EXISTS ");
    createTableQuery.append(m_tableName);
    // This table schema is compliant with Mozilla's.
    createTableQuery.append(" (" + databaseFields + ", " + primaryKeyFields+");");

    m_db.setBusyTimeout(1000);

    if (!m_db.executeCommand(createTableQuery.toString())) {
        LOG_ERROR("Could not create the table to store the cookies into. No cookie will be stored!");
        LOG_ERROR("SQLite Error Message: %s", m_db.lastErrorMsg());
        close();
        return;
    }

    StringBuilder insertQuery;
    insertQuery.append("INSERT OR REPLACE INTO ");
    insertQuery.append(m_tableName);
    insertQuery.append(" (name, value, host, path, expiry, lastAccessed, isSecure, isHttpOnly, creationTime, protocol) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10);");

    m_insertStatement = new SQLiteStatement(m_db, insertQuery.toString());
    if (m_insertStatement->prepare()) {
        LOG_ERROR("Cannot save cookies");
        LOG_ERROR("SQLite Error Message: %s", m_db.lastErrorMsg());
    }

    StringBuilder updateQuery;
    updateQuery.append("UPDATE ");
    updateQuery.append(m_tableName);
    // The where statement is chosen to match CookieMap key.
    updateQuery.append(" SET name = ?1, value = ?2, host = ?3, path = ?4, expiry = ?5, lastAccessed = ?6, isSecure = ?7, isHttpOnly = ?8, creationTime = ?9, protocol = ?10 where name = ?1 and host = ?3 and path = ?4;");
    m_updateStatement = new SQLiteStatement(m_db, updateQuery.toString());

    if (m_updateStatement->prepare()) {
        LOG_ERROR("Cannot update cookies");
        LOG_ERROR("SQLite Error Message: %s", m_db.lastErrorMsg());
    }

    StringBuilder deleteQuery;
    deleteQuery.append("DELETE FROM ");
    deleteQuery.append(m_tableName);
    // The where statement is chosen to match CookieMap key.
    deleteQuery.append(" WHERE name=?1 and host=?2 and path=?3 and protocol=?4;");
    m_deleteStatement = new SQLiteStatement(m_db, deleteQuery.toString());

    if (m_deleteStatement->prepare()) {
        LOG_ERROR("Cannot delete cookies");
        LOG_ERROR("SQLite Error Message: %s", m_db.lastErrorMsg());
    }

    BlackBerry::Platform::webKitThreadMessageClient()->dispatchMessage(createMethodCallMessage(&CookieManager::getBackingStoreCookies, &cookieManager()));
}
Пример #23
0
void clearCookieCache()
{
    cookieManager().removeAllCookies(RemoveFromBackingStore);
}
Пример #24
0
void ResourceRequest::initializePlatformRequest(NetworkRequest& platformRequest, bool cookiesEnabled, bool isInitial, bool isRedirect) const
{
    // If this is the initial load, skip the request body and headers.
    if (isInitial)
        platformRequest.setRequestInitial(timeoutInterval());
    else {
        platformRequest.setRequestUrl(url().string(),
            httpMethod(),
                platformCachePolicyForRequest(*this),
                platformTargetTypeForRequest(*this),
                timeoutInterval());

        platformRequest.setConditional(isConditional());
        platformRequest.setSuggestedSaveName(suggestedSaveName());

        if (httpBody() && !httpBody()->isEmpty()) {
            RefPtr<FormData> formData = httpBody();
#if ENABLE(BLOB)
            formData = formData->resolveBlobReferences();
#endif
            const Vector<FormDataElement>& elements = formData->elements();
            // Use setData for simple forms because it is slightly more efficient.
            if (elements.size() == 1 && elements[0].m_type == FormDataElement::data)
                platformRequest.setData(elements[0].m_data.data(), elements[0].m_data.size());
            else {
                for (unsigned i = 0; i < elements.size(); ++i) {
                    const FormDataElement& element = elements[i];
                    if (element.m_type == FormDataElement::data)
                        platformRequest.addMultipartData(element.m_data.data(), element.m_data.size());
                    else if (element.m_type == FormDataElement::encodedFile)
                        platformRequest.addMultipartFilename(element.m_filename.characters(), element.m_filename.length());
                    else
                        ASSERT_NOT_REACHED(); // Blobs should be resolved at this point.
                }
            }
        }

        // When ResourceRequest is reused by CacheResourceLoader, page refreshing or redirection, its cookies may be dirtied. We won't use these cookies any more.
        bool cookieHeaderMayBeDirty = isRedirect || cachePolicy() == WebCore::ReloadIgnoringCacheData || cachePolicy() == WebCore::ReturnCacheDataElseLoad;

        for (HTTPHeaderMap::const_iterator it = httpHeaderFields().begin(); it != httpHeaderFields().end(); ++it) {
            String key = it->key;
            String value = it->value;
            if (!key.isEmpty()) {
                if (equalIgnoringCase(key, "Cookie")) {
                    // We won't use the old cookies of resourceRequest for new location because these cookies may be changed by redirection.
                    if (cookieHeaderMayBeDirty)
                        continue;
                    // We need to check the encoding and encode the cookie's value using latin1 or utf8 to support unicode data.
                    if (!value.containsOnlyLatin1()) {
                        platformRequest.addHeader("Cookie", value.utf8().data());
                        continue;
                    }
                }
                platformRequest.addHeader(key, value);
            }
        }

        // If request's cookies may be dirty, they must be set again.
        // If there aren't cookies in the header list, we need trying to add cookies.
        if (cookiesEnabled && (cookieHeaderMayBeDirty || !httpHeaderFields().contains("Cookie")) && !url().isNull()) {
            // Prepare a cookie header if there are cookies related to this url.
            String cookiePairs = cookieManager().getCookie(url(), WithHttpOnlyCookies);
            if (!cookiePairs.isEmpty())
                platformRequest.addHeader("Cookie", cookiePairs.containsOnlyLatin1() ? cookiePairs.latin1().data() : cookiePairs.utf8().data());
        }

        if (!httpHeaderFields().contains("Accept-Language"))
            platformRequest.addAcceptLanguageHeader();
    }
}
nsresult
nsNetscapeProfileMigratorBase::ImportNetscapeCookies(nsIFile* aCookiesFile)
{
  nsresult rv;
  nsCOMPtr<nsIInputStream> cookiesStream;
  rv = NS_NewLocalFileInputStream(getter_AddRefs(cookiesStream), aCookiesFile);
  if (NS_FAILED(rv)) return rv;

  nsCOMPtr<nsILineInputStream> lineInputStream(do_QueryInterface(cookiesStream));

  // This code is copied from mozilla/netwerk/cookie/src/nsCookieManager.cpp
  static NS_NAMED_LITERAL_CSTRING(kTrue, "TRUE");

  nsCAutoString buffer;
  PRBool isMore = PR_TRUE;
  PRInt32 hostIndex = 0, isDomainIndex, pathIndex, secureIndex, expiresIndex, nameIndex, cookieIndex;
  PRInt32 numInts;
  PRInt64 expires;
  PRBool isDomain;
  PRInt64 currentTime = PR_Now() / PR_USEC_PER_SEC;

  nsCOMPtr<nsICookieManager2> cookieManager(do_GetService(NS_COOKIEMANAGER_CONTRACTID, &rv));
  if (NS_FAILED(rv)) return rv;

  /* file format is:
   *
   * host \t isDomain \t path \t secure \t expires \t name \t cookie
   *
   * if this format isn't respected we move onto the next line in the file.
   * isDomain is "TRUE" or "FALSE" (default to "FALSE")
   * isSecure is "TRUE" or "FALSE" (default to "TRUE")
   * expires is a PRInt64 integer
   * note 1: cookie can contain tabs.
   * note 2: cookies are written in order of lastAccessed time:
   *         most-recently used come first; least-recently-used come last.
   */

  while (isMore && NS_SUCCEEDED(lineInputStream->ReadLine(buffer, &isMore))) {
    if (buffer.IsEmpty() || buffer.First() == '#')
      continue;

    // this is a cheap, cheesy way of parsing a tab-delimited line into
    // string indexes, which can be lopped off into substrings. just for
    // purposes of obfuscation, it also checks that each token was found.
    // todo: use iterators?
    if ((isDomainIndex = buffer.FindChar('\t', hostIndex)     + 1) == 0 ||
        (pathIndex     = buffer.FindChar('\t', isDomainIndex) + 1) == 0 ||
        (secureIndex   = buffer.FindChar('\t', pathIndex)     + 1) == 0 ||
        (expiresIndex  = buffer.FindChar('\t', secureIndex)   + 1) == 0 ||
        (nameIndex     = buffer.FindChar('\t', expiresIndex)  + 1) == 0 ||
        (cookieIndex   = buffer.FindChar('\t', nameIndex)     + 1) == 0)
      continue;

    // check the expirytime first - if it's expired, ignore
    // nullstomp the trailing tab, to avoid copying the string
    char *iter = buffer.BeginWriting();
    *(iter += nameIndex - 1) = char(0);
    numInts = PR_sscanf(buffer.get() + expiresIndex, "%lld", &expires);
    if (numInts != 1 || expires < currentTime)
      continue;

    isDomain = Substring(buffer, isDomainIndex, pathIndex - isDomainIndex - 1).Equals(kTrue);
    const nsDependentCSubstring host =
      Substring(buffer, hostIndex, isDomainIndex - hostIndex - 1);
    // check for bad legacy cookies (domain not starting with a dot, or containing a port),
    // and discard
    if (isDomain && !host.IsEmpty() && host.First() != '.' ||
        host.FindChar(':') != -1)
      continue;

    // create a new nsCookie and assign the data.
    rv = cookieManager->Add(host,
                            Substring(buffer, pathIndex, secureIndex - pathIndex - 1),
                            Substring(buffer, nameIndex, cookieIndex - nameIndex - 1),
                            Substring(buffer, cookieIndex, buffer.Length() - cookieIndex),
                            Substring(buffer, secureIndex, expiresIndex - secureIndex - 1).Equals(kTrue),
                            PR_FALSE, // isHttpOnly
                            PR_FALSE, // isSession
                            expires);
  }

  return rv;
}