-
Notifications
You must be signed in to change notification settings - Fork 39
/
nsHttpHandler.cpp
2373 lines (2072 loc) · 76.3 KB
/
nsHttpHandler.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* vim:set ts=4 sw=4 sts=4 et cin: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// HttpLog.h should generally be included first
#include "HttpLog.h"
#include "nsHttp.h"
#include "nsHttpHandler.h"
#include "nsHttpChannel.h"
#include "nsHttpAuthCache.h"
#include "nsStandardURL.h"
#include "nsIDOMWindow.h"
#include "nsIDOMNavigator.h"
#include "nsIMozNavigatorNetwork.h"
#include "nsINetworkProperties.h"
#include "nsIHttpChannel.h"
#include "nsIStandardURL.h"
#include "LoadContextInfo.h"
#include "nsCategoryManagerUtils.h"
#include "nsIPrefService.h"
#include "nsIPrefBranch.h"
#include "nsIPrefLocalizedString.h"
#include "nsISocketProviderService.h"
#include "nsISocketProvider.h"
#include "nsPrintfCString.h"
#include "nsCOMPtr.h"
#include "nsNetCID.h"
#include "prprf.h"
#include "mozilla/Snprintf.h"
#include "nsAsyncRedirectVerifyHelper.h"
#include "nsSocketTransportService2.h"
#include "nsAlgorithm.h"
#include "ASpdySession.h"
#include "mozIApplicationClearPrivateDataParams.h"
#include "EventTokenBucket.h"
#include "Tickler.h"
#include "nsIXULAppInfo.h"
#include "nsICookieService.h"
#include "nsIObserverService.h"
#include "nsISiteSecurityService.h"
#include "nsIStreamConverterService.h"
#include "nsITimer.h"
#include "nsCRT.h"
#include "SpdyZlibReporter.h"
#include "nsIMemoryReporter.h"
#include "nsIParentalControlsService.h"
#include "nsPIDOMWindow.h"
#include "nsINetworkLinkService.h"
#include "nsHttpChannelAuthProvider.h"
#include "nsServiceManagerUtils.h"
#include "nsComponentManagerUtils.h"
#include "nsSocketTransportService2.h"
#include "mozilla/net/NeckoChild.h"
#include "mozilla/ipc/URIUtils.h"
#include "mozilla/Telemetry.h"
#if defined(XP_UNIX)
#include <sys/utsname.h>
#endif
#if defined(XP_WIN)
#include <windows.h>
#endif
#if defined(XP_MACOSX)
#include <CoreServices/CoreServices.h>
#include "nsCocoaFeatures.h"
#endif
#include "mozilla-config.h"
#include "plvmx.h"
//-----------------------------------------------------------------------------
#include "mozilla/net/HttpChannelChild.h"
#include "OptimizedFor.h" // 10.4Fx
#define UA_PREF_PREFIX "general.useragent."
#ifdef XP_WIN
#define UA_SPARE_PLATFORM
#endif
#define HTTP_PREF_PREFIX "network.http."
#define INTL_ACCEPT_LANGUAGES "intl.accept_languages"
#define BROWSER_PREF_PREFIX "browser.cache."
#define DONOTTRACK_HEADER_ENABLED "privacy.donottrackheader.enabled"
#define H2MANDATORY_SUITE "security.ssl3.ecdhe_rsa_aes_128_gcm_sha256"
#define TELEMETRY_ENABLED "toolkit.telemetry.enabled"
#define ALLOW_EXPERIMENTS "network.allow-experiments"
#define SAFE_HINT_HEADER_VALUE "safeHint.enabled"
#define UA_PREF(_pref) UA_PREF_PREFIX _pref
#define HTTP_PREF(_pref) HTTP_PREF_PREFIX _pref
#define BROWSER_PREF(_pref) BROWSER_PREF_PREFIX _pref
#define NS_HTTP_PROTOCOL_FLAGS (URI_STD | ALLOWS_PROXY | ALLOWS_PROXY_HTTP | URI_LOADABLE_BY_ANYONE)
//-----------------------------------------------------------------------------
namespace mozilla {
namespace net {
LazyLogModule gHttpLog("nsHttp");
static nsresult
NewURI(const nsACString &aSpec,
const char *aCharset,
nsIURI *aBaseURI,
int32_t aDefaultPort,
nsIURI **aURI)
{
nsStandardURL *url = new nsStandardURL();
if (!url)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(url);
nsresult rv = url->Init(nsIStandardURL::URLTYPE_AUTHORITY,
aDefaultPort, aSpec, aCharset, aBaseURI);
if (NS_FAILED(rv)) {
NS_RELEASE(url);
return rv;
}
*aURI = url; // no QI needed
return NS_OK;
}
//-----------------------------------------------------------------------------
// nsHttpHandler <public>
//-----------------------------------------------------------------------------
nsHttpHandler *gHttpHandler = nullptr;
nsHttpHandler::nsHttpHandler()
: mConnMgr(nullptr)
, mHttpVersion(NS_HTTP_VERSION_1_1)
, mProxyHttpVersion(NS_HTTP_VERSION_1_1)
, mCapabilities(NS_HTTP_ALLOW_KEEPALIVE)
, mReferrerLevel(0xff) // by default we always send a referrer
, mSpoofReferrerSource(false)
, mReferrerTrimmingPolicy(0)
, mReferrerXOriginPolicy(0)
, mFastFallbackToIPv4(false)
, mProxyPipelining(true)
, mIdleTimeout(PR_SecondsToInterval(10))
, mSpdyTimeout(PR_SecondsToInterval(180))
, mResponseTimeout(PR_SecondsToInterval(300))
, mResponseTimeoutEnabled(false)
, mNetworkChangedTimeout(5000)
, mMaxRequestAttempts(10)
, mMaxRequestDelay(10)
, mIdleSynTimeout(250)
, mH2MandatorySuiteEnabled(false)
, mPipeliningEnabled(false)
, mMaxConnections(24)
, mMaxPersistentConnectionsPerServer(2)
, mMaxPersistentConnectionsPerProxy(4)
, mMaxPipelinedRequests(32)
, mMaxOptimisticPipelinedRequests(4)
, mPipelineAggressive(false)
, mMaxPipelineObjectSize(300000)
, mPipelineRescheduleOnTimeout(true)
, mPipelineRescheduleTimeout(PR_MillisecondsToInterval(1500))
, mPipelineReadTimeout(PR_MillisecondsToInterval(30000))
, mRedirectionLimit(10)
, mPhishyUserPassLength(1)
, mQoSBits(0x00)
, mPipeliningOverSSL(false)
, mEnforceAssocReq(false)
, mLastUniqueID(NowInSeconds())
, mSessionStartTime(0)
, mLegacyAppName("Mozilla")
, mLegacyAppVersion("5.0")
, mProduct("Gecko")
, mCompatFirefoxEnabled(false)
, mUserAgentIsDirty(true)
, mPromptTempRedirect(true)
, mSendSecureXSiteReferrer(true)
, mEnablePersistentHttpsCaching(false)
, mDoNotTrackEnabled(false)
, mSafeHintEnabled(false)
, mParentalControlEnabled(false)
, mHandlerActive(false)
, mTelemetryEnabled(false)
, mAllowExperiments(true)
, mDebugObservations(false)
, mEnableSpdy(false)
, mSpdyV31(true)
, mHttp2Enabled(true)
, mUseH2Deps(true)
, mEnforceHttp2TlsProfile(true)
, mCoalesceSpdy(true)
, mSpdyPersistentSettings(false)
, mAllowPush(true)
, mEnableAltSvc(false)
, mEnableAltSvcOE(false)
, mSpdySendingChunkSize(ASpdySession::kSendingChunkSize)
, mSpdySendBufferSize(ASpdySession::kTCPSendBufferSize)
, mSpdyPushAllowance(32768)
, mSpdyPullAllowance(ASpdySession::kInitialRwin)
, mDefaultSpdyConcurrent(ASpdySession::kDefaultMaxConcurrent)
, mSpdyPingThreshold(PR_SecondsToInterval(58))
, mSpdyPingTimeout(PR_SecondsToInterval(8))
, mConnectTimeout(90000)
, mParallelSpeculativeConnectLimit(6)
, mRequestTokenBucketEnabled(true)
, mRequestTokenBucketMinParallelism(6)
, mRequestTokenBucketHz(100)
, mRequestTokenBucketBurst(32)
, mCriticalRequestPrioritization(true)
, mTCPKeepaliveShortLivedEnabled(false)
, mTCPKeepaliveShortLivedTimeS(60)
, mTCPKeepaliveShortLivedIdleTimeS(10)
, mTCPKeepaliveLongLivedEnabled(false)
, mTCPKeepaliveLongLivedIdleTimeS(600)
, mEnforceH1Framing(FRAMECHECK_BARELY)
{
LOG(("Creating nsHttpHandler [this=%p].\n", this));
RegisterStrongMemoryReporter(new SpdyZlibReporter());
MOZ_ASSERT(!gHttpHandler, "HTTP handler already created!");
gHttpHandler = this;
}
nsHttpHandler::~nsHttpHandler()
{
LOG(("Deleting nsHttpHandler [this=%p]\n", this));
// make sure the connection manager is shutdown
if (mConnMgr) {
mConnMgr->Shutdown();
NS_RELEASE(mConnMgr);
}
// Note: don't call NeckoChild::DestroyNeckoChild() here, as it's too late
// and it'll segfault. NeckoChild will get cleaned up by process exit.
nsHttp::DestroyAtomTable();
if (mPipelineTestTimer) {
mPipelineTestTimer->Cancel();
mPipelineTestTimer = nullptr;
}
gHttpHandler = nullptr;
}
nsresult
nsHttpHandler::Init()
{
nsresult rv;
LOG(("nsHttpHandler::Init\n"));
MOZ_ASSERT(NS_IsMainThread());
rv = nsHttp::CreateAtomTable();
if (NS_FAILED(rv))
return rv;
nsCOMPtr<nsIIOService> service = do_GetService(NS_IOSERVICE_CONTRACTID, &rv);
if (NS_FAILED(rv)) {
NS_WARNING("unable to continue without io service");
return rv;
}
mIOService = new nsMainThreadPtrHolder<nsIIOService>(service);
if (IsNeckoChild())
NeckoChild::InitNeckoChild();
InitUserAgentComponents();
// monitor some preference changes
nsCOMPtr<nsIPrefBranch> prefBranch = do_GetService(NS_PREFSERVICE_CONTRACTID);
if (prefBranch) {
prefBranch->AddObserver(HTTP_PREF_PREFIX, this, true);
prefBranch->AddObserver(UA_PREF_PREFIX, this, true);
prefBranch->AddObserver(INTL_ACCEPT_LANGUAGES, this, true);
prefBranch->AddObserver(BROWSER_PREF("disk_cache_ssl"), this, true);
prefBranch->AddObserver(DONOTTRACK_HEADER_ENABLED, this, true);
prefBranch->AddObserver(TELEMETRY_ENABLED, this, true);
prefBranch->AddObserver(H2MANDATORY_SUITE, this, true);
prefBranch->AddObserver(HTTP_PREF("tcp_keepalive.short_lived_connections"), this, true);
prefBranch->AddObserver(HTTP_PREF("tcp_keepalive.long_lived_connections"), this, true);
prefBranch->AddObserver(SAFE_HINT_HEADER_VALUE, this, true);
PrefsChanged(prefBranch, nullptr);
}
rv = Preferences::AddBoolVarCache(&mPackagedAppsEnabled,
"network.http.enable-packaged-apps", false);
if (NS_FAILED(rv)) {
mPackagedAppsEnabled = false;
}
nsHttpChannelAuthProvider::InitializePrefs();
mMisc.AssignLiteral(TENFOURFOX_FPRVERSION "; rv:" MOZILLA_UAVERSION);
mCompatFirefox.AssignLiteral("Firefox/" MOZILLA_UAVERSION);
nsCOMPtr<nsIXULAppInfo> appInfo =
do_GetService("@mozilla.org/xre/app-info;1");
mAppName.AssignLiteral(MOZ_APP_UA_NAME);
if (mAppName.Length() == 0 && appInfo) {
// Try to get the UA name from appInfo, falling back to the name
appInfo->GetUAName(mAppName);
if (mAppName.Length() == 0) {
appInfo->GetName(mAppName);
}
appInfo->GetVersion(mAppVersion);
mAppName.StripChars(" ()<>@,;:\\\"/[]?={}");
} else {
mAppVersion.AssignLiteral(MOZ_APP_UA_VERSION);
}
mSessionStartTime = NowInSeconds();
mHandlerActive = true;
rv = mAuthCache.Init();
if (NS_FAILED(rv)) return rv;
rv = mPrivateAuthCache.Init();
if (NS_FAILED(rv)) return rv;
rv = InitConnectionMgr();
if (NS_FAILED(rv)) return rv;
mSchedulingContextService =
do_GetService("@mozilla.org/network/scheduling-context-service;1");
#ifdef ANDROID
mProductSub.AssignLiteral(MOZILLA_UAVERSION);
#else
mProductSub.AssignLiteral("20100101");
#endif
#if DEBUG
// dump user agent prefs
LOG(("> legacy-app-name = %s\n", mLegacyAppName.get()));
LOG(("> legacy-app-version = %s\n", mLegacyAppVersion.get()));
LOG(("> platform = %s\n", mPlatform.get()));
LOG(("> oscpu = %s\n", mOscpu.get()));
LOG(("> misc = %s\n", mMisc.get()));
LOG(("> product = %s\n", mProduct.get()));
LOG(("> product-sub = %s\n", mProductSub.get()));
LOG(("> app-name = %s\n", mAppName.get()));
LOG(("> app-version = %s\n", mAppVersion.get()));
LOG(("> compat-firefox = %s\n", mCompatFirefox.get()));
LOG(("> user-agent = %s\n", UserAgent().get()));
#endif
// Startup the http category
// Bring alive the objects in the http-protocol-startup category
NS_CreateServicesFromCategory(NS_HTTP_STARTUP_CATEGORY,
static_cast<nsISupports*>(static_cast<void*>(this)),
NS_HTTP_STARTUP_TOPIC);
nsCOMPtr<nsIObserverService> obsService = services::GetObserverService();
if (obsService) {
// register the handler object as a weak callback as we don't need to worry
// about shutdown ordering.
obsService->AddObserver(this, "profile-change-net-teardown", true);
obsService->AddObserver(this, "profile-change-net-restore", true);
obsService->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, true);
obsService->AddObserver(this, "net:clear-active-logins", true);
obsService->AddObserver(this, "net:prune-dead-connections", true);
// Sent by the TorButton add-on in the Tor Browser
obsService->AddObserver(this, "net:prune-all-connections", true);
obsService->AddObserver(this, "net:failed-to-process-uri-content", true);
obsService->AddObserver(this, "last-pb-context-exited", true);
obsService->AddObserver(this, "webapps-clear-data", true);
obsService->AddObserver(this, "browser:purge-session-history", true);
obsService->AddObserver(this, NS_NETWORK_LINK_TOPIC, true);
obsService->AddObserver(this, "application-background", true);
}
MakeNewRequestTokenBucket();
mWifiTickler = new Tickler();
if (NS_FAILED(mWifiTickler->Init()))
mWifiTickler = nullptr;
nsCOMPtr<nsIParentalControlsService> pc = do_CreateInstance("@mozilla.org/parental-controls-service;1");
if (pc) {
pc->GetParentalControlsEnabled(&mParentalControlEnabled);
}
return NS_OK;
}
void
nsHttpHandler::MakeNewRequestTokenBucket()
{
LOG(("nsHttpHandler::MakeNewRequestTokenBucket this=%p child=%d\n",
this, IsNeckoChild()));
if (!mConnMgr || IsNeckoChild()) {
return;
}
RefPtr<EventTokenBucket> tokenBucket =
new EventTokenBucket(RequestTokenBucketHz(), RequestTokenBucketBurst());
mConnMgr->UpdateRequestTokenBucket(tokenBucket);
}
nsresult
nsHttpHandler::InitConnectionMgr()
{
nsresult rv;
if (!mConnMgr) {
mConnMgr = new nsHttpConnectionMgr();
if (!mConnMgr)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(mConnMgr);
}
rv = mConnMgr->Init(mMaxConnections,
mMaxPersistentConnectionsPerServer,
mMaxPersistentConnectionsPerProxy,
mMaxRequestDelay,
mMaxPipelinedRequests,
mMaxOptimisticPipelinedRequests);
return rv;
}
nsresult
nsHttpHandler::AddStandardRequestHeaders(nsHttpHeaderArray *request,
bool isSecure,
const nsACString &hostLine)
{
nsresult rv;
// Add the "User-Agent" header (unless we have blacklisted this site and
// we aren't using a custom user agent; see TenFourFox issue 422).
if (mUserAgentOverride || (
!hostLine.EqualsLiteral("i.imgur.com") &&
!hostLine.EqualsLiteral("imgur.com") &&
1)) {
rv = request->SetHeader(nsHttp::User_Agent, UserAgent(),
false, nsHttpHeaderArray::eVarietyDefault);
if (NS_FAILED(rv)) return rv;
}
#if DEBUG
else {
fprintf(stderr, "User agent header suppressed for host: %s\n",
PromiseFlatCString(hostLine).get());
}
#endif
// MIME based content negotiation lives!
// Add the "Accept" header. Note, this is set as an override because the
// service worker expects to see it. The other "default" headers are
// hidden from service worker interception.
rv = request->SetHeader(nsHttp::Accept, mAccept,
false, nsHttpHeaderArray::eVarietyOverride);
if (NS_FAILED(rv)) return rv;
// Add the "Accept-Language" header. This header is also exposed to the
// service worker.
if (!mAcceptLanguages.IsEmpty()) {
// Add the "Accept-Language" header
rv = request->SetHeader(nsHttp::Accept_Language, mAcceptLanguages,
false, nsHttpHeaderArray::eVarietyOverride);
if (NS_FAILED(rv)) return rv;
}
// Add the "Accept-Encoding" header
if (isSecure) {
rv = request->SetHeader(nsHttp::Accept_Encoding, mHttpsAcceptEncodings,
false, nsHttpHeaderArray::eVarietyDefault);
} else {
rv = request->SetHeader(nsHttp::Accept_Encoding, mHttpAcceptEncodings,
false, nsHttpHeaderArray::eVarietyDefault);
}
if (NS_FAILED(rv)) return rv;
// Add the "Do-Not-Track" header
if (mDoNotTrackEnabled) {
rv = request->SetHeader(nsHttp::DoNotTrack, NS_LITERAL_CSTRING("1"),
false, nsHttpHeaderArray::eVarietyDefault);
if (NS_FAILED(rv)) return rv;
}
// add the "Send Hint" header
if (mSafeHintEnabled || mParentalControlEnabled) {
rv = request->SetHeader(nsHttp::Prefer, NS_LITERAL_CSTRING("safe"),
false, nsHttpHeaderArray::eVarietyDefault);
if (NS_FAILED(rv)) return rv;
}
return NS_OK;
}
nsresult
nsHttpHandler::AddConnectionHeader(nsHttpHeaderArray *request,
uint32_t caps)
{
// RFC2616 section 19.6.2 states that the "Connection: keep-alive"
// and "Keep-alive" request headers should not be sent by HTTP/1.1
// user-agents. But this is not a problem in practice, and the
// alternative proxy-connection is worse. see 570283
NS_NAMED_LITERAL_CSTRING(close, "close");
NS_NAMED_LITERAL_CSTRING(keepAlive, "keep-alive");
const nsACString *connectionType = &close;
if (caps & NS_HTTP_ALLOW_KEEPALIVE) {
connectionType = &keepAlive;
}
return request->SetHeader(nsHttp::Connection, *connectionType);
}
bool
nsHttpHandler::IsAcceptableEncoding(const char *enc, bool isSecure)
{
if (!enc)
return false;
// we used to accept x-foo anytime foo was acceptable, but that's just
// continuing bad behavior.. so limit it to known x-* patterns
bool rv;
if (isSecure) {
rv = nsHttp::FindToken(mHttpsAcceptEncodings.get(), enc, HTTP_LWS ",") != nullptr;
} else {
rv = nsHttp::FindToken(mHttpAcceptEncodings.get(), enc, HTTP_LWS ",") != nullptr;
}
// gzip and deflate are inherently acceptable in modern HTTP - always
// process them if a stream converter can also be found.
if (!rv &&
(!PL_strcasecmp(enc, "gzip") || !PL_strcasecmp(enc, "deflate") ||
!PL_strcasecmp(enc, "x-gzip") || !PL_strcasecmp(enc, "x-deflate"))) {
rv = true;
}
LOG(("nsHttpHandler::IsAceptableEncoding %s https=%d %d\n",
enc, isSecure, rv));
return rv;
}
nsresult
nsHttpHandler::GetStreamConverterService(nsIStreamConverterService **result)
{
if (!mStreamConvSvc) {
nsresult rv;
nsCOMPtr<nsIStreamConverterService> service =
do_GetService(NS_STREAMCONVERTERSERVICE_CONTRACTID, &rv);
if (NS_FAILED(rv))
return rv;
mStreamConvSvc = new nsMainThreadPtrHolder<nsIStreamConverterService>(service);
}
*result = mStreamConvSvc;
NS_ADDREF(*result);
return NS_OK;
}
nsISiteSecurityService*
nsHttpHandler::GetSSService()
{
if (!mSSService) {
nsCOMPtr<nsISiteSecurityService> service = do_GetService(NS_SSSERVICE_CONTRACTID);
mSSService = new nsMainThreadPtrHolder<nsISiteSecurityService>(service);
}
return mSSService;
}
nsICookieService *
nsHttpHandler::GetCookieService()
{
if (!mCookieService) {
nsCOMPtr<nsICookieService> service = do_GetService(NS_COOKIESERVICE_CONTRACTID);
mCookieService = new nsMainThreadPtrHolder<nsICookieService>(service);
}
return mCookieService;
}
nsresult
nsHttpHandler::GetIOService(nsIIOService** result)
{
NS_ADDREF(*result = mIOService);
return NS_OK;
}
uint32_t
nsHttpHandler::Get32BitsOfPseudoRandom()
{
// only confirm rand seeding on socket thread
MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
// rand() provides different amounts of PRNG on different platforms.
// 15 or 31 bits are common amounts.
PR_STATIC_ASSERT(RAND_MAX >= 0xfff);
#if RAND_MAX < 0xffffU
return ((uint16_t) rand() << 20) |
(((uint16_t) rand() & 0xfff) << 8) |
((uint16_t) rand() & 0xff);
#elif RAND_MAX < 0xffffffffU
return ((uint16_t) rand() << 16) | ((uint16_t) rand() & 0xffff);
#else
return (uint32_t) rand();
#endif
}
void
nsHttpHandler::NotifyObservers(nsIHttpChannel *chan, const char *event)
{
LOG(("nsHttpHandler::NotifyObservers [chan=%x event=\"%s\"]\n", chan, event));
nsCOMPtr<nsIObserverService> obsService = services::GetObserverService();
if (obsService)
obsService->NotifyObservers(chan, event, nullptr);
}
nsresult
nsHttpHandler::AsyncOnChannelRedirect(nsIChannel* oldChan, nsIChannel* newChan,
uint32_t flags)
{
// TODO E10S This helper has to be initialized on the other process
RefPtr<nsAsyncRedirectVerifyHelper> redirectCallbackHelper =
new nsAsyncRedirectVerifyHelper();
return redirectCallbackHelper->Init(oldChan, newChan, flags);
}
/* static */ nsresult
nsHttpHandler::GenerateHostPort(const nsCString& host, int32_t port,
nsACString& hostLine)
{
return NS_GenerateHostPort(host, port, hostLine);
}
//-----------------------------------------------------------------------------
// nsHttpHandler <private>
//-----------------------------------------------------------------------------
const nsAFlatCString &
nsHttpHandler::UserAgent()
{
if (mUserAgentOverride) {
LOG(("using general.useragent.override : %s\n", mUserAgentOverride.get()));
return mUserAgentOverride;
}
if (mUserAgentIsDirty) {
BuildUserAgent();
mUserAgentIsDirty = false;
}
return mUserAgent;
}
void
nsHttpHandler::BuildUserAgent()
{
LOG(("nsHttpHandler::BuildUserAgent\n"));
MOZ_ASSERT(!mLegacyAppName.IsEmpty() &&
!mLegacyAppVersion.IsEmpty(),
"HTTP cannot send practical requests without this much");
// preallocate to worst-case size, which should always be better
// than if we didn't preallocate at all.
mUserAgent.SetCapacity(mLegacyAppName.Length() +
mLegacyAppVersion.Length() +
#ifndef UA_SPARE_PLATFORM
mPlatform.Length() +
#endif
mOscpu.Length() +
mMisc.Length() +
mProduct.Length() +
mProductSub.Length() +
mAppName.Length() +
mAppVersion.Length() +
mCompatFirefox.Length() +
mCompatDevice.Length() +
mDeviceModelId.Length() +
#ifdef FX104_OPTIMIZED_FOR
// needs to be length of SP "TenFourFox/Debugging"
// this is the longest string we support
21 +
#endif
13);
// Application portion
mUserAgent.Assign(mLegacyAppName);
mUserAgent += '/';
mUserAgent += mLegacyAppVersion;
mUserAgent += ' ';
// Application comment
mUserAgent += '(';
#ifndef UA_SPARE_PLATFORM
if (!mPlatform.IsEmpty()) {
mUserAgent += mPlatform;
mUserAgent.AppendLiteral("; ");
}
#endif
if (!mCompatDevice.IsEmpty()) {
mUserAgent += mCompatDevice;
mUserAgent.AppendLiteral("; ");
}
else if (!mOscpu.IsEmpty()) {
mUserAgent += mOscpu;
mUserAgent.AppendLiteral("; ");
}
if (!mDeviceModelId.IsEmpty()) {
mUserAgent += mDeviceModelId;
mUserAgent.AppendLiteral("; ");
}
mUserAgent += mMisc;
mUserAgent += ')';
// Product portion
mUserAgent += ' ';
mUserAgent += mProduct;
mUserAgent += '/';
mUserAgent += mProductSub;
bool isFirefox = mAppName.EqualsLiteral("Firefox");
if (isFirefox || mCompatFirefoxEnabled) {
// "Firefox/x.y" (compatibility) app token
mUserAgent += ' ';
mUserAgent += mCompatFirefox;
}
if (!isFirefox) {
// App portion
mUserAgent += ' ';
mUserAgent += mAppName;
mUserAgent += '/';
mUserAgent += mAppVersion;
}
#ifdef FX104_OPTIMIZED_FOR
mUserAgent.AppendLiteral(" TenFourFox/" FX104_OPTIMIZED_FOR );
#endif
}
#ifdef XP_WIN
#define WNT_BASE "Windows NT %ld.%ld"
#define W64_PREFIX "; Win64"
#endif
void
nsHttpHandler::InitUserAgentComponents()
{
#ifndef MOZ_UA_OS_AGNOSTIC
// Gather platform.
mPlatform.AssignLiteral(
#if defined(ANDROID)
"Android"
#elif defined(XP_WIN)
"Windows"
#elif defined(XP_MACOSX)
"Macintosh"
#elif defined(XP_UNIX)
// We historically have always had X11 here,
// and there seems little a webpage can sensibly do
// based on it being something else, so use X11 for
// backwards compatibility in all cases.
"X11"
#endif
);
#endif
#ifdef ANDROID
nsCOMPtr<nsIPropertyBag2> infoService = do_GetService("@mozilla.org/system-info;1");
MOZ_ASSERT(infoService, "Could not find a system info service");
nsresult rv;
// Add the Android version number to the Fennec platform identifier.
#if defined MOZ_WIDGET_ANDROID
#ifndef MOZ_UA_OS_AGNOSTIC // Don't add anything to mPlatform since it's empty.
nsAutoString androidVersion;
rv = infoService->GetPropertyAsAString(
NS_LITERAL_STRING("release_version"), androidVersion);
if (NS_SUCCEEDED(rv)) {
mPlatform += " ";
// If the 2nd character is a ".", we know the major version is a single
// digit. If we're running on a version below 4 we pretend to be on
// Android KitKat (4.4) to work around scripts sniffing for low versions.
if (androidVersion[1] == 46 && androidVersion[0] < 52) {
mPlatform += "4.4";
} else {
mPlatform += NS_LossyConvertUTF16toASCII(androidVersion);
}
}
#endif
#endif
// Add the `Mobile` or `Tablet` or `TV` token when running on device.
bool isTablet;
rv = infoService->GetPropertyAsBool(NS_LITERAL_STRING("tablet"), &isTablet);
if (NS_SUCCEEDED(rv) && isTablet) {
mCompatDevice.AssignLiteral("Tablet");
} else {
bool isTV;
rv = infoService->GetPropertyAsBool(NS_LITERAL_STRING("tv"), &isTV);
if (NS_SUCCEEDED(rv) && isTV) {
mCompatDevice.AssignLiteral("TV");
} else {
mCompatDevice.AssignLiteral("Mobile");
}
}
#endif // ANDROID
#ifdef FXOS_SIMULATOR
{
// Add the `Mobile` or `Tablet` or `TV` token when running in the b2g
// desktop simulator via preference.
nsCString deviceType;
nsresult rv = Preferences::GetCString("devtools.useragent.device_type", &deviceType);
if (NS_SUCCEEDED(rv)) {
mCompatDevice.Assign(deviceType);
} else {
mCompatDevice.AssignLiteral("Mobile");
}
}
#endif // FXOS_SIMULATOR
#if defined(MOZ_WIDGET_GONK)
// Device model identifier should be a simple token, which can be composed
// of letters, numbers, hyphen ("-") and dot (".").
// Any other characters means the identifier is invalid and ignored.
nsCString deviceId;
rv = Preferences::GetCString("general.useragent.device_id", &deviceId);
if (NS_SUCCEEDED(rv)) {
bool valid = true;
deviceId.Trim(" ", true, true);
for (size_t i = 0; i < deviceId.Length(); i++) {
char c = deviceId.CharAt(i);
if (!(isalnum(c) || c == '-' || c == '.')) {
valid = false;
break;
}
}
if (valid) {
mDeviceModelId = deviceId;
} else {
LOG(("nsHttpHandler: Ignore invalid device ID: [%s]\n",
deviceId.get()));
}
}
#endif
#ifndef MOZ_UA_OS_AGNOSTIC
// Gather OS/CPU.
#if defined(XP_WIN)
OSVERSIONINFO info = { sizeof(OSVERSIONINFO) };
#pragma warning(push)
#pragma warning(disable:4996)
if (GetVersionEx(&info)) {
#pragma warning(pop)
const char *format;
#if defined _M_IA64
format = WNT_BASE W64_PREFIX "; IA64";
#elif defined _M_X64 || defined _M_AMD64
format = WNT_BASE W64_PREFIX "; x64";
#else
BOOL isWow64 = FALSE;
if (!IsWow64Process(GetCurrentProcess(), &isWow64)) {
isWow64 = FALSE;
}
format = isWow64
? WNT_BASE "; WOW64"
: WNT_BASE;
#endif
char *buf = PR_smprintf(format,
info.dwMajorVersion,
info.dwMinorVersion);
if (buf) {
mOscpu = buf;
PR_smprintf_free(buf);
}
}
#elif defined (XP_MACOSX)
#if defined(__ppc__)
mOscpu.AssignLiteral("PPC Mac OS X");
#elif defined(__i386__) || defined(__x86_64__)
mOscpu.AssignLiteral("Intel Mac OS X");
#endif
SInt32 majorVersion = nsCocoaFeatures::OSXVersionMajor();
SInt32 minorVersion = nsCocoaFeatures::OSXVersionMinor();
mOscpu += nsPrintfCString(" %d.%d", majorVersion, minorVersion);
#elif defined (XP_UNIX)
struct utsname name;
int ret = uname(&name);
if (ret >= 0) {
nsAutoCString buf;
buf = (char*)name.sysname;
if (strcmp(name.machine, "x86_64") == 0 &&
sizeof(void *) == sizeof(int32_t)) {
// We're running 32-bit code on x86_64. Make this browser
// look like it's running on i686 hardware, but append "
// (x86_64)" to the end of the oscpu identifier to be able
// to differentiate this from someone running 64-bit code
// on x86_64..
buf += " i686 on x86_64";
} else {
buf += ' ';
#ifdef AIX
// AIX uname returns machine specific info in the uname.machine
// field and does not return the cpu type like other platforms.
// We use the AIX version and release numbers instead.
buf += (char*)name.version;
buf += '.';
buf += (char*)name.release;
#else
buf += (char*)name.machine;
#endif
}
mOscpu.Assign(buf);
}
#endif
#endif
mUserAgentIsDirty = true;
}
uint32_t
nsHttpHandler::MaxSocketCount()
{
PR_CallOnce(&nsSocketTransportService::gMaxCountInitOnce,
nsSocketTransportService::DiscoverMaxCount);
// Don't use the full max count because sockets can be held in
// the persistent connection pool for a long time and that could
// starve other users.
uint32_t maxCount = nsSocketTransportService::gMaxCount;
if (maxCount <= 8)
maxCount = 1;
else
maxCount -= 8;
return maxCount;
}
void
nsHttpHandler::PrefsChanged(nsIPrefBranch *prefs, const char *pref)
{
nsresult rv = NS_OK;
int32_t val;
LOG(("nsHttpHandler::PrefsChanged [pref=%s]\n", pref));
#define PREF_CHANGED(p) ((pref == nullptr) || !PL_strcmp(pref, p))
#define MULTI_PREF_CHANGED(p) \
((pref == nullptr) || !PL_strncmp(pref, p, sizeof(p) - 1))
//
// UA components
//
bool cVar = false;
if (PREF_CHANGED(UA_PREF("compatMode.firefox"))) {
rv = prefs->GetBoolPref(UA_PREF("compatMode.firefox"), &cVar);
mCompatFirefoxEnabled = (NS_SUCCEEDED(rv) && cVar);
mUserAgentIsDirty = true;
}
// general.useragent.override
if (PREF_CHANGED(UA_PREF("override"))) {
prefs->GetCharPref(UA_PREF("override"),
getter_Copies(mUserAgentOverride));
mUserAgentIsDirty = true;
}
//
// HTTP options
//
if (PREF_CHANGED(HTTP_PREF("keep-alive.timeout"))) {
rv = prefs->GetIntPref(HTTP_PREF("keep-alive.timeout"), &val);
if (NS_SUCCEEDED(rv))
mIdleTimeout = PR_SecondsToInterval(clamped(val, 1, 0xffff));
}
if (PREF_CHANGED(HTTP_PREF("request.max-attempts"))) {
rv = prefs->GetIntPref(HTTP_PREF("request.max-attempts"), &val);
if (NS_SUCCEEDED(rv))
mMaxRequestAttempts = (uint16_t) clamped(val, 1, 0xffff);
}
if (PREF_CHANGED(HTTP_PREF("request.max-start-delay"))) {
rv = prefs->GetIntPref(HTTP_PREF("request.max-start-delay"), &val);
if (NS_SUCCEEDED(rv)) {
mMaxRequestDelay = (uint16_t) clamped(val, 0, 0xffff);
if (mConnMgr)
mConnMgr->UpdateParam(nsHttpConnectionMgr::MAX_REQUEST_DELAY,
mMaxRequestDelay);
}
}
if (PREF_CHANGED(HTTP_PREF("response.timeout"))) {
rv = prefs->GetIntPref(HTTP_PREF("response.timeout"), &val);
if (NS_SUCCEEDED(rv))