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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set sw=2 ts=8 et tw=80 : */
/* 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/. */
#include "TRRServiceChannel.h"
#include "HttpLog.h"
#include "AltServiceChild.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/StaticPrefs_network.h"
#include "mozilla/Unused.h"
#include "nsDNSPrefetch.h"
#include "nsEscape.h"
#include "nsHttpTransaction.h"
#include "nsICancelable.h"
#include "nsICachingChannel.h"
#include "nsIHttpPushListener.h"
#include "nsIProtocolProxyService2.h"
#include "nsIOService.h"
#include "nsISeekableStream.h"
#include "nsURLHelper.h"
#include "ProxyConfigLookup.h"
#include "TRRLoadInfo.h"
#include "ReferrerInfo.h"
#include "TRR.h"
#include "TRRService.h"
namespace mozilla::net {
NS_IMPL_ADDREF(TRRServiceChannel)
// Because nsSupportsWeakReference isn't thread-safe we must ensure that
// TRRServiceChannel is destroyed on the target thread. Any Release() called
// on a different thread is dispatched to the target thread.
bool TRRServiceChannel::DispatchRelease() {
if (mCurrentEventTarget->IsOnCurrentThread()) {
return false;
}
mCurrentEventTarget->Dispatch(
NewNonOwningRunnableMethod("net::TRRServiceChannel::Release", this,
&TRRServiceChannel::Release),
NS_DISPATCH_NORMAL);
return true;
}
NS_IMETHODIMP_(MozExternalRefCountType)
TRRServiceChannel::Release() {
nsrefcnt count = mRefCnt - 1;
if (DispatchRelease()) {
// Redispatched to the target thread.
return count;
}
MOZ_ASSERT(0 != mRefCnt, "dup release");
count = --mRefCnt;
NS_LOG_RELEASE(this, count, "TRRServiceChannel");
if (0 == count) {
mRefCnt = 1;
delete (this);
return 0;
}
return count;
}
NS_INTERFACE_MAP_BEGIN(TRRServiceChannel)
NS_INTERFACE_MAP_ENTRY(nsIRequest)
NS_INTERFACE_MAP_ENTRY(nsIChannel)
NS_INTERFACE_MAP_ENTRY(nsIHttpChannel)
NS_INTERFACE_MAP_ENTRY(nsIHttpChannelInternal)
NS_INTERFACE_MAP_ENTRY(nsISupportsPriority)
NS_INTERFACE_MAP_ENTRY(nsIClassOfService)
NS_INTERFACE_MAP_ENTRY(nsIProxiedChannel)
NS_INTERFACE_MAP_ENTRY(nsIProtocolProxyCallback)
NS_INTERFACE_MAP_ENTRY(nsIStreamListener)
NS_INTERFACE_MAP_ENTRY(nsIRequestObserver)
NS_INTERFACE_MAP_ENTRY(nsITransportEventSink)
NS_INTERFACE_MAP_ENTRY(nsIDNSListener)
NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
NS_INTERFACE_MAP_ENTRY(nsIUploadChannel2)
NS_INTERFACE_MAP_ENTRY_CONCRETE(TRRServiceChannel)
NS_INTERFACE_MAP_END_INHERITING(HttpBaseChannel)
TRRServiceChannel::TRRServiceChannel()
: HttpAsyncAborter<TRRServiceChannel>(this),
mProxyRequest(nullptr, "TRRServiceChannel::mProxyRequest"),
mCurrentEventTarget(GetCurrentSerialEventTarget()) {
LOG(("TRRServiceChannel ctor [this=%p]\n", this));
}
TRRServiceChannel::~TRRServiceChannel() {
LOG(("TRRServiceChannel dtor [this=%p]\n", this));
}
NS_IMETHODIMP TRRServiceChannel::SetCanceledReason(const nsACString& aReason) {
return SetCanceledReasonImpl(aReason);
}
NS_IMETHODIMP TRRServiceChannel::GetCanceledReason(nsACString& aReason) {
return GetCanceledReasonImpl(aReason);
}
NS_IMETHODIMP
TRRServiceChannel::CancelWithReason(nsresult aStatus,
const nsACString& aReason) {
return CancelWithReasonImpl(aStatus, aReason);
}
NS_IMETHODIMP
TRRServiceChannel::Cancel(nsresult status) {
LOG(("TRRServiceChannel::Cancel [this=%p status=%" PRIx32 "]\n", this,
static_cast<uint32_t>(status)));
if (mCanceled) {
LOG((" ignoring; already canceled\n"));
return NS_OK;
}
mCanceled = true;
mStatus = status;
nsCOMPtr<nsICancelable> proxyRequest;
{
auto req = mProxyRequest.Lock();
proxyRequest.swap(*req);
}
if (proxyRequest) {
NS_DispatchToMainThread(
NS_NewRunnableFunction(
"CancelProxyRequest",
[proxyRequest, status]() { proxyRequest->Cancel(status); }),
NS_DISPATCH_NORMAL);
}
CancelNetworkRequest(status);
return NS_OK;
}
void TRRServiceChannel::CancelNetworkRequest(nsresult aStatus) {
if (mTransaction) {
nsresult rv = gHttpHandler->CancelTransaction(mTransaction, aStatus);
if (NS_FAILED(rv)) {
LOG(("failed to cancel the transaction\n"));
}
}
if (mTransactionPump) mTransactionPump->Cancel(aStatus);
}
NS_IMETHODIMP
TRRServiceChannel::Suspend() {
LOG(("TRRServiceChannel::SuspendInternal [this=%p]\n", this));
if (mTransactionPump) {
return mTransactionPump->Suspend();
}
return NS_OK;
}
NS_IMETHODIMP
TRRServiceChannel::Resume() {
LOG(("TRRServiceChannel::Resume [this=%p]\n", this));
if (mTransactionPump) {
return mTransactionPump->Resume();
}
return NS_OK;
}
NS_IMETHODIMP
TRRServiceChannel::GetSecurityInfo(nsITransportSecurityInfo** securityInfo) {
NS_ENSURE_ARG_POINTER(securityInfo);
*securityInfo = do_AddRef(mSecurityInfo).take();
return NS_OK;
}
NS_IMETHODIMP
TRRServiceChannel::AsyncOpen(nsIStreamListener* aListener) {
NS_ENSURE_ARG_POINTER(aListener);
NS_ENSURE_TRUE(!LoadIsPending(), NS_ERROR_IN_PROGRESS);
NS_ENSURE_TRUE(!LoadWasOpened(), NS_ERROR_ALREADY_OPENED);
if (mCanceled) {
ReleaseListeners();
return mStatus;
}
// HttpBaseChannel::MaybeWaitForUploadStreamNormalization can only be used on
// main thread, so we can only return an error here.
#ifdef NIGHTLY_BUILD
MOZ_ASSERT(!LoadPendingUploadStreamNormalization());
#endif
if (LoadPendingUploadStreamNormalization()) {
return NS_ERROR_FAILURE;
}
if (!gHttpHandler->Active()) {
LOG((" after HTTP shutdown..."));
ReleaseListeners();
return NS_ERROR_NOT_AVAILABLE;
}
nsresult rv = NS_CheckPortSafety(mURI);
if (NS_FAILED(rv)) {
ReleaseListeners();
return rv;
}
StoreIsPending(true);
StoreWasOpened(true);
mListener = aListener;
mAsyncOpenTime = TimeStamp::Now();
rv = MaybeResolveProxyAndBeginConnect();
if (NS_FAILED(rv)) {
Unused << AsyncAbort(rv);
}
return NS_OK;
}
nsresult TRRServiceChannel::MaybeResolveProxyAndBeginConnect() {
nsresult rv;
// The common case for HTTP channels is to begin proxy resolution and return
// at this point. The only time we know mProxyInfo already is if we're
// proxying a non-http protocol like ftp. We don't need to discover proxy
// settings if we are never going to make a network connection.
// If mConnectionInfo is already supplied, we don't need to do proxy
// resolution again.
if (!mProxyInfo && !mConnectionInfo &&
!(mLoadFlags & (nsICachingChannel::LOAD_ONLY_FROM_CACHE |
nsICachingChannel::LOAD_NO_NETWORK_IO)) &&
NS_SUCCEEDED(ResolveProxy())) {
return NS_OK;
}
rv = BeginConnect();
if (NS_FAILED(rv)) {
Unused << AsyncAbort(rv);
}
return NS_OK;
}
nsresult TRRServiceChannel::ResolveProxy() {
LOG(("TRRServiceChannel::ResolveProxy [this=%p]\n", this));
if (!NS_IsMainThread()) {
return NS_DispatchToMainThread(
NewRunnableMethod("TRRServiceChannel::ResolveProxy", this,
&TRRServiceChannel::ResolveProxy),
NS_DISPATCH_NORMAL);
}
MOZ_ASSERT(NS_IsMainThread());
// TODO: bug 1625171. Consider moving proxy resolution to socket process.
RefPtr<TRRServiceChannel> self = this;
nsCOMPtr<nsICancelable> proxyRequest;
nsresult rv = ProxyConfigLookup::Create(
[self](nsIProxyInfo* aProxyInfo, nsresult aStatus) {
self->OnProxyAvailable(nullptr, nullptr, aProxyInfo, aStatus);
},
mURI, mProxyResolveFlags, getter_AddRefs(proxyRequest));
if (NS_FAILED(rv)) {
if (!mCurrentEventTarget->IsOnCurrentThread()) {
return mCurrentEventTarget->Dispatch(
NewRunnableMethod<nsresult>("TRRServiceChannel::AsyncAbort", this,
&TRRServiceChannel::AsyncAbort, rv),
NS_DISPATCH_NORMAL);
}
}
{
auto req = mProxyRequest.Lock();
// We only set mProxyRequest if the channel hasn't already been cancelled
// on another thread.
if (!mCanceled) {
*req = proxyRequest.forget();
}
}
// If the channel has been cancelled, we go ahead and cancel the proxy
// request right here.
if (proxyRequest) {
proxyRequest->Cancel(mStatus);
}
return rv;
}
NS_IMETHODIMP
TRRServiceChannel::OnProxyAvailable(nsICancelable* request, nsIChannel* channel,
nsIProxyInfo* pi, nsresult status) {
LOG(("TRRServiceChannel::OnProxyAvailable [this=%p pi=%p status=%" PRIx32
" mStatus=%" PRIx32 "]\n",
this, pi, static_cast<uint32_t>(status),
static_cast<uint32_t>(static_cast<nsresult>(mStatus))));
if (!mCurrentEventTarget->IsOnCurrentThread()) {
RefPtr<TRRServiceChannel> self = this;
nsCOMPtr<nsIProxyInfo> info = pi;
return mCurrentEventTarget->Dispatch(
NS_NewRunnableFunction("TRRServiceChannel::OnProxyAvailable",
[self, info, status]() {
self->OnProxyAvailable(nullptr, nullptr, info,
status);
}),
NS_DISPATCH_NORMAL);
}
MOZ_ASSERT(mCurrentEventTarget->IsOnCurrentThread());
{
auto proxyRequest = mProxyRequest.Lock();
*proxyRequest = nullptr;
}
nsresult rv;
// If status is a failure code, then it means that we failed to resolve
// proxy info. That is a non-fatal error assuming it wasn't because the
// request was canceled. We just failover to DIRECT when proxy resolution
// fails (failure can mean that the PAC URL could not be loaded).
if (NS_SUCCEEDED(status)) mProxyInfo = pi;
if (!gHttpHandler->Active()) {
LOG(
("nsHttpChannel::OnProxyAvailable [this=%p] "
"Handler no longer active.\n",
this));
rv = NS_ERROR_NOT_AVAILABLE;
} else {
rv = BeginConnect();
}
if (NS_FAILED(rv)) {
Unused << AsyncAbort(rv);
}
return rv;
}
nsresult TRRServiceChannel::BeginConnect() {
LOG(("TRRServiceChannel::BeginConnect [this=%p]\n", this));
nsresult rv;
// Construct connection info object
nsAutoCString host;
nsAutoCString scheme;
int32_t port = -1;
bool isHttps = mURI->SchemeIs("https");
rv = mURI->GetScheme(scheme);
if (NS_SUCCEEDED(rv)) rv = mURI->GetAsciiHost(host);
if (NS_SUCCEEDED(rv)) rv = mURI->GetPort(&port);
if (NS_SUCCEEDED(rv)) rv = mURI->GetAsciiSpec(mSpec);
if (NS_FAILED(rv)) {
return rv;
}
// Just a warning here because some nsIURIs do not implement this method.
Unused << NS_WARN_IF(NS_FAILED(mURI->GetUsername(mUsername)));
// Reject the URL if it doesn't specify a host
if (host.IsEmpty()) {
rv = NS_ERROR_MALFORMED_URI;
return rv;
}
LOG(("host=%s port=%d\n", host.get(), port));
LOG(("uri=%s\n", mSpec.get()));
nsCOMPtr<nsProxyInfo> proxyInfo;
if (mProxyInfo) proxyInfo = do_QueryInterface(mProxyInfo);
mRequestHead.SetHTTPS(isHttps);
mRequestHead.SetOrigin(scheme, host, port);
RefPtr<nsHttpConnectionInfo> connInfo = new nsHttpConnectionInfo(
host, port, ""_ns, mUsername, proxyInfo, OriginAttributes(), isHttps);
// TODO: Bug 1622778 for using AltService in socket process.
StoreAllowAltSvc(XRE_IsParentProcess() && LoadAllowAltSvc());
bool http2Allowed = !gHttpHandler->IsHttp2Excluded(connInfo);
bool http3Allowed = Http3Allowed();
if (!http3Allowed) {
mCaps |= NS_HTTP_DISALLOW_HTTP3;
}
RefPtr<AltSvcMapping> mapping;
if (!mConnectionInfo && LoadAllowAltSvc() && // per channel
(http2Allowed || http3Allowed) && !(mLoadFlags & LOAD_FRESH_CONNECTION) &&
AltSvcMapping::AcceptableProxy(proxyInfo) &&
(scheme.EqualsLiteral("http") || scheme.EqualsLiteral("https")) &&
(mapping = gHttpHandler->GetAltServiceMapping(
scheme, host, port, mPrivateBrowsing, OriginAttributes(),
http2Allowed, http3Allowed))) {
LOG(("TRRServiceChannel %p Alt Service Mapping Found %s://%s:%d [%s]\n",
this, scheme.get(), mapping->AlternateHost().get(),
mapping->AlternatePort(), mapping->HashKey().get()));
if (!(mLoadFlags & LOAD_ANONYMOUS) && !mPrivateBrowsing) {
nsAutoCString altUsedLine(mapping->AlternateHost());
bool defaultPort =
mapping->AlternatePort() ==
(isHttps ? NS_HTTPS_DEFAULT_PORT : NS_HTTP_DEFAULT_PORT);
if (!defaultPort) {
altUsedLine.AppendLiteral(":");
altUsedLine.AppendInt(mapping->AlternatePort());
}
rv = mRequestHead.SetHeader(nsHttp::Alternate_Service_Used, altUsedLine);
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
LOG(("TRRServiceChannel %p Using connection info from altsvc mapping",
this));
mapping->GetConnectionInfo(getter_AddRefs(mConnectionInfo), proxyInfo,
OriginAttributes());
Telemetry::Accumulate(Telemetry::HTTP_TRANSACTION_USE_ALTSVC, true);
Telemetry::Accumulate(Telemetry::HTTP_TRANSACTION_USE_ALTSVC_OE, !isHttps);
} else if (mConnectionInfo) {
LOG(("TRRServiceChannel %p Using channel supplied connection info", this));
} else {
LOG(("TRRServiceChannel %p Using default connection info", this));
mConnectionInfo = connInfo;
Telemetry::Accumulate(Telemetry::HTTP_TRANSACTION_USE_ALTSVC, false);
}
// Need to re-ask the handler, since mConnectionInfo may not be the connInfo
// we used earlier
if (gHttpHandler->IsHttp2Excluded(mConnectionInfo)) {
StoreAllowSpdy(0);
mCaps |= NS_HTTP_DISALLOW_SPDY;
mConnectionInfo->SetNoSpdy(true);
}
// If TimingEnabled flag is not set after OnModifyRequest() then
// clear the already recorded AsyncOpen value for consistency.
if (!LoadTimingEnabled()) mAsyncOpenTime = TimeStamp();
// if this somehow fails we can go on without it
Unused << gHttpHandler->AddConnectionHeader(&mRequestHead, mCaps);
// Adjust mCaps according to our request headers:
// - If "Connection: close" is set as a request header, then do not bother
// trying to establish a keep-alive connection.
if (mRequestHead.HasHeaderValue(nsHttp::Connection, "close")) {
mCaps &= ~(NS_HTTP_ALLOW_KEEPALIVE);
}
if (gHttpHandler->CriticalRequestPrioritization()) {
if (mClassOfService.Flags() & nsIClassOfService::Leader) {
mCaps |= NS_HTTP_LOAD_AS_BLOCKING;
}
if (mClassOfService.Flags() & nsIClassOfService::Unblocked) {
mCaps |= NS_HTTP_LOAD_UNBLOCKED;
}
if (mClassOfService.Flags() & nsIClassOfService::UrgentStart &&
gHttpHandler->IsUrgentStartEnabled()) {
mCaps |= NS_HTTP_URGENT_START;
SetPriority(nsISupportsPriority::PRIORITY_HIGHEST);
}
}
if (mCanceled) {
return mStatus;
}
MaybeStartDNSPrefetch();
rv = ContinueOnBeforeConnect();
if (NS_FAILED(rv)) {
return rv;
}
return NS_OK;
}
nsresult TRRServiceChannel::ContinueOnBeforeConnect() {
LOG(("TRRServiceChannel::ContinueOnBeforeConnect [this=%p]\n", this));
// ensure that we are using a valid hostname
if (!net_IsValidHostName(nsDependentCString(mConnectionInfo->Origin()))) {
return NS_ERROR_UNKNOWN_HOST;
}
if (LoadIsTRRServiceChannel()) {
mCaps |= NS_HTTP_LARGE_KEEPALIVE;
mCaps |= NS_HTTP_DISALLOW_HTTPS_RR;
}
mCaps |= NS_HTTP_TRR_FLAGS_FROM_MODE(nsIRequest::GetTRRMode());
// Finalize ConnectionInfo flags before SpeculativeConnect
mConnectionInfo->SetAnonymous((mLoadFlags & LOAD_ANONYMOUS) != 0);
mConnectionInfo->SetPrivate(mPrivateBrowsing);
mConnectionInfo->SetNoSpdy(mCaps & NS_HTTP_DISALLOW_SPDY);
mConnectionInfo->SetBeConservative((mCaps & NS_HTTP_BE_CONSERVATIVE) ||
LoadBeConservative());
mConnectionInfo->SetTlsFlags(mTlsFlags);
mConnectionInfo->SetIsTrrServiceChannel(LoadIsTRRServiceChannel());
mConnectionInfo->SetTRRMode(nsIRequest::GetTRRMode());
mConnectionInfo->SetIPv4Disabled(mCaps & NS_HTTP_DISABLE_IPV4);
mConnectionInfo->SetIPv6Disabled(mCaps & NS_HTTP_DISABLE_IPV6);
if (mLoadFlags & LOAD_FRESH_CONNECTION) {
Telemetry::ScalarAdd(
Telemetry::ScalarID::NETWORKING_TRR_CONNECTION_CYCLE_COUNT,
NS_ConvertUTF8toUTF16(TRRService::ProviderKey()), 1);
nsresult rv =
gHttpHandler->ConnMgr()->DoSingleConnectionCleanup(mConnectionInfo);
LOG(
("TRRServiceChannel::BeginConnect "
"DoSingleConnectionCleanup succeeded=%d %08x [this=%p]",
NS_SUCCEEDED(rv), static_cast<uint32_t>(rv), this));
}
return Connect();
}
nsresult TRRServiceChannel::Connect() {
LOG(("TRRServiceChannel::Connect [this=%p]\n", this));
nsresult rv = SetupTransaction();
if (NS_FAILED(rv)) {
return rv;
}
rv = gHttpHandler->InitiateTransaction(mTransaction, mPriority);
if (NS_FAILED(rv)) {
return rv;
}
return mTransaction->AsyncRead(this, getter_AddRefs(mTransactionPump));
}
nsresult TRRServiceChannel::SetupTransaction() {
LOG((
"TRRServiceChannel::SetupTransaction "
"[this=%p, cos=%lu, inc=%d, prio=%d]\n",
this, mClassOfService.Flags(), mClassOfService.Incremental(), mPriority));
NS_ENSURE_TRUE(!mTransaction, NS_ERROR_ALREADY_INITIALIZED);
nsresult rv;
if (!LoadAllowSpdy()) {
mCaps |= NS_HTTP_DISALLOW_SPDY;
}
// Check a proxy info from mConnectionInfo. TRR channel may use a proxy that
// is set in mConnectionInfo but acutally the channel do not have mProxyInfo
// set. This can happend when network.trr.async_connInfo is true.
bool useNonDirectProxy = mConnectionInfo->ProxyInfo()
? !mConnectionInfo->ProxyInfo()->IsDirect()
: false;
if (!Http3Allowed() || useNonDirectProxy) {
mCaps |= NS_HTTP_DISALLOW_HTTP3;
}
if (LoadBeConservative()) {
mCaps |= NS_HTTP_BE_CONSERVATIVE;
}
// Use the URI path if not proxying (transparent proxying such as proxy
// CONNECT does not count here). Also figure out what HTTP version to use.
nsAutoCString buf, path;
nsCString* requestURI;
// This is the normal e2e H1 path syntax "/index.html"
rv = mURI->GetPathQueryRef(path);
if (NS_FAILED(rv)) {
return rv;
}
// path may contain UTF-8 characters, so ensure that they're escaped.
if (NS_EscapeURL(path.get(), path.Length(), esc_OnlyNonASCII | esc_Spaces,
buf)) {
requestURI = &buf;
} else {
requestURI = &path;
}
// trim off the #ref portion if any...
int32_t ref1 = requestURI->FindChar('#');
if (ref1 != kNotFound) {
requestURI->SetLength(ref1);
}
if (mConnectionInfo->UsingConnect() || !mConnectionInfo->UsingHttpProxy()) {
mRequestHead.SetVersion(gHttpHandler->HttpVersion());
} else {
mRequestHead.SetPath(*requestURI);
// RequestURI should be the absolute uri H1 proxy syntax
// "http://foo/index.html" so we will overwrite the relative version in
// requestURI
rv = mURI->GetUserPass(buf);
if (NS_FAILED(rv)) return rv;
if (!buf.IsEmpty() && ((strncmp(mSpec.get(), "http:", 5) == 0) ||
strncmp(mSpec.get(), "https:", 6) == 0)) {
nsCOMPtr<nsIURI> tempURI = nsIOService::CreateExposableURI(mURI);
rv = tempURI->GetAsciiSpec(path);
if (NS_FAILED(rv)) return rv;
requestURI = &path;
} else {
requestURI = &mSpec;
}
// trim off the #ref portion if any...
int32_t ref2 = requestURI->FindChar('#');
if (ref2 != kNotFound) {
requestURI->SetLength(ref2);
}
mRequestHead.SetVersion(gHttpHandler->ProxyHttpVersion());
}
mRequestHead.SetRequestURI(*requestURI);
// Force setting no-cache header for TRRServiceChannel.
// We need to send 'Pragma:no-cache' to inhibit proxy caching even if
// no proxy is configured since we might be talking with a transparent
// proxy, i.e. one that operates at the network level. See bug #14772.
rv = mRequestHead.SetHeaderOnce(nsHttp::Pragma, "no-cache", true);
MOZ_ASSERT(NS_SUCCEEDED(rv));
// If we're configured to speak HTTP/1.1 then also send 'Cache-control:
// no-cache'
if (mRequestHead.Version() >= HttpVersion::v1_1) {
rv = mRequestHead.SetHeaderOnce(nsHttp::Cache_Control, "no-cache", true);
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
// create wrapper for this channel's notification callbacks
nsCOMPtr<nsIInterfaceRequestor> callbacks;
NS_NewNotificationCallbacksAggregation(mCallbacks, mLoadGroup,
getter_AddRefs(callbacks));
// create the transaction object
mTransaction = new nsHttpTransaction();
LOG1(("TRRServiceChannel %p created nsHttpTransaction %p\n", this,
mTransaction.get()));
// See bug #466080. Transfer LOAD_ANONYMOUS flag to socket-layer.
if (mLoadFlags & LOAD_ANONYMOUS) mCaps |= NS_HTTP_LOAD_ANONYMOUS;
if (LoadTimingEnabled()) mCaps |= NS_HTTP_TIMING_ENABLED;
nsCOMPtr<nsIHttpPushListener> pushListener;
NS_QueryNotificationCallbacks(mCallbacks, mLoadGroup,
NS_GET_IID(nsIHttpPushListener),
getter_AddRefs(pushListener));
HttpTransactionShell::OnPushCallback pushCallback = nullptr;
if (pushListener) {
mCaps |= NS_HTTP_ONPUSH_LISTENER;
nsWeakPtr weakPtrThis(
do_GetWeakReference(static_cast<nsIHttpChannel*>(this)));
pushCallback = [weakPtrThis](uint32_t aPushedStreamId,
const nsACString& aUrl,
const nsACString& aRequestString,
HttpTransactionShell* aTransaction) {
if (nsCOMPtr<nsIHttpChannel> channel = do_QueryReferent(weakPtrThis)) {
return static_cast<TRRServiceChannel*>(channel.get())
->OnPush(aPushedStreamId, aUrl, aRequestString, aTransaction);
}
return NS_ERROR_NOT_AVAILABLE;
};
}
EnsureRequestContext();
rv = mTransaction->Init(
mCaps, mConnectionInfo, &mRequestHead, mUploadStream, mReqContentLength,
LoadUploadStreamHasHeaders(), mCurrentEventTarget, callbacks, this,
mBrowserId, HttpTrafficCategory::eInvalid, mRequestContext,
mClassOfService, mInitialRwin, LoadResponseTimeoutEnabled(), mChannelId,
nullptr, std::move(pushCallback), mTransWithPushedStream,
mPushedStreamId);
mTransWithPushedStream = nullptr;
if (NS_FAILED(rv)) {
mTransaction = nullptr;
return rv;
}
return rv;
}
void TRRServiceChannel::SetPushedStreamTransactionAndId(
HttpTransactionShell* aTransWithPushedStream, uint32_t aPushedStreamId) {
MOZ_ASSERT(!mTransWithPushedStream);
LOG(("TRRServiceChannel::SetPushedStreamTransaction [this=%p] trans=%p", this,
aTransWithPushedStream));
mTransWithPushedStream = aTransWithPushedStream;
mPushedStreamId = aPushedStreamId;
}
nsresult TRRServiceChannel::OnPush(uint32_t aPushedStreamId,
const nsACString& aUrl,
const nsACString& aRequestString,
HttpTransactionShell* aTransaction) {
MOZ_ASSERT(aTransaction);
LOG(("TRRServiceChannel::OnPush [this=%p, trans=%p]\n", this, aTransaction));
MOZ_ASSERT(mCaps & NS_HTTP_ONPUSH_LISTENER);
nsCOMPtr<nsIHttpPushListener> pushListener;
NS_QueryNotificationCallbacks(mCallbacks, mLoadGroup,
NS_GET_IID(nsIHttpPushListener),
getter_AddRefs(pushListener));
if (!pushListener) {
LOG(
("TRRServiceChannel::OnPush [this=%p] notification callbacks do not "
"implement nsIHttpPushListener\n",
this));
return NS_ERROR_NOT_AVAILABLE;
}
nsCOMPtr<nsIURI> pushResource;
nsresult rv;
// Create a Channel for the Push Resource
rv = NS_NewURI(getter_AddRefs(pushResource), aUrl);
if (NS_FAILED(rv)) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsILoadInfo> loadInfo =
static_cast<TRRLoadInfo*>(mLoadInfo.get())->Clone();
nsCOMPtr<nsIChannel> pushHttpChannel;
rv = gHttpHandler->CreateTRRServiceChannel(pushResource, nullptr, 0, nullptr,
loadInfo,
getter_AddRefs(pushHttpChannel));
NS_ENSURE_SUCCESS(rv, rv);
rv = pushHttpChannel->SetLoadFlags(mLoadFlags);
NS_ENSURE_SUCCESS(rv, rv);
RefPtr<TRRServiceChannel> channel;
CallQueryInterface(pushHttpChannel, channel.StartAssignment());
MOZ_ASSERT(channel);
if (!channel) {
return NS_ERROR_UNEXPECTED;
}
// new channel needs mrqeuesthead and headers from pushedStream
channel->mRequestHead.ParseHeaderSet(aRequestString.BeginReading());
channel->mLoadGroup = mLoadGroup;
channel->mCallbacks = mCallbacks;
// Link the pushed stream with the new channel and call listener
channel->SetPushedStreamTransactionAndId(aTransaction, aPushedStreamId);
rv = pushListener->OnPush(this, channel);
return rv;
}
void TRRServiceChannel::MaybeStartDNSPrefetch() {
if (mConnectionInfo->UsingHttpProxy() ||
(mLoadFlags & (nsICachingChannel::LOAD_NO_NETWORK_IO |
nsICachingChannel::LOAD_ONLY_FROM_CACHE))) {
return;
}
LOG(
("TRRServiceChannel::MaybeStartDNSPrefetch [this=%p] "
"prefetching%s\n",
this, mCaps & NS_HTTP_REFRESH_DNS ? ", refresh requested" : ""));
OriginAttributes originAttributes;
mDNSPrefetch =
new nsDNSPrefetch(mURI, originAttributes, nsIRequest::GetTRRMode(), this,
LoadTimingEnabled());
nsIDNSService::DNSFlags dnsFlags = nsIDNSService::RESOLVE_DEFAULT_FLAGS;
if (mCaps & NS_HTTP_REFRESH_DNS) {
dnsFlags |= nsIDNSService::RESOLVE_BYPASS_CACHE;
}
nsresult rv = mDNSPrefetch->PrefetchHigh(dnsFlags);
NS_ENSURE_SUCCESS_VOID(rv);
}
NS_IMETHODIMP
TRRServiceChannel::OnTransportStatus(nsITransport* trans, nsresult status,
int64_t progress, int64_t progressMax) {
return NS_OK;
}
nsresult TRRServiceChannel::CallOnStartRequest() {
LOG(("TRRServiceChannel::CallOnStartRequest [this=%p]", this));
if (LoadOnStartRequestCalled()) {
LOG(("CallOnStartRequest already invoked before"));
return mStatus;
}
nsresult rv = NS_OK;
StoreTracingEnabled(false);
// Ensure mListener->OnStartRequest will be invoked before exiting
// this function.
auto onStartGuard = MakeScopeExit([&] {
LOG(
(" calling mListener->OnStartRequest by ScopeExit [this=%p, "
"listener=%p]\n",
this, mListener.get()));
MOZ_ASSERT(!LoadOnStartRequestCalled());
if (mListener) {
nsCOMPtr<nsIStreamListener> deleteProtector(mListener);
StoreOnStartRequestCalled(true);
deleteProtector->OnStartRequest(this);
}
StoreOnStartRequestCalled(true);
});
if (mResponseHead && !mResponseHead->HasContentCharset()) {
mResponseHead->SetContentCharset(mContentCharsetHint);
}
LOG((" calling mListener->OnStartRequest [this=%p, listener=%p]\n", this,
mListener.get()));
// About to call OnStartRequest, dismiss the guard object.
onStartGuard.release();
if (mListener) {
MOZ_ASSERT(!LoadOnStartRequestCalled(),
"We should not call OsStartRequest twice");
nsCOMPtr<nsIStreamListener> deleteProtector(mListener);
StoreOnStartRequestCalled(true);
rv = deleteProtector->OnStartRequest(this);
if (NS_FAILED(rv)) return rv;
} else {
NS_WARNING("OnStartRequest skipped because of null listener");
StoreOnStartRequestCalled(true);
}
if (!mResponseHead) {
return NS_OK;
}
nsAutoCString contentEncoding;
rv = mResponseHead->GetHeader(nsHttp::Content_Encoding, contentEncoding);
if (NS_FAILED(rv) || contentEncoding.IsEmpty()) {
return NS_OK;
}
// DoApplyContentConversions can only be called on the main thread.
if (NS_IsMainThread()) {
nsCOMPtr<nsIStreamListener> listener;
rv =
DoApplyContentConversions(mListener, getter_AddRefs(listener), nullptr);
if (NS_FAILED(rv)) {
return rv;
}
AfterApplyContentConversions(rv, listener);
return NS_OK;
}
Suspend();
RefPtr<TRRServiceChannel> self = this;
rv = NS_DispatchToMainThread(
NS_NewRunnableFunction("TRRServiceChannel::DoApplyContentConversions",
[self]() {
nsCOMPtr<nsIStreamListener> listener;
nsresult rv = self->DoApplyContentConversions(
self->mListener, getter_AddRefs(listener),
nullptr);
self->AfterApplyContentConversions(rv, listener);
}),
NS_DISPATCH_NORMAL);
if (NS_FAILED(rv)) {
Resume();
return rv;
}
return NS_OK;
}
void TRRServiceChannel::AfterApplyContentConversions(
nsresult aResult, nsIStreamListener* aListener) {
LOG(("TRRServiceChannel::AfterApplyContentConversions [this=%p]", this));
if (!mCurrentEventTarget->IsOnCurrentThread()) {
RefPtr<TRRServiceChannel> self = this;
nsCOMPtr<nsIStreamListener> listener = aListener;
self->mCurrentEventTarget->Dispatch(
NS_NewRunnableFunction(
"TRRServiceChannel::AfterApplyContentConversions",
[self, aResult, listener]() {
self->Resume();
self->AfterApplyContentConversions(aResult, listener);
}),
NS_DISPATCH_NORMAL);
return;
}
if (mCanceled) {
return;
}
if (NS_FAILED(aResult)) {
Unused << AsyncAbort(aResult);
return;
}
if (aListener) {
mListener = aListener;
mCompressListener = aListener;
StoreHasAppliedConversion(true);
}
}
void TRRServiceChannel::ProcessAltService() {
// e.g. Alt-Svc: h2=":443"; ma=60
// e.g. Alt-Svc: h2="otherhost:443"
// Alt-Svc = 1#( alternative *( OWS ";" OWS parameter ) )
// alternative = protocol-id "=" alt-authority
// protocol-id = token ; percent-encoded ALPN protocol identifier
// alt-authority = quoted-string ; containing [ uri-host ] ":" port
if (!LoadAllowAltSvc()) { // per channel opt out
return;
}
if (!gHttpHandler->AllowAltSvc() || (mCaps & NS_HTTP_DISALLOW_SPDY)) {
return;
}
nsCString scheme;
mURI->GetScheme(scheme);
bool isHttp = scheme.EqualsLiteral("http");
if (!isHttp && !scheme.EqualsLiteral("https")) {
return;
}
nsCString altSvc;
Unused << mResponseHead->GetHeader(nsHttp::Alternate_Service, altSvc);
if (altSvc.IsEmpty()) {
return;
}
if (!nsHttp::IsReasonableHeaderValue(altSvc)) {
LOG(("Alt-Svc Response Header seems unreasonable - skipping\n"));
return;
}
nsCString originHost;
int32_t originPort = 80;
mURI->GetPort(&originPort);
if (NS_FAILED(mURI->GetAsciiHost(originHost))) {
return;
}
nsCOMPtr<nsIInterfaceRequestor> callbacks;
nsCOMPtr<nsProxyInfo> proxyInfo;
NS_NewNotificationCallbacksAggregation(mCallbacks, mLoadGroup,
getter_AddRefs(callbacks));
if (mProxyInfo) {
proxyInfo = do_QueryInterface(mProxyInfo);
}
auto processHeaderTask = [altSvc, scheme, originHost, originPort,
userName(mUsername),
privateBrowsing(mPrivateBrowsing), callbacks,
proxyInfo, caps(mCaps)]() {
if (XRE_IsSocketProcess()) {
AltServiceChild::ProcessHeader(altSvc, scheme, originHost, originPort,
userName, privateBrowsing, callbacks,
proxyInfo, caps & NS_HTTP_DISALLOW_SPDY,
OriginAttributes());
return;
}
AltSvcMapping::ProcessHeader(
altSvc, scheme, originHost, originPort, userName, privateBrowsing,
callbacks, proxyInfo, caps & NS_HTTP_DISALLOW_SPDY, OriginAttributes());
};
if (NS_IsMainThread()) {
processHeaderTask();
return;
}
NS_DispatchToMainThread(NS_NewRunnableFunction(
"TRRServiceChannel::ProcessAltService", std::move(processHeaderTask)));
}
NS_IMETHODIMP
TRRServiceChannel::OnStartRequest(nsIRequest* request) {
LOG(("TRRServiceChannel::OnStartRequest [this=%p request=%p status=%" PRIx32
"]\n",
this, request, static_cast<uint32_t>(static_cast<nsresult>(mStatus))));
if (!(mCanceled || NS_FAILED(mStatus))) {
// capture the request's status, so our consumers will know ASAP of any
// connection failures, etc - bug 93581
nsresult status;
request->GetStatus(&status);
mStatus = status;
}
MOZ_ASSERT(request == mTransactionPump, "Unexpected request");
StoreAfterOnStartRequestBegun(true);
if (mTransaction) {
if (!mSecurityInfo) {
// grab the security info from the connection object; the transaction
// is guaranteed to own a reference to the connection.
mSecurityInfo = mTransaction->SecurityInfo();
}
}
if (NS_SUCCEEDED(mStatus) && mTransaction) {
// mTransactionPump doesn't hit OnInputStreamReady and call this until
// all of the response headers have been acquired, so we can take
// ownership of them from the transaction.
mResponseHead = mTransaction->TakeResponseHead();
if (mResponseHead) {
uint32_t httpStatus = mResponseHead->Status();
if (mTransaction->ProxyConnectFailed()) {
LOG(("TRRServiceChannel proxy connect failed httpStatus: %d",
httpStatus));
MOZ_ASSERT(mConnectionInfo->UsingConnect(),
"proxy connect failed but not using CONNECT?");
nsresult rv = HttpProxyResponseToErrorCode(httpStatus);
mTransaction->DontReuseConnection();
Cancel(rv);
return CallOnStartRequest();
}
if ((httpStatus < 500) && (httpStatus != 421) && (httpStatus != 407)) {
ProcessAltService();
}
if (httpStatus == 300 || httpStatus == 301 || httpStatus == 302 ||
httpStatus == 303 || httpStatus == 307 || httpStatus == 308) {
nsresult rv = SyncProcessRedirection(httpStatus);
if (NS_SUCCEEDED(rv)) {
return rv;
}
mStatus = rv;
DoNotifyListener();
return rv;
}
} else {
NS_WARNING("No response head in OnStartRequest");
}
}
// avoid crashing if mListener happens to be null...
if (!mListener) {
MOZ_ASSERT_UNREACHABLE("mListener is null");
return NS_OK;
}
return CallOnStartRequest();
}
nsresult TRRServiceChannel::SyncProcessRedirection(uint32_t aHttpStatus) {
nsAutoCString location;
// if a location header was not given, then we can't perform the redirect,
// so just carry on as though this were a normal response.
if (NS_FAILED(mResponseHead->GetHeader(nsHttp::Location, location))) {
return NS_ERROR_FAILURE;
}
// make sure non-ASCII characters in the location header are escaped.
nsAutoCString locationBuf;
if (NS_EscapeURL(location.get(), -1, esc_OnlyNonASCII | esc_Spaces,
locationBuf)) {
location = locationBuf;
}
LOG(("redirecting to: %s [redirection-limit=%u]\n", location.get(),
uint32_t(mRedirectionLimit)));
nsCOMPtr<nsIURI> redirectURI;
nsresult rv = NS_NewURI(getter_AddRefs(redirectURI), location);
if (NS_FAILED(rv)) {
LOG(("Invalid URI for redirect: Location: %s\n", location.get()));
return NS_ERROR_CORRUPTED_CONTENT;
}
// move the reference of the old location to the new one if the new
// one has none.
PropagateReferenceIfNeeded(mURI, redirectURI);
bool rewriteToGET =
ShouldRewriteRedirectToGET(aHttpStatus, mRequestHead.ParsedMethod());
// Let's not rewrite the method to GET for TRR requests.
if (rewriteToGET) {
return NS_ERROR_FAILURE;
}
// If the method is not safe (such as POST, PUT, DELETE, ...)
if (!mRequestHead.IsSafeMethod()) {
LOG(("TRRServiceChannel: unsafe redirect to:%s\n", location.get()));
}
uint32_t redirectFlags;
if (nsHttp::IsPermanentRedirect(aHttpStatus)) {
redirectFlags = nsIChannelEventSink::REDIRECT_PERMANENT;
} else {
redirectFlags = nsIChannelEventSink::REDIRECT_TEMPORARY;
}
nsCOMPtr<nsIChannel> newChannel;
nsCOMPtr<nsILoadInfo> redirectLoadInfo =
static_cast<TRRLoadInfo*>(mLoadInfo.get())->Clone();
rv = gHttpHandler->CreateTRRServiceChannel(redirectURI, nullptr, 0, nullptr,
redirectLoadInfo,
getter_AddRefs(newChannel));
if (NS_FAILED(rv)) {
return rv;
}
rv = SetupReplacementChannel(redirectURI, newChannel, !rewriteToGET,
redirectFlags);
if (NS_FAILED(rv)) {
return rv;
}
// Make sure to do this after we received redirect veto answer,
// i.e. after all sinks had been notified
newChannel->SetOriginalURI(mOriginalURI);
rv = newChannel->AsyncOpen(mListener);
LOG((" new channel AsyncOpen returned %" PRIX32, static_cast<uint32_t>(rv)));
// close down this channel
Cancel(NS_BINDING_REDIRECTED);
ReleaseListeners();
return NS_OK;
}
nsresult TRRServiceChannel::SetupReplacementChannel(nsIURI* aNewURI,
nsIChannel* aNewChannel,
bool aPreserveMethod,
uint32_t aRedirectFlags) {
LOG(
("TRRServiceChannel::SetupReplacementChannel "
"[this=%p newChannel=%p preserveMethod=%d]",
this, aNewChannel, aPreserveMethod));
nsresult rv = HttpBaseChannel::SetupReplacementChannel(
aNewURI, aNewChannel, aPreserveMethod, aRedirectFlags);
if (NS_FAILED(rv)) {
return rv;
}
rv = CheckRedirectLimit(aRedirectFlags);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(aNewChannel);
if (!httpChannel) {
MOZ_ASSERT(false);
return NS_ERROR_FAILURE;
}
// convey the ApplyConversion flag (bug 91862)
nsCOMPtr<nsIEncodedChannel> encodedChannel = do_QueryInterface(httpChannel);
if (encodedChannel) {
encodedChannel->SetApplyConversion(LoadApplyConversion());
}
if (mContentTypeHint.IsEmpty()) {
return NS_OK;
}
// Make sure we set content-type on the old channel properly.
MOZ_ASSERT(mContentTypeHint.Equals("application/dns-message"));
// Apply TRR specific settings. Note that we already know mContentTypeHint is
// "application/dns-message" here.
return TRR::SetupTRRServiceChannelInternal(
httpChannel,
mRequestHead.ParsedMethod() == nsHttpRequestHead::kMethod_Get,
mContentTypeHint);
}
NS_IMETHODIMP
TRRServiceChannel::OnDataAvailable(nsIRequest* request, nsIInputStream* input,
uint64_t offset, uint32_t count) {
LOG(("TRRServiceChannel::OnDataAvailable [this=%p request=%p offset=%" PRIu64
" count=%" PRIu32 "]\n",
this, request, offset, count));
// don't send out OnDataAvailable notifications if we've been canceled.
if (mCanceled) return mStatus;
MOZ_ASSERT(mResponseHead, "No response head in ODA!!");
if (mListener) {
return mListener->OnDataAvailable(this, input, offset, count);
}
return NS_ERROR_ABORT;
}
NS_IMETHODIMP
TRRServiceChannel::OnStopRequest(nsIRequest* request, nsresult status) {
LOG(("TRRServiceChannel::OnStopRequest [this=%p request=%p status=%" PRIx32
"]\n",
this, request, static_cast<uint32_t>(status)));
if (mCanceled || NS_FAILED(mStatus)) status = mStatus;
mTransactionTimings = mTransaction->Timings();
mTransaction = nullptr;
mTransactionPump = nullptr;
if (mListener) {
LOG(("TRRServiceChannel %p calling OnStopRequest\n", this));
MOZ_ASSERT(LoadOnStartRequestCalled(),
"OnStartRequest should be called before OnStopRequest");
MOZ_ASSERT(!LoadOnStopRequestCalled(),
"We should not call OnStopRequest twice");
StoreOnStopRequestCalled(true);
mListener->OnStopRequest(this, status);
}
StoreOnStopRequestCalled(true);
mDNSPrefetch = nullptr;
if (mLoadGroup) {
mLoadGroup->RemoveRequest(this, nullptr, status);
}
ReleaseListeners();
return NS_OK;
}
NS_IMETHODIMP
TRRServiceChannel::OnLookupComplete(nsICancelable* request, nsIDNSRecord* rec,
nsresult status) {
LOG(
("TRRServiceChannel::OnLookupComplete [this=%p] prefetch complete%s: "
"%s status[0x%" PRIx32 "]\n",
this, mCaps & NS_HTTP_REFRESH_DNS ? ", refresh requested" : "",
NS_SUCCEEDED(status) ? "success" : "failure",
static_cast<uint32_t>(status)));
// We no longer need the dns prefetch object. Note: mDNSPrefetch could be
// validly null if OnStopRequest has already been called.
// We only need the domainLookup timestamps when not loading from cache
if (mDNSPrefetch && mDNSPrefetch->TimingsValid() && mTransaction) {
TimeStamp connectStart = mTransaction->GetConnectStart();
TimeStamp requestStart = mTransaction->GetRequestStart();
// We only set the domainLookup timestamps if we're not using a
// persistent connection.
if (requestStart.IsNull() && connectStart.IsNull()) {
mTransaction->SetDomainLookupStart(mDNSPrefetch->StartTimestamp());
mTransaction->SetDomainLookupEnd(mDNSPrefetch->EndTimestamp());
}
}
mDNSPrefetch = nullptr;
// Unset DNS cache refresh if it was requested,
if (mCaps & NS_HTTP_REFRESH_DNS) {
mCaps &= ~NS_HTTP_REFRESH_DNS;
if (mTransaction) {
mTransaction->SetDNSWasRefreshed();
}
}
return NS_OK;
}
NS_IMETHODIMP
TRRServiceChannel::LogBlockedCORSRequest(const nsAString& aMessage,
const nsACString& aCategory,
bool aIsWarning) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
TRRServiceChannel::LogMimeTypeMismatch(const nsACString& aMessageName,
bool aWarning, const nsAString& aURL,
const nsAString& aContentType) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
TRRServiceChannel::GetIsAuthChannel(bool* aIsAuthChannel) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
TRRServiceChannel::SetNotificationCallbacks(nsIInterfaceRequestor* aCallbacks) {
mCallbacks = aCallbacks;
return NS_OK;
}
NS_IMETHODIMP
TRRServiceChannel::SetPriority(int32_t value) {
return NS_ERROR_NOT_IMPLEMENTED;
}
void TRRServiceChannel::OnClassOfServiceUpdated() {
LOG(("TRRServiceChannel::OnClassOfServiceUpdated this=%p, cos=%lu inc=%d",
this, mClassOfService.Flags(), mClassOfService.Incremental()));
if (mTransaction) {
gHttpHandler->UpdateClassOfServiceOnTransaction(mTransaction,
mClassOfService);
}
}
NS_IMETHODIMP
TRRServiceChannel::SetClassFlags(uint32_t inFlags) {
uint32_t previous = mClassOfService.Flags();
mClassOfService.SetFlags(inFlags);
if (previous != mClassOfService.Flags()) {
OnClassOfServiceUpdated();
}
return NS_OK;
}
NS_IMETHODIMP
TRRServiceChannel::SetIncremental(bool inFlag) {
bool previous = mClassOfService.Incremental();
mClassOfService.SetIncremental(inFlag);
if (previous != mClassOfService.Incremental()) {
OnClassOfServiceUpdated();
}
return NS_OK;
}
NS_IMETHODIMP
TRRServiceChannel::SetClassOfService(ClassOfService cos) {
ClassOfService previous = mClassOfService;
mClassOfService = cos;
if (previous != mClassOfService) {
OnClassOfServiceUpdated();
}
return NS_OK;
}
NS_IMETHODIMP
TRRServiceChannel::AddClassFlags(uint32_t inFlags) {
uint32_t previous = mClassOfService.Flags();
mClassOfService.SetFlags(inFlags | mClassOfService.Flags());
if (previous != mClassOfService.Flags()) {
OnClassOfServiceUpdated();
}
return NS_OK;
}
NS_IMETHODIMP
TRRServiceChannel::ClearClassFlags(uint32_t inFlags) {
uint32_t previous = mClassOfService.Flags();
mClassOfService.SetFlags(~inFlags & mClassOfService.Flags());
if (previous != mClassOfService.Flags()) {
OnClassOfServiceUpdated();
}
return NS_OK;
}
NS_IMETHODIMP
TRRServiceChannel::ResumeAt(uint64_t aStartPos, const nsACString& aEntityID) {
return NS_ERROR_NOT_IMPLEMENTED;
}
void TRRServiceChannel::DoAsyncAbort(nsresult aStatus) {
Unused << AsyncAbort(aStatus);
}
NS_IMETHODIMP
TRRServiceChannel::GetProxyInfo(nsIProxyInfo** result) {
if (!mConnectionInfo) {
*result = do_AddRef(mProxyInfo).take();
} else {
*result = do_AddRef(mConnectionInfo->ProxyInfo()).take();
}
return NS_OK;
}
NS_IMETHODIMP TRRServiceChannel::GetHttpProxyConnectResponseCode(
int32_t* aResponseCode) {
NS_ENSURE_ARG_POINTER(aResponseCode);
*aResponseCode = -1;
return NS_OK;
}
NS_IMETHODIMP
TRRServiceChannel::GetLoadFlags(nsLoadFlags* aLoadFlags) {
return HttpBaseChannel::GetLoadFlags(aLoadFlags);
}
NS_IMETHODIMP
TRRServiceChannel::SetLoadFlags(nsLoadFlags aLoadFlags) {
if (aLoadFlags & (nsICachingChannel::LOAD_ONLY_FROM_CACHE | LOAD_FROM_CACHE |
nsICachingChannel::LOAD_NO_NETWORK_IO)) {
MOZ_ASSERT(false, "Wrong load flags!");
return NS_ERROR_FAILURE;
}
return HttpBaseChannel::SetLoadFlags(aLoadFlags);
}
NS_IMETHODIMP
TRRServiceChannel::GetURI(nsIURI** aURI) {
return HttpBaseChannel::GetURI(aURI);
}
NS_IMETHODIMP
TRRServiceChannel::GetNotificationCallbacks(
nsIInterfaceRequestor** aCallbacks) {
return HttpBaseChannel::GetNotificationCallbacks(aCallbacks);
}
NS_IMETHODIMP
TRRServiceChannel::GetLoadGroup(nsILoadGroup** aLoadGroup) {
return HttpBaseChannel::GetLoadGroup(aLoadGroup);
}
NS_IMETHODIMP
TRRServiceChannel::GetRequestMethod(nsACString& aMethod) {
return HttpBaseChannel::GetRequestMethod(aMethod);
}
void TRRServiceChannel::DoNotifyListener() {
LOG(("TRRServiceChannel::DoNotifyListener this=%p", this));
// In case nsHttpChannel::OnStartRequest wasn't called (e.g. due to flag
// LOAD_ONLY_IF_MODIFIED) we want to set AfterOnStartRequestBegun to true
// before notifying listener.
if (!LoadAfterOnStartRequestBegun()) {
StoreAfterOnStartRequestBegun(true);
}
if (mListener && !LoadOnStartRequestCalled()) {
nsCOMPtr<nsIStreamListener> listener = mListener;
StoreOnStartRequestCalled(true);
listener->OnStartRequest(this);
}
StoreOnStartRequestCalled(true);
// Make sure IsPending is set to false. At this moment we are done from
// the point of view of our consumer and we have to report our self
// as not-pending.
StoreIsPending(false);
if (mListener && !LoadOnStopRequestCalled()) {
nsCOMPtr<nsIStreamListener> listener = mListener;
StoreOnStopRequestCalled(true);
listener->OnStopRequest(this, mStatus);
}
StoreOnStopRequestCalled(true);
// We have to make sure to drop the references to listeners and callbacks
// no longer needed.
ReleaseListeners();
DoNotifyListenerCleanup();
}
void TRRServiceChannel::DoNotifyListenerCleanup() {}
NS_IMETHODIMP
TRRServiceChannel::GetDomainLookupStart(TimeStamp* _retval) {
if (mTransaction) {
*_retval = mTransaction->GetDomainLookupStart();
} else {
*_retval = mTransactionTimings.domainLookupStart;
}
return NS_OK;
}
NS_IMETHODIMP
TRRServiceChannel::GetDomainLookupEnd(TimeStamp* _retval) {
if (mTransaction) {
*_retval = mTransaction->GetDomainLookupEnd();
} else {
*_retval = mTransactionTimings.domainLookupEnd;
}
return NS_OK;
}
NS_IMETHODIMP
TRRServiceChannel::GetConnectStart(TimeStamp* _retval) {
if (mTransaction) {
*_retval = mTransaction->GetConnectStart();
} else {
*_retval = mTransactionTimings.connectStart;
}
return NS_OK;
}
NS_IMETHODIMP
TRRServiceChannel::GetTcpConnectEnd(TimeStamp* _retval) {
if (mTransaction) {
*_retval = mTransaction->GetTcpConnectEnd();
} else {
*_retval = mTransactionTimings.tcpConnectEnd;
}
return NS_OK;
}
NS_IMETHODIMP
TRRServiceChannel::GetSecureConnectionStart(TimeStamp* _retval) {
if (mTransaction) {
*_retval = mTransaction->GetSecureConnectionStart();
} else {
*_retval = mTransactionTimings.secureConnectionStart;
}
return NS_OK;
}
NS_IMETHODIMP
TRRServiceChannel::GetConnectEnd(TimeStamp* _retval) {
if (mTransaction) {
*_retval = mTransaction->GetConnectEnd();
} else {
*_retval = mTransactionTimings.connectEnd;
}
return NS_OK;
}
NS_IMETHODIMP
TRRServiceChannel::GetRequestStart(TimeStamp* _retval) {
if (mTransaction) {
*_retval = mTransaction->GetRequestStart();
} else {
*_retval = mTransactionTimings.requestStart;
}
return NS_OK;
}
NS_IMETHODIMP
TRRServiceChannel::GetResponseStart(TimeStamp* _retval) {
if (mTransaction) {
*_retval = mTransaction->GetResponseStart();
} else {
*_retval = mTransactionTimings.responseStart;
}
return NS_OK;
}
NS_IMETHODIMP
TRRServiceChannel::GetResponseEnd(TimeStamp* _retval) {
if (mTransaction) {
*_retval = mTransaction->GetResponseEnd();
} else {
*_retval = mTransactionTimings.responseEnd;
}
return NS_OK;
}
NS_IMETHODIMP TRRServiceChannel::SetLoadGroup(nsILoadGroup* aLoadGroup) {
return NS_OK;
}
NS_IMETHODIMP
TRRServiceChannel::TimingAllowCheck(nsIPrincipal* aOrigin, bool* aResult) {
NS_ENSURE_ARG_POINTER(aResult);
*aResult = true;
return NS_OK;
}
bool TRRServiceChannel::SameOriginWithOriginalUri(nsIURI* aURI) { return true; }
} // namespace mozilla::net
|