network_location_provider.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. // Copyright (c) 2012 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 "services/device/geolocation/network_location_provider.h"
  5. #include <utility>
  6. #include "base/bind.h"
  7. #include "base/location.h"
  8. #include "base/memory/scoped_refptr.h"
  9. #include "base/metrics/histogram_macros.h"
  10. #include "base/strings/utf_string_conversions.h"
  11. #include "base/task/single_thread_task_runner.h"
  12. #include "base/task/task_runner.h"
  13. #include "base/threading/thread_task_runner_handle.h"
  14. #include "base/time/time.h"
  15. #include "build/build_config.h"
  16. #include "net/traffic_annotation/network_traffic_annotation.h"
  17. #include "services/device/geolocation/position_cache.h"
  18. #include "services/device/public/cpp/geolocation/geoposition.h"
  19. #include "services/network/public/cpp/shared_url_loader_factory.h"
  20. #if BUILDFLAG(IS_MAC)
  21. #include "services/device/public/cpp/device_features.h"
  22. #endif
  23. namespace device {
  24. namespace {
  25. // The maximum period of time we'll wait for a complete set of wifi data
  26. // before sending the request.
  27. const int kDataCompleteWaitSeconds = 2;
  28. // The maximum age of a cached network location estimate before it can no longer
  29. // be returned as a fresh estimate. This should be at least as long as the
  30. // longest polling interval used by the WifiDataProvider.
  31. const int kLastPositionMaxAgeSeconds = 10 * 60; // 10 minutes
  32. } // namespace
  33. // NetworkLocationProvider
  34. NetworkLocationProvider::NetworkLocationProvider(
  35. scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
  36. GeolocationManager* geolocation_manager,
  37. const scoped_refptr<base::SingleThreadTaskRunner> main_task_runner,
  38. const std::string& api_key,
  39. PositionCache* position_cache)
  40. : wifi_data_update_callback_(
  41. base::BindRepeating(&NetworkLocationProvider::OnWifiDataUpdate,
  42. base::Unretained(this))),
  43. is_wifi_data_complete_(false),
  44. position_cache_(position_cache),
  45. is_permission_granted_(false),
  46. is_new_data_available_(false),
  47. request_(new NetworkLocationRequest(
  48. std::move(url_loader_factory),
  49. api_key,
  50. base::BindRepeating(&NetworkLocationProvider::OnLocationResponse,
  51. base::Unretained(this)))) {
  52. DCHECK(position_cache_);
  53. #if BUILDFLAG(IS_MAC)
  54. geolocation_manager_ = geolocation_manager;
  55. permission_observers_ = geolocation_manager->GetObserverList();
  56. permission_observers_->AddObserver(this);
  57. main_task_runner->PostTaskAndReplyWithResult(
  58. FROM_HERE,
  59. base::BindOnce(&GeolocationManager::GetSystemPermission,
  60. base::Unretained(geolocation_manager)),
  61. base::BindOnce(&NetworkLocationProvider::OnSystemPermissionUpdated,
  62. weak_factory_.GetWeakPtr()));
  63. #endif
  64. }
  65. NetworkLocationProvider::~NetworkLocationProvider() {
  66. DCHECK(thread_checker_.CalledOnValidThread());
  67. #if BUILDFLAG(IS_MAC)
  68. permission_observers_->RemoveObserver(this);
  69. #endif
  70. if (IsStarted())
  71. StopProvider();
  72. }
  73. void NetworkLocationProvider::SetUpdateCallback(
  74. const LocationProvider::LocationProviderUpdateCallback& callback) {
  75. DCHECK(thread_checker_.CalledOnValidThread());
  76. location_provider_update_callback_ = callback;
  77. }
  78. void NetworkLocationProvider::OnPermissionGranted() {
  79. const bool was_permission_granted = is_permission_granted_;
  80. is_permission_granted_ = true;
  81. if (!was_permission_granted && IsStarted())
  82. RequestPosition();
  83. }
  84. void NetworkLocationProvider::OnSystemPermissionUpdated(
  85. LocationSystemPermissionStatus new_status) {
  86. is_awaiting_initial_permission_status_ = false;
  87. const bool was_permission_granted = is_system_permission_granted_;
  88. is_system_permission_granted_ =
  89. (new_status == LocationSystemPermissionStatus::kAllowed);
  90. if (!is_system_permission_granted_ && location_provider_update_callback_) {
  91. mojom::Geoposition error_position;
  92. error_position.error_code =
  93. mojom::Geoposition::ErrorCode::PERMISSION_DENIED;
  94. error_position.error_message =
  95. "User has not allowed access to system location.";
  96. location_provider_update_callback_.Run(this, error_position);
  97. }
  98. if (!was_permission_granted && is_system_permission_granted_ && IsStarted()) {
  99. wifi_data_provider_handle_->ForceRescan();
  100. OnWifiDataUpdate();
  101. }
  102. }
  103. void NetworkLocationProvider::OnWifiDataUpdate() {
  104. DCHECK(thread_checker_.CalledOnValidThread());
  105. DCHECK(IsStarted());
  106. #if BUILDFLAG(IS_MAC)
  107. if (!is_system_permission_granted_) {
  108. if (!is_awaiting_initial_permission_status_) {
  109. mojom::Geoposition error_position;
  110. error_position.error_code =
  111. mojom::Geoposition::ErrorCode::PERMISSION_DENIED;
  112. error_position.error_message =
  113. "User has not allowed access to system location.";
  114. location_provider_update_callback_.Run(this, error_position);
  115. }
  116. return;
  117. }
  118. #endif
  119. is_wifi_data_complete_ = wifi_data_provider_handle_->GetData(&wifi_data_);
  120. if (is_wifi_data_complete_) {
  121. wifi_timestamp_ = base::Time::Now();
  122. is_new_data_available_ = true;
  123. }
  124. // When RequestPosition is called, the most recent wifi data is sent to the
  125. // geolocation service. If the wifi data is incomplete but a cached estimate
  126. // is available, the cached estimate may be returned instead.
  127. //
  128. // If no wifi data is available or the data is incomplete, it may mean the
  129. // provider is still performing the wifi scan. In this case we should wait
  130. // for the scan to complete rather than return cached data.
  131. //
  132. // A lack of wifi data may also mean the scan is delayed due to the wifi
  133. // scanning policy. This delay can vary based on how frequently the wifi
  134. // data changes, but is on the order of a few seconds to several minutes.
  135. // In this case it is better to call RequestPosition and return a cached
  136. // position estimate if it is available.
  137. bool delayed = wifi_data_provider_handle_->DelayedByPolicy();
  138. if (is_wifi_data_complete_ || delayed)
  139. RequestPosition();
  140. }
  141. void NetworkLocationProvider::OnLocationResponse(
  142. const mojom::Geoposition& position,
  143. bool server_error,
  144. const WifiData& wifi_data) {
  145. DCHECK(thread_checker_.CalledOnValidThread());
  146. // Record the position and update our cache.
  147. position_cache_->SetLastUsedNetworkPosition(position);
  148. if (ValidateGeoposition(position))
  149. position_cache_->CachePosition(wifi_data, position);
  150. // Let listeners know that we now have a position available.
  151. if (!location_provider_update_callback_.is_null()) {
  152. location_provider_update_callback_.Run(this, position);
  153. }
  154. }
  155. void NetworkLocationProvider::StartProvider(bool high_accuracy) {
  156. DCHECK(thread_checker_.CalledOnValidThread());
  157. if (IsStarted())
  158. return;
  159. // Registers a callback with the data provider.
  160. // Releasing the handle will automatically unregister the callback.
  161. wifi_data_provider_handle_ =
  162. WifiDataProviderHandle::CreateHandle(&wifi_data_update_callback_);
  163. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  164. FROM_HERE,
  165. base::BindOnce(&NetworkLocationProvider::RequestPosition,
  166. weak_factory_.GetWeakPtr()),
  167. base::Seconds(kDataCompleteWaitSeconds));
  168. OnWifiDataUpdate();
  169. }
  170. void NetworkLocationProvider::StopProvider() {
  171. DCHECK(thread_checker_.CalledOnValidThread());
  172. DCHECK(IsStarted());
  173. wifi_data_provider_handle_ = nullptr;
  174. weak_factory_.InvalidateWeakPtrs();
  175. }
  176. const mojom::Geoposition& NetworkLocationProvider::GetPosition() {
  177. return position_cache_->GetLastUsedNetworkPosition();
  178. }
  179. void NetworkLocationProvider::RequestPosition() {
  180. DCHECK(thread_checker_.CalledOnValidThread());
  181. #if BUILDFLAG(IS_MAC)
  182. if (!is_system_permission_granted_) {
  183. return;
  184. }
  185. #endif
  186. // The wifi polling policy may require us to wait for several minutes before
  187. // fresh wifi data is available. To ensure we can return a position estimate
  188. // quickly when the network location provider is the primary provider, allow
  189. // a cached value to be returned under certain conditions.
  190. //
  191. // If we have a sufficiently recent network location estimate and we do not
  192. // expect to receive a new one soon (i.e., no new wifi data is available and
  193. // there is no pending network request), report the last network position
  194. // estimate as if it were a fresh estimate.
  195. const mojom::Geoposition& last_position =
  196. position_cache_->GetLastUsedNetworkPosition();
  197. if (!is_new_data_available_ && !request_->is_request_pending() &&
  198. ValidateGeoposition(last_position)) {
  199. base::Time now = base::Time::Now();
  200. base::TimeDelta last_position_age = now - last_position.timestamp;
  201. if (last_position_age.InSeconds() < kLastPositionMaxAgeSeconds &&
  202. !location_provider_update_callback_.is_null()) {
  203. // Update the timestamp to the current time.
  204. mojom::Geoposition position = last_position;
  205. position.timestamp = now;
  206. location_provider_update_callback_.Run(this, position);
  207. }
  208. }
  209. if (!is_new_data_available_ || !is_wifi_data_complete_)
  210. return;
  211. DCHECK(!wifi_timestamp_.is_null())
  212. << "|wifi_timestamp_| must be set before looking up position";
  213. const mojom::Geoposition* cached_position =
  214. position_cache_->FindPosition(wifi_data_);
  215. UMA_HISTOGRAM_BOOLEAN("Geolocation.PositionCache.CacheHit",
  216. cached_position != nullptr);
  217. UMA_HISTOGRAM_COUNTS_100("Geolocation.PositionCache.CacheSize",
  218. position_cache_->GetPositionCacheSize());
  219. if (cached_position) {
  220. mojom::Geoposition position(*cached_position);
  221. DCHECK(ValidateGeoposition(position));
  222. // The timestamp of a position fix is determined by the timestamp
  223. // of the source data update. (The value of position.timestamp from
  224. // the cache could be from weeks ago!)
  225. position.timestamp = wifi_timestamp_;
  226. is_new_data_available_ = false;
  227. // Record the position.
  228. position_cache_->SetLastUsedNetworkPosition(position);
  229. // Let listeners know that we now have a position available.
  230. if (!location_provider_update_callback_.is_null())
  231. location_provider_update_callback_.Run(this, position);
  232. return;
  233. }
  234. // Don't send network requests until authorized. http://crbug.com/39171
  235. if (!is_permission_granted_)
  236. return;
  237. is_new_data_available_ = false;
  238. // TODO(joth): Rather than cancel pending requests, we should create a new
  239. // NetworkLocationRequest for each and hold a set of pending requests.
  240. DLOG_IF(WARNING, request_->is_request_pending())
  241. << "NetworkLocationProvider - pre-empting pending network request "
  242. "with new data. Wifi APs: "
  243. << wifi_data_.access_point_data.size();
  244. net::PartialNetworkTrafficAnnotationTag partial_traffic_annotation =
  245. net::DefinePartialNetworkTrafficAnnotation("network_location_provider",
  246. "network_location_request",
  247. R"(
  248. semantics {
  249. sender: "Network Location Provider"
  250. }
  251. policy {
  252. setting:
  253. "Users can control this feature via the Location setting under "
  254. "'Privacy', 'Content Settings', 'Location'."
  255. chrome_policy {
  256. DefaultGeolocationSetting {
  257. DefaultGeolocationSetting: 2
  258. }
  259. }
  260. })");
  261. request_->MakeRequest(wifi_data_, wifi_timestamp_,
  262. partial_traffic_annotation);
  263. }
  264. bool NetworkLocationProvider::IsStarted() const {
  265. return wifi_data_provider_handle_ != nullptr;
  266. }
  267. } // namespace device