1 // Copyright 2014 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 
5 #ifndef COMPONENTS_NETWORK_TIME_NETWORK_TIME_TRACKER_H_
6 #define COMPONENTS_NETWORK_TIME_NETWORK_TIME_TRACKER_H_
7 
8 #include <stdint.h>
9 #include <memory>
10 
11 #include "base/feature_list.h"
12 #include "base/gtest_prod_util.h"
13 #include "base/macros.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/threading/thread_checker.h"
16 #include "base/time/clock.h"
17 #include "base/time/time.h"
18 #include "base/timer/timer.h"
19 #include "url/gurl.h"
20 
21 class PrefRegistrySimple;
22 class PrefService;
23 
24 namespace base {
25 class TickClock;
26 }  // namespace base
27 
28 namespace client_update_protocol {
29 class Ecdsa;
30 }  // namespace client_update_protocol
31 
32 namespace network {
33 class SimpleURLLoader;
34 class SharedURLLoaderFactory;
35 }  // namespace network
36 
37 namespace network_time {
38 
39 // Clock resolution is platform dependent.
40 #if defined(OS_WIN)
41 const int64_t kTicksResolutionMs = base::Time::kMinLowResolutionThresholdMs;
42 #else
43 const int64_t kTicksResolutionMs = 1;  // Assume 1ms for non-windows platforms.
44 #endif
45 
46 // Variations Service feature that enables network time service querying.
47 extern const base::Feature kNetworkTimeServiceQuerying;
48 
49 // A class that receives network time updates and can provide the network time
50 // for a corresponding local time. This class is not thread safe.
51 class NetworkTimeTracker {
52  public:
53   // Describes the result of a GetNetworkTime() call, describing whether
54   // network time was available and if not, why not.
55   enum NetworkTimeResult {
56     // Network time is available.
57     NETWORK_TIME_AVAILABLE,
58     // A time has been retrieved from the network in the past, but
59     // network time is no longer available because the tracker fell out
60     // of sync due to, for example, a suspend/resume.
61     NETWORK_TIME_SYNC_LOST,
62     // Network time is unavailable because the tracker has not yet
63     // attempted to retrieve a time from the network.
64     NETWORK_TIME_NO_SYNC_ATTEMPT,
65     // Network time is unavailable because the tracker has not yet
66     // successfully retrieved a time from the network (at least one
67     // attempt has been made but all have failed).
68     NETWORK_TIME_NO_SUCCESSFUL_SYNC,
69     // Network time is unavailable because the tracker has not yet
70     // attempted to retrieve a time from the network, but the first
71     // attempt is currently pending.
72     NETWORK_TIME_FIRST_SYNC_PENDING,
73     // Network time is unavailable because the tracker has made failed
74     // attempts to retrieve a time from the network, but an attempt is
75     // currently pending.
76     NETWORK_TIME_SUBSEQUENT_SYNC_PENDING,
77   };
78 
79   // Describes the behavior of fetches to the network time service.
80   enum FetchBehavior {
81     // Only used in case of an unrecognize Finch experiment parameter.
82     FETCH_BEHAVIOR_UNKNOWN,
83     // Time queries will be issued in the background as needed.
84     FETCHES_IN_BACKGROUND_ONLY,
85     // Time queries will not be issued except when StartTimeFetch() is called.
86     FETCHES_ON_DEMAND_ONLY,
87     // Time queries will be issued both in the background as needed and also
88     // on-demand.
89     FETCHES_IN_BACKGROUND_AND_ON_DEMAND,
90   };
91 
92   static void RegisterPrefs(PrefRegistrySimple* registry);
93 
94   // Constructor.  Arguments may be stubbed out for tests. |url_loader_factory|
95   // must be non-null unless the kNetworkTimeServiceQuerying is disabled.
96   // Otherwise, time is available only if |UpdateNetworkTime| is called.
97   NetworkTimeTracker(
98       std::unique_ptr<base::Clock> clock,
99       std::unique_ptr<const base::TickClock> tick_clock,
100       PrefService* pref_service,
101       scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory);
102   ~NetworkTimeTracker();
103 
104   // Sets |network_time| to an estimate of the true time.  Returns
105   // NETWORK_TIME_AVAILABLE if time is available. If |uncertainty| is
106   // non-NULL, it will be set to an estimate of the error range.
107   //
108   // If network time is unavailable, this method returns
109   // NETWORK_TIME_SYNC_LOST or NETWORK_TIME_NO_SYNC to indicate the
110   // reason.
111   //
112   // Network time may be available on startup if deserialized from a pref.
113   // Failing that, a call to |UpdateNetworkTime| is required to make time
114   // available to callers of |GetNetworkTime|.  Subsequently, network time may
115   // become unavailable if |NetworkTimeTracker| has reason to believe it is no
116   // longer accurate.  Consumers should even be prepared to handle the case
117   // where calls to |GetNetworkTime| never once succeeds.
118   NetworkTimeResult GetNetworkTime(base::Time* network_time,
119                                    base::TimeDelta* uncertainty) const;
120 
121   // Starts a network time query if network time isn't already available
122   // and if there isn't already a time query in progress. If a new query
123   // is started or if there is one already in progress, |callback| will
124   // run when the query completes.
125   //
126   // Returns true if a time query is started or was already in progress,
127   // and false otherwise. For example, this method may return false if
128   // time queries are disabled or if network time is already available.
129   bool StartTimeFetch(base::OnceClosure callback);
130 
131   // Calculates corresponding time ticks according to the given parameters.
132   // The provided |network_time| is precise at the given |resolution| and
133   // represent the time between now and up to |latency| + (now - |post_time|)
134   // ago.
135   void UpdateNetworkTime(base::Time network_time,
136                          base::TimeDelta resolution,
137                          base::TimeDelta latency,
138                          base::TimeTicks post_time);
139 
140   bool AreTimeFetchesEnabled() const;
141   FetchBehavior GetFetchBehavior() const;
142 
143   void SetMaxResponseSizeForTesting(size_t limit);
144 
145   void SetPublicKeyForTesting(const base::StringPiece& key);
146 
147   void SetTimeServerURLForTesting(const GURL& url);
148 
149   GURL GetTimeServerURLForTesting() const;
150 
151   bool QueryTimeServiceForTesting();
152 
153   void WaitForFetchForTesting(uint32_t nonce);
154 
155   void OverrideNonceForTesting(uint32_t nonce);
156 
157   base::TimeDelta GetTimerDelayForTesting() const;
158 
159  private:
160   // Checks whether a network time query should be issued, and issues one if so.
161   // Upon response, execution resumes in |OnURLFetchComplete|.
162   void CheckTime();
163 
164   // Updates network time from a time server response, returning true
165   // if successful.
166   bool UpdateTimeFromResponse(std::unique_ptr<std::string> response_body);
167 
168   // Called to process responses from the secure time service.
169   void OnURLLoaderComplete(std::unique_ptr<std::string> response_body);
170 
171   // Sets the next time query to be run at the specified time.
172   void QueueCheckTime(base::TimeDelta delay);
173 
174   // Returns true if there's sufficient reason to suspect that
175   // NetworkTimeTracker does not know what time it is.  This returns true
176   // unconditionally every once in a long while, just to be on the safe side.
177   bool ShouldIssueTimeQuery();
178 
179   // State variables for internally-managed secure time service queries.
180   GURL server_url_;
181   size_t max_response_size_;
182   base::TimeDelta backoff_;
183   // Timer that runs CheckTime().  All backoff and delay is implemented by
184   // changing the delay of this timer, with the result that CheckTime() may
185   // assume that if it runs, it is eligible to issue a time query.
186   base::RepeatingTimer timer_;
187   scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
188   std::unique_ptr<network::SimpleURLLoader> time_fetcher_;
189   base::TimeTicks fetch_started_;
190   std::unique_ptr<client_update_protocol::Ecdsa> query_signer_;
191 
192   // The |Clock| and |TickClock| are used to sanity-check one another, allowing
193   // the NetworkTimeTracker to notice e.g. suspend/resume events and clock
194   // resets.
195   std::unique_ptr<base::Clock> clock_;
196   std::unique_ptr<const base::TickClock> tick_clock_;
197 
198   PrefService* pref_service_;
199 
200   // Network time based on last call to UpdateNetworkTime().
201   mutable base::Time network_time_at_last_measurement_;
202 
203   // The estimated local times that correspond with |network_time_|. Assumes
204   // the actual network time measurement was performed midway through the
205   // latency time.  See UpdateNetworkTime(...) implementation for details.  The
206   // tick clock is the one actually used to return values to callers, but both
207   // clocks must agree to within some tolerance.
208   base::Time time_at_last_measurement_;
209   base::TimeTicks ticks_at_last_measurement_;
210 
211   // Uncertainty of |network_time_| based on added inaccuracies/resolution.  See
212   // UpdateNetworkTime(...) implementation for details.
213   base::TimeDelta network_time_uncertainty_;
214 
215   // True if any time query has completed (but not necessarily succeeded) in
216   // this NetworkTimeTracker's lifetime.
217   bool time_query_completed_;
218 
219   // The time that was received from the last network time fetch made by
220   // CheckTime(). Unlike |network_time_at_least_measurement_|, this time
221   // is not updated when UpdateNetworkTime() is called. Used for UMA
222   // metrics.
223   base::Time last_fetched_time_;
224 
225   // Callbacks to run when the in-progress time fetch completes.
226   std::vector<base::OnceClosure> fetch_completion_callbacks_;
227 
228   base::ThreadChecker thread_checker_;
229 
230   DISALLOW_COPY_AND_ASSIGN(NetworkTimeTracker);
231 };
232 
233 }  // namespace network_time
234 
235 #endif  // COMPONENTS_NETWORK_TIME_NETWORK_TIME_TRACKER_H_
236