summaryrefslogtreecommitdiffstats
path: root/netwerk/base/nsProtocolProxyService.cpp
blob: fdfe24cc4a8a2a0fe48f14b2d8fe11794e575747 (plain)
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
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=4 sw=2 sts=2 et: */
/* 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 "mozilla/ArrayUtils.h"
#include "mozilla/Attributes.h"
#include "mozilla/AutoRestore.h"

#include "nsProtocolProxyService.h"
#include "nsProxyInfo.h"
#include "nsIClassInfoImpl.h"
#include "nsIIOService.h"
#include "nsIObserverService.h"
#include "nsIProtocolHandler.h"
#include "nsIProtocolProxyCallback.h"
#include "nsIChannel.h"
#include "nsICancelable.h"
#include "nsIDNSService.h"
#include "nsPIDNSService.h"
#include "nsIPrefBranch.h"
#include "nsIPrefService.h"
#include "nsContentUtils.h"
#include "nsThreadUtils.h"
#include "nsQueryObject.h"
#include "nsSOCKSIOLayer.h"
#include "nsString.h"
#include "nsNetUtil.h"
#include "nsNetCID.h"
#include "plstr.h"
#include "prnetdb.h"
#include "nsPACMan.h"
#include "nsProxyRelease.h"
#include "mozilla/Mutex.h"
#include "mozilla/CondVar.h"
#include "nsISystemProxySettings.h"
#include "nsINetworkLinkService.h"
#include "nsIHttpChannelInternal.h"
#include "mozilla/dom/nsMixedContentBlocker.h"
#include "mozilla/Logging.h"
#include "mozilla/StaticPrefs_network.h"
#include "mozilla/Tokenizer.h"
#include "mozilla/Unused.h"

//----------------------------------------------------------------------------

namespace mozilla {
namespace net {

extern const char kProxyType_HTTP[];
extern const char kProxyType_HTTPS[];
extern const char kProxyType_SOCKS[];
extern const char kProxyType_SOCKS4[];
extern const char kProxyType_SOCKS5[];
extern const char kProxyType_DIRECT[];

#undef LOG
#define LOG(args) MOZ_LOG(gProxyLog, LogLevel::Debug, args)

//----------------------------------------------------------------------------

#define PROXY_PREF_BRANCH "network.proxy"
#define PROXY_PREF(x) PROXY_PREF_BRANCH "." x

//----------------------------------------------------------------------------

// This structure is intended to be allocated on the stack
struct nsProtocolInfo {
  nsAutoCString scheme;
  uint32_t flags;
  int32_t defaultPort;
};

//----------------------------------------------------------------------------

// Return the channel's proxy URI, or if it doesn't exist, the
// channel's main URI.
static nsresult GetProxyURI(nsIChannel* channel, nsIURI** aOut) {
  nsresult rv = NS_OK;
  nsCOMPtr<nsIURI> proxyURI;
  nsCOMPtr<nsIHttpChannelInternal> httpChannel(do_QueryInterface(channel));
  if (httpChannel) {
    rv = httpChannel->GetProxyURI(getter_AddRefs(proxyURI));
  }
  if (!proxyURI) {
    rv = channel->GetURI(getter_AddRefs(proxyURI));
  }
  if (NS_FAILED(rv)) {
    return rv;
  }
  proxyURI.forget(aOut);
  return NS_OK;
}

//-----------------------------------------------------------------------------

nsProtocolProxyService::FilterLink::FilterLink(uint32_t p,
                                               nsIProtocolProxyFilter* f)
    : position(p), filter(f), channelFilter(nullptr) {
  LOG(("nsProtocolProxyService::FilterLink::FilterLink %p, filter=%p", this,
       f));
}
nsProtocolProxyService::FilterLink::FilterLink(
    uint32_t p, nsIProtocolProxyChannelFilter* cf)
    : position(p), filter(nullptr), channelFilter(cf) {
  LOG(("nsProtocolProxyService::FilterLink::FilterLink %p, channel-filter=%p",
       this, cf));
}

nsProtocolProxyService::FilterLink::~FilterLink() {
  LOG(("nsProtocolProxyService::FilterLink::~FilterLink %p", this));
}

//-----------------------------------------------------------------------------

// The nsPACManCallback portion of this implementation should be run
// on the main thread - so call nsPACMan::AsyncGetProxyForURI() with
// a true mainThreadResponse parameter.
class nsAsyncResolveRequest final : public nsIRunnable,
                                    public nsPACManCallback,
                                    public nsICancelable {
 public:
  NS_DECL_THREADSAFE_ISUPPORTS

  nsAsyncResolveRequest(nsProtocolProxyService* pps, nsIChannel* channel,
                        uint32_t aResolveFlags,
                        nsIProtocolProxyCallback* callback)
      : mStatus(NS_OK),
        mDispatched(false),
        mResolveFlags(aResolveFlags),
        mPPS(pps),
        mXPComPPS(pps),
        mChannel(channel),
        mCallback(callback) {
    NS_ASSERTION(mCallback, "null callback");
  }

 private:
  ~nsAsyncResolveRequest() {
    if (!NS_IsMainThread()) {
      // these xpcom pointers might need to be proxied back to the
      // main thread to delete safely, but if this request had its
      // callbacks called normally they will all be null and this is a nop

      if (mChannel) {
        NS_ReleaseOnMainThread("nsAsyncResolveRequest::mChannel",
                               mChannel.forget());
      }

      if (mCallback) {
        NS_ReleaseOnMainThread("nsAsyncResolveRequest::mCallback",
                               mCallback.forget());
      }

      if (mProxyInfo) {
        NS_ReleaseOnMainThread("nsAsyncResolveRequest::mProxyInfo",
                               mProxyInfo.forget());
      }

      if (mXPComPPS) {
        NS_ReleaseOnMainThread("nsAsyncResolveRequest::mXPComPPS",
                               mXPComPPS.forget());
      }
    }
  }

  // Helper class to loop over all registered asynchronous filters.
  // There is a cycle between nsAsyncResolveRequest and this class that
  // is broken after the last filter has called back on this object.
  class AsyncApplyFilters final : public nsIProxyProtocolFilterResult,
                                  public nsIRunnable,
                                  public nsICancelable {
    // The reference counter is thread-safe, but the processing logic is
    // considered single thread only.  We want the counter be thread safe,
    // since this class can be released on a background thread.
    NS_DECL_THREADSAFE_ISUPPORTS
    NS_DECL_NSIPROXYPROTOCOLFILTERRESULT
    NS_DECL_NSIRUNNABLE
    NS_DECL_NSICANCELABLE

    typedef std::function<nsresult(nsAsyncResolveRequest*, nsIProxyInfo*, bool)>
        Callback;

    explicit AsyncApplyFilters(nsProtocolInfo& aInfo,
                               Callback const& aCallback);
    // This method starts the processing or filters.  If all of them
    // answer synchronously (call back from within applyFilters) this method
    // will return immediately and the returning result will carry return
    // result of the callback given in constructor.
    // This method is looping the registered filters (that have been copied
    // locally) as long as an answer from a filter is obtained synchronously.
    // Note that filters are processed serially to let them build a list
    // of proxy info.
    nsresult AsyncProcess(nsAsyncResolveRequest* aRequest);

   private:
    typedef nsProtocolProxyService::FilterLink FilterLink;

    virtual ~AsyncApplyFilters();
    // Processes the next filter and loops until a filter is successfully
    // called on or it has called back to us.
    nsresult ProcessNextFilter();
    // Called after the last filter has been processed (=called back or failed
    // to be called on)
    nsresult Finish();

    nsProtocolInfo mInfo;
    // This is nullified before we call back on the request or when
    // Cancel() on this object has been called to break the cycle
    // and signal to stop.
    RefPtr<nsAsyncResolveRequest> mRequest;
    Callback mCallback;
    // A shallow snapshot of filters as they were registered at the moment
    // we started to process filters for the given resolve request.
    nsTArray<RefPtr<FilterLink>> mFiltersCopy;

    nsTArray<RefPtr<FilterLink>>::index_type mNextFilterIndex;
    // true when we are calling ProcessNextFilter() from inside AsyncProcess(),
    // false otherwise.
    bool mProcessingInLoop;
    // true after a filter called back to us with a result, dropped to false
    // just before we call a filter.
    bool mFilterCalledBack;

    // This keeps the initial value we pass to the first filter in line and also
    // collects the result from each filter call.
    nsCOMPtr<nsIProxyInfo> mProxyInfo;

    // The logic is written as non-thread safe, assert single-thread usage.
    nsCOMPtr<nsISerialEventTarget> mProcessingThread;
  };

  void EnsureResolveFlagsMatch() {
    nsCOMPtr<nsIProxyInfo> proxyInfo = mProxyInfo;
    while (proxyInfo) {
      proxyInfo->SetResolveFlags(mResolveFlags);
      proxyInfo->GetFailoverProxy(getter_AddRefs(proxyInfo));
    }
  }

 public:
  nsresult ProcessLocally(nsProtocolInfo& info, nsIProxyInfo* pi,
                          bool isSyncOK) {
    SetResult(NS_OK, pi);

    auto consumeFiltersResult = [isSyncOK](nsAsyncResolveRequest* ctx,
                                           nsIProxyInfo* pi,
                                           bool aCalledAsync) -> nsresult {
      ctx->SetResult(NS_OK, pi);
      if (isSyncOK || aCalledAsync) {
        ctx->Run();
        return NS_OK;
      }

      return ctx->DispatchCallback();
    };

    mAsyncFilterApplier = new AsyncApplyFilters(info, consumeFiltersResult);
    // may call consumeFiltersResult() directly
    return mAsyncFilterApplier->AsyncProcess(this);
  }

  void SetResult(nsresult status, nsIProxyInfo* pi) {
    mStatus = status;
    mProxyInfo = pi;
  }

  NS_IMETHOD Run() override {
    if (mCallback) DoCallback();
    return NS_OK;
  }

  NS_IMETHOD Cancel(nsresult reason) override {
    NS_ENSURE_ARG(NS_FAILED(reason));

    if (mAsyncFilterApplier) {
      mAsyncFilterApplier->Cancel(reason);
    }

    // If we've already called DoCallback then, nothing more to do.
    if (!mCallback) return NS_OK;

    SetResult(reason, nullptr);
    return DispatchCallback();
  }

  nsresult DispatchCallback() {
    if (mDispatched)  // Only need to dispatch once
      return NS_OK;

    nsresult rv = NS_DispatchToCurrentThread(this);
    if (NS_FAILED(rv))
      NS_WARNING("unable to dispatch callback event");
    else {
      mDispatched = true;
      return NS_OK;
    }

    mCallback = nullptr;  // break possible reference cycle
    return rv;
  }

 private:
  // Called asynchronously, so we do not need to post another PLEvent
  // before calling DoCallback.
  void OnQueryComplete(nsresult status, const nsACString& pacString,
                       const nsACString& newPACURL) override {
    // If we've already called DoCallback then, nothing more to do.
    if (!mCallback) return;

    // Provided we haven't been canceled...
    if (mStatus == NS_OK) {
      mStatus = status;
      mPACString = pacString;
      mPACURL = newPACURL;
    }

    // In the cancelation case, we may still have another PLEvent in
    // the queue that wants to call DoCallback.  No need to wait for
    // it, just run the callback now.
    DoCallback();
  }

  void DoCallback() {
    bool pacAvailable = true;
    if (mStatus == NS_ERROR_NOT_AVAILABLE && !mProxyInfo) {
      // If the PAC service is not avail (e.g. failed pac load
      // or shutdown) then we will be going direct. Make that
      // mapping now so that any filters are still applied.
      mPACString = "DIRECT;"_ns;
      mStatus = NS_OK;

      LOG(("pac not available, use DIRECT\n"));
      pacAvailable = false;
    }

    // Generate proxy info from the PAC string if appropriate
    if (NS_SUCCEEDED(mStatus) && !mProxyInfo && !mPACString.IsEmpty()) {
      mPPS->ProcessPACString(mPACString, mResolveFlags,
                             getter_AddRefs(mProxyInfo));
      nsCOMPtr<nsIURI> proxyURI;
      GetProxyURI(mChannel, getter_AddRefs(proxyURI));

      // Now apply proxy filters
      nsProtocolInfo info;
      mStatus = mPPS->GetProtocolInfo(proxyURI, &info);

      auto consumeFiltersResult = [pacAvailable](nsAsyncResolveRequest* self,
                                                 nsIProxyInfo* pi,
                                                 bool async) -> nsresult {
        LOG(("DoCallback::consumeFiltersResult this=%p, pi=%p, async=%d", self,
             pi, async));

        self->mProxyInfo = pi;

        if (pacAvailable) {
          // if !pacAvailable, it was already logged above
          LOG(("pac thread callback %s\n", self->mPACString.get()));
        }

        if (NS_SUCCEEDED(self->mStatus)) {
          self->mPPS->MaybeDisableDNSPrefetch(self->mProxyInfo);
        }

        self->EnsureResolveFlagsMatch();
        self->mCallback->OnProxyAvailable(self, self->mChannel,
                                          self->mProxyInfo, self->mStatus);

        return NS_OK;
      };

      if (NS_SUCCEEDED(mStatus)) {
        mAsyncFilterApplier = new AsyncApplyFilters(info, consumeFiltersResult);
        // This may call consumeFiltersResult() directly.
        mAsyncFilterApplier->AsyncProcess(this);
        return;
      }

      consumeFiltersResult(this, nullptr, false);
    } else if (NS_SUCCEEDED(mStatus) && !mPACURL.IsEmpty()) {
      LOG(("pac thread callback indicates new pac file load\n"));

      nsCOMPtr<nsIURI> proxyURI;
      GetProxyURI(mChannel, getter_AddRefs(proxyURI));

      // trigger load of new pac url
      nsresult rv = mPPS->ConfigureFromPAC(mPACURL, false);
      if (NS_SUCCEEDED(rv)) {
        // now that the load is triggered, we can resubmit the query
        RefPtr<nsAsyncResolveRequest> newRequest =
            new nsAsyncResolveRequest(mPPS, mChannel, mResolveFlags, mCallback);
        rv = mPPS->mPACMan->AsyncGetProxyForURI(proxyURI, newRequest,
                                                mResolveFlags, true);
      }

      if (NS_FAILED(rv))
        mCallback->OnProxyAvailable(this, mChannel, nullptr, rv);

      // do not call onproxyavailable() in SUCCESS case - the newRequest will
      // take care of that
    } else {
      LOG(("pac thread callback did not provide information %" PRIX32 "\n",
           static_cast<uint32_t>(mStatus)));
      if (NS_SUCCEEDED(mStatus)) mPPS->MaybeDisableDNSPrefetch(mProxyInfo);
      EnsureResolveFlagsMatch();
      mCallback->OnProxyAvailable(this, mChannel, mProxyInfo, mStatus);
    }

    // We are on the main thread now and don't need these any more so
    // release them to avoid having to proxy them back to the main thread
    // in the dtor
    mCallback = nullptr;  // in case the callback holds an owning ref to us
    mPPS = nullptr;
    mXPComPPS = nullptr;
    mChannel = nullptr;
    mProxyInfo = nullptr;
  }

 private:
  nsresult mStatus;
  nsCString mPACString;
  nsCString mPACURL;
  bool mDispatched;
  uint32_t mResolveFlags;

  nsProtocolProxyService* mPPS;
  nsCOMPtr<nsIProtocolProxyService> mXPComPPS;
  nsCOMPtr<nsIChannel> mChannel;
  nsCOMPtr<nsIProtocolProxyCallback> mCallback;
  nsCOMPtr<nsIProxyInfo> mProxyInfo;

  RefPtr<AsyncApplyFilters> mAsyncFilterApplier;
};

NS_IMPL_ISUPPORTS(nsAsyncResolveRequest, nsICancelable, nsIRunnable)

NS_IMPL_ISUPPORTS(nsAsyncResolveRequest::AsyncApplyFilters,
                  nsIProxyProtocolFilterResult, nsICancelable, nsIRunnable)

nsAsyncResolveRequest::AsyncApplyFilters::AsyncApplyFilters(
    nsProtocolInfo& aInfo, Callback const& aCallback)
    : mInfo(aInfo),
      mCallback(aCallback),
      mNextFilterIndex(0),
      mProcessingInLoop(false),
      mFilterCalledBack(false) {
  LOG(("AsyncApplyFilters %p", this));
}

nsAsyncResolveRequest::AsyncApplyFilters::~AsyncApplyFilters() {
  LOG(("~AsyncApplyFilters %p", this));

  MOZ_ASSERT(!mRequest);
  MOZ_ASSERT(!mProxyInfo);
  MOZ_ASSERT(!mFiltersCopy.Length());
}

nsresult nsAsyncResolveRequest::AsyncApplyFilters::AsyncProcess(
    nsAsyncResolveRequest* aRequest) {
  LOG(("AsyncApplyFilters::AsyncProcess %p for req %p", this, aRequest));

  MOZ_ASSERT(!mRequest, "AsyncApplyFilters started more than once!");

  if (!(mInfo.flags & nsIProtocolHandler::ALLOWS_PROXY)) {
    // Calling the callback directly (not via Finish()) since we
    // don't want to prune.
    return mCallback(aRequest, aRequest->mProxyInfo, false);
  }

  mProcessingThread = NS_GetCurrentThread();

  mRequest = aRequest;
  mProxyInfo = aRequest->mProxyInfo;

  aRequest->mPPS->CopyFilters(mFiltersCopy);

  // We want to give filters a chance to process in a single loop to prevent
  // any current-thread dispatch delays when those are not needed.
  // This code is rather "loopy" than "recursive" to prevent long stack traces.
  do {
    MOZ_ASSERT(!mProcessingInLoop);

    mozilla::AutoRestore<bool> restore(mProcessingInLoop);
    mProcessingInLoop = true;

    nsresult rv = ProcessNextFilter();
    if (NS_FAILED(rv)) {
      return rv;
    }
  } while (mFilterCalledBack);

  return NS_OK;
}

nsresult nsAsyncResolveRequest::AsyncApplyFilters::ProcessNextFilter() {
  LOG(("AsyncApplyFilters::ProcessNextFilter %p ENTER pi=%p", this,
       mProxyInfo.get()));

  RefPtr<FilterLink> filter;
  do {
    mFilterCalledBack = false;

    if (!mRequest) {
      // We got canceled
      LOG(("  canceled"));
      return NS_OK;  // should we let the consumer know?
    }

    if (mNextFilterIndex == mFiltersCopy.Length()) {
      return Finish();
    }

    filter = mFiltersCopy[mNextFilterIndex++];

    // Loop until a call to a filter succeeded.  Other option is to recurse
    // but that would waste stack trace when a number of filters gets registered
    // and all from some reason tend to fail.
    // The !mFilterCalledBack part of the condition is there to protect us from
    // calling on another filter when the current one managed to call back and
    // then threw. We already have the result so take it and use it since
    // the next filter will be processed by the root loop or a call to
    // ProcessNextFilter has already been dispatched to this thread.
    LOG(("  calling filter %p pi=%p", filter.get(), mProxyInfo.get()));
  } while (!mRequest->mPPS->ApplyFilter(filter, mRequest->mChannel, mInfo,
                                        mProxyInfo, this) &&
           !mFilterCalledBack);

  LOG(("AsyncApplyFilters::ProcessNextFilter %p LEAVE pi=%p", this,
       mProxyInfo.get()));
  return NS_OK;
}

NS_IMETHODIMP
nsAsyncResolveRequest::AsyncApplyFilters::OnProxyFilterResult(
    nsIProxyInfo* aProxyInfo) {
  LOG(("AsyncApplyFilters::OnProxyFilterResult %p pi=%p", this, aProxyInfo));

  MOZ_ASSERT(mProcessingThread && mProcessingThread->IsOnCurrentThread());
  MOZ_ASSERT(!mFilterCalledBack);

  if (mFilterCalledBack) {
    LOG(("  duplicate notification?"));
    return NS_OK;
  }

  mFilterCalledBack = true;

  if (!mRequest) {
    // We got canceled
    LOG(("  canceled"));
    return NS_OK;
  }

  mProxyInfo = aProxyInfo;

  if (mProcessingInLoop) {
    // No need to call/dispatch ProcessNextFilter(), we are in a control
    // loop that will do this for us and save recursion/dispatching.
    LOG(("  in a root loop"));
    return NS_OK;
  }

  if (mNextFilterIndex == mFiltersCopy.Length()) {
    // We are done, all filters have been called on!
    Finish();
    return NS_OK;
  }

  // Redispatch, since we don't want long stacks when filters respond
  // synchronously.
  LOG(("  redispatching"));
  NS_DispatchToCurrentThread(this);
  return NS_OK;
}

NS_IMETHODIMP
nsAsyncResolveRequest::AsyncApplyFilters::Run() {
  LOG(("AsyncApplyFilters::Run %p", this));

  MOZ_ASSERT(mProcessingThread && mProcessingThread->IsOnCurrentThread());

  ProcessNextFilter();
  return NS_OK;
}

nsresult nsAsyncResolveRequest::AsyncApplyFilters::Finish() {
  LOG(("AsyncApplyFilters::Finish %p pi=%p", this, mProxyInfo.get()));

  MOZ_ASSERT(mRequest);

  mFiltersCopy.Clear();

  RefPtr<nsAsyncResolveRequest> request;
  request.swap(mRequest);

  nsCOMPtr<nsIProxyInfo> pi;
  pi.swap(mProxyInfo);

  request->mPPS->PruneProxyInfo(mInfo, pi);
  return mCallback(request, pi, !mProcessingInLoop);
}

NS_IMETHODIMP
nsAsyncResolveRequest::AsyncApplyFilters::Cancel(nsresult reason) {
  LOG(("AsyncApplyFilters::Cancel %p", this));

  MOZ_ASSERT(mProcessingThread && mProcessingThread->IsOnCurrentThread());

  // This will be called only from inside the request, so don't call
  // its's callback.  Dropping the members means we simply break the cycle.
  mFiltersCopy.Clear();
  mProxyInfo = nullptr;
  mRequest = nullptr;

  return NS_OK;
}

// Bug 1366133: make GetPACURI off-main-thread since it may hang on Windows
// platform
class AsyncGetPACURIRequest final : public nsIRunnable {
 public:
  NS_DECL_THREADSAFE_ISUPPORTS

  using CallbackFunc = nsresult (nsProtocolProxyService::*)(bool, bool,
                                                            nsresult,
                                                            const nsACString&);

  AsyncGetPACURIRequest(nsProtocolProxyService* aService,
                        CallbackFunc aCallback,
                        nsISystemProxySettings* aSystemProxySettings,
                        bool aMainThreadOnly, bool aForceReload,
                        bool aResetPACThread)
      : mIsMainThreadOnly(aMainThreadOnly),
        mService(aService),
        mServiceHolder(do_QueryObject(aService)),
        mCallback(aCallback),
        mSystemProxySettings(aSystemProxySettings),
        mForceReload(aForceReload),
        mResetPACThread(aResetPACThread) {
    MOZ_ASSERT(NS_IsMainThread());
    Unused << mIsMainThreadOnly;
  }

  NS_IMETHOD Run() override {
    MOZ_ASSERT(NS_IsMainThread() == mIsMainThreadOnly);

    nsCString pacUri;
    nsresult rv = mSystemProxySettings->GetPACURI(pacUri);

    nsCOMPtr<nsIRunnable> event =
        NewNonOwningCancelableRunnableMethod<bool, bool, nsresult, nsCString>(
            "AsyncGetPACURIRequestCallback", mService, mCallback, mForceReload,
            mResetPACThread, rv, pacUri);

    return NS_DispatchToMainThread(event);
  }

 private:
  ~AsyncGetPACURIRequest() {
    NS_ReleaseOnMainThread("AsyncGetPACURIRequest::mServiceHolder",
                           mServiceHolder.forget());
  }

  bool mIsMainThreadOnly;

  nsProtocolProxyService* mService;  // ref-count is hold by mServiceHolder
  nsCOMPtr<nsIProtocolProxyService2> mServiceHolder;
  CallbackFunc mCallback;
  nsCOMPtr<nsISystemProxySettings> mSystemProxySettings;

  bool mForceReload;
  bool mResetPACThread;
};

NS_IMPL_ISUPPORTS(AsyncGetPACURIRequest, nsIRunnable)

//----------------------------------------------------------------------------

//
// apply mask to address (zeros out excluded bits).
//
// NOTE: we do the byte swapping here to minimize overall swapping.
//
static void proxy_MaskIPv6Addr(PRIPv6Addr& addr, uint16_t mask_len) {
  if (mask_len == 128) return;

  if (mask_len > 96) {
    addr.pr_s6_addr32[3] =
        PR_htonl(PR_ntohl(addr.pr_s6_addr32[3]) & (~0uL << (128 - mask_len)));
  } else if (mask_len > 64) {
    addr.pr_s6_addr32[3] = 0;
    addr.pr_s6_addr32[2] =
        PR_htonl(PR_ntohl(addr.pr_s6_addr32[2]) & (~0uL << (96 - mask_len)));
  } else if (mask_len > 32) {
    addr.pr_s6_addr32[3] = 0;
    addr.pr_s6_addr32[2] = 0;
    addr.pr_s6_addr32[1] =
        PR_htonl(PR_ntohl(addr.pr_s6_addr32[1]) & (~0uL << (64 - mask_len)));
  } else {
    addr.pr_s6_addr32[3] = 0;
    addr.pr_s6_addr32[2] = 0;
    addr.pr_s6_addr32[1] = 0;
    addr.pr_s6_addr32[0] =
        PR_htonl(PR_ntohl(addr.pr_s6_addr32[0]) & (~0uL << (32 - mask_len)));
  }
}

static void proxy_GetStringPref(nsIPrefBranch* aPrefBranch, const char* aPref,
                                nsCString& aResult) {
  nsAutoCString temp;
  nsresult rv = aPrefBranch->GetCharPref(aPref, temp);
  if (NS_FAILED(rv))
    aResult.Truncate();
  else {
    aResult.Assign(temp);
    // all of our string prefs are hostnames, so we should remove any
    // whitespace characters that the user might have unknowingly entered.
    aResult.StripWhitespace();
  }
}

static void proxy_GetIntPref(nsIPrefBranch* aPrefBranch, const char* aPref,
                             int32_t& aResult) {
  int32_t temp;
  nsresult rv = aPrefBranch->GetIntPref(aPref, &temp);
  if (NS_FAILED(rv))
    aResult = -1;
  else
    aResult = temp;
}

static void proxy_GetBoolPref(nsIPrefBranch* aPrefBranch, const char* aPref,
                              bool& aResult) {
  bool temp;
  nsresult rv = aPrefBranch->GetBoolPref(aPref, &temp);
  if (NS_FAILED(rv))
    aResult = false;
  else
    aResult = temp;
}

//----------------------------------------------------------------------------

static const int32_t PROXYCONFIG_DIRECT4X = 3;
static const int32_t PROXYCONFIG_COUNT = 6;

NS_IMPL_ADDREF(nsProtocolProxyService)
NS_IMPL_RELEASE(nsProtocolProxyService)
NS_IMPL_CLASSINFO(nsProtocolProxyService, nullptr, nsIClassInfo::SINGLETON,
                  NS_PROTOCOLPROXYSERVICE_CID)

// NS_IMPL_QUERY_INTERFACE_CI with the nsProtocolProxyService QI change
NS_INTERFACE_MAP_BEGIN(nsProtocolProxyService)
  NS_INTERFACE_MAP_ENTRY(nsIProtocolProxyService)
  NS_INTERFACE_MAP_ENTRY(nsIProtocolProxyService2)
  NS_INTERFACE_MAP_ENTRY(nsIObserver)
  NS_INTERFACE_MAP_ENTRY_CONCRETE(nsProtocolProxyService)
  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIProtocolProxyService)
  NS_IMPL_QUERY_CLASSINFO(nsProtocolProxyService)
NS_INTERFACE_MAP_END

NS_IMPL_CI_INTERFACE_GETTER(nsProtocolProxyService, nsIProtocolProxyService,
                            nsIProtocolProxyService2)

nsProtocolProxyService::nsProtocolProxyService()
    : mFilterLocalHosts(false),
      mProxyConfig(PROXYCONFIG_DIRECT),
      mHTTPProxyPort(-1),
      mFTPProxyPort(-1),
      mHTTPSProxyPort(-1),
      mSOCKSProxyPort(-1),
      mSOCKSProxyVersion(4),
      mSOCKSProxyRemoteDNS(false),
      mProxyOverTLS(true),
      mWPADOverDHCPEnabled(false),
      mPACMan(nullptr),
      mSessionStart(PR_Now()),
      mFailedProxyTimeout(30 * 60)  // 30 minute default
      ,
      mIsShutdown(false) {}

nsProtocolProxyService::~nsProtocolProxyService() {
  // These should have been cleaned up in our Observe method.
  NS_ASSERTION(mHostFiltersArray.Length() == 0 && mFilters.Length() == 0 &&
                   mPACMan == nullptr,
               "what happened to xpcom-shutdown?");
}

// nsProtocolProxyService methods
nsresult nsProtocolProxyService::Init() {
  mProxySettingTarget = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);

  // failure to access prefs is non-fatal
  nsCOMPtr<nsIPrefBranch> prefBranch = do_GetService(NS_PREFSERVICE_CONTRACTID);
  if (prefBranch) {
    // monitor proxy prefs
    prefBranch->AddObserver(PROXY_PREF_BRANCH, this, false);

    // read all prefs
    PrefsChanged(prefBranch, nullptr);
  }

  nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
  if (obs) {
    // register for shutdown notification so we can clean ourselves up
    // properly.
    obs->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false);
    obs->AddObserver(this, NS_NETWORK_LINK_TOPIC, false);
  }

  return NS_OK;
}

// ReloadNetworkPAC() checks if there's a non-networked PAC in use then avoids
// to call ReloadPAC()
nsresult nsProtocolProxyService::ReloadNetworkPAC() {
  nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
  if (!prefs) {
    return NS_OK;
  }

  int32_t type;
  nsresult rv = prefs->GetIntPref(PROXY_PREF("type"), &type);
  if (NS_FAILED(rv)) {
    return NS_OK;
  }

  if (type == PROXYCONFIG_PAC) {
    nsAutoCString pacSpec;
    prefs->GetCharPref(PROXY_PREF("autoconfig_url"), pacSpec);
    if (!pacSpec.IsEmpty()) {
      nsCOMPtr<nsIURI> pacURI;
      rv = NS_NewURI(getter_AddRefs(pacURI), pacSpec);
      if (!NS_SUCCEEDED(rv)) {
        return rv;
      }

      nsProtocolInfo pac;
      rv = GetProtocolInfo(pacURI, &pac);
      if (!NS_SUCCEEDED(rv)) {
        return rv;
      }

      if (!pac.scheme.EqualsLiteral("file") &&
          !pac.scheme.EqualsLiteral("data")) {
        LOG((": received network changed event, reload PAC"));
        ReloadPAC();
      }
    }
  } else if ((type == PROXYCONFIG_WPAD) || (type == PROXYCONFIG_SYSTEM)) {
    ReloadPAC();
  }

  return NS_OK;
}

nsresult nsProtocolProxyService::AsyncConfigureFromPAC(bool aForceReload,
                                                       bool aResetPACThread) {
  MOZ_ASSERT(NS_IsMainThread());

  bool mainThreadOnly;
  nsresult rv = mSystemProxySettings->GetMainThreadOnly(&mainThreadOnly);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  nsCOMPtr<nsIRunnable> req = new AsyncGetPACURIRequest(
      this, &nsProtocolProxyService::OnAsyncGetPACURI, mSystemProxySettings,
      mainThreadOnly, aForceReload, aResetPACThread);

  if (mainThreadOnly) {
    return req->Run();
  }

  if (NS_WARN_IF(!mProxySettingTarget)) {
    return NS_ERROR_NOT_INITIALIZED;
  }
  return mProxySettingTarget->Dispatch(req, nsIEventTarget::DISPATCH_NORMAL);
}

nsresult nsProtocolProxyService::OnAsyncGetPACURI(bool aForceReload,
                                                  bool aResetPACThread,
                                                  nsresult aResult,
                                                  const nsACString& aUri) {
  MOZ_ASSERT(NS_IsMainThread());

  if (aResetPACThread) {
    ResetPACThread();
  }

  if (NS_SUCCEEDED(aResult) && !aUri.IsEmpty()) {
    ConfigureFromPAC(PromiseFlatCString(aUri), aForceReload);
  }

  return NS_OK;
}

NS_IMETHODIMP
nsProtocolProxyService::Observe(nsISupports* aSubject, const char* aTopic,
                                const char16_t* aData) {
  if (strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID) == 0) {
    mIsShutdown = true;
    // cleanup
    mHostFiltersArray.Clear();
    mFilters.Clear();

    if (mPACMan) {
      mPACMan->Shutdown();
      mPACMan = nullptr;
    }

    if (mProxySettingTarget) {
      mProxySettingTarget = nullptr;
    }

    nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
    if (obs) {
      obs->RemoveObserver(this, NS_NETWORK_LINK_TOPIC);
      obs->RemoveObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID);
    }

  } else if (strcmp(aTopic, NS_NETWORK_LINK_TOPIC) == 0) {
    nsCString converted = NS_ConvertUTF16toUTF8(aData);
    const char* state = converted.get();
    if (!strcmp(state, NS_NETWORK_LINK_DATA_CHANGED)) {
      ReloadNetworkPAC();
    }
  } else {
    NS_ASSERTION(strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID) == 0,
                 "what is this random observer event?");
    nsCOMPtr<nsIPrefBranch> prefs = do_QueryInterface(aSubject);
    if (prefs) PrefsChanged(prefs, NS_LossyConvertUTF16toASCII(aData).get());
  }
  return NS_OK;
}

void nsProtocolProxyService::PrefsChanged(nsIPrefBranch* prefBranch,
                                          const char* pref) {
  nsresult rv = NS_OK;
  bool reloadPAC = false;
  nsAutoCString tempString;

  if (!pref || !strcmp(pref, PROXY_PREF("type"))) {
    int32_t type = -1;
    rv = prefBranch->GetIntPref(PROXY_PREF("type"), &type);
    if (NS_SUCCEEDED(rv)) {
      // bug 115720 - for ns4.x backwards compatibility
      if (type == PROXYCONFIG_DIRECT4X) {
        type = PROXYCONFIG_DIRECT;
        // Reset the type so that the dialog looks correct, and we
        // don't have to handle this case everywhere else
        // I'm paranoid about a loop of some sort - only do this
        // if we're enumerating all prefs, and ignore any error
        if (!pref) prefBranch->SetIntPref(PROXY_PREF("type"), type);
      } else if (type >= PROXYCONFIG_COUNT) {
        LOG(("unknown proxy type: %" PRId32 "; assuming direct\n", type));
        type = PROXYCONFIG_DIRECT;
      }
      mProxyConfig = type;
      reloadPAC = true;
    }

    if (mProxyConfig == PROXYCONFIG_SYSTEM) {
      mSystemProxySettings = do_GetService(NS_SYSTEMPROXYSETTINGS_CONTRACTID);
      if (!mSystemProxySettings) mProxyConfig = PROXYCONFIG_DIRECT;
      ResetPACThread();
    } else {
      if (mSystemProxySettings) {
        mSystemProxySettings = nullptr;
        ResetPACThread();
      }
    }
  }

  if (!pref || !strcmp(pref, PROXY_PREF("http")))
    proxy_GetStringPref(prefBranch, PROXY_PREF("http"), mHTTPProxyHost);

  if (!pref || !strcmp(pref, PROXY_PREF("http_port")))
    proxy_GetIntPref(prefBranch, PROXY_PREF("http_port"), mHTTPProxyPort);

  if (!pref || !strcmp(pref, PROXY_PREF("ssl")))
    proxy_GetStringPref(prefBranch, PROXY_PREF("ssl"), mHTTPSProxyHost);

  if (!pref || !strcmp(pref, PROXY_PREF("ssl_port")))
    proxy_GetIntPref(prefBranch, PROXY_PREF("ssl_port"), mHTTPSProxyPort);

  if (!pref || !strcmp(pref, PROXY_PREF("ftp")))
    proxy_GetStringPref(prefBranch, PROXY_PREF("ftp"), mFTPProxyHost);

  if (!pref || !strcmp(pref, PROXY_PREF("ftp_port")))
    proxy_GetIntPref(prefBranch, PROXY_PREF("ftp_port"), mFTPProxyPort);

  if (!pref || !strcmp(pref, PROXY_PREF("socks")))
    proxy_GetStringPref(prefBranch, PROXY_PREF("socks"), mSOCKSProxyTarget);

  if (!pref || !strcmp(pref, PROXY_PREF("socks_port")))
    proxy_GetIntPref(prefBranch, PROXY_PREF("socks_port"), mSOCKSProxyPort);

  if (!pref || !strcmp(pref, PROXY_PREF("socks_version"))) {
    int32_t version;
    proxy_GetIntPref(prefBranch, PROXY_PREF("socks_version"), version);
    // make sure this preference value remains sane
    if (version == 5)
      mSOCKSProxyVersion = 5;
    else
      mSOCKSProxyVersion = 4;
  }

  if (!pref || !strcmp(pref, PROXY_PREF("socks_remote_dns")))
    proxy_GetBoolPref(prefBranch, PROXY_PREF("socks_remote_dns"),
                      mSOCKSProxyRemoteDNS);

  if (!pref || !strcmp(pref, PROXY_PREF("proxy_over_tls"))) {
    proxy_GetBoolPref(prefBranch, PROXY_PREF("proxy_over_tls"), mProxyOverTLS);
  }

  if (!pref || !strcmp(pref, PROXY_PREF("enable_wpad_over_dhcp"))) {
    proxy_GetBoolPref(prefBranch, PROXY_PREF("enable_wpad_over_dhcp"),
                      mWPADOverDHCPEnabled);
    reloadPAC = reloadPAC || mProxyConfig == PROXYCONFIG_WPAD;
  }

  if (!pref || !strcmp(pref, PROXY_PREF("failover_timeout")))
    proxy_GetIntPref(prefBranch, PROXY_PREF("failover_timeout"),
                     mFailedProxyTimeout);

  if (!pref || !strcmp(pref, PROXY_PREF("no_proxies_on"))) {
    rv = prefBranch->GetCharPref(PROXY_PREF("no_proxies_on"), tempString);
    if (NS_SUCCEEDED(rv)) LoadHostFilters(tempString);
  }

  // We're done if not using something that could give us a PAC URL
  // (PAC, WPAD or System)
  if (mProxyConfig != PROXYCONFIG_PAC && mProxyConfig != PROXYCONFIG_WPAD &&
      mProxyConfig != PROXYCONFIG_SYSTEM)
    return;

  // OK, we need to reload the PAC file if:
  //  1) network.proxy.type changed, or
  //  2) network.proxy.autoconfig_url changed and PAC is configured

  if (!pref || !strcmp(pref, PROXY_PREF("autoconfig_url"))) reloadPAC = true;

  if (reloadPAC) {
    tempString.Truncate();
    if (mProxyConfig == PROXYCONFIG_PAC) {
      prefBranch->GetCharPref(PROXY_PREF("autoconfig_url"), tempString);
      if (mPACMan && !mPACMan->IsPACURI(tempString)) {
        LOG(("PAC Thread URI Changed - Reset Pac Thread"));
        ResetPACThread();
      }
    } else if (mProxyConfig == PROXYCONFIG_WPAD) {
      LOG(("Auto-detecting proxy - Reset Pac Thread"));
      ResetPACThread();
    } else if (mSystemProxySettings) {
      // Get System Proxy settings if available
      AsyncConfigureFromPAC(false, false);
    }
    if (!tempString.IsEmpty() || mProxyConfig == PROXYCONFIG_WPAD) {
      ConfigureFromPAC(tempString, false);
    }
  }
}

bool nsProtocolProxyService::CanUseProxy(nsIURI* aURI, int32_t defaultPort) {
  int32_t port;
  nsAutoCString host;

  nsresult rv = aURI->GetAsciiHost(host);
  if (NS_FAILED(rv) || host.IsEmpty()) return false;

  rv = aURI->GetPort(&port);
  if (NS_FAILED(rv)) return false;
  if (port == -1) port = defaultPort;

  PRNetAddr addr;
  bool is_ipaddr = (PR_StringToNetAddr(host.get(), &addr) == PR_SUCCESS);

  PRIPv6Addr ipv6;
  if (is_ipaddr) {
    // convert parsed address to IPv6
    if (addr.raw.family == PR_AF_INET) {
      // convert to IPv4-mapped address
      PR_ConvertIPv4AddrToIPv6(addr.inet.ip, &ipv6);
    } else if (addr.raw.family == PR_AF_INET6) {
      // copy the address
      memcpy(&ipv6, &addr.ipv6.ip, sizeof(PRIPv6Addr));
    } else {
      NS_WARNING("unknown address family");
      return true;  // allow proxying
    }
  }

  // Don't use proxy for local hosts (plain hostname, no dots)
  if ((!is_ipaddr && mFilterLocalHosts && !host.Contains('.')) ||
      // This method detects if we have network.proxy.allow_hijacking_localhost
      // pref enabled. If it's true then this method will always return false
      // otherwise it returns true if the host matches an address that's
      // hardcoded to the loopback address.
      (!StaticPrefs::network_proxy_allow_hijacking_localhost() &&
       nsMixedContentBlocker::IsPotentiallyTrustworthyLoopbackHost(host))) {
    LOG(("Not using proxy for this local host [%s]!\n", host.get()));
    return false;  // don't allow proxying
  }

  int32_t index = -1;
  while (++index < int32_t(mHostFiltersArray.Length())) {
    const auto& hinfo = mHostFiltersArray[index];

    if (is_ipaddr != hinfo->is_ipaddr) continue;
    if (hinfo->port && hinfo->port != port) continue;

    if (is_ipaddr) {
      // generate masked version of target IPv6 address
      PRIPv6Addr masked;
      memcpy(&masked, &ipv6, sizeof(PRIPv6Addr));
      proxy_MaskIPv6Addr(masked, hinfo->ip.mask_len);

      // check for a match
      if (memcmp(&masked, &hinfo->ip.addr, sizeof(PRIPv6Addr)) == 0)
        return false;  // proxy disallowed
    } else {
      uint32_t host_len = host.Length();
      uint32_t filter_host_len = hinfo->name.host_len;

      if (host_len >= filter_host_len) {
        //
        // compare last |filter_host_len| bytes of target hostname.
        //
        const char* host_tail = host.get() + host_len - filter_host_len;
        if (!PL_strncasecmp(host_tail, hinfo->name.host, filter_host_len)) {
          // If the tail of the host string matches the filter

          if (filter_host_len > 0 && hinfo->name.host[0] == '.') {
            // If the filter was of the form .foo.bar.tld, all such
            // matches are correct
            return false;  // proxy disallowed
          }

          // abc-def.example.org should not match def.example.org
          // however, *.def.example.org should match .def.example.org
          // We check that the filter doesn't start with a `.`. If it does,
          // then the strncasecmp above should suffice. If it doesn't,
          // then we should only consider it a match if the strncasecmp happened
          // at a subdomain boundary
          if (host_len > filter_host_len && *(host_tail - 1) == '.') {
            // If the host was something.foo.bar.tld and the filter
            // was foo.bar.tld, it's still a match.
            // the character right before the tail must be a
            // `.` for this to work
            return false;  // proxy disallowed
          }

          if (host_len == filter_host_len) {
            // If the host and filter are of the same length,
            // they should match
            return false;  // proxy disallowed
          }
        }
      }
    }
  }
  return true;
}

// kProxyType\* may be referred to externally in
// nsProxyInfo in order to compare by string pointer
const char kProxyType_HTTP[] = "http";
const char kProxyType_HTTPS[] = "https";
const char kProxyType_PROXY[] = "proxy";
const char kProxyType_SOCKS[] = "socks";
const char kProxyType_SOCKS4[] = "socks4";
const char kProxyType_SOCKS5[] = "socks5";
const char kProxyType_DIRECT[] = "direct";

const char* nsProtocolProxyService::ExtractProxyInfo(const char* start,
                                                     uint32_t aResolveFlags,
                                                     nsProxyInfo** result) {
  *result = nullptr;
  uint32_t flags = 0;

  // see BNF in ProxyAutoConfig.h and notes in nsISystemProxySettings.idl

  // find end of proxy info delimiter
  const char* end = start;
  while (*end && *end != ';') ++end;

  // find end of proxy type delimiter
  const char* sp = start;
  while (sp < end && *sp != ' ' && *sp != '\t') ++sp;

  uint32_t len = sp - start;
  const char* type = nullptr;
  switch (len) {
    case 4:
      if (PL_strncasecmp(start, kProxyType_HTTP, 4) == 0) {
        type = kProxyType_HTTP;
      }
      break;
    case 5:
      if (PL_strncasecmp(start, kProxyType_PROXY, 5) == 0) {
        type = kProxyType_HTTP;
      } else if (PL_strncasecmp(start, kProxyType_SOCKS, 5) == 0) {
        type = kProxyType_SOCKS4;  // assume v4 for 4x compat
      } else if (PL_strncasecmp(start, kProxyType_HTTPS, 5) == 0) {
        type = kProxyType_HTTPS;
      }
      break;
    case 6:
      if (PL_strncasecmp(start, kProxyType_DIRECT, 6) == 0)
        type = kProxyType_DIRECT;
      else if (PL_strncasecmp(start, kProxyType_SOCKS4, 6) == 0)
        type = kProxyType_SOCKS4;
      else if (PL_strncasecmp(start, kProxyType_SOCKS5, 6) == 0)
        // map "SOCKS5" to "socks" to match contract-id of registered
        // SOCKS-v5 socket provider.
        type = kProxyType_SOCKS;
      break;
  }
  if (type) {
    int32_t port = -1;

    // If it's a SOCKS5 proxy, do name resolution on the server side.
    // We could use this with SOCKS4a servers too, but they might not
    // support it.
    if (type == kProxyType_SOCKS || mSOCKSProxyRemoteDNS)
      flags |= nsIProxyInfo::TRANSPARENT_PROXY_RESOLVES_HOST;

    // extract host:port
    start = sp;
    while ((*start == ' ' || *start == '\t') && start < end) start++;

    // port defaults
    if (type == kProxyType_HTTP) {
      port = 80;
    } else if (type == kProxyType_HTTPS) {
      port = 443;
    } else {
      port = 1080;
    }

    RefPtr<nsProxyInfo> pi = new nsProxyInfo();
    pi->mType = type;
    pi->mFlags = flags;
    pi->mResolveFlags = aResolveFlags;
    pi->mTimeout = mFailedProxyTimeout;

    // www.foo.com:8080 and http://www.foo.com:8080
    nsDependentCSubstring maybeURL(start, end - start);
    nsCOMPtr<nsIURI> pacURI;

    nsAutoCString urlHost;
    // First assume the scheme is present, e.g. http://www.example.com:8080
    if (NS_FAILED(NS_NewURI(getter_AddRefs(pacURI), maybeURL)) ||
        NS_FAILED(pacURI->GetAsciiHost(urlHost)) || urlHost.IsEmpty()) {
      // It isn't, assume www.example.com:8080
      maybeURL.Insert("http://", 0);

      if (NS_SUCCEEDED(NS_NewURI(getter_AddRefs(pacURI), maybeURL))) {
        pacURI->GetAsciiHost(urlHost);
      }
    }

    if (!urlHost.IsEmpty()) {
      pi->mHost = urlHost;

      int32_t tPort;
      if (NS_SUCCEEDED(pacURI->GetPort(&tPort)) && tPort != -1) {
        port = tPort;
      }
      pi->mPort = port;
    }

    pi.forget(result);
  }

  while (*end == ';' || *end == ' ' || *end == '\t') ++end;
  return end;
}

void nsProtocolProxyService::GetProxyKey(nsProxyInfo* pi, nsCString& key) {
  key.AssignASCII(pi->mType);
  if (!pi->mHost.IsEmpty()) {
    key.Append(' ');
    key.Append(pi->mHost);
    key.Append(':');
    key.AppendInt(pi->mPort);
  }
}

uint32_t nsProtocolProxyService::SecondsSinceSessionStart() {
  PRTime now = PR_Now();

  // get time elapsed since session start
  int64_t diff = now - mSessionStart;

  // convert microseconds to seconds
  diff /= PR_USEC_PER_SEC;

  // return converted 32 bit value
  return uint32_t(diff);
}

void nsProtocolProxyService::EnableProxy(nsProxyInfo* pi) {
  nsAutoCString key;
  GetProxyKey(pi, key);
  mFailedProxies.Remove(key);
}

void nsProtocolProxyService::DisableProxy(nsProxyInfo* pi) {
  nsAutoCString key;
  GetProxyKey(pi, key);

  uint32_t dsec = SecondsSinceSessionStart();

  // Add timeout to interval (this is the time when the proxy can
  // be tried again).
  dsec += pi->mTimeout;

  // NOTE: The classic codebase would increase the timeout value
  //       incrementally each time a subsequent failure occurred.
  //       We could do the same, but it would require that we not
  //       remove proxy entries in IsProxyDisabled or otherwise
  //       change the way we are recording disabled proxies.
  //       Simpler is probably better for now, and at least the
  //       user can tune the timeout setting via preferences.

  LOG(("DisableProxy %s %d\n", key.get(), dsec));

  // If this fails, oh well... means we don't have enough memory
  // to remember the failed proxy.
  mFailedProxies.Put(key, dsec);
}

bool nsProtocolProxyService::IsProxyDisabled(nsProxyInfo* pi) {
  nsAutoCString key;
  GetProxyKey(pi, key);

  uint32_t val;
  if (!mFailedProxies.Get(key, &val)) return false;

  uint32_t dsec = SecondsSinceSessionStart();

  // if time passed has exceeded interval, then try proxy again.
  if (dsec > val) {
    mFailedProxies.Remove(key);
    return false;
  }

  return true;
}

nsresult nsProtocolProxyService::SetupPACThread(
    nsISerialEventTarget* mainThreadEventTarget) {
  if (mIsShutdown) {
    return NS_ERROR_FAILURE;
  }

  if (mPACMan) return NS_OK;

  mPACMan = new nsPACMan(mainThreadEventTarget);

  bool mainThreadOnly;
  nsresult rv;
  if (mSystemProxySettings &&
      NS_SUCCEEDED(mSystemProxySettings->GetMainThreadOnly(&mainThreadOnly)) &&
      !mainThreadOnly) {
    rv = mPACMan->Init(mSystemProxySettings);
  } else {
    rv = mPACMan->Init(nullptr);
  }
  if (NS_FAILED(rv)) {
    mPACMan->Shutdown();
    mPACMan = nullptr;
  }
  return rv;
}

nsresult nsProtocolProxyService::ResetPACThread() {
  if (!mPACMan) return NS_OK;

  mPACMan->Shutdown();
  mPACMan = nullptr;
  return SetupPACThread();
}

nsresult nsProtocolProxyService::ConfigureFromPAC(const nsCString& spec,
                                                  bool forceReload) {
  nsresult rv = SetupPACThread();
  NS_ENSURE_SUCCESS(rv, rv);

  bool autodetect = spec.IsEmpty();
  if (!forceReload && ((!autodetect && mPACMan->IsPACURI(spec)) ||
                       (autodetect && mPACMan->IsUsingWPAD()))) {
    return NS_OK;
  }

  mFailedProxies.Clear();

  mPACMan->SetWPADOverDHCPEnabled(mWPADOverDHCPEnabled);
  return mPACMan->LoadPACFromURI(spec);
}

void nsProtocolProxyService::ProcessPACString(const nsCString& pacString,
                                              uint32_t aResolveFlags,
                                              nsIProxyInfo** result) {
  if (pacString.IsEmpty()) {
    *result = nullptr;
    return;
  }

  const char* proxies = pacString.get();

  nsProxyInfo *pi = nullptr, *first = nullptr, *last = nullptr;
  while (*proxies) {
    proxies = ExtractProxyInfo(proxies, aResolveFlags, &pi);
    if (pi && (pi->mType == kProxyType_HTTPS) && !mProxyOverTLS) {
      delete pi;
      pi = nullptr;
    }

    if (pi) {
      if (last) {
        NS_ASSERTION(last->mNext == nullptr, "leaking nsProxyInfo");
        last->mNext = pi;
      } else
        first = pi;
      last = pi;
    }
  }
  *result = first;
}

// nsIProtocolProxyService2
NS_IMETHODIMP
nsProtocolProxyService::ReloadPAC() {
  nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
  if (!prefs) return NS_OK;

  int32_t type;
  nsresult rv = prefs->GetIntPref(PROXY_PREF("type"), &type);
  if (NS_FAILED(rv)) return NS_OK;

  nsAutoCString pacSpec;
  if (type == PROXYCONFIG_PAC)
    prefs->GetCharPref(PROXY_PREF("autoconfig_url"), pacSpec);
  else if (type == PROXYCONFIG_SYSTEM) {
    if (mSystemProxySettings) {
      AsyncConfigureFromPAC(true, true);
    } else {
      ResetPACThread();
    }
  }

  if (!pacSpec.IsEmpty() || type == PROXYCONFIG_WPAD)
    ConfigureFromPAC(pacSpec, true);
  return NS_OK;
}

// When sync interface is removed this can go away too
// The nsPACManCallback portion of this implementation should be run
// off the main thread, because it uses a condvar for signaling and
// the main thread is blocking on that condvar -
//  so call nsPACMan::AsyncGetProxyForURI() with
// a false mainThreadResponse parameter.
class nsAsyncBridgeRequest final : public nsPACManCallback {
  NS_DECL_THREADSAFE_ISUPPORTS

  nsAsyncBridgeRequest()
      : mMutex("nsDeprecatedCallback"),
        mCondVar(mMutex, "nsDeprecatedCallback"),
        mStatus(NS_OK),
        mCompleted(false) {}

  void OnQueryComplete(nsresult status, const nsACString& pacString,
                       const nsACString& newPACURL) override {
    MutexAutoLock lock(mMutex);
    mCompleted = true;
    mStatus = status;
    mPACString = pacString;
    mPACURL = newPACURL;
    mCondVar.Notify();
  }

  void Lock() { mMutex.Lock(); }
  void Unlock() { mMutex.Unlock(); }
  void Wait() { mCondVar.Wait(TimeDuration::FromSeconds(3)); }

 private:
  ~nsAsyncBridgeRequest() = default;

  friend class nsProtocolProxyService;

  Mutex mMutex;
  CondVar mCondVar;

  nsresult mStatus;
  nsCString mPACString;
  nsCString mPACURL;
  bool mCompleted;
};
NS_IMPL_ISUPPORTS0(nsAsyncBridgeRequest)

nsresult nsProtocolProxyService::AsyncResolveInternal(
    nsIChannel* channel, uint32_t flags, nsIProtocolProxyCallback* callback,
    nsICancelable** result, bool isSyncOK,
    nsISerialEventTarget* mainThreadEventTarget) {
  NS_ENSURE_ARG_POINTER(channel);
  NS_ENSURE_ARG_POINTER(callback);

  nsCOMPtr<nsIURI> uri;
  nsresult rv = GetProxyURI(channel, getter_AddRefs(uri));
  if (NS_FAILED(rv)) return rv;

  *result = nullptr;
  RefPtr<nsAsyncResolveRequest> ctx =
      new nsAsyncResolveRequest(this, channel, flags, callback);

  nsProtocolInfo info;
  rv = GetProtocolInfo(uri, &info);
  if (NS_FAILED(rv)) return rv;

  nsCOMPtr<nsIProxyInfo> pi;
  bool usePACThread;

  // adapt to realtime changes in the system proxy service
  if (mProxyConfig == PROXYCONFIG_SYSTEM) {
    nsCOMPtr<nsISystemProxySettings> sp2 =
        do_GetService(NS_SYSTEMPROXYSETTINGS_CONTRACTID);
    if (sp2 != mSystemProxySettings) {
      mSystemProxySettings = sp2;
      ResetPACThread();
    }
  }

  rv = SetupPACThread(mainThreadEventTarget);
  if (NS_FAILED(rv)) {
    return rv;
  }

  // SystemProxySettings and PAC files can block the main thread
  // but if neither of them are in use, we can just do the work
  // right here and directly invoke the callback

  rv =
      Resolve_Internal(channel, info, flags, &usePACThread, getter_AddRefs(pi));
  if (NS_FAILED(rv)) return rv;

  if (!usePACThread || !mPACMan) {
    // we can do it locally
    rv = ctx->ProcessLocally(info, pi, isSyncOK);
    if (NS_SUCCEEDED(rv) && !isSyncOK) {
      ctx.forget(result);
    }
    return rv;
  }

  // else kick off a PAC thread query
  rv = mPACMan->AsyncGetProxyForURI(uri, ctx, flags, true);
  if (NS_SUCCEEDED(rv)) ctx.forget(result);
  return rv;
}

// nsIProtocolProxyService
NS_IMETHODIMP
nsProtocolProxyService::AsyncResolve2(
    nsIChannel* channel, uint32_t flags, nsIProtocolProxyCallback* callback,
    nsISerialEventTarget* mainThreadEventTarget, nsICancelable** result) {
  return AsyncResolveInternal(channel, flags, callback, result, true,
                              mainThreadEventTarget);
}

NS_IMETHODIMP
nsProtocolProxyService::AsyncResolve(
    nsISupports* channelOrURI, uint32_t flags,
    nsIProtocolProxyCallback* callback,
    nsISerialEventTarget* mainThreadEventTarget, nsICancelable** result) {
  nsresult rv;
  // Check if we got a channel:
  nsCOMPtr<nsIChannel> channel = do_QueryInterface(channelOrURI);
  if (!channel) {
    nsCOMPtr<nsIURI> uri = do_QueryInterface(channelOrURI);
    if (!uri) {
      return NS_ERROR_NO_INTERFACE;
    }

    // creating a temporary channel from the URI which is not
    // used to perform any network loads, hence its safe to
    // use systemPrincipal as the loadingPrincipal.
    rv = NS_NewChannel(getter_AddRefs(channel), uri,
                       nsContentUtils::GetSystemPrincipal(),
                       nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL,
                       nsIContentPolicy::TYPE_OTHER);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  return AsyncResolveInternal(channel, flags, callback, result, false,
                              mainThreadEventTarget);
}

NS_IMETHODIMP
nsProtocolProxyService::NewProxyInfo(
    const nsACString& aType, const nsACString& aHost, int32_t aPort,
    const nsACString& aProxyAuthorizationHeader,
    const nsACString& aConnectionIsolationKey, uint32_t aFlags,
    uint32_t aFailoverTimeout, nsIProxyInfo* aFailoverProxy,
    nsIProxyInfo** aResult) {
  return NewProxyInfoWithAuth(aType, aHost, aPort, ""_ns, ""_ns,
                              aProxyAuthorizationHeader,
                              aConnectionIsolationKey, aFlags, aFailoverTimeout,
                              aFailoverProxy, aResult);
}

NS_IMETHODIMP
nsProtocolProxyService::NewProxyInfoWithAuth(
    const nsACString& aType, const nsACString& aHost, int32_t aPort,
    const nsACString& aUsername, const nsACString& aPassword,
    const nsACString& aProxyAuthorizationHeader,
    const nsACString& aConnectionIsolationKey, uint32_t aFlags,
    uint32_t aFailoverTimeout, nsIProxyInfo* aFailoverProxy,
    nsIProxyInfo** aResult) {
  static const char* types[] = {kProxyType_HTTP, kProxyType_HTTPS,
                                kProxyType_SOCKS, kProxyType_SOCKS4,
                                kProxyType_DIRECT};

  // resolve type; this allows us to avoid copying the type string into each
  // proxy info instance.  we just reference the string literals directly :)
  const char* type = nullptr;
  for (auto& t : types) {
    if (aType.LowerCaseEqualsASCII(t)) {
      type = t;
      break;
    }
  }
  NS_ENSURE_TRUE(type, NS_ERROR_INVALID_ARG);

  // We have only implemented username/password for SOCKS proxies.
  if ((!aUsername.IsEmpty() || !aPassword.IsEmpty()) &&
      !aType.LowerCaseEqualsASCII(kProxyType_SOCKS) &&
      !aType.LowerCaseEqualsASCII(kProxyType_SOCKS4)) {
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  return NewProxyInfo_Internal(type, aHost, aPort, aUsername, aPassword,
                               aProxyAuthorizationHeader,
                               aConnectionIsolationKey, aFlags,
                               aFailoverTimeout, aFailoverProxy, 0, aResult);
}

NS_IMETHODIMP
nsProtocolProxyService::GetFailoverForProxy(nsIProxyInfo* aProxy, nsIURI* aURI,
                                            nsresult aStatus,
                                            nsIProxyInfo** aResult) {
  // We only support failover when a PAC file is configured, either
  // directly or via system settings
  if (mProxyConfig != PROXYCONFIG_PAC && mProxyConfig != PROXYCONFIG_WPAD &&
      mProxyConfig != PROXYCONFIG_SYSTEM)
    return NS_ERROR_NOT_AVAILABLE;

  // Verify that |aProxy| is one of our nsProxyInfo objects.
  nsCOMPtr<nsProxyInfo> pi = do_QueryInterface(aProxy);
  NS_ENSURE_ARG(pi);
  // OK, the QI checked out.  We can proceed.

  // Remember that this proxy is down.
  DisableProxy(pi);

  // NOTE: At this point, we might want to prompt the user if we have
  //       not already tried going DIRECT.  This is something that the
  //       classic codebase supported; however, IE6 does not prompt.

  if (!pi->mNext) return NS_ERROR_NOT_AVAILABLE;

  LOG(("PAC failover from %s %s:%d to %s %s:%d\n", pi->mType, pi->mHost.get(),
       pi->mPort, pi->mNext->mType, pi->mNext->mHost.get(), pi->mNext->mPort));

  *aResult = do_AddRef(pi->mNext).take();
  return NS_OK;
}

namespace {  // anon

class ProxyFilterPositionComparator {
  typedef RefPtr<nsProtocolProxyService::FilterLink> FilterLinkRef;

 public:
  bool Equals(const FilterLinkRef& a, const FilterLinkRef& b) const {
    return a->position == b->position;
  }
  bool LessThan(const FilterLinkRef& a, const FilterLinkRef& b) const {
    return a->position < b->position;
  }
};

class ProxyFilterObjectComparator {
  typedef RefPtr<nsProtocolProxyService::FilterLink> FilterLinkRef;

 public:
  bool Equals(const FilterLinkRef& link, const nsISupports* obj) const {
    return obj == nsCOMPtr<nsISupports>(do_QueryInterface(link->filter)) ||
           obj == nsCOMPtr<nsISupports>(do_QueryInterface(link->channelFilter));
  }
};

}  // namespace

nsresult nsProtocolProxyService::InsertFilterLink(RefPtr<FilterLink>&& link) {
  LOG(("nsProtocolProxyService::InsertFilterLink filter=%p", link.get()));

  if (mIsShutdown) {
    return NS_ERROR_FAILURE;
  }

  mFilters.AppendElement(link);
  mFilters.Sort(ProxyFilterPositionComparator());
  return NS_OK;
}

NS_IMETHODIMP
nsProtocolProxyService::RegisterFilter(nsIProtocolProxyFilter* filter,
                                       uint32_t position) {
  UnregisterFilter(filter);  // remove this filter if we already have it

  RefPtr<FilterLink> link = new FilterLink(position, filter);
  return InsertFilterLink(std::move(link));
}

NS_IMETHODIMP
nsProtocolProxyService::RegisterChannelFilter(
    nsIProtocolProxyChannelFilter* channelFilter, uint32_t position) {
  UnregisterChannelFilter(
      channelFilter);  // remove this filter if we already have it

  RefPtr<FilterLink> link = new FilterLink(position, channelFilter);
  return InsertFilterLink(std::move(link));
}

nsresult nsProtocolProxyService::RemoveFilterLink(nsISupports* givenObject) {
  LOG(("nsProtocolProxyService::RemoveFilterLink target=%p", givenObject));

  return mFilters.RemoveElement(givenObject, ProxyFilterObjectComparator())
             ? NS_OK
             : NS_ERROR_UNEXPECTED;
}

NS_IMETHODIMP
nsProtocolProxyService::UnregisterFilter(nsIProtocolProxyFilter* filter) {
  // QI to nsISupports so we can safely test object identity.
  nsCOMPtr<nsISupports> givenObject = do_QueryInterface(filter);
  return RemoveFilterLink(givenObject);
}

NS_IMETHODIMP
nsProtocolProxyService::UnregisterChannelFilter(
    nsIProtocolProxyChannelFilter* channelFilter) {
  // QI to nsISupports so we can safely test object identity.
  nsCOMPtr<nsISupports> givenObject = do_QueryInterface(channelFilter);
  return RemoveFilterLink(givenObject);
}

NS_IMETHODIMP
nsProtocolProxyService::GetProxyConfigType(uint32_t* aProxyConfigType) {
  *aProxyConfigType = mProxyConfig;
  return NS_OK;
}

void nsProtocolProxyService::LoadHostFilters(const nsACString& aFilters) {
  if (mIsShutdown) {
    return;
  }

  // check to see the owners flag? /!?/ TODO
  if (mHostFiltersArray.Length() > 0) {
    mHostFiltersArray.Clear();
  }

  // Reset mFilterLocalHosts - will be set to true if "<local>" is in pref
  // string
  mFilterLocalHosts = false;

  if (aFilters.IsEmpty()) {
    return;
  }

  //
  // filter  = ( host | domain | ipaddr ["/" mask] ) [":" port]
  // filters = filter *( "," LWS filter)
  //
  mozilla::Tokenizer t(aFilters);
  mozilla::Tokenizer::Token token;
  bool eof = false;
  // while (*filters) {
  while (!eof) {
    // skip over spaces and ,
    t.SkipWhites();
    while (t.CheckChar(',')) {
      t.SkipWhites();
    }

    nsAutoCString portStr;
    nsAutoCString hostStr;
    nsAutoCString maskStr;
    t.Record();

    bool parsingIPv6 = false;
    bool parsingPort = false;
    bool parsingMask = false;
    while (t.Next(token)) {
      if (token.Equals(mozilla::Tokenizer::Token::EndOfFile())) {
        eof = true;
        break;
      }
      if (token.Equals(mozilla::Tokenizer::Token::Char(',')) ||
          token.Type() == mozilla::Tokenizer::TOKEN_WS) {
        break;
      }

      if (token.Equals(mozilla::Tokenizer::Token::Char('['))) {
        parsingIPv6 = true;
        continue;
      }

      if (!parsingIPv6 && token.Equals(mozilla::Tokenizer::Token::Char(':'))) {
        // Port is starting. Claim the previous as host.
        if (parsingMask) {
          t.Claim(maskStr);
        } else {
          t.Claim(hostStr);
        }
        t.Record();
        parsingPort = true;
        continue;
      }

      if (token.Equals(mozilla::Tokenizer::Token::Char('/'))) {
        t.Claim(hostStr);
        t.Record();
        parsingMask = true;
        continue;
      }

      if (token.Equals(mozilla::Tokenizer::Token::Char(']'))) {
        parsingIPv6 = false;
        continue;
      }
    }
    if (!parsingPort && !parsingMask) {
      t.Claim(hostStr);
    } else if (parsingPort) {
      t.Claim(portStr);
    } else if (parsingMask) {
      t.Claim(maskStr);
    } else {
      NS_WARNING("Could not parse this rule");
      continue;
    }

    if (hostStr.IsEmpty()) {
      continue;
    }

    // If the current host filter is "<local>", then all local (i.e.
    // no dots in the hostname) hosts should bypass the proxy
    if (hostStr.EqualsIgnoreCase("<local>")) {
      mFilterLocalHosts = true;
      LOG(
          ("loaded filter for local hosts "
           "(plain host names, no dots)\n"));
      // Continue to next host filter;
      continue;
    }

    // For all other host filters, create HostInfo object and add to list
    HostInfo* hinfo = new HostInfo();
    nsresult rv = NS_OK;

    int32_t port = portStr.ToInteger(&rv);
    if (NS_FAILED(rv)) {
      port = 0;
    }
    hinfo->port = port;

    int32_t maskLen = maskStr.ToInteger(&rv);
    if (NS_FAILED(rv)) {
      maskLen = 128;
    }

    // PR_StringToNetAddr can't parse brackets enclosed IPv6
    nsAutoCString addrString = hostStr;
    if (hostStr.First() == '[' && hostStr.Last() == ']') {
      addrString = Substring(hostStr, 1, hostStr.Length() - 2);
    }

    PRNetAddr addr;
    if (PR_StringToNetAddr(addrString.get(), &addr) == PR_SUCCESS) {
      hinfo->is_ipaddr = true;
      hinfo->ip.family = PR_AF_INET6;  // we always store address as IPv6
      hinfo->ip.mask_len = maskLen;

      if (hinfo->ip.mask_len == 0) {
        NS_WARNING("invalid mask");
        goto loser;
      }

      if (addr.raw.family == PR_AF_INET) {
        // convert to IPv4-mapped address
        PR_ConvertIPv4AddrToIPv6(addr.inet.ip, &hinfo->ip.addr);
        // adjust mask_len accordingly
        if (hinfo->ip.mask_len <= 32) hinfo->ip.mask_len += 96;
      } else if (addr.raw.family == PR_AF_INET6) {
        // copy the address
        memcpy(&hinfo->ip.addr, &addr.ipv6.ip, sizeof(PRIPv6Addr));
      } else {
        NS_WARNING("unknown address family");
        goto loser;
      }

      // apply mask to IPv6 address
      proxy_MaskIPv6Addr(hinfo->ip.addr, hinfo->ip.mask_len);
    } else {
      nsAutoCString host;
      if (hostStr.First() == '*') {
        host = Substring(hostStr, 1);
      } else {
        host = hostStr;
      }

      if (host.IsEmpty()) {
        hinfo->name.host = nullptr;
        goto loser;
      }

      hinfo->name.host_len = host.Length();

      hinfo->is_ipaddr = false;
      hinfo->name.host = ToNewCString(host, mozilla::fallible);

      if (!hinfo->name.host) goto loser;
    }

//#define DEBUG_DUMP_FILTERS
#ifdef DEBUG_DUMP_FILTERS
    printf("loaded filter[%zu]:\n", mHostFiltersArray.Length());
    printf("  is_ipaddr = %u\n", hinfo->is_ipaddr);
    printf("  port = %u\n", hinfo->port);
    printf("  host = %s\n", hostStr.get());
    if (hinfo->is_ipaddr) {
      printf("  ip.family = %x\n", hinfo->ip.family);
      printf("  ip.mask_len = %u\n", hinfo->ip.mask_len);

      PRNetAddr netAddr;
      PR_SetNetAddr(PR_IpAddrNull, PR_AF_INET6, 0, &netAddr);
      memcpy(&netAddr.ipv6.ip, &hinfo->ip.addr, sizeof(hinfo->ip.addr));

      char buf[256];
      PR_NetAddrToString(&netAddr, buf, sizeof(buf));

      printf("  ip.addr = %s\n", buf);
    } else {
      printf("  name.host = %s\n", hinfo->name.host);
    }
#endif

    mHostFiltersArray.AppendElement(hinfo);
    hinfo = nullptr;
  loser:
    delete hinfo;
  }
}

nsresult nsProtocolProxyService::GetProtocolInfo(nsIURI* uri,
                                                 nsProtocolInfo* info) {
  MOZ_ASSERT(uri, "URI is null");
  MOZ_ASSERT(info, "info is null");

  nsresult rv;

  rv = uri->GetScheme(info->scheme);
  if (NS_FAILED(rv)) return rv;

  nsCOMPtr<nsIIOService> ios = do_GetIOService(&rv);
  if (NS_FAILED(rv)) return rv;

  nsCOMPtr<nsIProtocolHandler> handler;
  rv = ios->GetProtocolHandler(info->scheme.get(), getter_AddRefs(handler));
  if (NS_FAILED(rv)) return rv;

  rv = handler->DoGetProtocolFlags(uri, &info->flags);
  if (NS_FAILED(rv)) return rv;

  rv = handler->GetDefaultPort(&info->defaultPort);
  return rv;
}

nsresult nsProtocolProxyService::NewProxyInfo_Internal(
    const char* aType, const nsACString& aHost, int32_t aPort,
    const nsACString& aUsername, const nsACString& aPassword,
    const nsACString& aProxyAuthorizationHeader,
    const nsACString& aConnectionIsolationKey, uint32_t aFlags,
    uint32_t aFailoverTimeout, nsIProxyInfo* aFailoverProxy,
    uint32_t aResolveFlags, nsIProxyInfo** aResult) {
  if (aPort <= 0) aPort = -1;

  nsCOMPtr<nsProxyInfo> failover;
  if (aFailoverProxy) {
    failover = do_QueryInterface(aFailoverProxy);
    NS_ENSURE_ARG(failover);
  }

  RefPtr<nsProxyInfo> proxyInfo = new nsProxyInfo();

  proxyInfo->mType = aType;
  proxyInfo->mHost = aHost;
  proxyInfo->mPort = aPort;
  proxyInfo->mUsername = aUsername;
  proxyInfo->mPassword = aPassword;
  proxyInfo->mFlags = aFlags;
  proxyInfo->mResolveFlags = aResolveFlags;
  proxyInfo->mTimeout =
      aFailoverTimeout == UINT32_MAX ? mFailedProxyTimeout : aFailoverTimeout;
  proxyInfo->mProxyAuthorizationHeader = aProxyAuthorizationHeader;
  proxyInfo->mConnectionIsolationKey = aConnectionIsolationKey;
  failover.swap(proxyInfo->mNext);

  proxyInfo.forget(aResult);
  return NS_OK;
}

nsresult nsProtocolProxyService::Resolve_Internal(nsIChannel* channel,
                                                  const nsProtocolInfo& info,
                                                  uint32_t flags,
                                                  bool* usePACThread,
                                                  nsIProxyInfo** result) {
  NS_ENSURE_ARG_POINTER(channel);

  *usePACThread = false;
  *result = nullptr;

  if (!(info.flags & nsIProtocolHandler::ALLOWS_PROXY))
    return NS_OK;  // Can't proxy this (filters may not override)

  nsCOMPtr<nsIURI> uri;
  nsresult rv = GetProxyURI(channel, getter_AddRefs(uri));
  if (NS_FAILED(rv)) return rv;

  // See bug #586908.
  // Avoid endless loop if |uri| is the current PAC-URI. Returning OK
  // here means that we will not use a proxy for this connection.
  if (mPACMan && mPACMan->IsPACURI(uri)) return NS_OK;

  // if proxies are enabled and this host:port combo is supposed to use a
  // proxy, check for a proxy.
  if ((mProxyConfig == PROXYCONFIG_DIRECT) ||
      !CanUseProxy(uri, info.defaultPort))
    return NS_OK;

  bool mainThreadOnly;
  if (mSystemProxySettings && mProxyConfig == PROXYCONFIG_SYSTEM &&
      NS_SUCCEEDED(mSystemProxySettings->GetMainThreadOnly(&mainThreadOnly)) &&
      !mainThreadOnly) {
    *usePACThread = true;
    return NS_OK;
  }

  if (mSystemProxySettings && mProxyConfig == PROXYCONFIG_SYSTEM) {
    // If the system proxy setting implementation is not threadsafe (e.g
    // linux gconf), we'll do it inline here. Such implementations promise
    // not to block
    // bug 1366133: this block uses GetPACURI & GetProxyForURI, which may
    // hang on Windows platform. Fortunately, current implementation on
    // Windows is not main thread only, so we are safe here.

    nsAutoCString PACURI;
    nsAutoCString pacString;

    if (NS_SUCCEEDED(mSystemProxySettings->GetPACURI(PACURI)) &&
        !PACURI.IsEmpty()) {
      // There is a PAC URI configured. If it is unchanged, then
      // just execute the PAC thread. If it is changed then load
      // the new value

      if (mPACMan && mPACMan->IsPACURI(PACURI)) {
        // unchanged
        *usePACThread = true;
        return NS_OK;
      }

      ConfigureFromPAC(PACURI, false);
      return NS_OK;
    }

    nsAutoCString spec;
    nsAutoCString host;
    nsAutoCString scheme;
    int32_t port = -1;

    uri->GetAsciiSpec(spec);
    uri->GetAsciiHost(host);
    uri->GetScheme(scheme);
    uri->GetPort(&port);

    if (flags & RESOLVE_PREFER_SOCKS_PROXY) {
      LOG(("Ignoring RESOLVE_PREFER_SOCKS_PROXY for system proxy setting\n"));
    } else if (flags & RESOLVE_PREFER_HTTPS_PROXY) {
      scheme.AssignLiteral("https");
    } else if (flags & RESOLVE_IGNORE_URI_SCHEME) {
      scheme.AssignLiteral("http");
    }

    // now try the system proxy settings for this particular url
    if (NS_SUCCEEDED(mSystemProxySettings->GetProxyForURI(spec, scheme, host,
                                                          port, pacString))) {
      nsCOMPtr<nsIProxyInfo> pi;
      ProcessPACString(pacString, 0, getter_AddRefs(pi));

      if (flags & RESOLVE_PREFER_SOCKS_PROXY &&
          flags & RESOLVE_PREFER_HTTPS_PROXY) {
        nsAutoCString type;
        pi->GetType(type);
        // DIRECT from ProcessPACString indicates that system proxy settings
        // are not configured to use SOCKS proxy. Try https proxy as a
        // secondary preferrable proxy. This is mainly for websocket whose
        // proxy precedence is SOCKS > HTTPS > DIRECT.
        if (type.EqualsLiteral(kProxyType_DIRECT)) {
          scheme.AssignLiteral(kProxyType_HTTPS);
          if (NS_SUCCEEDED(mSystemProxySettings->GetProxyForURI(
                  spec, scheme, host, port, pacString))) {
            ProcessPACString(pacString, 0, getter_AddRefs(pi));
          }
        }
      }
      pi.forget(result);
      return NS_OK;
    }
  }

  // if proxies are enabled and this host:port combo is supposed to use a
  // proxy, check for a proxy.
  if (mProxyConfig == PROXYCONFIG_DIRECT ||
      (mProxyConfig == PROXYCONFIG_MANUAL &&
       !CanUseProxy(uri, info.defaultPort)))
    return NS_OK;

  // Proxy auto config magic...
  if (mProxyConfig == PROXYCONFIG_PAC || mProxyConfig == PROXYCONFIG_WPAD) {
    // Do not query PAC now.
    *usePACThread = true;
    return NS_OK;
  }

  // If we aren't in manual proxy configuration mode then we don't
  // want to honor any manual specific prefs that might be still set
  if (mProxyConfig != PROXYCONFIG_MANUAL) return NS_OK;

  // proxy info values for manual configuration mode
  const char* type = nullptr;
  const nsACString* host = nullptr;
  int32_t port = -1;

  uint32_t proxyFlags = 0;

  if ((flags & RESOLVE_PREFER_SOCKS_PROXY) && !mSOCKSProxyTarget.IsEmpty() &&
      (IsHostLocalTarget(mSOCKSProxyTarget) || mSOCKSProxyPort > 0)) {
    host = &mSOCKSProxyTarget;
    if (mSOCKSProxyVersion == 4)
      type = kProxyType_SOCKS4;
    else
      type = kProxyType_SOCKS;
    port = mSOCKSProxyPort;
    if (mSOCKSProxyRemoteDNS)
      proxyFlags |= nsIProxyInfo::TRANSPARENT_PROXY_RESOLVES_HOST;
  } else if ((flags & RESOLVE_PREFER_HTTPS_PROXY) &&
             !mHTTPSProxyHost.IsEmpty() && mHTTPSProxyPort > 0) {
    host = &mHTTPSProxyHost;
    type = kProxyType_HTTP;
    port = mHTTPSProxyPort;
  } else if (!mHTTPProxyHost.IsEmpty() && mHTTPProxyPort > 0 &&
             ((flags & RESOLVE_IGNORE_URI_SCHEME) ||
              info.scheme.EqualsLiteral("http"))) {
    host = &mHTTPProxyHost;
    type = kProxyType_HTTP;
    port = mHTTPProxyPort;
  } else if (!mHTTPSProxyHost.IsEmpty() && mHTTPSProxyPort > 0 &&
             !(flags & RESOLVE_IGNORE_URI_SCHEME) &&
             info.scheme.EqualsLiteral("https")) {
    host = &mHTTPSProxyHost;
    type = kProxyType_HTTP;
    port = mHTTPSProxyPort;
  } else if (!mFTPProxyHost.IsEmpty() && mFTPProxyPort > 0 &&
             !(flags & RESOLVE_IGNORE_URI_SCHEME) &&
             info.scheme.EqualsLiteral("ftp")) {
    host = &mFTPProxyHost;
    type = kProxyType_HTTP;
    port = mFTPProxyPort;
  } else if (!mSOCKSProxyTarget.IsEmpty() &&
             (IsHostLocalTarget(mSOCKSProxyTarget) || mSOCKSProxyPort > 0)) {
    host = &mSOCKSProxyTarget;
    if (mSOCKSProxyVersion == 4)
      type = kProxyType_SOCKS4;
    else
      type = kProxyType_SOCKS;
    port = mSOCKSProxyPort;
    if (mSOCKSProxyRemoteDNS)
      proxyFlags |= nsIProxyInfo::TRANSPARENT_PROXY_RESOLVES_HOST;
  }

  if (type) {
    rv = NewProxyInfo_Internal(type, *host, port, ""_ns, ""_ns, ""_ns, ""_ns,
                               proxyFlags, UINT32_MAX, nullptr, flags, result);
    if (NS_FAILED(rv)) return rv;
  }

  return NS_OK;
}

void nsProtocolProxyService::MaybeDisableDNSPrefetch(nsIProxyInfo* aProxy) {
  // Disable Prefetch in the DNS service if a proxy is in use.
  if (!aProxy) return;

  nsCOMPtr<nsProxyInfo> pi = do_QueryInterface(aProxy);
  if (!pi || !pi->mType || pi->mType == kProxyType_DIRECT) return;

  nsCOMPtr<nsIDNSService> dns = do_GetService(NS_DNSSERVICE_CONTRACTID);
  if (!dns) return;
  nsCOMPtr<nsPIDNSService> pdns = do_QueryInterface(dns);
  if (!pdns) return;

  // We lose the prefetch optimization for the life of the dns service.
  pdns->SetPrefetchEnabled(false);
}

void nsProtocolProxyService::CopyFilters(nsTArray<RefPtr<FilterLink>>& aCopy) {
  MOZ_ASSERT(aCopy.Length() == 0);
  aCopy.AppendElements(mFilters);
}

bool nsProtocolProxyService::ApplyFilter(
    FilterLink const* filterLink, nsIChannel* channel,
    const nsProtocolInfo& info, nsCOMPtr<nsIProxyInfo> list,
    nsIProxyProtocolFilterResult* callback) {
  nsresult rv;

  // We prune the proxy list prior to invoking each filter.  This may be
  // somewhat inefficient, but it seems like a good idea since we want each
  // filter to "see" a valid proxy list.
  PruneProxyInfo(info, list);

  if (filterLink->filter) {
    nsCOMPtr<nsIURI> uri;
    Unused << GetProxyURI(channel, getter_AddRefs(uri));
    if (!uri) {
      return false;
    }

    rv = filterLink->filter->ApplyFilter(uri, list, callback);
    return NS_SUCCEEDED(rv);
  }

  if (filterLink->channelFilter) {
    rv = filterLink->channelFilter->ApplyFilter(channel, list, callback);
    return NS_SUCCEEDED(rv);
  }

  return false;
}

void nsProtocolProxyService::PruneProxyInfo(const nsProtocolInfo& info,
                                            nsIProxyInfo** list) {
  if (!*list) return;

  LOG(("nsProtocolProxyService::PruneProxyInfo ENTER list=%p", *list));

  nsProxyInfo* head = nullptr;
  CallQueryInterface(*list, &head);
  if (!head) {
    MOZ_ASSERT_UNREACHABLE("nsIProxyInfo must QI to nsProxyInfo");
    return;
  }
  NS_RELEASE(*list);

  // Pruning of disabled proxies works like this:
  //   - If all proxies are disabled, return the full list
  //   - Otherwise, remove the disabled proxies.
  //
  // Pruning of disallowed proxies works like this:
  //   - If the protocol handler disallows the proxy, then we disallow it.

  // Start by removing all disallowed proxies if required:
  if (!(info.flags & nsIProtocolHandler::ALLOWS_PROXY_HTTP)) {
    nsProxyInfo *last = nullptr, *iter = head;
    while (iter) {
      if ((iter->Type() == kProxyType_HTTP) ||
          (iter->Type() == kProxyType_HTTPS)) {
        // reject!
        if (last)
          last->mNext = iter->mNext;
        else
          head = iter->mNext;
        nsProxyInfo* next = iter->mNext;
        iter->mNext = nullptr;
        iter->Release();
        iter = next;
      } else {
        last = iter;
        iter = iter->mNext;
      }
    }
    if (!head) {
      return;
    }
  }

  // Scan to see if all remaining non-direct proxies are disabled. If so, then
  // we'll just bail and return them all.  Otherwise, we'll go and prune the
  // disabled ones.

  bool allNonDirectProxiesDisabled = true;

  nsProxyInfo* iter;
  for (iter = head; iter; iter = iter->mNext) {
    if (!IsProxyDisabled(iter) && iter->mType != kProxyType_DIRECT) {
      allNonDirectProxiesDisabled = false;
      break;
    }
  }

  if (allNonDirectProxiesDisabled) {
    LOG(("All proxies are disabled, so trying all again"));
  } else {
    // remove any disabled proxies.
    nsProxyInfo* last = nullptr;
    for (iter = head; iter;) {
      if (IsProxyDisabled(iter)) {
        // reject!
        nsProxyInfo* reject = iter;

        iter = iter->mNext;
        if (last)
          last->mNext = iter;
        else
          head = iter;

        reject->mNext = nullptr;
        NS_RELEASE(reject);
        continue;
      }

      // since we are about to use this proxy, make sure it is not on
      // the disabled proxy list.  we'll add it back to that list if
      // we have to (in GetFailoverForProxy).
      //
      // XXX(darin): It might be better to do this as a final pass.
      //
      EnableProxy(iter);

      last = iter;
      iter = iter->mNext;
    }
  }

  // if only DIRECT was specified then return no proxy info, and we're done.
  if (head && !head->mNext && head->mType == kProxyType_DIRECT)
    NS_RELEASE(head);

  *list = head;  // Transfer ownership

  LOG(("nsProtocolProxyService::PruneProxyInfo LEAVE list=%p", *list));
}

bool nsProtocolProxyService::GetIsPACLoading() {
  return mPACMan && mPACMan->IsLoading();
}

}  // namespace net
}  // namespace mozilla