forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfigured_proxy_resolution_service.cc
1590 lines (1377 loc) · 57.4 KB
/
configured_proxy_resolution_service.cc
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
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/proxy_resolution/configured_proxy_resolution_service.h"
#include <algorithm>
#include <cmath>
#include <memory>
#include <utility>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/compiler_specific.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/weak_ptr.h"
#include "base/metrics/histogram_macros.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/values.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "net/base/net_errors.h"
#include "net/base/net_info_source_list.h"
#include "net/base/network_isolation_key.h"
#include "net/base/proxy_delegate.h"
#include "net/base/url_util.h"
#include "net/log/net_log.h"
#include "net/log/net_log_event_type.h"
#include "net/log/net_log_util.h"
#include "net/log/net_log_with_source.h"
#include "net/proxy_resolution/configured_proxy_resolution_request.h"
#include "net/proxy_resolution/dhcp_pac_file_fetcher.h"
#include "net/proxy_resolution/multi_threaded_proxy_resolver.h"
#include "net/proxy_resolution/pac_file_decider.h"
#include "net/proxy_resolution/pac_file_fetcher.h"
#include "net/proxy_resolution/proxy_config_service_fixed.h"
#include "net/proxy_resolution/proxy_resolver_factory.h"
#include "net/url_request/url_request_context.h"
#if defined(OS_WIN)
#include "net/proxy_resolution/win/proxy_config_service_win.h"
#include "net/proxy_resolution/win/proxy_resolver_winhttp.h"
#elif defined(OS_IOS)
#include "net/proxy_resolution/proxy_config_service_ios.h"
#include "net/proxy_resolution/proxy_resolver_mac.h"
#elif defined(OS_MAC)
#include "net/proxy_resolution/proxy_config_service_mac.h"
#include "net/proxy_resolution/proxy_resolver_mac.h"
// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch
// of lacros-chrome is complete.
#elif defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)
#include "net/proxy_resolution/proxy_config_service_linux.h"
#elif defined(OS_ANDROID)
#include "net/proxy_resolution/proxy_config_service_android.h"
#endif
using base::TimeDelta;
using base::TimeTicks;
namespace net {
namespace {
// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch
// of lacros-chrome is complete.
#if defined(OS_WIN) || defined(OS_APPLE) || \
(defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
constexpr net::NetworkTrafficAnnotationTag kSystemProxyConfigTrafficAnnotation =
net::DefineNetworkTrafficAnnotation("proxy_config_system", R"(
semantics {
sender: "Proxy Config"
description:
"Establishing a connection through a proxy server using system proxy "
"settings."
trigger:
"Whenever a network request is made when the system proxy settings "
"are used, and they indicate to use a proxy server."
data:
"Proxy configuration."
destination: OTHER
destination_other:
"The proxy server specified in the configuration."
}
policy {
cookies_allowed: NO
setting:
"User cannot override system proxy settings, but can change them "
"through 'Advanced/System/Open proxy settings'."
policy_exception_justification:
"Using either of 'ProxyMode', 'ProxyServer', or 'ProxyPacUrl' "
"policies can set Chrome to use a specific proxy settings and avoid "
"system proxy."
})");
#endif
const size_t kDefaultNumPacThreads = 4;
// When the IP address changes we don't immediately re-run proxy auto-config.
// Instead, we wait for |kDelayAfterNetworkChangesMs| before
// attempting to re-valuate proxy auto-config.
//
// During this time window, any resolve requests sent to the
// ConfiguredProxyResolutionService will be queued. Once we have waited the
// required amount of them, the proxy auto-config step will be run, and the
// queued requests resumed.
//
// The reason we play this game is that our signal for detecting network
// changes (NetworkChangeNotifier) may fire *before* the system's networking
// dependencies are fully configured. This is a problem since it means if
// we were to run proxy auto-config right away, it could fail due to spurious
// DNS failures. (see http://crbug.com/50779 for more details.)
//
// By adding the wait window, we give things a better chance to get properly
// set up. Network failures can happen at any time though, so we additionally
// poll the PAC script for changes, which will allow us to recover from these
// sorts of problems.
const int64_t kDelayAfterNetworkChangesMs = 2000;
// This is the default policy for polling the PAC script.
//
// In response to a failure, the poll intervals are:
// 0: 8 seconds (scheduled on timer)
// 1: 32 seconds
// 2: 2 minutes
// 3+: 4 hours
//
// In response to a success, the poll intervals are:
// 0+: 12 hours
//
// Only the 8 second poll is scheduled on a timer, the rest happen in response
// to network activity (and hence will take longer than the written time).
//
// Explanation for these values:
//
// TODO(eroman): These values are somewhat arbitrary, and need to be tuned
// using some histograms data. Trying to be conservative so as not to break
// existing setups when deployed. A simple exponential retry scheme would be
// more elegant, but places more load on server.
//
// The motivation for trying quickly after failures (8 seconds) is to recover
// from spurious network failures, which are common after the IP address has
// just changed (like DNS failing to resolve). The next 32 second boundary is
// to try and catch other VPN weirdness which anecdotally I have seen take
// 10+ seconds for some users.
//
// The motivation for re-trying after a success is to check for possible
// content changes to the script, or to the WPAD auto-discovery results. We are
// not very aggressive with these checks so as to minimize the risk of
// overloading existing PAC setups. Moreover it is unlikely that PAC scripts
// change very frequently in existing setups. More research is needed to
// motivate what safe values are here, and what other user agents do.
//
// Comparison to other browsers:
//
// In Firefox the PAC URL is re-tried on failures according to
// network.proxy.autoconfig_retry_interval_min and
// network.proxy.autoconfig_retry_interval_max. The defaults are 5 seconds and
// 5 minutes respectively. It doubles the interval at each attempt.
//
// TODO(eroman): Figure out what Internet Explorer does.
class DefaultPollPolicy
: public ConfiguredProxyResolutionService::PacPollPolicy {
public:
DefaultPollPolicy() = default;
Mode GetNextDelay(int initial_error,
TimeDelta current_delay,
TimeDelta* next_delay) const override {
if (initial_error != OK) {
// Re-try policy for failures.
const int kDelay1Seconds = 8;
const int kDelay2Seconds = 32;
const int kDelay3Seconds = 2 * 60; // 2 minutes
const int kDelay4Seconds = 4 * 60 * 60; // 4 Hours
// Initial poll.
if (current_delay < TimeDelta()) {
*next_delay = TimeDelta::FromSeconds(kDelay1Seconds);
return MODE_USE_TIMER;
}
switch (current_delay.InSeconds()) {
case kDelay1Seconds:
*next_delay = TimeDelta::FromSeconds(kDelay2Seconds);
return MODE_START_AFTER_ACTIVITY;
case kDelay2Seconds:
*next_delay = TimeDelta::FromSeconds(kDelay3Seconds);
return MODE_START_AFTER_ACTIVITY;
default:
*next_delay = TimeDelta::FromSeconds(kDelay4Seconds);
return MODE_START_AFTER_ACTIVITY;
}
} else {
// Re-try policy for succeses.
*next_delay = TimeDelta::FromHours(12);
return MODE_START_AFTER_ACTIVITY;
}
}
private:
DISALLOW_COPY_AND_ASSIGN(DefaultPollPolicy);
};
// Config getter that always returns direct settings.
class ProxyConfigServiceDirect : public ProxyConfigService {
public:
// ProxyConfigService implementation:
void AddObserver(Observer* observer) override {}
void RemoveObserver(Observer* observer) override {}
ConfigAvailability GetLatestProxyConfig(
ProxyConfigWithAnnotation* config) override {
*config = ProxyConfigWithAnnotation::CreateDirect();
return CONFIG_VALID;
}
};
// Proxy resolver that fails every time.
class ProxyResolverNull : public ProxyResolver {
public:
ProxyResolverNull() = default;
// ProxyResolver implementation.
int GetProxyForURL(const GURL& url,
const NetworkIsolationKey& network_isolation_key,
ProxyInfo* results,
CompletionOnceCallback callback,
std::unique_ptr<Request>* request,
const NetLogWithSource& net_log) override {
return ERR_NOT_IMPLEMENTED;
}
};
// ProxyResolver that simulates a PAC script which returns
// |pac_string| for every single URL.
class ProxyResolverFromPacString : public ProxyResolver {
public:
explicit ProxyResolverFromPacString(const std::string& pac_string)
: pac_string_(pac_string) {}
int GetProxyForURL(const GURL& url,
const NetworkIsolationKey& network_isolation_key,
ProxyInfo* results,
CompletionOnceCallback callback,
std::unique_ptr<Request>* request,
const NetLogWithSource& net_log) override {
results->UsePacString(pac_string_);
return OK;
}
private:
const std::string pac_string_;
};
// Creates ProxyResolvers using a platform-specific implementation.
class ProxyResolverFactoryForSystem : public MultiThreadedProxyResolverFactory {
public:
explicit ProxyResolverFactoryForSystem(size_t max_num_threads)
: MultiThreadedProxyResolverFactory(max_num_threads,
false /*expects_pac_bytes*/) {}
std::unique_ptr<ProxyResolverFactory> CreateProxyResolverFactory() override {
#if defined(OS_WIN)
return std::make_unique<ProxyResolverFactoryWinHttp>();
#elif defined(OS_APPLE)
return std::make_unique<ProxyResolverFactoryMac>();
#else
NOTREACHED();
return nullptr;
#endif
}
static bool IsSupported() {
#if defined(OS_WIN) || defined(OS_APPLE)
return true;
#else
return false;
#endif
}
private:
DISALLOW_COPY_AND_ASSIGN(ProxyResolverFactoryForSystem);
};
class ProxyResolverFactoryForNullResolver : public ProxyResolverFactory {
public:
ProxyResolverFactoryForNullResolver() : ProxyResolverFactory(false) {}
// ProxyResolverFactory overrides.
int CreateProxyResolver(const scoped_refptr<PacFileData>& pac_script,
std::unique_ptr<ProxyResolver>* resolver,
CompletionOnceCallback callback,
std::unique_ptr<Request>* request) override {
*resolver = std::make_unique<ProxyResolverNull>();
return OK;
}
private:
DISALLOW_COPY_AND_ASSIGN(ProxyResolverFactoryForNullResolver);
};
class ProxyResolverFactoryForPacResult : public ProxyResolverFactory {
public:
explicit ProxyResolverFactoryForPacResult(const std::string& pac_string)
: ProxyResolverFactory(false), pac_string_(pac_string) {}
// ProxyResolverFactory override.
int CreateProxyResolver(const scoped_refptr<PacFileData>& pac_script,
std::unique_ptr<ProxyResolver>* resolver,
CompletionOnceCallback callback,
std::unique_ptr<Request>* request) override {
*resolver = std::make_unique<ProxyResolverFromPacString>(pac_string_);
return OK;
}
private:
const std::string pac_string_;
DISALLOW_COPY_AND_ASSIGN(ProxyResolverFactoryForPacResult);
};
// Returns NetLog parameters describing a proxy configuration change.
base::Value NetLogProxyConfigChangedParams(
const absl::optional<ProxyConfigWithAnnotation>* old_config,
const ProxyConfigWithAnnotation* new_config) {
base::Value dict(base::Value::Type::DICTIONARY);
// The "old_config" is optional -- the first notification will not have
// any "previous" configuration.
if (old_config->has_value())
dict.SetKey("old_config", (*old_config)->value().ToValue());
dict.SetKey("new_config", new_config->value().ToValue());
return dict;
}
base::Value NetLogBadProxyListParams(const ProxyRetryInfoMap* retry_info) {
base::Value dict(base::Value::Type::DICTIONARY);
base::Value list(base::Value::Type::LIST);
for (const auto& retry_info_pair : *retry_info)
list.Append(retry_info_pair.first);
dict.SetKey("bad_proxy_list", std::move(list));
return dict;
}
// Returns NetLog parameters on a successful proxy resolution.
base::Value NetLogFinishedResolvingProxyParams(const ProxyInfo* result) {
base::Value dict(base::Value::Type::DICTIONARY);
dict.SetStringKey("pac_string", result->ToPacString());
return dict;
}
#if BUILDFLAG(IS_CHROMEOS_ASH)
class UnsetProxyConfigService : public ProxyConfigService {
public:
UnsetProxyConfigService() = default;
~UnsetProxyConfigService() override = default;
void AddObserver(Observer* observer) override {}
void RemoveObserver(Observer* observer) override {}
ConfigAvailability GetLatestProxyConfig(
ProxyConfigWithAnnotation* config) override {
return CONFIG_UNSET;
}
};
#endif
// Returns a sanitized copy of |url| which is safe to pass on to a PAC script.
//
// PAC scripts are modelled as being controllable by a network-present
// attacker (since such an attacker can influence the outcome of proxy
// auto-discovery, or modify the contents of insecurely delivered PAC scripts).
//
// As such, it is important that the full path/query of https:// URLs not be
// sent to PAC scripts, since that would give an attacker access to data that
// is ordinarily protected by TLS.
//
// Obscuring the path for http:// URLs isn't being done since it doesn't matter
// for security (attacker can already route traffic through their HTTP proxy
// and see the full URL for http:// requests).
//
// TODO(https://crbug.com/882536): Use the same stripping for insecure URL
// schemes.
GURL SanitizeUrl(const GURL& url) {
DCHECK(url.is_valid());
GURL::Replacements replacements;
replacements.ClearUsername();
replacements.ClearPassword();
replacements.ClearRef();
if (url.SchemeIsCryptographic()) {
replacements.ClearPath();
replacements.ClearQuery();
}
return url.ReplaceComponents(replacements);
}
} // namespace
// ConfiguredProxyResolutionService::InitProxyResolver
// ----------------------------------
// This glues together two asynchronous steps:
// (1) PacFileDecider -- try to fetch/validate a sequence of PAC scripts
// to figure out what we should configure against.
// (2) Feed the fetched PAC script into the ProxyResolver.
//
// InitProxyResolver is a single-use class which encapsulates cancellation as
// part of its destructor. Start() or StartSkipDecider() should be called just
// once. The instance can be destroyed at any time, and the request will be
// cancelled.
class ConfiguredProxyResolutionService::InitProxyResolver {
public:
InitProxyResolver()
: proxy_resolver_factory_(nullptr),
proxy_resolver_(nullptr),
next_state_(STATE_NONE),
quick_check_enabled_(true) {}
// Note that the destruction of PacFileDecider will automatically cancel
// any outstanding work.
~InitProxyResolver() = default;
// Begins initializing the proxy resolver; calls |callback| when done. A
// ProxyResolver instance will be created using |proxy_resolver_factory| and
// assigned to |*proxy_resolver| if the final result is OK.
int Start(std::unique_ptr<ProxyResolver>* proxy_resolver,
ProxyResolverFactory* proxy_resolver_factory,
PacFileFetcher* pac_file_fetcher,
DhcpPacFileFetcher* dhcp_pac_file_fetcher,
NetLog* net_log,
const ProxyConfigWithAnnotation& config,
TimeDelta wait_delay,
CompletionOnceCallback callback) {
DCHECK_EQ(STATE_NONE, next_state_);
proxy_resolver_ = proxy_resolver;
proxy_resolver_factory_ = proxy_resolver_factory;
decider_ = std::make_unique<PacFileDecider>(pac_file_fetcher,
dhcp_pac_file_fetcher, net_log);
decider_->set_quick_check_enabled(quick_check_enabled_);
config_ = config;
wait_delay_ = wait_delay;
callback_ = std::move(callback);
next_state_ = STATE_DECIDE_PAC_FILE;
return DoLoop(OK);
}
// Similar to Start(), however it skips the PacFileDecider stage. Instead
// |effective_config|, |decider_result| and |script_data| will be used as the
// inputs for initializing the ProxyResolver. A ProxyResolver instance will
// be created using |proxy_resolver_factory| and assigned to
// |*proxy_resolver| if the final result is OK.
int StartSkipDecider(std::unique_ptr<ProxyResolver>* proxy_resolver,
ProxyResolverFactory* proxy_resolver_factory,
const ProxyConfigWithAnnotation& effective_config,
int decider_result,
const PacFileDataWithSource& script_data,
CompletionOnceCallback callback) {
DCHECK_EQ(STATE_NONE, next_state_);
proxy_resolver_ = proxy_resolver;
proxy_resolver_factory_ = proxy_resolver_factory;
effective_config_ = effective_config;
script_data_ = script_data;
callback_ = std::move(callback);
if (decider_result != OK)
return decider_result;
next_state_ = STATE_CREATE_RESOLVER;
return DoLoop(OK);
}
// Returns the proxy configuration that was selected by PacFileDecider.
// Should only be called upon completion of the initialization.
const ProxyConfigWithAnnotation& effective_config() const {
DCHECK_EQ(STATE_NONE, next_state_);
return effective_config_;
}
// Returns the PAC script data that was selected by PacFileDecider.
// Should only be called upon completion of the initialization.
const PacFileDataWithSource& script_data() {
DCHECK_EQ(STATE_NONE, next_state_);
return script_data_;
}
LoadState GetLoadState() const {
if (next_state_ == STATE_DECIDE_PAC_FILE_COMPLETE) {
// In addition to downloading, this state may also include the stall time
// after network change events (kDelayAfterNetworkChangesMs).
return LOAD_STATE_DOWNLOADING_PAC_FILE;
}
return LOAD_STATE_RESOLVING_PROXY_FOR_URL;
}
// This must be called before the HostResolver is torn down.
void OnShutdown() {
if (decider_)
decider_->OnShutdown();
}
void set_quick_check_enabled(bool enabled) { quick_check_enabled_ = enabled; }
bool quick_check_enabled() const { return quick_check_enabled_; }
private:
enum State {
STATE_NONE,
STATE_DECIDE_PAC_FILE,
STATE_DECIDE_PAC_FILE_COMPLETE,
STATE_CREATE_RESOLVER,
STATE_CREATE_RESOLVER_COMPLETE,
};
int DoLoop(int result) {
DCHECK_NE(next_state_, STATE_NONE);
int rv = result;
do {
State state = next_state_;
next_state_ = STATE_NONE;
switch (state) {
case STATE_DECIDE_PAC_FILE:
DCHECK_EQ(OK, rv);
rv = DoDecidePacFile();
break;
case STATE_DECIDE_PAC_FILE_COMPLETE:
rv = DoDecidePacFileComplete(rv);
break;
case STATE_CREATE_RESOLVER:
DCHECK_EQ(OK, rv);
rv = DoCreateResolver();
break;
case STATE_CREATE_RESOLVER_COMPLETE:
rv = DoCreateResolverComplete(rv);
break;
default:
NOTREACHED() << "bad state: " << state;
rv = ERR_UNEXPECTED;
break;
}
} while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
return rv;
}
int DoDecidePacFile() {
next_state_ = STATE_DECIDE_PAC_FILE_COMPLETE;
return decider_->Start(config_, wait_delay_,
proxy_resolver_factory_->expects_pac_bytes(),
base::BindOnce(&InitProxyResolver::OnIOCompletion,
base::Unretained(this)));
}
int DoDecidePacFileComplete(int result) {
if (result != OK)
return result;
effective_config_ = decider_->effective_config();
script_data_ = decider_->script_data();
next_state_ = STATE_CREATE_RESOLVER;
return OK;
}
int DoCreateResolver() {
DCHECK(script_data_.data);
// TODO(eroman): Should log this latency to the NetLog.
next_state_ = STATE_CREATE_RESOLVER_COMPLETE;
return proxy_resolver_factory_->CreateProxyResolver(
script_data_.data, proxy_resolver_,
base::BindOnce(&InitProxyResolver::OnIOCompletion,
base::Unretained(this)),
&create_resolver_request_);
}
int DoCreateResolverComplete(int result) {
if (result != OK)
proxy_resolver_->reset();
return result;
}
void OnIOCompletion(int result) {
DCHECK_NE(STATE_NONE, next_state_);
int rv = DoLoop(result);
if (rv != ERR_IO_PENDING)
std::move(callback_).Run(result);
}
ProxyConfigWithAnnotation config_;
ProxyConfigWithAnnotation effective_config_;
PacFileDataWithSource script_data_;
TimeDelta wait_delay_;
std::unique_ptr<PacFileDecider> decider_;
ProxyResolverFactory* proxy_resolver_factory_;
std::unique_ptr<ProxyResolverFactory::Request> create_resolver_request_;
std::unique_ptr<ProxyResolver>* proxy_resolver_;
CompletionOnceCallback callback_;
State next_state_;
bool quick_check_enabled_;
DISALLOW_COPY_AND_ASSIGN(InitProxyResolver);
};
// ConfiguredProxyResolutionService::PacFileDeciderPoller
// ---------------------------
// This helper class encapsulates the logic to schedule and run periodic
// background checks to see if the PAC script (or effective proxy configuration)
// has changed. If a change is detected, then the caller will be notified via
// the ChangeCallback.
class ConfiguredProxyResolutionService::PacFileDeciderPoller {
public:
typedef base::RepeatingCallback<
void(int, const PacFileDataWithSource&, const ProxyConfigWithAnnotation&)>
ChangeCallback;
// Builds a poller helper, and starts polling for updates. Whenever a change
// is observed, |callback| will be invoked with the details.
//
// |config| specifies the (unresolved) proxy configuration to poll.
// |proxy_resolver_expects_pac_bytes| the type of proxy resolver we expect
// to use the resulting script data with
// (so it can choose the right format).
// |pac_file_fetcher| this pointer must remain alive throughout our
// lifetime. It is the dependency that will be used
// for downloading PAC files.
// |dhcp_pac_file_fetcher| similar to |pac_file_fetcher|, but for
// he DHCP dependency.
// |init_net_error| This is the initial network error (possibly success)
// encountered by the first PAC fetch attempt. We use it
// to schedule updates more aggressively if the initial
// fetch resulted in an error.
// |init_script_data| the initial script data from the PAC fetch attempt.
// This is the baseline used to determine when the
// script's contents have changed.
// |net_log| the NetLog to log progress into.
PacFileDeciderPoller(ChangeCallback callback,
const ProxyConfigWithAnnotation& config,
bool proxy_resolver_expects_pac_bytes,
PacFileFetcher* pac_file_fetcher,
DhcpPacFileFetcher* dhcp_pac_file_fetcher,
int init_net_error,
const PacFileDataWithSource& init_script_data,
NetLog* net_log)
: change_callback_(callback),
config_(config),
proxy_resolver_expects_pac_bytes_(proxy_resolver_expects_pac_bytes),
pac_file_fetcher_(pac_file_fetcher),
dhcp_pac_file_fetcher_(dhcp_pac_file_fetcher),
last_error_(init_net_error),
last_script_data_(init_script_data),
last_poll_time_(TimeTicks::Now()) {
// Set the initial poll delay.
next_poll_mode_ = poll_policy()->GetNextDelay(
last_error_, TimeDelta::FromSeconds(-1), &next_poll_delay_);
TryToStartNextPoll(false);
}
void OnLazyPoll() {
// We have just been notified of network activity. Use this opportunity to
// see if we can start our next poll.
TryToStartNextPoll(true);
}
static const PacPollPolicy* set_policy(const PacPollPolicy* policy) {
const PacPollPolicy* prev = poll_policy_;
poll_policy_ = policy;
return prev;
}
void set_quick_check_enabled(bool enabled) { quick_check_enabled_ = enabled; }
bool quick_check_enabled() const { return quick_check_enabled_; }
private:
// Returns the effective poll policy (the one injected by unit-tests, or the
// default).
const PacPollPolicy* poll_policy() {
if (poll_policy_)
return poll_policy_;
return &default_poll_policy_;
}
void StartPollTimer() {
DCHECK(!decider_.get());
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&PacFileDeciderPoller::DoPoll,
weak_factory_.GetWeakPtr()),
next_poll_delay_);
}
void TryToStartNextPoll(bool triggered_by_activity) {
switch (next_poll_mode_) {
case PacPollPolicy::MODE_USE_TIMER:
if (!triggered_by_activity)
StartPollTimer();
break;
case PacPollPolicy::MODE_START_AFTER_ACTIVITY:
if (triggered_by_activity && !decider_.get()) {
TimeDelta elapsed_time = TimeTicks::Now() - last_poll_time_;
if (elapsed_time >= next_poll_delay_)
DoPoll();
}
break;
}
}
void DoPoll() {
last_poll_time_ = TimeTicks::Now();
// Start the PAC file decider to see if anything has changed.
// TODO(eroman): Pass a proper NetLog rather than nullptr.
decider_ = std::make_unique<PacFileDecider>(
pac_file_fetcher_, dhcp_pac_file_fetcher_, nullptr);
decider_->set_quick_check_enabled(quick_check_enabled_);
int result = decider_->Start(
config_, TimeDelta(), proxy_resolver_expects_pac_bytes_,
base::BindOnce(&PacFileDeciderPoller::OnPacFileDeciderCompleted,
base::Unretained(this)));
if (result != ERR_IO_PENDING)
OnPacFileDeciderCompleted(result);
}
void OnPacFileDeciderCompleted(int result) {
if (HasScriptDataChanged(result, decider_->script_data())) {
// Something has changed, we must notify the
// ConfiguredProxyResolutionService so it can re-initialize its
// ProxyResolver. Note that we post a notification task rather than
// calling it directly -- this is done to avoid an ugly destruction
// sequence, since |this| might be destroyed as a result of the
// notification.
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(
&PacFileDeciderPoller::NotifyProxyResolutionServiceOfChange,
weak_factory_.GetWeakPtr(), result, decider_->script_data(),
decider_->effective_config()));
return;
}
decider_.reset();
// Decide when the next poll should take place, and possibly start the
// next timer.
next_poll_mode_ = poll_policy()->GetNextDelay(last_error_, next_poll_delay_,
&next_poll_delay_);
TryToStartNextPoll(false);
}
bool HasScriptDataChanged(int result,
const PacFileDataWithSource& script_data) {
if (result != last_error_) {
// Something changed -- it was failing before and now it succeeded, or
// conversely it succeeded before and now it failed. Or it failed in
// both cases, however the specific failure error codes differ.
return true;
}
if (result != OK) {
// If it failed last time and failed again with the same error code this
// time, then nothing has actually changed.
return false;
}
// Otherwise if it succeeded both this time and last time, we need to look
// closer and see if we ended up downloading different content for the PAC
// script.
return !script_data.data->Equals(last_script_data_.data.get()) ||
(script_data.from_auto_detect != last_script_data_.from_auto_detect);
}
void NotifyProxyResolutionServiceOfChange(
int result,
const PacFileDataWithSource& script_data,
const ProxyConfigWithAnnotation& effective_config) {
// Note that |this| may be deleted after calling into the
// ConfiguredProxyResolutionService.
change_callback_.Run(result, script_data, effective_config);
}
ChangeCallback change_callback_;
ProxyConfigWithAnnotation config_;
bool proxy_resolver_expects_pac_bytes_;
PacFileFetcher* pac_file_fetcher_;
DhcpPacFileFetcher* dhcp_pac_file_fetcher_;
int last_error_;
PacFileDataWithSource last_script_data_;
std::unique_ptr<PacFileDecider> decider_;
TimeDelta next_poll_delay_;
PacPollPolicy::Mode next_poll_mode_;
TimeTicks last_poll_time_;
// Polling policy injected by unit-tests. Otherwise this is nullptr and the
// default policy will be used.
static const PacPollPolicy* poll_policy_;
const DefaultPollPolicy default_poll_policy_;
bool quick_check_enabled_;
base::WeakPtrFactory<PacFileDeciderPoller> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(PacFileDeciderPoller);
};
// static
const ConfiguredProxyResolutionService::PacPollPolicy*
ConfiguredProxyResolutionService::PacFileDeciderPoller::poll_policy_ =
nullptr;
// ConfiguredProxyResolutionService
// -----------------------------------------------------
ConfiguredProxyResolutionService::ConfiguredProxyResolutionService(
std::unique_ptr<ProxyConfigService> config_service,
std::unique_ptr<ProxyResolverFactory> resolver_factory,
NetLog* net_log,
bool quick_check_enabled)
: config_service_(std::move(config_service)),
resolver_factory_(std::move(resolver_factory)),
current_state_(STATE_NONE),
permanent_error_(OK),
net_log_(net_log),
stall_proxy_auto_config_delay_(
TimeDelta::FromMilliseconds(kDelayAfterNetworkChangesMs)),
quick_check_enabled_(quick_check_enabled) {
NetworkChangeNotifier::AddIPAddressObserver(this);
NetworkChangeNotifier::AddDNSObserver(this);
config_service_->AddObserver(this);
}
// static
std::unique_ptr<ConfiguredProxyResolutionService>
ConfiguredProxyResolutionService::CreateUsingSystemProxyResolver(
std::unique_ptr<ProxyConfigService> proxy_config_service,
NetLog* net_log,
bool quick_check_enabled) {
DCHECK(proxy_config_service);
if (!ProxyResolverFactoryForSystem::IsSupported()) {
VLOG(1) << "PAC support disabled because there is no system implementation";
return CreateWithoutProxyResolver(std::move(proxy_config_service), net_log);
}
std::unique_ptr<ConfiguredProxyResolutionService> proxy_resolution_service =
std::make_unique<ConfiguredProxyResolutionService>(
std::move(proxy_config_service),
std::make_unique<ProxyResolverFactoryForSystem>(
kDefaultNumPacThreads),
net_log, quick_check_enabled);
return proxy_resolution_service;
}
// static
std::unique_ptr<ConfiguredProxyResolutionService>
ConfiguredProxyResolutionService::CreateWithoutProxyResolver(
std::unique_ptr<ProxyConfigService> proxy_config_service,
NetLog* net_log) {
return std::make_unique<ConfiguredProxyResolutionService>(
std::move(proxy_config_service),
std::make_unique<ProxyResolverFactoryForNullResolver>(), net_log,
/*quick_check_enabled=*/false);
}
// static
std::unique_ptr<ConfiguredProxyResolutionService>
ConfiguredProxyResolutionService::CreateFixed(
const ProxyConfigWithAnnotation& pc) {
// TODO(eroman): This isn't quite right, won't work if |pc| specifies
// a PAC script.
return CreateUsingSystemProxyResolver(
std::make_unique<ProxyConfigServiceFixed>(pc), nullptr,
/*quick_check_enabled=*/true);
}
// static
std::unique_ptr<ConfiguredProxyResolutionService>
ConfiguredProxyResolutionService::CreateFixed(
const std::string& proxy,
const NetworkTrafficAnnotationTag& traffic_annotation) {
ProxyConfig proxy_config;
proxy_config.proxy_rules().ParseFromString(proxy);
ProxyConfigWithAnnotation annotated_config(proxy_config, traffic_annotation);
return ConfiguredProxyResolutionService::CreateFixed(annotated_config);
}
// static
std::unique_ptr<ConfiguredProxyResolutionService>
ConfiguredProxyResolutionService::CreateDirect() {
// Use direct connections.
return std::make_unique<ConfiguredProxyResolutionService>(
std::make_unique<ProxyConfigServiceDirect>(),
std::make_unique<ProxyResolverFactoryForNullResolver>(), nullptr,
/*quick_check_enabled=*/true);
}
// static
std::unique_ptr<ConfiguredProxyResolutionService>
ConfiguredProxyResolutionService::CreateFixedFromPacResult(
const std::string& pac_string,
const NetworkTrafficAnnotationTag& traffic_annotation) {
// We need the settings to contain an "automatic" setting, otherwise the
// ProxyResolver dependency we give it will never be used.
std::unique_ptr<ProxyConfigService> proxy_config_service(
new ProxyConfigServiceFixed(ProxyConfigWithAnnotation(
ProxyConfig::CreateFromCustomPacURL(
GURL("https://my-pac-script.invalid/wpad.dat")),
traffic_annotation)));
return std::make_unique<ConfiguredProxyResolutionService>(
std::move(proxy_config_service),
std::make_unique<ProxyResolverFactoryForPacResult>(pac_string), nullptr,
/*quick_check_enabled=*/true);
}
// static
std::unique_ptr<ConfiguredProxyResolutionService>
ConfiguredProxyResolutionService::CreateFixedFromAutoDetectedPacResult(
const std::string& pac_string,
const NetworkTrafficAnnotationTag& traffic_annotation) {
std::unique_ptr<ProxyConfigService> proxy_config_service(
new ProxyConfigServiceFixed(ProxyConfigWithAnnotation(
ProxyConfig::CreateAutoDetect(), traffic_annotation)));
return std::make_unique<ConfiguredProxyResolutionService>(
std::move(proxy_config_service),
std::make_unique<ProxyResolverFactoryForPacResult>(pac_string), nullptr,
/*quick_check_enabled=*/true);
}
int ConfiguredProxyResolutionService::ResolveProxy(
const GURL& raw_url,
const std::string& method,
const NetworkIsolationKey& network_isolation_key,
ProxyInfo* result,
CompletionOnceCallback callback,
std::unique_ptr<ProxyResolutionRequest>* out_request,
const NetLogWithSource& net_log) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(!callback.is_null());
DCHECK(out_request);
net_log.BeginEvent(NetLogEventType::PROXY_RESOLUTION_SERVICE);
// Notify our polling-based dependencies that a resolve is taking place.
// This way they can schedule their polls in response to network activity.
config_service_->OnLazyPoll();
if (script_poller_.get())
script_poller_->OnLazyPoll();
if (current_state_ == STATE_NONE)
ApplyProxyConfigIfAvailable();
// Sanitize the URL before passing it on to the proxy resolver (i.e. PAC
// script). The goal is to remove sensitive data (like embedded user names
// and password), and local data (i.e. reference fragment) which does not need
// to be disclosed to the resolver.
GURL url = SanitizeUrl(raw_url);
// Check if the request can be completed right away. (This is the case when
// using a direct connection for example).
int rv = TryToCompleteSynchronously(url, result);
if (rv != ERR_IO_PENDING) {
rv = DidFinishResolvingProxy(url, method, result, rv, net_log);
return rv;
}
auto req = std::make_unique<ConfiguredProxyResolutionRequest>(
this, url, method, network_isolation_key, result, std::move(callback),
net_log);
if (current_state_ == STATE_READY) {
// Start the resolve request.
rv = req->Start();
if (rv != ERR_IO_PENDING)
return req->QueryDidCompleteSynchronously(rv);
} else {
req->net_log()->BeginEvent(
NetLogEventType::PROXY_RESOLUTION_SERVICE_WAITING_FOR_INIT_PAC);
}
DCHECK_EQ(ERR_IO_PENDING, rv);
DCHECK(!ContainsPendingRequest(req.get()));
pending_requests_.insert(req.get());
// Completion will be notified through |callback|, unless the caller cancels
// the request using |out_request|.
*out_request = std::move(req);
return rv; // ERR_IO_PENDING