netwerk/protocol/http/nsHttpHandler.cpp

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/netwerk/protocol/http/nsHttpHandler.cpp	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,2055 @@
     1.4 +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
     1.5 +/* vim:set ts=4 sw=4 sts=4 et cin: */
     1.6 +/* This Source Code Form is subject to the terms of the Mozilla Public
     1.7 + * License, v. 2.0. If a copy of the MPL was not distributed with this
     1.8 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
     1.9 +
    1.10 +// HttpLog.h should generally be included first
    1.11 +#include "HttpLog.h"
    1.12 +
    1.13 +#include "nsHttp.h"
    1.14 +#include "nsHttpHandler.h"
    1.15 +#include "nsHttpChannel.h"
    1.16 +#include "nsHttpAuthCache.h"
    1.17 +#include "nsStandardURL.h"
    1.18 +#include "nsIDOMWindow.h"
    1.19 +#include "nsIDOMNavigator.h"
    1.20 +#include "nsIMozNavigatorNetwork.h"
    1.21 +#include "nsINetworkProperties.h"
    1.22 +#include "nsIHttpChannel.h"
    1.23 +#include "nsIStandardURL.h"
    1.24 +#include "LoadContextInfo.h"
    1.25 +#include "nsCategoryManagerUtils.h"
    1.26 +#include "nsIPrefService.h"
    1.27 +#include "nsIPrefBranch.h"
    1.28 +#include "nsIPrefLocalizedString.h"
    1.29 +#include "nsISocketProviderService.h"
    1.30 +#include "nsISocketProvider.h"
    1.31 +#include "nsPrintfCString.h"
    1.32 +#include "nsCOMPtr.h"
    1.33 +#include "nsNetCID.h"
    1.34 +#include "prprf.h"
    1.35 +#include "nsNetUtil.h"
    1.36 +#include "nsAsyncRedirectVerifyHelper.h"
    1.37 +#include "nsSocketTransportService2.h"
    1.38 +#include "nsAlgorithm.h"
    1.39 +#include "ASpdySession.h"
    1.40 +#include "mozIApplicationClearPrivateDataParams.h"
    1.41 +#include "EventTokenBucket.h"
    1.42 +#include "Tickler.h"
    1.43 +#include "nsIXULAppInfo.h"
    1.44 +#include "nsICacheSession.h"
    1.45 +#include "nsICookieService.h"
    1.46 +#include "nsIObserverService.h"
    1.47 +#include "nsISiteSecurityService.h"
    1.48 +#include "nsIStreamConverterService.h"
    1.49 +#include "nsITimer.h"
    1.50 +#include "nsCRT.h"
    1.51 +#include "SpdyZlibReporter.h"
    1.52 +#include "nsIMemoryReporter.h"
    1.53 +#include "nsIParentalControlsService.h"
    1.54 +
    1.55 +#include "mozilla/net/NeckoChild.h"
    1.56 +#include "mozilla/Telemetry.h"
    1.57 +
    1.58 +#if defined(XP_UNIX)
    1.59 +#include <sys/utsname.h>
    1.60 +#endif
    1.61 +
    1.62 +#if defined(XP_WIN)
    1.63 +#include <windows.h>
    1.64 +#endif
    1.65 +
    1.66 +#if defined(XP_MACOSX)
    1.67 +#include <CoreServices/CoreServices.h>
    1.68 +#include "nsCocoaFeatures.h"
    1.69 +#endif
    1.70 +
    1.71 +//-----------------------------------------------------------------------------
    1.72 +#include "mozilla/net/HttpChannelChild.h"
    1.73 +
    1.74 +
    1.75 +#ifdef DEBUG
    1.76 +// defined by the socket transport service while active
    1.77 +extern PRThread *gSocketThread;
    1.78 +#endif
    1.79 +
    1.80 +#define UA_PREF_PREFIX          "general.useragent."
    1.81 +#ifdef XP_WIN
    1.82 +#define UA_SPARE_PLATFORM
    1.83 +#endif
    1.84 +
    1.85 +#define HTTP_PREF_PREFIX        "network.http."
    1.86 +#define INTL_ACCEPT_LANGUAGES   "intl.accept_languages"
    1.87 +#define BROWSER_PREF_PREFIX     "browser.cache."
    1.88 +#define DONOTTRACK_HEADER_ENABLED "privacy.donottrackheader.enabled"
    1.89 +#define DONOTTRACK_HEADER_VALUE   "privacy.donottrackheader.value"
    1.90 +#define DONOTTRACK_VALUE_UNSET    2
    1.91 +#define TELEMETRY_ENABLED        "toolkit.telemetry.enabled"
    1.92 +#define ALLOW_EXPERIMENTS        "network.allow-experiments"
    1.93 +#define SAFE_HINT_HEADER_VALUE   "safeHint.enabled"
    1.94 +
    1.95 +#define UA_PREF(_pref) UA_PREF_PREFIX _pref
    1.96 +#define HTTP_PREF(_pref) HTTP_PREF_PREFIX _pref
    1.97 +#define BROWSER_PREF(_pref) BROWSER_PREF_PREFIX _pref
    1.98 +
    1.99 +#define NS_HTTP_PROTOCOL_FLAGS (URI_STD | ALLOWS_PROXY | ALLOWS_PROXY_HTTP | URI_LOADABLE_BY_ANYONE)
   1.100 +
   1.101 +//-----------------------------------------------------------------------------
   1.102 +
   1.103 +namespace mozilla {
   1.104 +namespace net {
   1.105 +
   1.106 +static nsresult
   1.107 +NewURI(const nsACString &aSpec,
   1.108 +       const char *aCharset,
   1.109 +       nsIURI *aBaseURI,
   1.110 +       int32_t aDefaultPort,
   1.111 +       nsIURI **aURI)
   1.112 +{
   1.113 +    nsStandardURL *url = new nsStandardURL();
   1.114 +    if (!url)
   1.115 +        return NS_ERROR_OUT_OF_MEMORY;
   1.116 +    NS_ADDREF(url);
   1.117 +
   1.118 +    nsresult rv = url->Init(nsIStandardURL::URLTYPE_AUTHORITY,
   1.119 +                            aDefaultPort, aSpec, aCharset, aBaseURI);
   1.120 +    if (NS_FAILED(rv)) {
   1.121 +        NS_RELEASE(url);
   1.122 +        return rv;
   1.123 +    }
   1.124 +
   1.125 +    *aURI = url; // no QI needed
   1.126 +    return NS_OK;
   1.127 +}
   1.128 +
   1.129 +//-----------------------------------------------------------------------------
   1.130 +// nsHttpHandler <public>
   1.131 +//-----------------------------------------------------------------------------
   1.132 +
   1.133 +nsHttpHandler *gHttpHandler = nullptr;
   1.134 +
   1.135 +nsHttpHandler::nsHttpHandler()
   1.136 +    : mConnMgr(nullptr)
   1.137 +    , mHttpVersion(NS_HTTP_VERSION_1_1)
   1.138 +    , mProxyHttpVersion(NS_HTTP_VERSION_1_1)
   1.139 +    , mCapabilities(NS_HTTP_ALLOW_KEEPALIVE)
   1.140 +    , mReferrerLevel(0xff) // by default we always send a referrer
   1.141 +    , mSpoofReferrerSource(false)
   1.142 +    , mReferrerTrimmingPolicy(0)
   1.143 +    , mReferrerXOriginPolicy(0)
   1.144 +    , mFastFallbackToIPv4(false)
   1.145 +    , mProxyPipelining(true)
   1.146 +    , mIdleTimeout(PR_SecondsToInterval(10))
   1.147 +    , mSpdyTimeout(PR_SecondsToInterval(180))
   1.148 +    , mResponseTimeout(300)
   1.149 +    , mResponseTimeoutEnabled(false)
   1.150 +    , mMaxRequestAttempts(10)
   1.151 +    , mMaxRequestDelay(10)
   1.152 +    , mIdleSynTimeout(250)
   1.153 +    , mPipeliningEnabled(false)
   1.154 +    , mMaxConnections(24)
   1.155 +    , mMaxPersistentConnectionsPerServer(2)
   1.156 +    , mMaxPersistentConnectionsPerProxy(4)
   1.157 +    , mMaxPipelinedRequests(32)
   1.158 +    , mMaxOptimisticPipelinedRequests(4)
   1.159 +    , mPipelineAggressive(false)
   1.160 +    , mMaxPipelineObjectSize(300000)
   1.161 +    , mPipelineRescheduleOnTimeout(true)
   1.162 +    , mPipelineRescheduleTimeout(PR_MillisecondsToInterval(1500))
   1.163 +    , mPipelineReadTimeout(PR_MillisecondsToInterval(30000))
   1.164 +    , mRedirectionLimit(10)
   1.165 +    , mPhishyUserPassLength(1)
   1.166 +    , mQoSBits(0x00)
   1.167 +    , mPipeliningOverSSL(false)
   1.168 +    , mEnforceAssocReq(false)
   1.169 +    , mLastUniqueID(NowInSeconds())
   1.170 +    , mSessionStartTime(0)
   1.171 +    , mLegacyAppName("Mozilla")
   1.172 +    , mLegacyAppVersion("5.0")
   1.173 +    , mProduct("Gecko")
   1.174 +    , mUserAgentIsDirty(true)
   1.175 +    , mUseCache(true)
   1.176 +    , mPromptTempRedirect(true)
   1.177 +    , mSendSecureXSiteReferrer(true)
   1.178 +    , mEnablePersistentHttpsCaching(false)
   1.179 +    , mDoNotTrackEnabled(false)
   1.180 +    , mDoNotTrackValue(1)
   1.181 +    , mSafeHintEnabled(false)
   1.182 +    , mParentalControlEnabled(false)
   1.183 +    , mTelemetryEnabled(false)
   1.184 +    , mAllowExperiments(true)
   1.185 +    , mHandlerActive(false)
   1.186 +    , mEnableSpdy(false)
   1.187 +    , mSpdyV3(true)
   1.188 +    , mSpdyV31(true)
   1.189 +    , mHttp2DraftEnabled(true)
   1.190 +    , mEnforceHttp2TlsProfile(true)
   1.191 +    , mCoalesceSpdy(true)
   1.192 +    , mSpdyPersistentSettings(false)
   1.193 +    , mAllowPush(true)
   1.194 +    , mSpdySendingChunkSize(ASpdySession::kSendingChunkSize)
   1.195 +    , mSpdySendBufferSize(ASpdySession::kTCPSendBufferSize)
   1.196 +    , mSpdyPushAllowance(32768)
   1.197 +    , mSpdyPingThreshold(PR_SecondsToInterval(58))
   1.198 +    , mSpdyPingTimeout(PR_SecondsToInterval(8))
   1.199 +    , mConnectTimeout(90000)
   1.200 +    , mBypassCacheLockThreshold(250.0)
   1.201 +    , mParallelSpeculativeConnectLimit(6)
   1.202 +    , mRequestTokenBucketEnabled(true)
   1.203 +    , mRequestTokenBucketMinParallelism(6)
   1.204 +    , mRequestTokenBucketHz(100)
   1.205 +    , mRequestTokenBucketBurst(32)
   1.206 +    , mTCPKeepaliveShortLivedEnabled(false)
   1.207 +    , mTCPKeepaliveShortLivedTimeS(60)
   1.208 +    , mTCPKeepaliveShortLivedIdleTimeS(10)
   1.209 +    , mTCPKeepaliveLongLivedEnabled(false)
   1.210 +    , mTCPKeepaliveLongLivedIdleTimeS(600)
   1.211 +{
   1.212 +#if defined(PR_LOGGING)
   1.213 +    gHttpLog = PR_NewLogModule("nsHttp");
   1.214 +#endif
   1.215 +
   1.216 +    LOG(("Creating nsHttpHandler [this=%p].\n", this));
   1.217 +
   1.218 +    RegisterStrongMemoryReporter(new SpdyZlibReporter());
   1.219 +
   1.220 +    MOZ_ASSERT(!gHttpHandler, "HTTP handler already created!");
   1.221 +    gHttpHandler = this;
   1.222 +}
   1.223 +
   1.224 +nsHttpHandler::~nsHttpHandler()
   1.225 +{
   1.226 +    LOG(("Deleting nsHttpHandler [this=%p]\n", this));
   1.227 +
   1.228 +    // make sure the connection manager is shutdown
   1.229 +    if (mConnMgr) {
   1.230 +        mConnMgr->Shutdown();
   1.231 +        NS_RELEASE(mConnMgr);
   1.232 +    }
   1.233 +
   1.234 +    // Note: don't call NeckoChild::DestroyNeckoChild() here, as it's too late
   1.235 +    // and it'll segfault.  NeckoChild will get cleaned up by process exit.
   1.236 +
   1.237 +    nsHttp::DestroyAtomTable();
   1.238 +    if (mPipelineTestTimer) {
   1.239 +        mPipelineTestTimer->Cancel();
   1.240 +        mPipelineTestTimer = nullptr;
   1.241 +    }
   1.242 +
   1.243 +    gHttpHandler = nullptr;
   1.244 +}
   1.245 +
   1.246 +nsresult
   1.247 +nsHttpHandler::Init()
   1.248 +{
   1.249 +    nsresult rv;
   1.250 +
   1.251 +    LOG(("nsHttpHandler::Init\n"));
   1.252 +
   1.253 +    rv = nsHttp::CreateAtomTable();
   1.254 +    if (NS_FAILED(rv))
   1.255 +        return rv;
   1.256 +
   1.257 +    nsCOMPtr<nsIIOService> service = do_GetService(NS_IOSERVICE_CONTRACTID, &rv);
   1.258 +    if (NS_FAILED(rv)) {
   1.259 +        NS_WARNING("unable to continue without io service");
   1.260 +        return rv;
   1.261 +    }
   1.262 +    mIOService = new nsMainThreadPtrHolder<nsIIOService>(service);
   1.263 +
   1.264 +    if (IsNeckoChild())
   1.265 +        NeckoChild::InitNeckoChild();
   1.266 +
   1.267 +    InitUserAgentComponents();
   1.268 +
   1.269 +    // monitor some preference changes
   1.270 +    nsCOMPtr<nsIPrefBranch> prefBranch = do_GetService(NS_PREFSERVICE_CONTRACTID);
   1.271 +    if (prefBranch) {
   1.272 +        prefBranch->AddObserver(HTTP_PREF_PREFIX, this, true);
   1.273 +        prefBranch->AddObserver(UA_PREF_PREFIX, this, true);
   1.274 +        prefBranch->AddObserver(INTL_ACCEPT_LANGUAGES, this, true);
   1.275 +        prefBranch->AddObserver(BROWSER_PREF("disk_cache_ssl"), this, true);
   1.276 +        prefBranch->AddObserver(DONOTTRACK_HEADER_ENABLED, this, true);
   1.277 +        prefBranch->AddObserver(DONOTTRACK_HEADER_VALUE, this, true);
   1.278 +        prefBranch->AddObserver(TELEMETRY_ENABLED, this, true);
   1.279 +        prefBranch->AddObserver(HTTP_PREF("tcp_keepalive.short_lived_connections"), this, true);
   1.280 +        prefBranch->AddObserver(HTTP_PREF("tcp_keepalive.long_lived_connections"), this, true);
   1.281 +        prefBranch->AddObserver(SAFE_HINT_HEADER_VALUE, this, true);
   1.282 +        PrefsChanged(prefBranch, nullptr);
   1.283 +    }
   1.284 +
   1.285 +    mMisc.AssignLiteral("rv:" MOZILLA_UAVERSION);
   1.286 +
   1.287 +    mCompatFirefox.AssignLiteral("Firefox/" MOZILLA_UAVERSION);
   1.288 +
   1.289 +    nsCOMPtr<nsIXULAppInfo> appInfo =
   1.290 +        do_GetService("@mozilla.org/xre/app-info;1");
   1.291 +
   1.292 +    mAppName.AssignLiteral(MOZ_APP_UA_NAME);
   1.293 +    if (mAppName.Length() == 0 && appInfo) {
   1.294 +        // Try to get the UA name from appInfo, falling back to the name
   1.295 +        appInfo->GetUAName(mAppName);
   1.296 +        if (mAppName.Length() == 0) {
   1.297 +          appInfo->GetName(mAppName);
   1.298 +        }
   1.299 +        appInfo->GetVersion(mAppVersion);
   1.300 +        mAppName.StripChars(" ()<>@,;:\\\"/[]?={}");
   1.301 +    } else {
   1.302 +        mAppVersion.AssignLiteral(MOZ_APP_UA_VERSION);
   1.303 +    }
   1.304 +
   1.305 +    mSessionStartTime = NowInSeconds();
   1.306 +    mHandlerActive = true;
   1.307 +
   1.308 +    rv = mAuthCache.Init();
   1.309 +    if (NS_FAILED(rv)) return rv;
   1.310 +
   1.311 +    rv = mPrivateAuthCache.Init();
   1.312 +    if (NS_FAILED(rv)) return rv;
   1.313 +
   1.314 +    rv = InitConnectionMgr();
   1.315 +    if (NS_FAILED(rv)) return rv;
   1.316 +
   1.317 +#ifdef ANDROID
   1.318 +    mProductSub.AssignLiteral(MOZILLA_UAVERSION);
   1.319 +#else
   1.320 +    mProductSub.AssignLiteral("20100101");
   1.321 +#endif
   1.322 +
   1.323 +#if DEBUG
   1.324 +    // dump user agent prefs
   1.325 +    LOG(("> legacy-app-name = %s\n", mLegacyAppName.get()));
   1.326 +    LOG(("> legacy-app-version = %s\n", mLegacyAppVersion.get()));
   1.327 +    LOG(("> platform = %s\n", mPlatform.get()));
   1.328 +    LOG(("> oscpu = %s\n", mOscpu.get()));
   1.329 +    LOG(("> misc = %s\n", mMisc.get()));
   1.330 +    LOG(("> product = %s\n", mProduct.get()));
   1.331 +    LOG(("> product-sub = %s\n", mProductSub.get()));
   1.332 +    LOG(("> app-name = %s\n", mAppName.get()));
   1.333 +    LOG(("> app-version = %s\n", mAppVersion.get()));
   1.334 +    LOG(("> compat-firefox = %s\n", mCompatFirefox.get()));
   1.335 +    LOG(("> user-agent = %s\n", UserAgent().get()));
   1.336 +#endif
   1.337 +
   1.338 +    // Startup the http category
   1.339 +    // Bring alive the objects in the http-protocol-startup category
   1.340 +    NS_CreateServicesFromCategory(NS_HTTP_STARTUP_CATEGORY,
   1.341 +                                  static_cast<nsISupports*>(static_cast<void*>(this)),
   1.342 +                                  NS_HTTP_STARTUP_TOPIC);
   1.343 +
   1.344 +    nsCOMPtr<nsIObserverService> obsService = services::GetObserverService();
   1.345 +    mObserverService = new nsMainThreadPtrHolder<nsIObserverService>(obsService);
   1.346 +    if (mObserverService) {
   1.347 +        mObserverService->AddObserver(this, "profile-change-net-teardown", true);
   1.348 +        mObserverService->AddObserver(this, "profile-change-net-restore", true);
   1.349 +        mObserverService->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, true);
   1.350 +        mObserverService->AddObserver(this, "net:clear-active-logins", true);
   1.351 +        mObserverService->AddObserver(this, "net:prune-dead-connections", true);
   1.352 +        mObserverService->AddObserver(this, "net:prune-all-connections", true);        
   1.353 +        mObserverService->AddObserver(this, "net:failed-to-process-uri-content", true);
   1.354 +        mObserverService->AddObserver(this, "last-pb-context-exited", true);
   1.355 +    }
   1.356 +
   1.357 +    MakeNewRequestTokenBucket();
   1.358 +    mWifiTickler = new Tickler();
   1.359 +    if (NS_FAILED(mWifiTickler->Init()))
   1.360 +        mWifiTickler = nullptr;
   1.361 +
   1.362 +    nsCOMPtr<nsIParentalControlsService> pc = do_CreateInstance("@mozilla.org/parental-controls-service;1");
   1.363 +    if (pc) {
   1.364 +        pc->GetParentalControlsEnabled(&mParentalControlEnabled);
   1.365 +    }
   1.366 +    return NS_OK;
   1.367 +}
   1.368 +
   1.369 +void
   1.370 +nsHttpHandler::MakeNewRequestTokenBucket()
   1.371 +{
   1.372 +    if (!mConnMgr)
   1.373 +        return;
   1.374 +
   1.375 +    nsRefPtr<EventTokenBucket> tokenBucket =
   1.376 +        new EventTokenBucket(RequestTokenBucketHz(),
   1.377 +                                           RequestTokenBucketBurst());
   1.378 +    mConnMgr->UpdateRequestTokenBucket(tokenBucket);
   1.379 +}
   1.380 +
   1.381 +nsresult
   1.382 +nsHttpHandler::InitConnectionMgr()
   1.383 +{
   1.384 +    nsresult rv;
   1.385 +
   1.386 +    if (!mConnMgr) {
   1.387 +        mConnMgr = new nsHttpConnectionMgr();
   1.388 +        if (!mConnMgr)
   1.389 +            return NS_ERROR_OUT_OF_MEMORY;
   1.390 +        NS_ADDREF(mConnMgr);
   1.391 +    }
   1.392 +
   1.393 +    rv = mConnMgr->Init(mMaxConnections,
   1.394 +                        mMaxPersistentConnectionsPerServer,
   1.395 +                        mMaxPersistentConnectionsPerProxy,
   1.396 +                        mMaxRequestDelay,
   1.397 +                        mMaxPipelinedRequests,
   1.398 +                        mMaxOptimisticPipelinedRequests);
   1.399 +    return rv;
   1.400 +}
   1.401 +
   1.402 +nsresult
   1.403 +nsHttpHandler::AddStandardRequestHeaders(nsHttpHeaderArray *request)
   1.404 +{
   1.405 +    nsresult rv;
   1.406 +
   1.407 +    // Add the "User-Agent" header
   1.408 +    rv = request->SetHeader(nsHttp::User_Agent, UserAgent());
   1.409 +    if (NS_FAILED(rv)) return rv;
   1.410 +
   1.411 +    // MIME based content negotiation lives!
   1.412 +    // Add the "Accept" header
   1.413 +    rv = request->SetHeader(nsHttp::Accept, mAccept);
   1.414 +    if (NS_FAILED(rv)) return rv;
   1.415 +
   1.416 +    // Add the "Accept-Language" header
   1.417 +    if (!mAcceptLanguages.IsEmpty()) {
   1.418 +        // Add the "Accept-Language" header
   1.419 +        rv = request->SetHeader(nsHttp::Accept_Language, mAcceptLanguages);
   1.420 +        if (NS_FAILED(rv)) return rv;
   1.421 +    }
   1.422 +
   1.423 +    // Add the "Accept-Encoding" header
   1.424 +    rv = request->SetHeader(nsHttp::Accept_Encoding, mAcceptEncodings);
   1.425 +    if (NS_FAILED(rv)) return rv;
   1.426 +
   1.427 +    // Add the "Do-Not-Track" header
   1.428 +    if (mDoNotTrackEnabled) {
   1.429 +      rv = request->SetHeader(nsHttp::DoNotTrack,
   1.430 +                              nsPrintfCString("%d", mDoNotTrackValue));
   1.431 +      if (NS_FAILED(rv)) return rv;
   1.432 +    }
   1.433 +
   1.434 +    // add the "Send Hint" header
   1.435 +    if (mSafeHintEnabled || mParentalControlEnabled) {
   1.436 +      rv = request->SetHeader(nsHttp::Prefer, NS_LITERAL_CSTRING("safe"));
   1.437 +      if (NS_FAILED(rv)) return rv;
   1.438 +    }
   1.439 +    return NS_OK;
   1.440 +}
   1.441 +
   1.442 +nsresult
   1.443 +nsHttpHandler::AddConnectionHeader(nsHttpHeaderArray *request,
   1.444 +                                   uint32_t caps)
   1.445 +{
   1.446 +    // RFC2616 section 19.6.2 states that the "Connection: keep-alive"
   1.447 +    // and "Keep-alive" request headers should not be sent by HTTP/1.1
   1.448 +    // user-agents.  But this is not a problem in practice, and the
   1.449 +    // alternative proxy-connection is worse. see 570283
   1.450 +
   1.451 +    NS_NAMED_LITERAL_CSTRING(close, "close");
   1.452 +    NS_NAMED_LITERAL_CSTRING(keepAlive, "keep-alive");
   1.453 +
   1.454 +    const nsACString *connectionType = &close;
   1.455 +    if (caps & NS_HTTP_ALLOW_KEEPALIVE) {
   1.456 +        connectionType = &keepAlive;
   1.457 +    }
   1.458 +
   1.459 +    return request->SetHeader(nsHttp::Connection, *connectionType);
   1.460 +}
   1.461 +
   1.462 +bool
   1.463 +nsHttpHandler::IsAcceptableEncoding(const char *enc)
   1.464 +{
   1.465 +    if (!enc)
   1.466 +        return false;
   1.467 +
   1.468 +    // HTTP 1.1 allows servers to send x-gzip and x-compress instead
   1.469 +    // of gzip and compress, for example.  So, we'll always strip off
   1.470 +    // an "x-" prefix before matching the encoding to one we claim
   1.471 +    // to accept.
   1.472 +    if (!PL_strncasecmp(enc, "x-", 2))
   1.473 +        enc += 2;
   1.474 +
   1.475 +    // gzip and deflate are inherently acceptable in modern HTTP - always
   1.476 +    // process them if a stream converter can also be found.
   1.477 +    if (!PL_strcasecmp(enc, "gzip") || !PL_strcasecmp(enc, "deflate"))
   1.478 +        return true;
   1.479 +
   1.480 +    return nsHttp::FindToken(mAcceptEncodings.get(), enc, HTTP_LWS ",") != nullptr;
   1.481 +}
   1.482 +
   1.483 +nsresult
   1.484 +nsHttpHandler::GetStreamConverterService(nsIStreamConverterService **result)
   1.485 +{
   1.486 +    if (!mStreamConvSvc) {
   1.487 +        nsresult rv;
   1.488 +        nsCOMPtr<nsIStreamConverterService> service =
   1.489 +            do_GetService(NS_STREAMCONVERTERSERVICE_CONTRACTID, &rv);
   1.490 +        if (NS_FAILED(rv))
   1.491 +            return rv;
   1.492 +        mStreamConvSvc = new nsMainThreadPtrHolder<nsIStreamConverterService>(service);
   1.493 +    }
   1.494 +    *result = mStreamConvSvc;
   1.495 +    NS_ADDREF(*result);
   1.496 +    return NS_OK;
   1.497 +}
   1.498 +
   1.499 +nsISiteSecurityService*
   1.500 +nsHttpHandler::GetSSService()
   1.501 +{
   1.502 +    if (!mSSService) {
   1.503 +        nsCOMPtr<nsISiteSecurityService> service = do_GetService(NS_SSSERVICE_CONTRACTID);
   1.504 +        mSSService = new nsMainThreadPtrHolder<nsISiteSecurityService>(service);
   1.505 +    }
   1.506 +    return mSSService;
   1.507 +}
   1.508 +
   1.509 +nsICookieService *
   1.510 +nsHttpHandler::GetCookieService()
   1.511 +{
   1.512 +    if (!mCookieService) {
   1.513 +        nsCOMPtr<nsICookieService> service = do_GetService(NS_COOKIESERVICE_CONTRACTID);
   1.514 +        mCookieService = new nsMainThreadPtrHolder<nsICookieService>(service);
   1.515 +    }
   1.516 +    return mCookieService;
   1.517 +}
   1.518 +
   1.519 +nsresult
   1.520 +nsHttpHandler::GetIOService(nsIIOService** result)
   1.521 +{
   1.522 +    NS_ADDREF(*result = mIOService);
   1.523 +    return NS_OK;
   1.524 +}
   1.525 +
   1.526 +uint32_t
   1.527 +nsHttpHandler::Get32BitsOfPseudoRandom()
   1.528 +{
   1.529 +    // only confirm rand seeding on socket thread
   1.530 +    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
   1.531 +
   1.532 +    // rand() provides different amounts of PRNG on different platforms.
   1.533 +    // 15 or 31 bits are common amounts.
   1.534 +
   1.535 +    PR_STATIC_ASSERT(RAND_MAX >= 0xfff);
   1.536 +
   1.537 +#if RAND_MAX < 0xffffU
   1.538 +    return ((uint16_t) rand() << 20) |
   1.539 +            (((uint16_t) rand() & 0xfff) << 8) |
   1.540 +            ((uint16_t) rand() & 0xff);
   1.541 +#elif RAND_MAX < 0xffffffffU
   1.542 +    return ((uint16_t) rand() << 16) | ((uint16_t) rand() & 0xffff);
   1.543 +#else
   1.544 +    return (uint32_t) rand();
   1.545 +#endif
   1.546 +}
   1.547 +
   1.548 +void
   1.549 +nsHttpHandler::NotifyObservers(nsIHttpChannel *chan, const char *event)
   1.550 +{
   1.551 +    LOG(("nsHttpHandler::NotifyObservers [chan=%x event=\"%s\"]\n", chan, event));
   1.552 +    if (mObserverService)
   1.553 +        mObserverService->NotifyObservers(chan, event, nullptr);
   1.554 +}
   1.555 +
   1.556 +nsresult
   1.557 +nsHttpHandler::AsyncOnChannelRedirect(nsIChannel* oldChan, nsIChannel* newChan,
   1.558 +                                 uint32_t flags)
   1.559 +{
   1.560 +    // TODO E10S This helper has to be initialized on the other process
   1.561 +    nsRefPtr<nsAsyncRedirectVerifyHelper> redirectCallbackHelper =
   1.562 +        new nsAsyncRedirectVerifyHelper();
   1.563 +
   1.564 +    return redirectCallbackHelper->Init(oldChan, newChan, flags);
   1.565 +}
   1.566 +
   1.567 +/* static */ nsresult
   1.568 +nsHttpHandler::GenerateHostPort(const nsCString& host, int32_t port,
   1.569 +                                nsCString& hostLine)
   1.570 +{
   1.571 +    return NS_GenerateHostPort(host, port, hostLine);
   1.572 +}
   1.573 +
   1.574 +//-----------------------------------------------------------------------------
   1.575 +// nsHttpHandler <private>
   1.576 +//-----------------------------------------------------------------------------
   1.577 +
   1.578 +const nsAFlatCString &
   1.579 +nsHttpHandler::UserAgent()
   1.580 +{
   1.581 +    if (mUserAgentOverride) {
   1.582 +        LOG(("using general.useragent.override : %s\n", mUserAgentOverride.get()));
   1.583 +        return mUserAgentOverride;
   1.584 +    }
   1.585 +
   1.586 +    if (mUserAgentIsDirty) {
   1.587 +        BuildUserAgent();
   1.588 +        mUserAgentIsDirty = false;
   1.589 +    }
   1.590 +
   1.591 +    return mUserAgent;
   1.592 +}
   1.593 +
   1.594 +void
   1.595 +nsHttpHandler::BuildUserAgent()
   1.596 +{
   1.597 +    LOG(("nsHttpHandler::BuildUserAgent\n"));
   1.598 +
   1.599 +    MOZ_ASSERT(!mLegacyAppName.IsEmpty() &&
   1.600 +               !mLegacyAppVersion.IsEmpty(),
   1.601 +               "HTTP cannot send practical requests without this much");
   1.602 +
   1.603 +    // preallocate to worst-case size, which should always be better
   1.604 +    // than if we didn't preallocate at all.
   1.605 +    mUserAgent.SetCapacity(mLegacyAppName.Length() +
   1.606 +                           mLegacyAppVersion.Length() +
   1.607 +#ifndef UA_SPARE_PLATFORM
   1.608 +                           mPlatform.Length() +
   1.609 +#endif
   1.610 +                           mOscpu.Length() +
   1.611 +                           mMisc.Length() +
   1.612 +                           mProduct.Length() +
   1.613 +                           mProductSub.Length() +
   1.614 +                           mAppName.Length() +
   1.615 +                           mAppVersion.Length() +
   1.616 +                           mCompatFirefox.Length() +
   1.617 +                           mCompatDevice.Length() +
   1.618 +                           13);
   1.619 +
   1.620 +    // Application portion
   1.621 +    mUserAgent.Assign(mLegacyAppName);
   1.622 +    mUserAgent += '/';
   1.623 +    mUserAgent += mLegacyAppVersion;
   1.624 +    mUserAgent += ' ';
   1.625 +
   1.626 +    // Application comment
   1.627 +    mUserAgent += '(';
   1.628 +#ifndef UA_SPARE_PLATFORM
   1.629 +    if (!mPlatform.IsEmpty()) {
   1.630 +      mUserAgent += mPlatform;
   1.631 +      mUserAgent.AppendLiteral("; ");
   1.632 +    }
   1.633 +#endif
   1.634 +    if (!mCompatDevice.IsEmpty()) {
   1.635 +        mUserAgent += mCompatDevice;
   1.636 +        mUserAgent.AppendLiteral("; ");
   1.637 +    }
   1.638 +    else if (!mOscpu.IsEmpty()) {
   1.639 +      mUserAgent += mOscpu;
   1.640 +      mUserAgent.AppendLiteral("; ");
   1.641 +    }
   1.642 +    mUserAgent += mMisc;
   1.643 +    mUserAgent += ')';
   1.644 +
   1.645 +    // Product portion
   1.646 +    mUserAgent += ' ';
   1.647 +    mUserAgent += mProduct;
   1.648 +    mUserAgent += '/';
   1.649 +    mUserAgent += mProductSub;
   1.650 +
   1.651 +    bool isFirefox = mAppName.EqualsLiteral("Firefox");
   1.652 +    if (isFirefox || mCompatFirefoxEnabled) {
   1.653 +        // "Firefox/x.y" (compatibility) app token
   1.654 +        mUserAgent += ' ';
   1.655 +        mUserAgent += mCompatFirefox;
   1.656 +    }
   1.657 +    if (!isFirefox) {
   1.658 +        // App portion
   1.659 +        mUserAgent += ' ';
   1.660 +        mUserAgent += mAppName;
   1.661 +        mUserAgent += '/';
   1.662 +        mUserAgent += mAppVersion;
   1.663 +    }
   1.664 +}
   1.665 +
   1.666 +#ifdef XP_WIN
   1.667 +#define WNT_BASE "Windows NT %ld.%ld"
   1.668 +#define W64_PREFIX "; Win64"
   1.669 +#endif
   1.670 +
   1.671 +void
   1.672 +nsHttpHandler::InitUserAgentComponents()
   1.673 +{
   1.674 +#ifndef MOZ_UA_OS_AGNOSTIC
   1.675 +    // Gather platform.
   1.676 +    mPlatform.AssignLiteral(
   1.677 +#if defined(ANDROID)
   1.678 +    "Android"
   1.679 +#elif defined(XP_WIN)
   1.680 +    "Windows"
   1.681 +#elif defined(XP_MACOSX)
   1.682 +    "Macintosh"
   1.683 +#elif defined(MOZ_X11)
   1.684 +    "X11"
   1.685 +#endif
   1.686 +    );
   1.687 +#endif
   1.688 +
   1.689 +#if defined(ANDROID) || defined(MOZ_B2G)
   1.690 +    nsCOMPtr<nsIPropertyBag2> infoService = do_GetService("@mozilla.org/system-info;1");
   1.691 +    MOZ_ASSERT(infoService, "Could not find a system info service");
   1.692 +
   1.693 +    bool isTablet;
   1.694 +    nsresult rv = infoService->GetPropertyAsBool(NS_LITERAL_STRING("tablet"), &isTablet);
   1.695 +    if (NS_SUCCEEDED(rv) && isTablet)
   1.696 +        mCompatDevice.AssignLiteral("Tablet");
   1.697 +    else
   1.698 +        mCompatDevice.AssignLiteral("Mobile");
   1.699 +#endif
   1.700 +
   1.701 +#ifndef MOZ_UA_OS_AGNOSTIC
   1.702 +    // Gather OS/CPU.
   1.703 +#if defined(XP_WIN)
   1.704 +    OSVERSIONINFO info = { sizeof(OSVERSIONINFO) };
   1.705 +#pragma warning(push)
   1.706 +#pragma warning(disable:4996)
   1.707 +    if (GetVersionEx(&info)) {
   1.708 +#pragma warning(pop)
   1.709 +        const char *format;
   1.710 +#if defined _M_IA64
   1.711 +        format = WNT_BASE W64_PREFIX "; IA64";
   1.712 +#elif defined _M_X64 || defined _M_AMD64
   1.713 +        format = WNT_BASE W64_PREFIX "; x64";
   1.714 +#else
   1.715 +        BOOL isWow64 = FALSE;
   1.716 +        if (!IsWow64Process(GetCurrentProcess(), &isWow64)) {
   1.717 +            isWow64 = FALSE;
   1.718 +        }
   1.719 +        format = isWow64
   1.720 +          ? WNT_BASE "; WOW64"
   1.721 +          : WNT_BASE;
   1.722 +#endif
   1.723 +        char *buf = PR_smprintf(format,
   1.724 +                                info.dwMajorVersion,
   1.725 +                                info.dwMinorVersion);
   1.726 +        if (buf) {
   1.727 +            mOscpu = buf;
   1.728 +            PR_smprintf_free(buf);
   1.729 +        }
   1.730 +    }
   1.731 +#elif defined (XP_MACOSX)
   1.732 +#if defined(__ppc__)
   1.733 +    mOscpu.AssignLiteral("PPC Mac OS X");
   1.734 +#elif defined(__i386__) || defined(__x86_64__)
   1.735 +    mOscpu.AssignLiteral("Intel Mac OS X");
   1.736 +#endif
   1.737 +    SInt32 majorVersion = nsCocoaFeatures::OSXVersionMajor();
   1.738 +    SInt32 minorVersion = nsCocoaFeatures::OSXVersionMinor();
   1.739 +    mOscpu += nsPrintfCString(" %d.%d", majorVersion, minorVersion);
   1.740 +#elif defined (XP_UNIX)
   1.741 +    struct utsname name;
   1.742 +
   1.743 +    int ret = uname(&name);
   1.744 +    if (ret >= 0) {
   1.745 +        nsAutoCString buf;
   1.746 +        buf =  (char*)name.sysname;
   1.747 +
   1.748 +        if (strcmp(name.machine, "x86_64") == 0 &&
   1.749 +            sizeof(void *) == sizeof(int32_t)) {
   1.750 +            // We're running 32-bit code on x86_64. Make this browser
   1.751 +            // look like it's running on i686 hardware, but append "
   1.752 +            // (x86_64)" to the end of the oscpu identifier to be able
   1.753 +            // to differentiate this from someone running 64-bit code
   1.754 +            // on x86_64..
   1.755 +
   1.756 +            buf += " i686 on x86_64";
   1.757 +        } else {
   1.758 +            buf += ' ';
   1.759 +
   1.760 +#ifdef AIX
   1.761 +            // AIX uname returns machine specific info in the uname.machine
   1.762 +            // field and does not return the cpu type like other platforms.
   1.763 +            // We use the AIX version and release numbers instead.
   1.764 +            buf += (char*)name.version;
   1.765 +            buf += '.';
   1.766 +            buf += (char*)name.release;
   1.767 +#else
   1.768 +            buf += (char*)name.machine;
   1.769 +#endif
   1.770 +        }
   1.771 +
   1.772 +        mOscpu.Assign(buf);
   1.773 +    }
   1.774 +#endif
   1.775 +#endif
   1.776 +
   1.777 +    mUserAgentIsDirty = true;
   1.778 +}
   1.779 +
   1.780 +uint32_t
   1.781 +nsHttpHandler::MaxSocketCount()
   1.782 +{
   1.783 +    PR_CallOnce(&nsSocketTransportService::gMaxCountInitOnce,
   1.784 +                nsSocketTransportService::DiscoverMaxCount);
   1.785 +    // Don't use the full max count because sockets can be held in
   1.786 +    // the persistent connection pool for a long time and that could
   1.787 +    // starve other users.
   1.788 +
   1.789 +    uint32_t maxCount = nsSocketTransportService::gMaxCount;
   1.790 +    if (maxCount <= 8)
   1.791 +        maxCount = 1;
   1.792 +    else
   1.793 +        maxCount -= 8;
   1.794 +
   1.795 +    return maxCount;
   1.796 +}
   1.797 +
   1.798 +void
   1.799 +nsHttpHandler::PrefsChanged(nsIPrefBranch *prefs, const char *pref)
   1.800 +{
   1.801 +    nsresult rv = NS_OK;
   1.802 +    int32_t val;
   1.803 +
   1.804 +    LOG(("nsHttpHandler::PrefsChanged [pref=%s]\n", pref));
   1.805 +
   1.806 +#define PREF_CHANGED(p) ((pref == nullptr) || !PL_strcmp(pref, p))
   1.807 +#define MULTI_PREF_CHANGED(p) \
   1.808 +  ((pref == nullptr) || !PL_strncmp(pref, p, sizeof(p) - 1))
   1.809 +
   1.810 +    //
   1.811 +    // UA components
   1.812 +    //
   1.813 +
   1.814 +    bool cVar = false;
   1.815 +
   1.816 +    if (PREF_CHANGED(UA_PREF("compatMode.firefox"))) {
   1.817 +        rv = prefs->GetBoolPref(UA_PREF("compatMode.firefox"), &cVar);
   1.818 +        mCompatFirefoxEnabled = (NS_SUCCEEDED(rv) && cVar);
   1.819 +        mUserAgentIsDirty = true;
   1.820 +    }
   1.821 +
   1.822 +    // general.useragent.override
   1.823 +    if (PREF_CHANGED(UA_PREF("override"))) {
   1.824 +        prefs->GetCharPref(UA_PREF("override"),
   1.825 +                            getter_Copies(mUserAgentOverride));
   1.826 +        mUserAgentIsDirty = true;
   1.827 +    }
   1.828 +
   1.829 +    //
   1.830 +    // HTTP options
   1.831 +    //
   1.832 +
   1.833 +    if (PREF_CHANGED(HTTP_PREF("keep-alive.timeout"))) {
   1.834 +        rv = prefs->GetIntPref(HTTP_PREF("keep-alive.timeout"), &val);
   1.835 +        if (NS_SUCCEEDED(rv))
   1.836 +            mIdleTimeout = PR_SecondsToInterval(clamped(val, 1, 0xffff));
   1.837 +    }
   1.838 +
   1.839 +    if (PREF_CHANGED(HTTP_PREF("request.max-attempts"))) {
   1.840 +        rv = prefs->GetIntPref(HTTP_PREF("request.max-attempts"), &val);
   1.841 +        if (NS_SUCCEEDED(rv))
   1.842 +            mMaxRequestAttempts = (uint16_t) clamped(val, 1, 0xffff);
   1.843 +    }
   1.844 +
   1.845 +    if (PREF_CHANGED(HTTP_PREF("request.max-start-delay"))) {
   1.846 +        rv = prefs->GetIntPref(HTTP_PREF("request.max-start-delay"), &val);
   1.847 +        if (NS_SUCCEEDED(rv)) {
   1.848 +            mMaxRequestDelay = (uint16_t) clamped(val, 0, 0xffff);
   1.849 +            if (mConnMgr)
   1.850 +                mConnMgr->UpdateParam(nsHttpConnectionMgr::MAX_REQUEST_DELAY,
   1.851 +                                      mMaxRequestDelay);
   1.852 +        }
   1.853 +    }
   1.854 +
   1.855 +    if (PREF_CHANGED(HTTP_PREF("response.timeout"))) {
   1.856 +        rv = prefs->GetIntPref(HTTP_PREF("response.timeout"), &val);
   1.857 +        if (NS_SUCCEEDED(rv))
   1.858 +            mResponseTimeout = PR_SecondsToInterval(clamped(val, 0, 0xffff));
   1.859 +    }
   1.860 +
   1.861 +    if (PREF_CHANGED(HTTP_PREF("max-connections"))) {
   1.862 +        rv = prefs->GetIntPref(HTTP_PREF("max-connections"), &val);
   1.863 +        if (NS_SUCCEEDED(rv)) {
   1.864 +
   1.865 +            mMaxConnections = (uint16_t) clamped((uint32_t)val,
   1.866 +                                                 (uint32_t)1, MaxSocketCount());
   1.867 +
   1.868 +            if (mConnMgr)
   1.869 +                mConnMgr->UpdateParam(nsHttpConnectionMgr::MAX_CONNECTIONS,
   1.870 +                                      mMaxConnections);
   1.871 +        }
   1.872 +    }
   1.873 +
   1.874 +    if (PREF_CHANGED(HTTP_PREF("max-persistent-connections-per-server"))) {
   1.875 +        rv = prefs->GetIntPref(HTTP_PREF("max-persistent-connections-per-server"), &val);
   1.876 +        if (NS_SUCCEEDED(rv)) {
   1.877 +            mMaxPersistentConnectionsPerServer = (uint8_t) clamped(val, 1, 0xff);
   1.878 +            if (mConnMgr)
   1.879 +                mConnMgr->UpdateParam(nsHttpConnectionMgr::MAX_PERSISTENT_CONNECTIONS_PER_HOST,
   1.880 +                                      mMaxPersistentConnectionsPerServer);
   1.881 +        }
   1.882 +    }
   1.883 +
   1.884 +    if (PREF_CHANGED(HTTP_PREF("max-persistent-connections-per-proxy"))) {
   1.885 +        rv = prefs->GetIntPref(HTTP_PREF("max-persistent-connections-per-proxy"), &val);
   1.886 +        if (NS_SUCCEEDED(rv)) {
   1.887 +            mMaxPersistentConnectionsPerProxy = (uint8_t) clamped(val, 1, 0xff);
   1.888 +            if (mConnMgr)
   1.889 +                mConnMgr->UpdateParam(nsHttpConnectionMgr::MAX_PERSISTENT_CONNECTIONS_PER_PROXY,
   1.890 +                                      mMaxPersistentConnectionsPerProxy);
   1.891 +        }
   1.892 +    }
   1.893 +
   1.894 +    if (PREF_CHANGED(HTTP_PREF("sendRefererHeader"))) {
   1.895 +        rv = prefs->GetIntPref(HTTP_PREF("sendRefererHeader"), &val);
   1.896 +        if (NS_SUCCEEDED(rv))
   1.897 +            mReferrerLevel = (uint8_t) clamped(val, 0, 0xff);
   1.898 +    }
   1.899 +
   1.900 +    if (PREF_CHANGED(HTTP_PREF("referer.spoofSource"))) {
   1.901 +        rv = prefs->GetBoolPref(HTTP_PREF("referer.spoofSource"), &cVar);
   1.902 +        if (NS_SUCCEEDED(rv))
   1.903 +            mSpoofReferrerSource = cVar;
   1.904 +    }
   1.905 +
   1.906 +    if (PREF_CHANGED(HTTP_PREF("referer.trimmingPolicy"))) {
   1.907 +        rv = prefs->GetIntPref(HTTP_PREF("referer.trimmingPolicy"), &val);
   1.908 +        if (NS_SUCCEEDED(rv))
   1.909 +            mReferrerTrimmingPolicy = (uint8_t) clamped(val, 0, 0xff);
   1.910 +    }
   1.911 +
   1.912 +    if (PREF_CHANGED(HTTP_PREF("referer.XOriginPolicy"))) {
   1.913 +        rv = prefs->GetIntPref(HTTP_PREF("referer.XOriginPolicy"), &val);
   1.914 +        if (NS_SUCCEEDED(rv))
   1.915 +            mReferrerXOriginPolicy = (uint8_t) clamped(val, 0, 0xff);
   1.916 +    }
   1.917 +
   1.918 +    if (PREF_CHANGED(HTTP_PREF("redirection-limit"))) {
   1.919 +        rv = prefs->GetIntPref(HTTP_PREF("redirection-limit"), &val);
   1.920 +        if (NS_SUCCEEDED(rv))
   1.921 +            mRedirectionLimit = (uint8_t) clamped(val, 0, 0xff);
   1.922 +    }
   1.923 +
   1.924 +    if (PREF_CHANGED(HTTP_PREF("connection-retry-timeout"))) {
   1.925 +        rv = prefs->GetIntPref(HTTP_PREF("connection-retry-timeout"), &val);
   1.926 +        if (NS_SUCCEEDED(rv))
   1.927 +            mIdleSynTimeout = (uint16_t) clamped(val, 0, 3000);
   1.928 +    }
   1.929 +
   1.930 +    if (PREF_CHANGED(HTTP_PREF("fast-fallback-to-IPv4"))) {
   1.931 +        rv = prefs->GetBoolPref(HTTP_PREF("fast-fallback-to-IPv4"), &cVar);
   1.932 +        if (NS_SUCCEEDED(rv))
   1.933 +            mFastFallbackToIPv4 = cVar;
   1.934 +    }
   1.935 +
   1.936 +    if (PREF_CHANGED(HTTP_PREF("version"))) {
   1.937 +        nsXPIDLCString httpVersion;
   1.938 +        prefs->GetCharPref(HTTP_PREF("version"), getter_Copies(httpVersion));
   1.939 +        if (httpVersion) {
   1.940 +            if (!PL_strcmp(httpVersion, "1.1"))
   1.941 +                mHttpVersion = NS_HTTP_VERSION_1_1;
   1.942 +            else if (!PL_strcmp(httpVersion, "0.9"))
   1.943 +                mHttpVersion = NS_HTTP_VERSION_0_9;
   1.944 +            else
   1.945 +                mHttpVersion = NS_HTTP_VERSION_1_0;
   1.946 +        }
   1.947 +    }
   1.948 +
   1.949 +    if (PREF_CHANGED(HTTP_PREF("proxy.version"))) {
   1.950 +        nsXPIDLCString httpVersion;
   1.951 +        prefs->GetCharPref(HTTP_PREF("proxy.version"), getter_Copies(httpVersion));
   1.952 +        if (httpVersion) {
   1.953 +            if (!PL_strcmp(httpVersion, "1.1"))
   1.954 +                mProxyHttpVersion = NS_HTTP_VERSION_1_1;
   1.955 +            else
   1.956 +                mProxyHttpVersion = NS_HTTP_VERSION_1_0;
   1.957 +            // it does not make sense to issue a HTTP/0.9 request to a proxy server
   1.958 +        }
   1.959 +    }
   1.960 +
   1.961 +    if (PREF_CHANGED(HTTP_PREF("pipelining"))) {
   1.962 +        rv = prefs->GetBoolPref(HTTP_PREF("pipelining"), &cVar);
   1.963 +        if (NS_SUCCEEDED(rv)) {
   1.964 +            if (cVar)
   1.965 +                mCapabilities |=  NS_HTTP_ALLOW_PIPELINING;
   1.966 +            else
   1.967 +                mCapabilities &= ~NS_HTTP_ALLOW_PIPELINING;
   1.968 +            mPipeliningEnabled = cVar;
   1.969 +        }
   1.970 +    }
   1.971 +
   1.972 +    if (PREF_CHANGED(HTTP_PREF("pipelining.maxrequests"))) {
   1.973 +        rv = prefs->GetIntPref(HTTP_PREF("pipelining.maxrequests"), &val);
   1.974 +        if (NS_SUCCEEDED(rv)) {
   1.975 +            mMaxPipelinedRequests = clamped(val, 1, 0xffff);
   1.976 +            if (mConnMgr)
   1.977 +                mConnMgr->UpdateParam(nsHttpConnectionMgr::MAX_PIPELINED_REQUESTS,
   1.978 +                                      mMaxPipelinedRequests);
   1.979 +        }
   1.980 +    }
   1.981 +
   1.982 +    if (PREF_CHANGED(HTTP_PREF("pipelining.max-optimistic-requests"))) {
   1.983 +        rv = prefs->
   1.984 +            GetIntPref(HTTP_PREF("pipelining.max-optimistic-requests"), &val);
   1.985 +        if (NS_SUCCEEDED(rv)) {
   1.986 +            mMaxOptimisticPipelinedRequests = clamped(val, 1, 0xffff);
   1.987 +            if (mConnMgr)
   1.988 +                mConnMgr->UpdateParam
   1.989 +                    (nsHttpConnectionMgr::MAX_OPTIMISTIC_PIPELINED_REQUESTS,
   1.990 +                     mMaxOptimisticPipelinedRequests);
   1.991 +        }
   1.992 +    }
   1.993 +
   1.994 +    if (PREF_CHANGED(HTTP_PREF("pipelining.aggressive"))) {
   1.995 +        rv = prefs->GetBoolPref(HTTP_PREF("pipelining.aggressive"), &cVar);
   1.996 +        if (NS_SUCCEEDED(rv))
   1.997 +            mPipelineAggressive = cVar;
   1.998 +    }
   1.999 +
  1.1000 +    if (PREF_CHANGED(HTTP_PREF("pipelining.maxsize"))) {
  1.1001 +        rv = prefs->GetIntPref(HTTP_PREF("pipelining.maxsize"), &val);
  1.1002 +        if (NS_SUCCEEDED(rv)) {
  1.1003 +            mMaxPipelineObjectSize =
  1.1004 +                static_cast<int64_t>(clamped(val, 1000, 100000000));
  1.1005 +        }
  1.1006 +    }
  1.1007 +
  1.1008 +    // Determines whether or not to actually reschedule after the
  1.1009 +    // reschedule-timeout has expired
  1.1010 +    if (PREF_CHANGED(HTTP_PREF("pipelining.reschedule-on-timeout"))) {
  1.1011 +        rv = prefs->GetBoolPref(HTTP_PREF("pipelining.reschedule-on-timeout"),
  1.1012 +                                &cVar);
  1.1013 +        if (NS_SUCCEEDED(rv))
  1.1014 +            mPipelineRescheduleOnTimeout = cVar;
  1.1015 +    }
  1.1016 +
  1.1017 +    // The amount of time head of line blocking is allowed (in ms)
  1.1018 +    // before the blocked transactions are moved to another pipeline
  1.1019 +    if (PREF_CHANGED(HTTP_PREF("pipelining.reschedule-timeout"))) {
  1.1020 +        rv = prefs->GetIntPref(HTTP_PREF("pipelining.reschedule-timeout"),
  1.1021 +                               &val);
  1.1022 +        if (NS_SUCCEEDED(rv)) {
  1.1023 +            mPipelineRescheduleTimeout =
  1.1024 +                PR_MillisecondsToInterval((uint16_t) clamped(val, 500, 0xffff));
  1.1025 +        }
  1.1026 +    }
  1.1027 +
  1.1028 +    // The amount of time a pipelined transaction is allowed to wait before
  1.1029 +    // being canceled and retried in a non-pipeline connection
  1.1030 +    if (PREF_CHANGED(HTTP_PREF("pipelining.read-timeout"))) {
  1.1031 +        rv = prefs->GetIntPref(HTTP_PREF("pipelining.read-timeout"), &val);
  1.1032 +        if (NS_SUCCEEDED(rv)) {
  1.1033 +            mPipelineReadTimeout =
  1.1034 +                PR_MillisecondsToInterval((uint16_t) clamped(val, 5000,
  1.1035 +                                                             0xffff));
  1.1036 +        }
  1.1037 +    }
  1.1038 +
  1.1039 +    if (PREF_CHANGED(HTTP_PREF("pipelining.ssl"))) {
  1.1040 +        rv = prefs->GetBoolPref(HTTP_PREF("pipelining.ssl"), &cVar);
  1.1041 +        if (NS_SUCCEEDED(rv))
  1.1042 +            mPipeliningOverSSL = cVar;
  1.1043 +    }
  1.1044 +
  1.1045 +    if (PREF_CHANGED(HTTP_PREF("proxy.pipelining"))) {
  1.1046 +        rv = prefs->GetBoolPref(HTTP_PREF("proxy.pipelining"), &cVar);
  1.1047 +        if (NS_SUCCEEDED(rv))
  1.1048 +            mProxyPipelining = cVar;
  1.1049 +    }
  1.1050 +
  1.1051 +    if (PREF_CHANGED(HTTP_PREF("qos"))) {
  1.1052 +        rv = prefs->GetIntPref(HTTP_PREF("qos"), &val);
  1.1053 +        if (NS_SUCCEEDED(rv))
  1.1054 +            mQoSBits = (uint8_t) clamped(val, 0, 0xff);
  1.1055 +    }
  1.1056 +
  1.1057 +    if (PREF_CHANGED(HTTP_PREF("sendSecureXSiteReferrer"))) {
  1.1058 +        rv = prefs->GetBoolPref(HTTP_PREF("sendSecureXSiteReferrer"), &cVar);
  1.1059 +        if (NS_SUCCEEDED(rv))
  1.1060 +            mSendSecureXSiteReferrer = cVar;
  1.1061 +    }
  1.1062 +
  1.1063 +    if (PREF_CHANGED(HTTP_PREF("accept.default"))) {
  1.1064 +        nsXPIDLCString accept;
  1.1065 +        rv = prefs->GetCharPref(HTTP_PREF("accept.default"),
  1.1066 +                                  getter_Copies(accept));
  1.1067 +        if (NS_SUCCEEDED(rv))
  1.1068 +            SetAccept(accept);
  1.1069 +    }
  1.1070 +
  1.1071 +    if (PREF_CHANGED(HTTP_PREF("accept-encoding"))) {
  1.1072 +        nsXPIDLCString acceptEncodings;
  1.1073 +        rv = prefs->GetCharPref(HTTP_PREF("accept-encoding"),
  1.1074 +                                  getter_Copies(acceptEncodings));
  1.1075 +        if (NS_SUCCEEDED(rv))
  1.1076 +            SetAcceptEncodings(acceptEncodings);
  1.1077 +    }
  1.1078 +
  1.1079 +    if (PREF_CHANGED(HTTP_PREF("use-cache"))) {
  1.1080 +        rv = prefs->GetBoolPref(HTTP_PREF("use-cache"), &cVar);
  1.1081 +        if (NS_SUCCEEDED(rv)) {
  1.1082 +            mUseCache = cVar;
  1.1083 +        }
  1.1084 +    }
  1.1085 +
  1.1086 +    if (PREF_CHANGED(HTTP_PREF("default-socket-type"))) {
  1.1087 +        nsXPIDLCString sval;
  1.1088 +        rv = prefs->GetCharPref(HTTP_PREF("default-socket-type"),
  1.1089 +                                getter_Copies(sval));
  1.1090 +        if (NS_SUCCEEDED(rv)) {
  1.1091 +            if (sval.IsEmpty())
  1.1092 +                mDefaultSocketType.Adopt(0);
  1.1093 +            else {
  1.1094 +                // verify that this socket type is actually valid
  1.1095 +                nsCOMPtr<nsISocketProviderService> sps(
  1.1096 +                        do_GetService(NS_SOCKETPROVIDERSERVICE_CONTRACTID));
  1.1097 +                if (sps) {
  1.1098 +                    nsCOMPtr<nsISocketProvider> sp;
  1.1099 +                    rv = sps->GetSocketProvider(sval, getter_AddRefs(sp));
  1.1100 +                    if (NS_SUCCEEDED(rv)) {
  1.1101 +                        // OK, this looks like a valid socket provider.
  1.1102 +                        mDefaultSocketType.Assign(sval);
  1.1103 +                    }
  1.1104 +                }
  1.1105 +            }
  1.1106 +        }
  1.1107 +    }
  1.1108 +
  1.1109 +    if (PREF_CHANGED(HTTP_PREF("prompt-temp-redirect"))) {
  1.1110 +        rv = prefs->GetBoolPref(HTTP_PREF("prompt-temp-redirect"), &cVar);
  1.1111 +        if (NS_SUCCEEDED(rv)) {
  1.1112 +            mPromptTempRedirect = cVar;
  1.1113 +        }
  1.1114 +    }
  1.1115 +
  1.1116 +    if (PREF_CHANGED(HTTP_PREF("assoc-req.enforce"))) {
  1.1117 +        cVar = false;
  1.1118 +        rv = prefs->GetBoolPref(HTTP_PREF("assoc-req.enforce"), &cVar);
  1.1119 +        if (NS_SUCCEEDED(rv))
  1.1120 +            mEnforceAssocReq = cVar;
  1.1121 +    }
  1.1122 +
  1.1123 +    // enable Persistent caching for HTTPS - bug#205921
  1.1124 +    if (PREF_CHANGED(BROWSER_PREF("disk_cache_ssl"))) {
  1.1125 +        cVar = false;
  1.1126 +        rv = prefs->GetBoolPref(BROWSER_PREF("disk_cache_ssl"), &cVar);
  1.1127 +        if (NS_SUCCEEDED(rv))
  1.1128 +            mEnablePersistentHttpsCaching = cVar;
  1.1129 +    }
  1.1130 +
  1.1131 +    if (PREF_CHANGED(HTTP_PREF("phishy-userpass-length"))) {
  1.1132 +        rv = prefs->GetIntPref(HTTP_PREF("phishy-userpass-length"), &val);
  1.1133 +        if (NS_SUCCEEDED(rv))
  1.1134 +            mPhishyUserPassLength = (uint8_t) clamped(val, 0, 0xff);
  1.1135 +    }
  1.1136 +
  1.1137 +    if (PREF_CHANGED(HTTP_PREF("spdy.enabled"))) {
  1.1138 +        rv = prefs->GetBoolPref(HTTP_PREF("spdy.enabled"), &cVar);
  1.1139 +        if (NS_SUCCEEDED(rv))
  1.1140 +            mEnableSpdy = cVar;
  1.1141 +    }
  1.1142 +
  1.1143 +    if (PREF_CHANGED(HTTP_PREF("spdy.enabled.v3"))) {
  1.1144 +        rv = prefs->GetBoolPref(HTTP_PREF("spdy.enabled.v3"), &cVar);
  1.1145 +        if (NS_SUCCEEDED(rv))
  1.1146 +            mSpdyV3 = cVar;
  1.1147 +    }
  1.1148 +
  1.1149 +    if (PREF_CHANGED(HTTP_PREF("spdy.enabled.v3-1"))) {
  1.1150 +        rv = prefs->GetBoolPref(HTTP_PREF("spdy.enabled.v3-1"), &cVar);
  1.1151 +        if (NS_SUCCEEDED(rv))
  1.1152 +            mSpdyV31 = cVar;
  1.1153 +    }
  1.1154 +
  1.1155 +    if (PREF_CHANGED(HTTP_PREF("spdy.enabled.http2draft"))) {
  1.1156 +        rv = prefs->GetBoolPref(HTTP_PREF("spdy.enabled.http2draft"), &cVar);
  1.1157 +        if (NS_SUCCEEDED(rv))
  1.1158 +            mHttp2DraftEnabled = cVar;
  1.1159 +    }
  1.1160 +
  1.1161 +    if (PREF_CHANGED(HTTP_PREF("spdy.enforce-tls-profile"))) {
  1.1162 +        rv = prefs->GetBoolPref(HTTP_PREF("spdy.enforce-tls-profile"), &cVar);
  1.1163 +        if (NS_SUCCEEDED(rv))
  1.1164 +            mEnforceHttp2TlsProfile = cVar;
  1.1165 +    }
  1.1166 +
  1.1167 +    if (PREF_CHANGED(HTTP_PREF("spdy.coalesce-hostnames"))) {
  1.1168 +        rv = prefs->GetBoolPref(HTTP_PREF("spdy.coalesce-hostnames"), &cVar);
  1.1169 +        if (NS_SUCCEEDED(rv))
  1.1170 +            mCoalesceSpdy = cVar;
  1.1171 +    }
  1.1172 +
  1.1173 +    if (PREF_CHANGED(HTTP_PREF("spdy.persistent-settings"))) {
  1.1174 +        rv = prefs->GetBoolPref(HTTP_PREF("spdy.persistent-settings"),
  1.1175 +                                &cVar);
  1.1176 +        if (NS_SUCCEEDED(rv))
  1.1177 +            mSpdyPersistentSettings = cVar;
  1.1178 +    }
  1.1179 +
  1.1180 +    if (PREF_CHANGED(HTTP_PREF("spdy.timeout"))) {
  1.1181 +        rv = prefs->GetIntPref(HTTP_PREF("spdy.timeout"), &val);
  1.1182 +        if (NS_SUCCEEDED(rv))
  1.1183 +            mSpdyTimeout = PR_SecondsToInterval(clamped(val, 1, 0xffff));
  1.1184 +    }
  1.1185 +
  1.1186 +    if (PREF_CHANGED(HTTP_PREF("spdy.chunk-size"))) {
  1.1187 +        // keep this within http/2 ranges of 1 to 2^14-1
  1.1188 +        rv = prefs->GetIntPref(HTTP_PREF("spdy.chunk-size"), &val);
  1.1189 +        if (NS_SUCCEEDED(rv))
  1.1190 +            mSpdySendingChunkSize = (uint32_t) clamped(val, 1, 0x3fff);
  1.1191 +    }
  1.1192 +
  1.1193 +    // The amount of idle seconds on a spdy connection before initiating a
  1.1194 +    // server ping. 0 will disable.
  1.1195 +    if (PREF_CHANGED(HTTP_PREF("spdy.ping-threshold"))) {
  1.1196 +        rv = prefs->GetIntPref(HTTP_PREF("spdy.ping-threshold"), &val);
  1.1197 +        if (NS_SUCCEEDED(rv))
  1.1198 +            mSpdyPingThreshold =
  1.1199 +                PR_SecondsToInterval((uint16_t) clamped(val, 0, 0x7fffffff));
  1.1200 +    }
  1.1201 +
  1.1202 +    // The amount of seconds to wait for a spdy ping response before
  1.1203 +    // closing the session.
  1.1204 +    if (PREF_CHANGED(HTTP_PREF("spdy.ping-timeout"))) {
  1.1205 +        rv = prefs->GetIntPref(HTTP_PREF("spdy.ping-timeout"), &val);
  1.1206 +        if (NS_SUCCEEDED(rv))
  1.1207 +            mSpdyPingTimeout =
  1.1208 +                PR_SecondsToInterval((uint16_t) clamped(val, 0, 0x7fffffff));
  1.1209 +    }
  1.1210 +
  1.1211 +    if (PREF_CHANGED(HTTP_PREF("spdy.allow-push"))) {
  1.1212 +        rv = prefs->GetBoolPref(HTTP_PREF("spdy.allow-push"),
  1.1213 +                                &cVar);
  1.1214 +        if (NS_SUCCEEDED(rv))
  1.1215 +            mAllowPush = cVar;
  1.1216 +    }
  1.1217 +
  1.1218 +    if (PREF_CHANGED(HTTP_PREF("spdy.push-allowance"))) {
  1.1219 +        rv = prefs->GetIntPref(HTTP_PREF("spdy.push-allowance"), &val);
  1.1220 +        if (NS_SUCCEEDED(rv)) {
  1.1221 +            mSpdyPushAllowance =
  1.1222 +                static_cast<uint32_t>
  1.1223 +                (clamped(val, 1024, static_cast<int32_t>(ASpdySession::kInitialRwin)));
  1.1224 +        }
  1.1225 +    }
  1.1226 +
  1.1227 +    // The amount of seconds to wait for a spdy ping response before
  1.1228 +    // closing the session.
  1.1229 +    if (PREF_CHANGED(HTTP_PREF("spdy.send-buffer-size"))) {
  1.1230 +        rv = prefs->GetIntPref(HTTP_PREF("spdy.send-buffer-size"), &val);
  1.1231 +        if (NS_SUCCEEDED(rv))
  1.1232 +            mSpdySendBufferSize = (uint32_t) clamped(val, 1500, 0x7fffffff);
  1.1233 +    }
  1.1234 +
  1.1235 +    // The maximum amount of time to wait for socket transport to be
  1.1236 +    // established
  1.1237 +    if (PREF_CHANGED(HTTP_PREF("connection-timeout"))) {
  1.1238 +        rv = prefs->GetIntPref(HTTP_PREF("connection-timeout"), &val);
  1.1239 +        if (NS_SUCCEEDED(rv))
  1.1240 +            // the pref is in seconds, but the variable is in milliseconds
  1.1241 +            mConnectTimeout = clamped(val, 1, 0xffff) * PR_MSEC_PER_SEC;
  1.1242 +    }
  1.1243 +
  1.1244 +    // The maximum amount of time the cache session lock can be held
  1.1245 +    // before a new transaction bypasses the cache. In milliseconds.
  1.1246 +    if (PREF_CHANGED(HTTP_PREF("bypass-cachelock-threshold"))) {
  1.1247 +        rv = prefs->GetIntPref(HTTP_PREF("bypass-cachelock-threshold"), &val);
  1.1248 +        if (NS_SUCCEEDED(rv))
  1.1249 +            // the pref and variable are both in milliseconds
  1.1250 +            mBypassCacheLockThreshold =
  1.1251 +                static_cast<double>(clamped(val, 0, 0x7ffffff));
  1.1252 +    }
  1.1253 +
  1.1254 +    // The maximum number of current global half open sockets allowable
  1.1255 +    // for starting a new speculative connection.
  1.1256 +    if (PREF_CHANGED(HTTP_PREF("speculative-parallel-limit"))) {
  1.1257 +        rv = prefs->GetIntPref(HTTP_PREF("speculative-parallel-limit"), &val);
  1.1258 +        if (NS_SUCCEEDED(rv))
  1.1259 +            mParallelSpeculativeConnectLimit = (uint32_t) clamped(val, 0, 1024);
  1.1260 +    }
  1.1261 +
  1.1262 +    // Whether or not to block requests for non head js/css items (e.g. media)
  1.1263 +    // while those elements load.
  1.1264 +    if (PREF_CHANGED(HTTP_PREF("rendering-critical-requests-prioritization"))) {
  1.1265 +        rv = prefs->GetBoolPref(HTTP_PREF("rendering-critical-requests-prioritization"), &cVar);
  1.1266 +        if (NS_SUCCEEDED(rv))
  1.1267 +            mCriticalRequestPrioritization = cVar;
  1.1268 +    }
  1.1269 +
  1.1270 +    // on transition of network.http.diagnostics to true print
  1.1271 +    // a bunch of information to the console
  1.1272 +    if (pref && PREF_CHANGED(HTTP_PREF("diagnostics"))) {
  1.1273 +        rv = prefs->GetBoolPref(HTTP_PREF("diagnostics"), &cVar);
  1.1274 +        if (NS_SUCCEEDED(rv) && cVar) {
  1.1275 +            if (mConnMgr)
  1.1276 +                mConnMgr->PrintDiagnostics();
  1.1277 +        }
  1.1278 +    }
  1.1279 +    //
  1.1280 +    // INTL options
  1.1281 +    //
  1.1282 +
  1.1283 +    if (PREF_CHANGED(INTL_ACCEPT_LANGUAGES)) {
  1.1284 +        nsCOMPtr<nsIPrefLocalizedString> pls;
  1.1285 +        prefs->GetComplexValue(INTL_ACCEPT_LANGUAGES,
  1.1286 +                                NS_GET_IID(nsIPrefLocalizedString),
  1.1287 +                                getter_AddRefs(pls));
  1.1288 +        if (pls) {
  1.1289 +            nsXPIDLString uval;
  1.1290 +            pls->ToString(getter_Copies(uval));
  1.1291 +            if (uval)
  1.1292 +                SetAcceptLanguages(NS_ConvertUTF16toUTF8(uval).get());
  1.1293 +        }
  1.1294 +    }
  1.1295 +
  1.1296 +    //
  1.1297 +    // Tracking options
  1.1298 +    //
  1.1299 +
  1.1300 +    if (PREF_CHANGED(DONOTTRACK_HEADER_ENABLED)) {
  1.1301 +        cVar = false;
  1.1302 +        rv = prefs->GetBoolPref(DONOTTRACK_HEADER_ENABLED, &cVar);
  1.1303 +        if (NS_SUCCEEDED(rv)) {
  1.1304 +            mDoNotTrackEnabled = cVar;
  1.1305 +        }
  1.1306 +    }
  1.1307 +    if (PREF_CHANGED(DONOTTRACK_HEADER_VALUE)) {
  1.1308 +        val = 1;
  1.1309 +        rv = prefs->GetIntPref(DONOTTRACK_HEADER_VALUE, &val);
  1.1310 +        if (NS_SUCCEEDED(rv)) {
  1.1311 +            mDoNotTrackValue = val;
  1.1312 +        }
  1.1313 +    }
  1.1314 +
  1.1315 +    // Hint option
  1.1316 +    if (PREF_CHANGED(SAFE_HINT_HEADER_VALUE)) {
  1.1317 +        cVar = false;
  1.1318 +        rv = prefs->GetBoolPref(SAFE_HINT_HEADER_VALUE, &cVar);
  1.1319 +        if (NS_SUCCEEDED(rv)) {
  1.1320 +            mSafeHintEnabled = cVar;
  1.1321 +        }
  1.1322 +    }
  1.1323 +
  1.1324 +    // toggle to true anytime a token bucket related pref is changed.. that
  1.1325 +    // includes telemetry and allow-experiments because of the abtest profile
  1.1326 +    bool requestTokenBucketUpdated = false;
  1.1327 +
  1.1328 +    //
  1.1329 +    // Telemetry
  1.1330 +    //
  1.1331 +
  1.1332 +    if (PREF_CHANGED(TELEMETRY_ENABLED)) {
  1.1333 +        cVar = false;
  1.1334 +        requestTokenBucketUpdated = true;
  1.1335 +        rv = prefs->GetBoolPref(TELEMETRY_ENABLED, &cVar);
  1.1336 +        if (NS_SUCCEEDED(rv)) {
  1.1337 +            mTelemetryEnabled = cVar;
  1.1338 +        }
  1.1339 +    }
  1.1340 +
  1.1341 +    //
  1.1342 +    // network.allow-experiments
  1.1343 +    //
  1.1344 +    if (PREF_CHANGED(ALLOW_EXPERIMENTS)) {
  1.1345 +        cVar = true;
  1.1346 +        requestTokenBucketUpdated = true;
  1.1347 +        rv = prefs->GetBoolPref(ALLOW_EXPERIMENTS, &cVar);
  1.1348 +        if (NS_SUCCEEDED(rv)) {
  1.1349 +            mAllowExperiments = cVar;
  1.1350 +        }
  1.1351 +    }
  1.1352 +
  1.1353 +    //
  1.1354 +    // Test HTTP Pipelining (bug796192)
  1.1355 +    // If experiments are allowed and pipelining is Off,
  1.1356 +    // turn it On for just 10 minutes
  1.1357 +    //
  1.1358 +    if (mAllowExperiments && !mPipeliningEnabled &&
  1.1359 +        PREF_CHANGED(HTTP_PREF("pipelining.abtest"))) {
  1.1360 +        rv = prefs->GetBoolPref(HTTP_PREF("pipelining.abtest"), &cVar);
  1.1361 +        if (NS_SUCCEEDED(rv)) {
  1.1362 +            // If option is enabled, only test for ~1% of sessions
  1.1363 +            if (cVar && !(rand() % 128)) {
  1.1364 +                mCapabilities |=  NS_HTTP_ALLOW_PIPELINING;
  1.1365 +                if (mPipelineTestTimer)
  1.1366 +                    mPipelineTestTimer->Cancel();
  1.1367 +                mPipelineTestTimer =
  1.1368 +                    do_CreateInstance("@mozilla.org/timer;1", &rv);
  1.1369 +                if (NS_SUCCEEDED(rv)) {
  1.1370 +                    rv = mPipelineTestTimer->InitWithFuncCallback(
  1.1371 +                        TimerCallback, this, 10*60*1000, // 10 minutes
  1.1372 +                        nsITimer::TYPE_ONE_SHOT);
  1.1373 +                }
  1.1374 +            } else {
  1.1375 +                mCapabilities &= ~NS_HTTP_ALLOW_PIPELINING;
  1.1376 +                if (mPipelineTestTimer) {
  1.1377 +                    mPipelineTestTimer->Cancel();
  1.1378 +                    mPipelineTestTimer = nullptr;
  1.1379 +                }
  1.1380 +            }
  1.1381 +        }
  1.1382 +    }
  1.1383 +    if (requestTokenBucketUpdated) {
  1.1384 +        MakeNewRequestTokenBucket();
  1.1385 +    }
  1.1386 +
  1.1387 +    if (PREF_CHANGED(HTTP_PREF("pacing.requests.enabled"))) {
  1.1388 +        rv = prefs->GetBoolPref(HTTP_PREF("pacing.requests.enabled"),
  1.1389 +                                &cVar);
  1.1390 +        if (NS_SUCCEEDED(rv)){
  1.1391 +            requestTokenBucketUpdated = true;
  1.1392 +            mRequestTokenBucketEnabled = cVar;
  1.1393 +        }
  1.1394 +    }
  1.1395 +
  1.1396 +    if (PREF_CHANGED(HTTP_PREF("pacing.requests.min-parallelism"))) {
  1.1397 +        rv = prefs->GetIntPref(HTTP_PREF("pacing.requests.min-parallelism"), &val);
  1.1398 +        if (NS_SUCCEEDED(rv))
  1.1399 +            mRequestTokenBucketMinParallelism = static_cast<uint16_t>(clamped(val, 1, 1024));
  1.1400 +    }
  1.1401 +    if (PREF_CHANGED(HTTP_PREF("pacing.requests.hz"))) {
  1.1402 +        rv = prefs->GetIntPref(HTTP_PREF("pacing.requests.hz"), &val);
  1.1403 +        if (NS_SUCCEEDED(rv)) {
  1.1404 +            mRequestTokenBucketHz = static_cast<uint32_t>(clamped(val, 1, 10000));
  1.1405 +            requestTokenBucketUpdated = true;
  1.1406 +        }
  1.1407 +    }
  1.1408 +    if (PREF_CHANGED(HTTP_PREF("pacing.requests.burst"))) {
  1.1409 +        rv = prefs->GetIntPref(HTTP_PREF("pacing.requests.burst"), &val);
  1.1410 +        if (NS_SUCCEEDED(rv)) {
  1.1411 +            mRequestTokenBucketBurst = val ? val : 1;
  1.1412 +            requestTokenBucketUpdated = true;
  1.1413 +        }
  1.1414 +    }
  1.1415 +    if (requestTokenBucketUpdated) {
  1.1416 +        mRequestTokenBucket =
  1.1417 +            new EventTokenBucket(RequestTokenBucketHz(),
  1.1418 +                                 RequestTokenBucketBurst());
  1.1419 +    }
  1.1420 +
  1.1421 +    // Keepalive values for initial and idle connections.
  1.1422 +    if (PREF_CHANGED(HTTP_PREF("tcp_keepalive.short_lived_connections"))) {
  1.1423 +        rv = prefs->GetBoolPref(
  1.1424 +            HTTP_PREF("tcp_keepalive.short_lived_connections"), &cVar);
  1.1425 +        if (NS_SUCCEEDED(rv) && cVar != mTCPKeepaliveShortLivedEnabled) {
  1.1426 +            mTCPKeepaliveShortLivedEnabled = cVar;
  1.1427 +        }
  1.1428 +    }
  1.1429 +
  1.1430 +    if (PREF_CHANGED(HTTP_PREF("tcp_keepalive.short_lived_time"))) {
  1.1431 +        rv = prefs->GetIntPref(
  1.1432 +            HTTP_PREF("tcp_keepalive.short_lived_time"), &val);
  1.1433 +        if (NS_SUCCEEDED(rv) && val > 0)
  1.1434 +            mTCPKeepaliveShortLivedTimeS = clamped(val, 1, 300); // Max 5 mins.
  1.1435 +    }
  1.1436 +
  1.1437 +    if (PREF_CHANGED(HTTP_PREF("tcp_keepalive.short_lived_idle_time"))) {
  1.1438 +        rv = prefs->GetIntPref(
  1.1439 +            HTTP_PREF("tcp_keepalive.short_lived_idle_time"), &val);
  1.1440 +        if (NS_SUCCEEDED(rv) && val > 0)
  1.1441 +            mTCPKeepaliveShortLivedIdleTimeS = clamped(val,
  1.1442 +                                                       1, kMaxTCPKeepIdle);
  1.1443 +    }
  1.1444 +
  1.1445 +    // Keepalive values for Long-lived Connections.
  1.1446 +    if (PREF_CHANGED(HTTP_PREF("tcp_keepalive.long_lived_connections"))) {
  1.1447 +        rv = prefs->GetBoolPref(
  1.1448 +            HTTP_PREF("tcp_keepalive.long_lived_connections"), &cVar);
  1.1449 +        if (NS_SUCCEEDED(rv) && cVar != mTCPKeepaliveLongLivedEnabled) {
  1.1450 +            mTCPKeepaliveLongLivedEnabled = cVar;
  1.1451 +        }
  1.1452 +    }
  1.1453 +
  1.1454 +    if (PREF_CHANGED(HTTP_PREF("tcp_keepalive.long_lived_idle_time"))) {
  1.1455 +        rv = prefs->GetIntPref(
  1.1456 +            HTTP_PREF("tcp_keepalive.long_lived_idle_time"), &val);
  1.1457 +        if (NS_SUCCEEDED(rv) && val > 0)
  1.1458 +            mTCPKeepaliveLongLivedIdleTimeS = clamped(val,
  1.1459 +                                                      1, kMaxTCPKeepIdle);
  1.1460 +    }
  1.1461 +
  1.1462 +    // Enable HTTP response timeout if TCP Keepalives are disabled.
  1.1463 +    mResponseTimeoutEnabled = !mTCPKeepaliveShortLivedEnabled &&
  1.1464 +                              !mTCPKeepaliveLongLivedEnabled;
  1.1465 +
  1.1466 +#undef PREF_CHANGED
  1.1467 +#undef MULTI_PREF_CHANGED
  1.1468 +}
  1.1469 +
  1.1470 +
  1.1471 +/**
  1.1472 + * Static method called by mPipelineTestTimer when it expires.
  1.1473 + */
  1.1474 +void
  1.1475 +nsHttpHandler::TimerCallback(nsITimer * aTimer, void * aClosure)
  1.1476 +{
  1.1477 +    nsRefPtr<nsHttpHandler> thisObject = static_cast<nsHttpHandler*>(aClosure);
  1.1478 +    if (!thisObject->mPipeliningEnabled)
  1.1479 +        thisObject->mCapabilities &= ~NS_HTTP_ALLOW_PIPELINING;
  1.1480 +}
  1.1481 +
  1.1482 +/**
  1.1483 + *  Allocates a C string into that contains a ISO 639 language list
  1.1484 + *  notated with HTTP "q" values for output with a HTTP Accept-Language
  1.1485 + *  header. Previous q values will be stripped because the order of
  1.1486 + *  the langs imply the q value. The q values are calculated by dividing
  1.1487 + *  1.0 amongst the number of languages present.
  1.1488 + *
  1.1489 + *  Ex: passing: "en, ja"
  1.1490 + *      returns: "en,ja;q=0.5"
  1.1491 + *
  1.1492 + *      passing: "en, ja, fr_CA"
  1.1493 + *      returns: "en,ja;q=0.7,fr_CA;q=0.3"
  1.1494 + */
  1.1495 +static nsresult
  1.1496 +PrepareAcceptLanguages(const char *i_AcceptLanguages, nsACString &o_AcceptLanguages)
  1.1497 +{
  1.1498 +    if (!i_AcceptLanguages)
  1.1499 +        return NS_OK;
  1.1500 +
  1.1501 +    uint32_t n, count_n, size, wrote;
  1.1502 +    double q, dec;
  1.1503 +    char *p, *p2, *token, *q_Accept, *o_Accept;
  1.1504 +    const char *comma;
  1.1505 +    int32_t available;
  1.1506 +
  1.1507 +    o_Accept = strdup(i_AcceptLanguages);
  1.1508 +    if (!o_Accept)
  1.1509 +        return NS_ERROR_OUT_OF_MEMORY;
  1.1510 +    for (p = o_Accept, n = size = 0; '\0' != *p; p++) {
  1.1511 +        if (*p == ',') n++;
  1.1512 +            size++;
  1.1513 +    }
  1.1514 +
  1.1515 +    available = size + ++n * 11 + 1;
  1.1516 +    q_Accept = new char[available];
  1.1517 +    if (!q_Accept) {
  1.1518 +        free(o_Accept);
  1.1519 +        return NS_ERROR_OUT_OF_MEMORY;
  1.1520 +    }
  1.1521 +    *q_Accept = '\0';
  1.1522 +    q = 1.0;
  1.1523 +    dec = q / (double) n;
  1.1524 +    count_n = 0;
  1.1525 +    p2 = q_Accept;
  1.1526 +    for (token = nsCRT::strtok(o_Accept, ",", &p);
  1.1527 +         token != (char *) 0;
  1.1528 +         token = nsCRT::strtok(p, ",", &p))
  1.1529 +    {
  1.1530 +        token = net_FindCharNotInSet(token, HTTP_LWS);
  1.1531 +        char* trim;
  1.1532 +        trim = net_FindCharInSet(token, ";" HTTP_LWS);
  1.1533 +        if (trim != (char*)0)  // remove "; q=..." if present
  1.1534 +            *trim = '\0';
  1.1535 +
  1.1536 +        if (*token != '\0') {
  1.1537 +            comma = count_n++ != 0 ? "," : ""; // delimiter if not first item
  1.1538 +            uint32_t u = QVAL_TO_UINT(q);
  1.1539 +
  1.1540 +            // Only display q-value if less than 1.00.
  1.1541 +            if (u < 100) {
  1.1542 +                const char *qval_str;
  1.1543 +
  1.1544 +                // With a small number of languages, one decimal place is enough to prevent duplicate q-values.
  1.1545 +                // Also, trailing zeroes do not add any information, so they can be removed.
  1.1546 +                if ((n < 10) || ((u % 10) == 0)) {
  1.1547 +                    u = (u + 5) / 10;
  1.1548 +                    qval_str = "%s%s;q=0.%u";
  1.1549 +                } else {
  1.1550 +                    // Values below 10 require zero padding.
  1.1551 +                    qval_str = "%s%s;q=0.%02u";
  1.1552 +                }
  1.1553 +
  1.1554 +                wrote = PR_snprintf(p2, available, qval_str, comma, token, u);
  1.1555 +            } else {
  1.1556 +                wrote = PR_snprintf(p2, available, "%s%s", comma, token);
  1.1557 +            }
  1.1558 +
  1.1559 +            q -= dec;
  1.1560 +            p2 += wrote;
  1.1561 +            available -= wrote;
  1.1562 +            MOZ_ASSERT(available > 0, "allocated string not long enough");
  1.1563 +        }
  1.1564 +    }
  1.1565 +    free(o_Accept);
  1.1566 +
  1.1567 +    o_AcceptLanguages.Assign((const char *) q_Accept);
  1.1568 +    delete [] q_Accept;
  1.1569 +
  1.1570 +    return NS_OK;
  1.1571 +}
  1.1572 +
  1.1573 +nsresult
  1.1574 +nsHttpHandler::SetAcceptLanguages(const char *aAcceptLanguages)
  1.1575 +{
  1.1576 +    nsAutoCString buf;
  1.1577 +    nsresult rv = PrepareAcceptLanguages(aAcceptLanguages, buf);
  1.1578 +    if (NS_SUCCEEDED(rv))
  1.1579 +        mAcceptLanguages.Assign(buf);
  1.1580 +    return rv;
  1.1581 +}
  1.1582 +
  1.1583 +nsresult
  1.1584 +nsHttpHandler::SetAccept(const char *aAccept)
  1.1585 +{
  1.1586 +    mAccept = aAccept;
  1.1587 +    return NS_OK;
  1.1588 +}
  1.1589 +
  1.1590 +nsresult
  1.1591 +nsHttpHandler::SetAcceptEncodings(const char *aAcceptEncodings)
  1.1592 +{
  1.1593 +    mAcceptEncodings = aAcceptEncodings;
  1.1594 +    return NS_OK;
  1.1595 +}
  1.1596 +
  1.1597 +//-----------------------------------------------------------------------------
  1.1598 +// nsHttpHandler::nsISupports
  1.1599 +//-----------------------------------------------------------------------------
  1.1600 +
  1.1601 +NS_IMPL_ISUPPORTS(nsHttpHandler,
  1.1602 +                  nsIHttpProtocolHandler,
  1.1603 +                  nsIProxiedProtocolHandler,
  1.1604 +                  nsIProtocolHandler,
  1.1605 +                  nsIObserver,
  1.1606 +                  nsISupportsWeakReference,
  1.1607 +                  nsISpeculativeConnect)
  1.1608 +
  1.1609 +//-----------------------------------------------------------------------------
  1.1610 +// nsHttpHandler::nsIProtocolHandler
  1.1611 +//-----------------------------------------------------------------------------
  1.1612 +
  1.1613 +NS_IMETHODIMP
  1.1614 +nsHttpHandler::GetScheme(nsACString &aScheme)
  1.1615 +{
  1.1616 +    aScheme.AssignLiteral("http");
  1.1617 +    return NS_OK;
  1.1618 +}
  1.1619 +
  1.1620 +NS_IMETHODIMP
  1.1621 +nsHttpHandler::GetDefaultPort(int32_t *result)
  1.1622 +{
  1.1623 +    *result = NS_HTTP_DEFAULT_PORT;
  1.1624 +    return NS_OK;
  1.1625 +}
  1.1626 +
  1.1627 +NS_IMETHODIMP
  1.1628 +nsHttpHandler::GetProtocolFlags(uint32_t *result)
  1.1629 +{
  1.1630 +    *result = NS_HTTP_PROTOCOL_FLAGS;
  1.1631 +    return NS_OK;
  1.1632 +}
  1.1633 +
  1.1634 +NS_IMETHODIMP
  1.1635 +nsHttpHandler::NewURI(const nsACString &aSpec,
  1.1636 +                      const char *aCharset,
  1.1637 +                      nsIURI *aBaseURI,
  1.1638 +                      nsIURI **aURI)
  1.1639 +{
  1.1640 +    return mozilla::net::NewURI(aSpec, aCharset, aBaseURI, NS_HTTP_DEFAULT_PORT, aURI);
  1.1641 +}
  1.1642 +
  1.1643 +NS_IMETHODIMP
  1.1644 +nsHttpHandler::NewChannel(nsIURI *uri, nsIChannel **result)
  1.1645 +{
  1.1646 +    LOG(("nsHttpHandler::NewChannel\n"));
  1.1647 +
  1.1648 +    NS_ENSURE_ARG_POINTER(uri);
  1.1649 +    NS_ENSURE_ARG_POINTER(result);
  1.1650 +
  1.1651 +    bool isHttp = false, isHttps = false;
  1.1652 +
  1.1653 +    // Verify that we have been given a valid scheme
  1.1654 +    nsresult rv = uri->SchemeIs("http", &isHttp);
  1.1655 +    if (NS_FAILED(rv)) return rv;
  1.1656 +    if (!isHttp) {
  1.1657 +        rv = uri->SchemeIs("https", &isHttps);
  1.1658 +        if (NS_FAILED(rv)) return rv;
  1.1659 +        if (!isHttps) {
  1.1660 +            NS_WARNING("Invalid URI scheme");
  1.1661 +            return NS_ERROR_UNEXPECTED;
  1.1662 +        }
  1.1663 +    }
  1.1664 +
  1.1665 +    return NewProxiedChannel(uri, nullptr, 0, nullptr, result);
  1.1666 +}
  1.1667 +
  1.1668 +NS_IMETHODIMP
  1.1669 +nsHttpHandler::AllowPort(int32_t port, const char *scheme, bool *_retval)
  1.1670 +{
  1.1671 +    // don't override anything.
  1.1672 +    *_retval = false;
  1.1673 +    return NS_OK;
  1.1674 +}
  1.1675 +
  1.1676 +//-----------------------------------------------------------------------------
  1.1677 +// nsHttpHandler::nsIProxiedProtocolHandler
  1.1678 +//-----------------------------------------------------------------------------
  1.1679 +
  1.1680 +NS_IMETHODIMP
  1.1681 +nsHttpHandler::NewProxiedChannel(nsIURI *uri,
  1.1682 +                                 nsIProxyInfo* givenProxyInfo,
  1.1683 +                                 uint32_t proxyResolveFlags,
  1.1684 +                                 nsIURI *proxyURI,
  1.1685 +                                 nsIChannel **result)
  1.1686 +{
  1.1687 +    nsRefPtr<HttpBaseChannel> httpChannel;
  1.1688 +
  1.1689 +    LOG(("nsHttpHandler::NewProxiedChannel [proxyInfo=%p]\n",
  1.1690 +        givenProxyInfo));
  1.1691 +
  1.1692 +    nsCOMPtr<nsProxyInfo> proxyInfo;
  1.1693 +    if (givenProxyInfo) {
  1.1694 +        proxyInfo = do_QueryInterface(givenProxyInfo);
  1.1695 +        NS_ENSURE_ARG(proxyInfo);
  1.1696 +    }
  1.1697 +
  1.1698 +    bool https;
  1.1699 +    nsresult rv = uri->SchemeIs("https", &https);
  1.1700 +    if (NS_FAILED(rv))
  1.1701 +        return rv;
  1.1702 +
  1.1703 +    if (IsNeckoChild()) {
  1.1704 +        httpChannel = new HttpChannelChild();
  1.1705 +    } else {
  1.1706 +        httpChannel = new nsHttpChannel();
  1.1707 +    }
  1.1708 +
  1.1709 +    uint32_t caps = mCapabilities;
  1.1710 +
  1.1711 +    if (https) {
  1.1712 +        // enable pipelining over SSL if requested
  1.1713 +        if (mPipeliningOverSSL)
  1.1714 +            caps |= NS_HTTP_ALLOW_PIPELINING;
  1.1715 +    }
  1.1716 +
  1.1717 +    if (!IsNeckoChild()) {
  1.1718 +        // HACK: make sure PSM gets initialized on the main thread.
  1.1719 +        net_EnsurePSMInit();
  1.1720 +    }
  1.1721 +
  1.1722 +    rv = httpChannel->Init(uri, caps, proxyInfo, proxyResolveFlags, proxyURI);
  1.1723 +    if (NS_FAILED(rv))
  1.1724 +        return rv;
  1.1725 +
  1.1726 +    httpChannel.forget(result);
  1.1727 +    return NS_OK;
  1.1728 +}
  1.1729 +
  1.1730 +//-----------------------------------------------------------------------------
  1.1731 +// nsHttpHandler::nsIHttpProtocolHandler
  1.1732 +//-----------------------------------------------------------------------------
  1.1733 +
  1.1734 +NS_IMETHODIMP
  1.1735 +nsHttpHandler::GetUserAgent(nsACString &value)
  1.1736 +{
  1.1737 +    value = UserAgent();
  1.1738 +    return NS_OK;
  1.1739 +}
  1.1740 +
  1.1741 +NS_IMETHODIMP
  1.1742 +nsHttpHandler::GetAppName(nsACString &value)
  1.1743 +{
  1.1744 +    value = mLegacyAppName;
  1.1745 +    return NS_OK;
  1.1746 +}
  1.1747 +
  1.1748 +NS_IMETHODIMP
  1.1749 +nsHttpHandler::GetAppVersion(nsACString &value)
  1.1750 +{
  1.1751 +    value = mLegacyAppVersion;
  1.1752 +    return NS_OK;
  1.1753 +}
  1.1754 +
  1.1755 +NS_IMETHODIMP
  1.1756 +nsHttpHandler::GetPlatform(nsACString &value)
  1.1757 +{
  1.1758 +    value = mPlatform;
  1.1759 +    return NS_OK;
  1.1760 +}
  1.1761 +
  1.1762 +NS_IMETHODIMP
  1.1763 +nsHttpHandler::GetOscpu(nsACString &value)
  1.1764 +{
  1.1765 +    value = mOscpu;
  1.1766 +    return NS_OK;
  1.1767 +}
  1.1768 +
  1.1769 +NS_IMETHODIMP
  1.1770 +nsHttpHandler::GetMisc(nsACString &value)
  1.1771 +{
  1.1772 +    value = mMisc;
  1.1773 +    return NS_OK;
  1.1774 +}
  1.1775 +
  1.1776 +/*static*/ void
  1.1777 +nsHttpHandler::GetCacheSessionNameForStoragePolicy(
  1.1778 +        nsCacheStoragePolicy storagePolicy,
  1.1779 +        bool isPrivate,
  1.1780 +        uint32_t appId,
  1.1781 +        bool inBrowser,
  1.1782 +        nsACString& sessionName)
  1.1783 +{
  1.1784 +    MOZ_ASSERT(!isPrivate || storagePolicy == nsICache::STORE_IN_MEMORY);
  1.1785 +
  1.1786 +    switch (storagePolicy) {
  1.1787 +        case nsICache::STORE_IN_MEMORY:
  1.1788 +            sessionName.AssignASCII(isPrivate ? "HTTP-memory-only-PB" : "HTTP-memory-only");
  1.1789 +            break;
  1.1790 +        case nsICache::STORE_OFFLINE:
  1.1791 +            sessionName.AssignLiteral("HTTP-offline");
  1.1792 +            break;
  1.1793 +        default:
  1.1794 +            sessionName.AssignLiteral("HTTP");
  1.1795 +            break;
  1.1796 +    }
  1.1797 +    if (appId != NECKO_NO_APP_ID || inBrowser) {
  1.1798 +        sessionName.Append('~');
  1.1799 +        sessionName.AppendInt(appId);
  1.1800 +        sessionName.Append('~');
  1.1801 +        sessionName.AppendInt(inBrowser);
  1.1802 +    }
  1.1803 +}
  1.1804 +
  1.1805 +//-----------------------------------------------------------------------------
  1.1806 +// nsHttpHandler::nsIObserver
  1.1807 +//-----------------------------------------------------------------------------
  1.1808 +
  1.1809 +NS_IMETHODIMP
  1.1810 +nsHttpHandler::Observe(nsISupports *subject,
  1.1811 +                       const char *topic,
  1.1812 +                       const char16_t *data)
  1.1813 +{
  1.1814 +    LOG(("nsHttpHandler::Observe [topic=\"%s\"]\n", topic));
  1.1815 +
  1.1816 +    if (strcmp(topic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID) == 0) {
  1.1817 +        nsCOMPtr<nsIPrefBranch> prefBranch = do_QueryInterface(subject);
  1.1818 +        if (prefBranch)
  1.1819 +            PrefsChanged(prefBranch, NS_ConvertUTF16toUTF8(data).get());
  1.1820 +    }
  1.1821 +    else if (strcmp(topic, "profile-change-net-teardown")    == 0 ||
  1.1822 +             strcmp(topic, NS_XPCOM_SHUTDOWN_OBSERVER_ID)    == 0) {
  1.1823 +
  1.1824 +        mHandlerActive = false;
  1.1825 +
  1.1826 +        // clear cache of all authentication credentials.
  1.1827 +        mAuthCache.ClearAll();
  1.1828 +        mPrivateAuthCache.ClearAll();
  1.1829 +        if (mWifiTickler)
  1.1830 +            mWifiTickler->Cancel();
  1.1831 +
  1.1832 +        // ensure connection manager is shutdown
  1.1833 +        if (mConnMgr)
  1.1834 +            mConnMgr->Shutdown();
  1.1835 +
  1.1836 +        // need to reset the session start time since cache validation may
  1.1837 +        // depend on this value.
  1.1838 +        mSessionStartTime = NowInSeconds();
  1.1839 +
  1.1840 +        if (!mDoNotTrackEnabled) {
  1.1841 +            Telemetry::Accumulate(Telemetry::DNT_USAGE, DONOTTRACK_VALUE_UNSET);
  1.1842 +        }
  1.1843 +        else {
  1.1844 +            Telemetry::Accumulate(Telemetry::DNT_USAGE, mDoNotTrackValue);
  1.1845 +        }
  1.1846 +    }
  1.1847 +    else if (strcmp(topic, "profile-change-net-restore") == 0) {
  1.1848 +        // initialize connection manager
  1.1849 +        InitConnectionMgr();
  1.1850 +    }
  1.1851 +    else if (strcmp(topic, "net:clear-active-logins") == 0) {
  1.1852 +        mAuthCache.ClearAll();
  1.1853 +        mPrivateAuthCache.ClearAll();
  1.1854 +    }
  1.1855 +    else if (strcmp(topic, "net:prune-dead-connections") == 0) {
  1.1856 +        if (mConnMgr) {
  1.1857 +            mConnMgr->PruneDeadConnections();
  1.1858 +        }
  1.1859 +    }
  1.1860 +    else if (strcmp(topic, "net:prune-all-connections") == 0) {
  1.1861 +        if (mConnMgr) {
  1.1862 +           mConnMgr->DoShiftReloadConnectionCleanup(nullptr);
  1.1863 +           mConnMgr->PruneDeadConnections();
  1.1864 +        }
  1.1865 +    }
  1.1866 +    else if (strcmp(topic, "net:failed-to-process-uri-content") == 0) {
  1.1867 +        nsCOMPtr<nsIURI> uri = do_QueryInterface(subject);
  1.1868 +        if (uri && mConnMgr)
  1.1869 +            mConnMgr->ReportFailedToProcess(uri);
  1.1870 +    }
  1.1871 +    else if (strcmp(topic, "last-pb-context-exited") == 0) {
  1.1872 +        mPrivateAuthCache.ClearAll();
  1.1873 +    }
  1.1874 +
  1.1875 +    return NS_OK;
  1.1876 +}
  1.1877 +
  1.1878 +// nsISpeculativeConnect
  1.1879 +
  1.1880 +NS_IMETHODIMP
  1.1881 +nsHttpHandler::SpeculativeConnect(nsIURI *aURI,
  1.1882 +                                  nsIInterfaceRequestor *aCallbacks)
  1.1883 +{
  1.1884 +    if (!mHandlerActive)
  1.1885 +        return NS_OK;
  1.1886 +
  1.1887 +    nsISiteSecurityService* sss = gHttpHandler->GetSSService();
  1.1888 +    bool isStsHost = false;
  1.1889 +    if (!sss)
  1.1890 +        return NS_OK;
  1.1891 +
  1.1892 +    nsCOMPtr<nsILoadContext> loadContext = do_GetInterface(aCallbacks);
  1.1893 +    uint32_t flags = 0;
  1.1894 +    if (loadContext && loadContext->UsePrivateBrowsing())
  1.1895 +        flags |= nsISocketProvider::NO_PERMANENT_STORAGE;
  1.1896 +    nsCOMPtr<nsIURI> clone;
  1.1897 +    if (NS_SUCCEEDED(sss->IsSecureURI(nsISiteSecurityService::HEADER_HSTS,
  1.1898 +                                      aURI, flags, &isStsHost)) && isStsHost) {
  1.1899 +        if (NS_SUCCEEDED(aURI->Clone(getter_AddRefs(clone)))) {
  1.1900 +            clone->SetScheme(NS_LITERAL_CSTRING("https"));
  1.1901 +            aURI = clone.get();
  1.1902 +        }
  1.1903 +    }
  1.1904 +
  1.1905 +    nsAutoCString scheme;
  1.1906 +    nsresult rv = aURI->GetScheme(scheme);
  1.1907 +    if (NS_FAILED(rv))
  1.1908 +        return rv;
  1.1909 +
  1.1910 +    // If this is HTTPS, make sure PSM is initialized as the channel
  1.1911 +    // creation path may have been bypassed
  1.1912 +    if (scheme.EqualsLiteral("https")) {
  1.1913 +        if (!IsNeckoChild()) {
  1.1914 +            // make sure PSM gets initialized on the main thread.
  1.1915 +            net_EnsurePSMInit();
  1.1916 +        }
  1.1917 +    }
  1.1918 +    // Ensure that this is HTTP or HTTPS, otherwise we don't do preconnect here
  1.1919 +    else if (!scheme.EqualsLiteral("http"))
  1.1920 +        return NS_ERROR_UNEXPECTED;
  1.1921 +
  1.1922 +    // Construct connection info object
  1.1923 +    bool usingSSL = false;
  1.1924 +    rv = aURI->SchemeIs("https", &usingSSL);
  1.1925 +    if (NS_FAILED(rv))
  1.1926 +        return rv;
  1.1927 +
  1.1928 +    nsAutoCString host;
  1.1929 +    rv = aURI->GetAsciiHost(host);
  1.1930 +    if (NS_FAILED(rv))
  1.1931 +        return rv;
  1.1932 +
  1.1933 +    int32_t port = -1;
  1.1934 +    rv = aURI->GetPort(&port);
  1.1935 +    if (NS_FAILED(rv))
  1.1936 +        return rv;
  1.1937 +
  1.1938 +    nsAutoCString username;
  1.1939 +    aURI->GetUsername(username);
  1.1940 +
  1.1941 +    nsHttpConnectionInfo *ci =
  1.1942 +        new nsHttpConnectionInfo(host, port, username, nullptr, usingSSL);
  1.1943 +
  1.1944 +    return SpeculativeConnect(ci, aCallbacks);
  1.1945 +}
  1.1946 +
  1.1947 +void
  1.1948 +nsHttpHandler::TickleWifi(nsIInterfaceRequestor *cb)
  1.1949 +{
  1.1950 +    if (!cb || !mWifiTickler)
  1.1951 +        return;
  1.1952 +
  1.1953 +    // If B2G requires a similar mechanism nsINetworkManager, currently only avail
  1.1954 +    // on B2G, contains the necessary information on wifi and gateway
  1.1955 +
  1.1956 +    nsCOMPtr<nsIDOMWindow> domWindow;
  1.1957 +    cb->GetInterface(NS_GET_IID(nsIDOMWindow), getter_AddRefs(domWindow));
  1.1958 +    if (!domWindow)
  1.1959 +        return;
  1.1960 +
  1.1961 +    nsCOMPtr<nsIDOMNavigator> domNavigator;
  1.1962 +    domWindow->GetNavigator(getter_AddRefs(domNavigator));
  1.1963 +    nsCOMPtr<nsIMozNavigatorNetwork> networkNavigator =
  1.1964 +        do_QueryInterface(domNavigator);
  1.1965 +    if (!networkNavigator)
  1.1966 +        return;
  1.1967 +
  1.1968 +    nsCOMPtr<nsINetworkProperties> networkProperties;
  1.1969 +    networkNavigator->GetProperties(getter_AddRefs(networkProperties));
  1.1970 +    if (!networkProperties)
  1.1971 +        return;
  1.1972 +
  1.1973 +    uint32_t gwAddress;
  1.1974 +    bool isWifi;
  1.1975 +    nsresult rv;
  1.1976 +
  1.1977 +    rv = networkProperties->GetDhcpGateway(&gwAddress);
  1.1978 +    if (NS_SUCCEEDED(rv))
  1.1979 +        rv = networkProperties->GetIsWifi(&isWifi);
  1.1980 +    if (NS_FAILED(rv))
  1.1981 +        return;
  1.1982 +
  1.1983 +    if (!gwAddress || !isWifi)
  1.1984 +        return;
  1.1985 +
  1.1986 +    mWifiTickler->SetIPV4Address(gwAddress);
  1.1987 +    mWifiTickler->Tickle();
  1.1988 +}
  1.1989 +
  1.1990 +//-----------------------------------------------------------------------------
  1.1991 +// nsHttpsHandler implementation
  1.1992 +//-----------------------------------------------------------------------------
  1.1993 +
  1.1994 +NS_IMPL_ISUPPORTS(nsHttpsHandler,
  1.1995 +                  nsIHttpProtocolHandler,
  1.1996 +                  nsIProxiedProtocolHandler,
  1.1997 +                  nsIProtocolHandler,
  1.1998 +                  nsISupportsWeakReference,
  1.1999 +                  nsISpeculativeConnect)
  1.2000 +
  1.2001 +nsresult
  1.2002 +nsHttpsHandler::Init()
  1.2003 +{
  1.2004 +    nsCOMPtr<nsIProtocolHandler> httpHandler(
  1.2005 +            do_GetService(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX "http"));
  1.2006 +    MOZ_ASSERT(httpHandler.get() != nullptr);
  1.2007 +    return NS_OK;
  1.2008 +}
  1.2009 +
  1.2010 +NS_IMETHODIMP
  1.2011 +nsHttpsHandler::GetScheme(nsACString &aScheme)
  1.2012 +{
  1.2013 +    aScheme.AssignLiteral("https");
  1.2014 +    return NS_OK;
  1.2015 +}
  1.2016 +
  1.2017 +NS_IMETHODIMP
  1.2018 +nsHttpsHandler::GetDefaultPort(int32_t *aPort)
  1.2019 +{
  1.2020 +    *aPort = NS_HTTPS_DEFAULT_PORT;
  1.2021 +    return NS_OK;
  1.2022 +}
  1.2023 +
  1.2024 +NS_IMETHODIMP
  1.2025 +nsHttpsHandler::GetProtocolFlags(uint32_t *aProtocolFlags)
  1.2026 +{
  1.2027 +    *aProtocolFlags = NS_HTTP_PROTOCOL_FLAGS | URI_SAFE_TO_LOAD_IN_SECURE_CONTEXT;
  1.2028 +    return NS_OK;
  1.2029 +}
  1.2030 +
  1.2031 +NS_IMETHODIMP
  1.2032 +nsHttpsHandler::NewURI(const nsACString &aSpec,
  1.2033 +                       const char *aOriginCharset,
  1.2034 +                       nsIURI *aBaseURI,
  1.2035 +                       nsIURI **_retval)
  1.2036 +{
  1.2037 +    return mozilla::net::NewURI(aSpec, aOriginCharset, aBaseURI, NS_HTTPS_DEFAULT_PORT, _retval);
  1.2038 +}
  1.2039 +
  1.2040 +NS_IMETHODIMP
  1.2041 +nsHttpsHandler::NewChannel(nsIURI *aURI, nsIChannel **_retval)
  1.2042 +{
  1.2043 +    MOZ_ASSERT(gHttpHandler);
  1.2044 +    if (!gHttpHandler)
  1.2045 +      return NS_ERROR_UNEXPECTED;
  1.2046 +    return gHttpHandler->NewChannel(aURI, _retval);
  1.2047 +}
  1.2048 +
  1.2049 +NS_IMETHODIMP
  1.2050 +nsHttpsHandler::AllowPort(int32_t aPort, const char *aScheme, bool *_retval)
  1.2051 +{
  1.2052 +    // don't override anything.
  1.2053 +    *_retval = false;
  1.2054 +    return NS_OK;
  1.2055 +}
  1.2056 +
  1.2057 +} // namespace mozilla::net
  1.2058 +} // namespace mozilla

mercurial