proxy_resolver_mac.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. // Copyright (c) 2011 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "net/proxy_resolution/proxy_resolver_mac.h"
  5. #include <CoreFoundation/CoreFoundation.h>
  6. #include <memory>
  7. #include "base/check.h"
  8. #include "base/lazy_instance.h"
  9. #include "base/mac/foundation_util.h"
  10. #include "base/mac/scoped_cftyperef.h"
  11. #include "base/strings/string_util.h"
  12. #include "base/strings/sys_string_conversions.h"
  13. #include "base/synchronization/lock.h"
  14. #include "base/threading/thread_checker.h"
  15. #include "build/build_config.h"
  16. #include "net/base/net_errors.h"
  17. #include "net/base/proxy_server.h"
  18. #include "net/base/proxy_string_util.h"
  19. #include "net/proxy_resolution/proxy_info.h"
  20. #include "net/proxy_resolution/proxy_list.h"
  21. #include "net/proxy_resolution/proxy_resolver.h"
  22. #include "url/gurl.h"
  23. #if BUILDFLAG(IS_IOS)
  24. #include <CFNetwork/CFProxySupport.h>
  25. #else
  26. #include <CoreServices/CoreServices.h>
  27. #endif
  28. namespace net {
  29. class NetworkIsolationKey;
  30. namespace {
  31. // A lock shared by all ProxyResolverMac instances. It is used to synchronize
  32. // the events of multiple CFNetworkExecuteProxyAutoConfigurationURL run loop
  33. // sources. These events are:
  34. // 1. Adding the source to the run loop.
  35. // 2. Handling the source result.
  36. // 3. Removing the source from the run loop.
  37. static base::LazyInstance<base::Lock>::Leaky g_cfnetwork_pac_runloop_lock =
  38. LAZY_INSTANCE_INITIALIZER;
  39. // Forward declaration of the callback function used by the
  40. // SynchronizedRunLoopObserver class.
  41. void RunLoopObserverCallBackFunc(CFRunLoopObserverRef observer,
  42. CFRunLoopActivity activity,
  43. void* info);
  44. // Utility function to map a CFProxyType to a ProxyServer::Scheme.
  45. // If the type is unknown, returns ProxyServer::SCHEME_INVALID.
  46. ProxyServer::Scheme GetProxyServerScheme(CFStringRef proxy_type) {
  47. if (CFEqual(proxy_type, kCFProxyTypeNone))
  48. return ProxyServer::SCHEME_DIRECT;
  49. if (CFEqual(proxy_type, kCFProxyTypeHTTP))
  50. return ProxyServer::SCHEME_HTTP;
  51. if (CFEqual(proxy_type, kCFProxyTypeHTTPS)) {
  52. // The "HTTPS" on the Mac side here means "proxy applies to https://" URLs;
  53. // the proxy itself is still expected to be an HTTP proxy.
  54. return ProxyServer::SCHEME_HTTP;
  55. }
  56. if (CFEqual(proxy_type, kCFProxyTypeSOCKS)) {
  57. // We can't tell whether this was v4 or v5. We will assume it is
  58. // v5 since that is the only version OS X supports.
  59. return ProxyServer::SCHEME_SOCKS5;
  60. }
  61. return ProxyServer::SCHEME_INVALID;
  62. }
  63. // Callback for CFNetworkExecuteProxyAutoConfigurationURL. |client| is a pointer
  64. // to a CFTypeRef. This stashes either |error| or |proxies| in that location.
  65. void ResultCallback(void* client, CFArrayRef proxies, CFErrorRef error) {
  66. DCHECK((proxies != nullptr) == (error == nullptr));
  67. CFTypeRef* result_ptr = reinterpret_cast<CFTypeRef*>(client);
  68. DCHECK(result_ptr != nullptr);
  69. DCHECK(*result_ptr == nullptr);
  70. if (error != nullptr) {
  71. *result_ptr = CFRetain(error);
  72. } else {
  73. *result_ptr = CFRetain(proxies);
  74. }
  75. CFRunLoopStop(CFRunLoopGetCurrent());
  76. }
  77. #pragma mark - SynchronizedRunLoopObserver
  78. // A run loop observer that guarantees that no two run loop sources protected
  79. // by the same lock will be fired concurrently in different threads.
  80. // The observer does not prevent the parallel execution of the sources but only
  81. // synchronizes the run loop events associated with the sources. In the context
  82. // of proxy resolver, the observer is used to synchronize the execution of the
  83. // callbacks function that handles the result of
  84. // CFNetworkExecuteProxyAutoConfigurationURL execution.
  85. class SynchronizedRunLoopObserver final {
  86. public:
  87. // Creates the instance of an observer that will synchronize the sources
  88. // using a given |lock|.
  89. SynchronizedRunLoopObserver(base::Lock& lock);
  90. SynchronizedRunLoopObserver(const SynchronizedRunLoopObserver&) = delete;
  91. SynchronizedRunLoopObserver& operator=(const SynchronizedRunLoopObserver&) =
  92. delete;
  93. // Destructor.
  94. ~SynchronizedRunLoopObserver();
  95. // Adds the observer to the current run loop for a given run loop mode.
  96. // This method should always be paired with |RemoveFromCurrentRunLoop|.
  97. void AddToCurrentRunLoop(const CFStringRef mode);
  98. // Removes the observer from the current run loop for a given run loop mode.
  99. // This method should always be paired with |AddToCurrentRunLoop|.
  100. void RemoveFromCurrentRunLoop(const CFStringRef mode);
  101. // Callback function that is called when an observable run loop event occurs.
  102. void RunLoopObserverCallBack(CFRunLoopObserverRef observer,
  103. CFRunLoopActivity activity);
  104. private:
  105. // Lock to use to synchronize the run loop sources.
  106. base::Lock& lock_;
  107. // Indicates whether the current observer holds the lock. It is used to
  108. // avoid double locking and releasing.
  109. bool lock_acquired_ = false;
  110. // The underlying CFRunLoopObserverRef structure wrapped by this instance.
  111. base::ScopedCFTypeRef<CFRunLoopObserverRef> observer_;
  112. // Validates that all methods of this class are executed on the same thread.
  113. base::ThreadChecker thread_checker_;
  114. };
  115. SynchronizedRunLoopObserver::SynchronizedRunLoopObserver(base::Lock& lock)
  116. : lock_(lock) {
  117. CFRunLoopObserverContext observer_context = {0, this, nullptr, nullptr,
  118. nullptr};
  119. observer_.reset(CFRunLoopObserverCreate(
  120. kCFAllocatorDefault,
  121. kCFRunLoopBeforeSources | kCFRunLoopBeforeWaiting | kCFRunLoopExit, true,
  122. 0, RunLoopObserverCallBackFunc, &observer_context));
  123. }
  124. SynchronizedRunLoopObserver::~SynchronizedRunLoopObserver() {
  125. DCHECK(thread_checker_.CalledOnValidThread());
  126. DCHECK(!lock_acquired_);
  127. }
  128. void SynchronizedRunLoopObserver::AddToCurrentRunLoop(const CFStringRef mode) {
  129. DCHECK(thread_checker_.CalledOnValidThread());
  130. CFRunLoopAddObserver(CFRunLoopGetCurrent(), observer_.get(), mode);
  131. }
  132. void SynchronizedRunLoopObserver::RemoveFromCurrentRunLoop(
  133. const CFStringRef mode) {
  134. DCHECK(thread_checker_.CalledOnValidThread());
  135. CFRunLoopRemoveObserver(CFRunLoopGetCurrent(), observer_.get(), mode);
  136. }
  137. void SynchronizedRunLoopObserver::RunLoopObserverCallBack(
  138. CFRunLoopObserverRef observer,
  139. CFRunLoopActivity activity) NO_THREAD_SAFETY_ANALYSIS {
  140. DCHECK(thread_checker_.CalledOnValidThread());
  141. // Acquire the lock when a source has been signaled and going to be fired.
  142. // In the context of the proxy resolver that happens when the proxy for a
  143. // given URL has been resolved and the callback function that handles the
  144. // result is going to be fired.
  145. // Release the lock when all source events have been handled.
  146. //
  147. // NO_THREAD_SAFETY_ANALYSIS: Runtime dependent locking.
  148. switch (activity) {
  149. case kCFRunLoopBeforeSources:
  150. if (!lock_acquired_) {
  151. lock_.Acquire();
  152. lock_acquired_ = true;
  153. }
  154. break;
  155. case kCFRunLoopBeforeWaiting:
  156. case kCFRunLoopExit:
  157. if (lock_acquired_) {
  158. lock_acquired_ = false;
  159. lock_.Release();
  160. }
  161. break;
  162. }
  163. }
  164. void RunLoopObserverCallBackFunc(CFRunLoopObserverRef observer,
  165. CFRunLoopActivity activity,
  166. void* info) {
  167. // Forward the call to the instance of SynchronizedRunLoopObserver
  168. // that is associated with the current CF run loop observer.
  169. SynchronizedRunLoopObserver* observerInstance =
  170. (SynchronizedRunLoopObserver*)info;
  171. observerInstance->RunLoopObserverCallBack(observer, activity);
  172. }
  173. #pragma mark - ProxyResolverMac
  174. class ProxyResolverMac : public ProxyResolver {
  175. public:
  176. explicit ProxyResolverMac(const scoped_refptr<PacFileData>& script_data);
  177. ~ProxyResolverMac() override;
  178. // ProxyResolver methods:
  179. int GetProxyForURL(const GURL& url,
  180. const NetworkIsolationKey& network_isolation_key,
  181. ProxyInfo* results,
  182. CompletionOnceCallback callback,
  183. std::unique_ptr<Request>* request,
  184. const NetLogWithSource& net_log) override;
  185. private:
  186. const scoped_refptr<PacFileData> script_data_;
  187. };
  188. ProxyResolverMac::ProxyResolverMac(
  189. const scoped_refptr<PacFileData>& script_data)
  190. : script_data_(script_data) {}
  191. ProxyResolverMac::~ProxyResolverMac() = default;
  192. // Gets the proxy information for a query URL from a PAC. Implementation
  193. // inspired by http://developer.apple.com/samplecode/CFProxySupportTool/
  194. int ProxyResolverMac::GetProxyForURL(
  195. const GURL& query_url,
  196. const NetworkIsolationKey& network_isolation_key,
  197. ProxyInfo* results,
  198. CompletionOnceCallback /*callback*/,
  199. std::unique_ptr<Request>* /*request*/,
  200. const NetLogWithSource& net_log) {
  201. // OS X's system resolver does not support WebSocket URLs in proxy.pac, as of
  202. // version 10.13.5. See https://crbug.com/862121.
  203. GURL mutable_query_url = query_url;
  204. if (query_url.SchemeIsWSOrWSS()) {
  205. GURL::Replacements replacements;
  206. replacements.SetSchemeStr(query_url.SchemeIsCryptographic() ? "https"
  207. : "http");
  208. mutable_query_url = query_url.ReplaceComponents(replacements);
  209. }
  210. base::ScopedCFTypeRef<CFStringRef> query_ref(
  211. base::SysUTF8ToCFStringRef(mutable_query_url.spec()));
  212. base::ScopedCFTypeRef<CFURLRef> query_url_ref(
  213. CFURLCreateWithString(kCFAllocatorDefault, query_ref.get(), nullptr));
  214. if (!query_url_ref.get())
  215. return ERR_FAILED;
  216. base::ScopedCFTypeRef<CFStringRef> pac_ref(base::SysUTF8ToCFStringRef(
  217. script_data_->type() == PacFileData::TYPE_AUTO_DETECT
  218. ? std::string()
  219. : script_data_->url().spec()));
  220. base::ScopedCFTypeRef<CFURLRef> pac_url_ref(
  221. CFURLCreateWithString(kCFAllocatorDefault, pac_ref.get(), nullptr));
  222. if (!pac_url_ref.get())
  223. return ERR_FAILED;
  224. // Work around <rdar://problem/5530166>. This dummy call to
  225. // CFNetworkCopyProxiesForURL initializes some state within CFNetwork that is
  226. // required by CFNetworkExecuteProxyAutoConfigurationURL.
  227. base::ScopedCFTypeRef<CFDictionaryRef> empty_dictionary(
  228. CFDictionaryCreate(nullptr, nullptr, nullptr, 0, nullptr, nullptr));
  229. CFArrayRef dummy_result =
  230. CFNetworkCopyProxiesForURL(query_url_ref.get(), empty_dictionary);
  231. if (dummy_result)
  232. CFRelease(dummy_result);
  233. // We cheat here. We need to act as if we were synchronous, so we pump the
  234. // runloop ourselves. Our caller moved us to a new thread anyway, so this is
  235. // OK to do. (BTW, CFNetworkExecuteProxyAutoConfigurationURL returns a
  236. // runloop source we need to release despite its name.)
  237. CFTypeRef result = nullptr;
  238. CFStreamClientContext context = {0, &result, nullptr, nullptr, nullptr};
  239. base::ScopedCFTypeRef<CFRunLoopSourceRef> runloop_source(
  240. CFNetworkExecuteProxyAutoConfigurationURL(
  241. pac_url_ref.get(), query_url_ref.get(), ResultCallback, &context));
  242. if (!runloop_source)
  243. return ERR_FAILED;
  244. const CFStringRef private_runloop_mode =
  245. CFSTR("org.chromium.ProxyResolverMac");
  246. // Add the run loop observer to synchronize events of
  247. // CFNetworkExecuteProxyAutoConfigurationURL sources. See the definition of
  248. // |g_cfnetwork_pac_runloop_lock|.
  249. SynchronizedRunLoopObserver observer(g_cfnetwork_pac_runloop_lock.Get());
  250. observer.AddToCurrentRunLoop(private_runloop_mode);
  251. // Make sure that no CFNetworkExecuteProxyAutoConfigurationURL sources
  252. // are added to the run loop concurrently.
  253. {
  254. base::AutoLock lock(g_cfnetwork_pac_runloop_lock.Get());
  255. CFRunLoopAddSource(CFRunLoopGetCurrent(), runloop_source.get(),
  256. private_runloop_mode);
  257. }
  258. CFRunLoopRunInMode(private_runloop_mode, DBL_MAX, false);
  259. // Make sure that no CFNetworkExecuteProxyAutoConfigurationURL sources
  260. // are removed from the run loop concurrently.
  261. {
  262. base::AutoLock lock(g_cfnetwork_pac_runloop_lock.Get());
  263. CFRunLoopRemoveSource(CFRunLoopGetCurrent(), runloop_source.get(),
  264. private_runloop_mode);
  265. }
  266. observer.RemoveFromCurrentRunLoop(private_runloop_mode);
  267. DCHECK(result != nullptr);
  268. if (CFGetTypeID(result) == CFErrorGetTypeID()) {
  269. // TODO(avi): do something better than this
  270. CFRelease(result);
  271. return ERR_FAILED;
  272. }
  273. base::ScopedCFTypeRef<CFArrayRef> proxy_array_ref(
  274. base::mac::CFCastStrict<CFArrayRef>(result));
  275. DCHECK(proxy_array_ref != nullptr);
  276. ProxyList proxy_list;
  277. CFIndex proxy_array_count = CFArrayGetCount(proxy_array_ref.get());
  278. for (CFIndex i = 0; i < proxy_array_count; ++i) {
  279. CFDictionaryRef proxy_dictionary = base::mac::CFCastStrict<CFDictionaryRef>(
  280. CFArrayGetValueAtIndex(proxy_array_ref.get(), i));
  281. DCHECK(proxy_dictionary != nullptr);
  282. // The dictionary may have the following keys:
  283. // - kCFProxyTypeKey : The type of the proxy
  284. // - kCFProxyHostNameKey
  285. // - kCFProxyPortNumberKey : The meat we're after.
  286. // - kCFProxyUsernameKey
  287. // - kCFProxyPasswordKey : Despite the existence of these keys in the
  288. // documentation, they're never populated. Even if a
  289. // username/password were to be set in the network
  290. // proxy system preferences, we'd need to fetch it
  291. // from the Keychain ourselves. CFProxy is such a
  292. // tease.
  293. // - kCFProxyAutoConfigurationURLKey : If the PAC file specifies another
  294. // PAC file, I'm going home.
  295. CFStringRef proxy_type = base::mac::GetValueFromDictionary<CFStringRef>(
  296. proxy_dictionary, kCFProxyTypeKey);
  297. ProxyServer proxy_server = ProxyDictionaryToProxyServer(
  298. GetProxyServerScheme(proxy_type), proxy_dictionary, kCFProxyHostNameKey,
  299. kCFProxyPortNumberKey);
  300. if (!proxy_server.is_valid())
  301. continue;
  302. proxy_list.AddProxyServer(proxy_server);
  303. }
  304. if (!proxy_list.IsEmpty())
  305. results->UseProxyList(proxy_list);
  306. // Else do nothing (results is already guaranteed to be in the default state).
  307. return OK;
  308. }
  309. } // namespace
  310. ProxyResolverFactoryMac::ProxyResolverFactoryMac()
  311. : ProxyResolverFactory(false /*expects_pac_bytes*/) {
  312. }
  313. int ProxyResolverFactoryMac::CreateProxyResolver(
  314. const scoped_refptr<PacFileData>& pac_script,
  315. std::unique_ptr<ProxyResolver>* resolver,
  316. CompletionOnceCallback callback,
  317. std::unique_ptr<Request>* request) {
  318. *resolver = std::make_unique<ProxyResolverMac>(pac_script);
  319. return OK;
  320. }
  321. } // namespace net