blob: 0284c223d9a82046ba485ac8611bf0273c5356b8 [file] [log] [blame]
Alex Deymoc705cc82014-02-19 11:15:00 -08001// Copyright (c) 2014 The Chromium OS 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
Alex Deymo63784a52014-05-28 10:46:14 -07005#include "update_engine/update_manager/chromeos_policy.h"
Alex Deymo0d11c602014-04-23 20:12:20 -07006
Gilad Arnolde1218812014-05-07 12:21:36 -07007#include <algorithm>
Gilad Arnold0adbc942014-05-12 10:35:43 -07008#include <set>
Alex Deymoc705cc82014-02-19 11:15:00 -08009#include <string>
10
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070011#include <base/logging.h>
Gilad Arnoldb3b05442014-05-30 14:25:05 -070012#include <base/strings/string_util.h>
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070013#include <base/time/time.h>
14
Gilad Arnoldb3b05442014-05-30 14:25:05 -070015#include "update_engine/error_code.h"
Alex Deymo63784a52014-05-28 10:46:14 -070016#include "update_engine/update_manager/device_policy_provider.h"
17#include "update_engine/update_manager/policy_utils.h"
18#include "update_engine/update_manager/shill_provider.h"
Gilad Arnoldb3b05442014-05-30 14:25:05 -070019#include "update_engine/utils.h"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070020
Alex Deymo0d11c602014-04-23 20:12:20 -070021using base::Time;
22using base::TimeDelta;
Gilad Arnoldb3b05442014-05-30 14:25:05 -070023using chromeos_update_engine::ErrorCode;
Gilad Arnolddc4bb262014-07-23 10:45:19 -070024using std::get;
Gilad Arnoldb3b05442014-05-30 14:25:05 -070025using std::max;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070026using std::min;
Gilad Arnold0adbc942014-05-12 10:35:43 -070027using std::set;
Alex Deymoc705cc82014-02-19 11:15:00 -080028using std::string;
29
Gilad Arnoldb3b05442014-05-30 14:25:05 -070030namespace {
31
Gilad Arnolddc4bb262014-07-23 10:45:19 -070032// Examines |err_code| and decides whether the URL index needs to be advanced,
33// the error count for the URL incremented, or none of the above. In the first
34// case, returns true; in the second case, increments |*url_num_error_p| and
35// returns false; otherwise just returns false.
Gilad Arnoldb3b05442014-05-30 14:25:05 -070036//
37// TODO(garnold) Adapted from PayloadState::UpdateFailed() (to be retired).
Gilad Arnolddc4bb262014-07-23 10:45:19 -070038bool HandleErrorCode(ErrorCode err_code, int* url_num_error_p) {
Gilad Arnoldb3b05442014-05-30 14:25:05 -070039 err_code = chromeos_update_engine::utils::GetBaseErrorCode(err_code);
40 switch (err_code) {
41 // Errors which are good indicators of a problem with a particular URL or
42 // the protocol used in the URL or entities in the communication channel
43 // (e.g. proxies). We should try the next available URL in the next update
44 // check to quickly recover from these errors.
45 case ErrorCode::kPayloadHashMismatchError:
46 case ErrorCode::kPayloadSizeMismatchError:
47 case ErrorCode::kDownloadPayloadVerificationError:
48 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
49 case ErrorCode::kSignedDeltaPayloadExpectedError:
50 case ErrorCode::kDownloadInvalidMetadataMagicString:
51 case ErrorCode::kDownloadSignatureMissingInManifest:
52 case ErrorCode::kDownloadManifestParseError:
53 case ErrorCode::kDownloadMetadataSignatureError:
54 case ErrorCode::kDownloadMetadataSignatureVerificationError:
55 case ErrorCode::kDownloadMetadataSignatureMismatch:
56 case ErrorCode::kDownloadOperationHashVerificationError:
57 case ErrorCode::kDownloadOperationExecutionError:
58 case ErrorCode::kDownloadOperationHashMismatch:
59 case ErrorCode::kDownloadInvalidMetadataSize:
60 case ErrorCode::kDownloadInvalidMetadataSignature:
61 case ErrorCode::kDownloadOperationHashMissingError:
62 case ErrorCode::kDownloadMetadataSignatureMissingError:
63 case ErrorCode::kPayloadMismatchedType:
64 case ErrorCode::kUnsupportedMajorPayloadVersion:
65 case ErrorCode::kUnsupportedMinorPayloadVersion:
66 LOG(INFO) << "Advancing download URL due to error "
67 << chromeos_update_engine::utils::CodeToString(err_code)
68 << " (" << static_cast<int>(err_code) << ")";
Gilad Arnoldb3b05442014-05-30 14:25:05 -070069 return true;
70
71 // Errors which seem to be just transient network/communication related
72 // failures and do not indicate any inherent problem with the URL itself.
73 // So, we should keep the current URL but just increment the
74 // failure count to give it more chances. This way, while we maximize our
75 // chances of downloading from the URLs that appear earlier in the response
76 // (because download from a local server URL that appears earlier in a
77 // response is preferable than downloading from the next URL which could be
Alex Vakulenko072359c2014-07-18 11:41:07 -070078 // an Internet URL and thus could be more expensive).
Gilad Arnoldb3b05442014-05-30 14:25:05 -070079 case ErrorCode::kError:
80 case ErrorCode::kDownloadTransferError:
81 case ErrorCode::kDownloadWriteError:
82 case ErrorCode::kDownloadStateInitializationError:
Gilad Arnold684219d2014-07-07 14:54:57 -070083 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Gilad Arnoldb3b05442014-05-30 14:25:05 -070084 LOG(INFO) << "Incrementing URL failure count due to error "
85 << chromeos_update_engine::utils::CodeToString(err_code)
86 << " (" << static_cast<int>(err_code) << ")";
Gilad Arnolddc4bb262014-07-23 10:45:19 -070087 *url_num_error_p += 1;
Gilad Arnoldb3b05442014-05-30 14:25:05 -070088 return false;
89
90 // Errors which are not specific to a URL and hence shouldn't result in
91 // the URL being penalized. This can happen in two cases:
92 // 1. We haven't started downloading anything: These errors don't cost us
93 // anything in terms of actual payload bytes, so we should just do the
94 // regular retries at the next update check.
95 // 2. We have successfully downloaded the payload: In this case, the
96 // payload attempt number would have been incremented and would take care
Alex Vakulenko072359c2014-07-18 11:41:07 -070097 // of the back-off at the next update check.
Gilad Arnoldb3b05442014-05-30 14:25:05 -070098 // In either case, there's no need to update URL index or failure count.
99 case ErrorCode::kOmahaRequestError:
100 case ErrorCode::kOmahaResponseHandlerError:
101 case ErrorCode::kPostinstallRunnerError:
102 case ErrorCode::kFilesystemCopierError:
103 case ErrorCode::kInstallDeviceOpenError:
104 case ErrorCode::kKernelDeviceOpenError:
105 case ErrorCode::kDownloadNewPartitionInfoError:
106 case ErrorCode::kNewRootfsVerificationError:
107 case ErrorCode::kNewKernelVerificationError:
108 case ErrorCode::kPostinstallBootedFromFirmwareB:
109 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
110 case ErrorCode::kOmahaRequestEmptyResponseError:
111 case ErrorCode::kOmahaRequestXMLParseError:
112 case ErrorCode::kOmahaResponseInvalid:
113 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
114 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
115 case ErrorCode::kOmahaUpdateDeferredForBackoff:
116 case ErrorCode::kPostinstallPowerwashError:
117 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400118 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700119 LOG(INFO) << "Not changing URL index or failure count due to error "
120 << chromeos_update_engine::utils::CodeToString(err_code)
121 << " (" << static_cast<int>(err_code) << ")";
122 return false;
123
124 case ErrorCode::kSuccess: // success code
125 case ErrorCode::kUmaReportedMax: // not an error code
126 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
127 case ErrorCode::kDevModeFlag: // not an error code
128 case ErrorCode::kResumedFlag: // not an error code
129 case ErrorCode::kTestImageFlag: // not an error code
130 case ErrorCode::kTestOmahaUrlFlag: // not an error code
131 case ErrorCode::kSpecialFlags: // not an error code
132 // These shouldn't happen. Enumerating these explicitly here so that we
133 // can let the compiler warn about new error codes that are added to
134 // action_processor.h but not added here.
135 LOG(WARNING) << "Unexpected error "
136 << chromeos_update_engine::utils::CodeToString(err_code)
137 << " (" << static_cast<int>(err_code) << ")";
138 // Note: Not adding a default here so as to let the compiler warn us of
139 // any new enums that were added in the .h but not listed in this switch.
140 }
141 return false;
142}
143
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700144// Checks whether |url| can be used under given download restrictions.
145bool IsUrlUsable(const string& url, bool http_allowed) {
146 return http_allowed || !StartsWithASCII(url, "http://", false);
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700147}
148
149} // namespace
150
Alex Deymo63784a52014-05-28 10:46:14 -0700151namespace chromeos_update_manager {
Alex Deymoc705cc82014-02-19 11:15:00 -0800152
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700153const int ChromeOSPolicy::kTimeoutInitialInterval = 7 * 60;
154const int ChromeOSPolicy::kTimeoutPeriodicInterval = 45 * 60;
155const int ChromeOSPolicy::kTimeoutMaxBackoffInterval = 4 * 60 * 60;
156const int ChromeOSPolicy::kTimeoutRegularFuzz = 10 * 60;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700157const int ChromeOSPolicy::kAttemptBackoffMaxIntervalInDays = 16;
158const int ChromeOSPolicy::kAttemptBackoffFuzzInHours = 12;
Gilad Arnold349ac832014-10-06 14:20:28 -0700159const int ChromeOSPolicy::kMaxP2PAttempts = 10;
160const int ChromeOSPolicy::kMaxP2PAttemptsPeriodInSeconds = 5 * 24 * 60 * 60;
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700161
Alex Deymo0d11c602014-04-23 20:12:20 -0700162EvalStatus ChromeOSPolicy::UpdateCheckAllowed(
163 EvaluationContext* ec, State* state, string* error,
164 UpdateCheckParams* result) const {
Gilad Arnold42f253b2014-06-25 12:39:17 -0700165 // Set the default return values.
166 result->updates_enabled = true;
167 result->target_channel.clear();
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700168 result->target_version_prefix.clear();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700169 result->is_interactive = false;
Gilad Arnold42f253b2014-06-25 12:39:17 -0700170
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700171 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700172 UpdaterProvider* const updater_provider = state->updater_provider();
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700173 SystemProvider* const system_provider = state->system_provider();
174
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700175 // Do not perform any updates if booted from removable device. This decision
176 // is final.
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700177 const bool* is_boot_device_removable_p = ec->GetValue(
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700178 system_provider->var_is_boot_device_removable());
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700179 if (is_boot_device_removable_p && *is_boot_device_removable_p) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700180 LOG(INFO) << "Booted from removable device, disabling update checks.";
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700181 result->updates_enabled = false;
182 return EvalStatus::kSucceeded;
183 }
184
Gilad Arnold42f253b2014-06-25 12:39:17 -0700185 const bool* device_policy_is_loaded_p = ec->GetValue(
186 dp_provider->var_device_policy_is_loaded());
187 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
188 // Check whether updates are disabled by policy.
189 const bool* update_disabled_p = ec->GetValue(
190 dp_provider->var_update_disabled());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700191 if (update_disabled_p && *update_disabled_p) {
192 LOG(INFO) << "Updates disabled by policy, blocking update checks.";
Gilad Arnold42f253b2014-06-25 12:39:17 -0700193 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700194 }
Gilad Arnold42f253b2014-06-25 12:39:17 -0700195
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700196 // Determine whether a target version prefix is dictated by policy.
197 const string* target_version_prefix_p = ec->GetValue(
198 dp_provider->var_target_version_prefix());
199 if (target_version_prefix_p)
200 result->target_version_prefix = *target_version_prefix_p;
201
Gilad Arnold42f253b2014-06-25 12:39:17 -0700202 // Determine whether a target channel is dictated by policy.
203 const bool* release_channel_delegated_p = ec->GetValue(
204 dp_provider->var_release_channel_delegated());
205 if (release_channel_delegated_p && !(*release_channel_delegated_p)) {
206 const string* release_channel_p = ec->GetValue(
207 dp_provider->var_release_channel());
208 if (release_channel_p)
209 result->target_channel = *release_channel_p;
210 }
211 }
212
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700213 // First, check to see if an interactive update was requested.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700214 const UpdateRequestStatus* forced_update_requested_p = ec->GetValue(
215 updater_provider->var_forced_update_requested());
216 if (forced_update_requested_p &&
217 *forced_update_requested_p != UpdateRequestStatus::kNone) {
218 result->is_interactive =
219 (*forced_update_requested_p == UpdateRequestStatus::kInteractive);
220 LOG(INFO) << "Forced update signaled ("
221 << (result->is_interactive ? "interactive" : "periodic")
222 << "), allowing update check.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700223 return EvalStatus::kSucceeded;
224 }
225
226 // The logic thereafter applies to periodic updates. Bear in mind that we
227 // should not return a final "no" if any of these criteria are not satisfied,
228 // because the system may still update due to an interactive update request.
229
230 // Unofficial builds should not perform periodic update checks.
231 const bool* is_official_build_p = ec->GetValue(
232 system_provider->var_is_official_build());
233 if (is_official_build_p && !(*is_official_build_p)) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700234 LOG(INFO) << "Unofficial build, blocking periodic update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700235 return EvalStatus::kAskMeAgainLater;
236 }
237
238 // If OOBE is enabled, wait until it is completed.
239 const bool* is_oobe_enabled_p = ec->GetValue(
240 state->config_provider()->var_is_oobe_enabled());
241 if (is_oobe_enabled_p && *is_oobe_enabled_p) {
242 const bool* is_oobe_complete_p = ec->GetValue(
243 system_provider->var_is_oobe_complete());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700244 if (is_oobe_complete_p && !(*is_oobe_complete_p)) {
245 LOG(INFO) << "OOBE not completed, blocking update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700246 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700247 }
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700248 }
249
250 // Ensure that periodic update checks are timed properly.
Alex Deymo0d11c602014-04-23 20:12:20 -0700251 Time next_update_check;
252 if (NextUpdateCheckTime(ec, state, error, &next_update_check) !=
253 EvalStatus::kSucceeded) {
254 return EvalStatus::kFailed;
255 }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700256 if (!ec->IsWallclockTimeGreaterThan(next_update_check)) {
257 LOG(INFO) << "Periodic check interval not satisfied, blocking until "
258 << chromeos_update_engine::utils::ToString(next_update_check);
Alex Deymo0d11c602014-04-23 20:12:20 -0700259 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700260 }
Alex Deymo0d11c602014-04-23 20:12:20 -0700261
262 // It is time to check for an update.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700263 LOG(INFO) << "Allowing update check.";
Alex Deymoe636c3c2014-03-11 19:02:08 -0700264 return EvalStatus::kSucceeded;
Alex Deymoc705cc82014-02-19 11:15:00 -0800265}
266
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700267EvalStatus ChromeOSPolicy::UpdateCanStart(
268 EvaluationContext* ec,
269 State* state,
270 string* error,
Gilad Arnold42f253b2014-06-25 12:39:17 -0700271 UpdateDownloadParams* result,
Gilad Arnoldd78caf92014-09-24 09:28:14 -0700272 const UpdateState update_state) const {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700273 // Set the default return values. Note that we set persisted values (backoff,
274 // scattering) to the same values presented in the update state. The reason is
275 // that preemptive returns, such as the case where an update check is due,
276 // should not clear off the said values; rather, it is the deliberate
277 // inference of new values that should cause them to be reset.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700278 result->update_can_start = false;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700279 result->cannot_start_reason = UpdateCannotStartReason::kUndefined;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700280 result->download_url_idx = -1;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700281 result->download_url_allowed = true;
282 result->download_url_num_errors = 0;
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700283 result->p2p_downloading_allowed = false;
284 result->p2p_sharing_allowed = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700285 result->do_increment_failures = false;
286 result->backoff_expiry = update_state.backoff_expiry;
287 result->scatter_wait_period = update_state.scatter_wait_period;
288 result->scatter_check_threshold = update_state.scatter_check_threshold;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700289
290 // Make sure that we're not due for an update check.
291 UpdateCheckParams check_result;
292 EvalStatus check_status = UpdateCheckAllowed(ec, state, error, &check_result);
293 if (check_status == EvalStatus::kFailed)
294 return EvalStatus::kFailed;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700295 bool is_check_due = (check_status == EvalStatus::kSucceeded &&
296 check_result.updates_enabled == true);
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700297
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700298 // Check whether backoff applies, and if not then which URL can be used for
299 // downloading. These require scanning the download error log, and so they are
300 // done together.
301 UpdateBackoffAndDownloadUrlResult backoff_url_result;
302 EvalStatus backoff_url_status = UpdateBackoffAndDownloadUrl(
303 ec, state, error, &backoff_url_result, update_state);
Gilad Arnold14a9e702014-10-08 08:09:09 -0700304 if (backoff_url_status == EvalStatus::kFailed)
305 return EvalStatus::kFailed;
306 result->download_url_idx = backoff_url_result.url_idx;
307 result->download_url_num_errors = backoff_url_result.url_num_errors;
308 result->do_increment_failures = backoff_url_result.do_increment_failures;
309 result->backoff_expiry = backoff_url_result.backoff_expiry;
310 bool is_backoff_active =
311 (backoff_url_status == EvalStatus::kAskMeAgainLater) ||
312 !backoff_url_result.backoff_expiry.is_null();
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700313
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700314 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold14a9e702014-10-08 08:09:09 -0700315 bool is_scattering_active = false;
316 EvalStatus scattering_status = EvalStatus::kSucceeded;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700317
318 const bool* device_policy_is_loaded_p = ec->GetValue(
319 dp_provider->var_device_policy_is_loaded());
320 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700321 // Check whether scattering applies to this update attempt. We should not be
322 // scattering if this is an interactive update check, or if OOBE is enabled
323 // but not completed.
324 //
325 // Note: current code further suppresses scattering if a "deadline"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700326 // attribute is found in the Omaha response. However, it appears that the
Gilad Arnold76a11f62014-05-20 09:02:12 -0700327 // presence of this attribute is merely indicative of an OOBE update, during
328 // which we suppress scattering anyway.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700329 bool is_scattering_applicable = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700330 result->scatter_wait_period = kZeroInterval;
331 result->scatter_check_threshold = 0;
332 if (!update_state.is_interactive) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700333 const bool* is_oobe_enabled_p = ec->GetValue(
334 state->config_provider()->var_is_oobe_enabled());
335 if (is_oobe_enabled_p && !(*is_oobe_enabled_p)) {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700336 is_scattering_applicable = true;
Gilad Arnold76a11f62014-05-20 09:02:12 -0700337 } else {
338 const bool* is_oobe_complete_p = ec->GetValue(
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700339 state->system_provider()->var_is_oobe_complete());
Gilad Arnold14a9e702014-10-08 08:09:09 -0700340 is_scattering_applicable = (is_oobe_complete_p && *is_oobe_complete_p);
Gilad Arnold76a11f62014-05-20 09:02:12 -0700341 }
342 }
343
344 // Compute scattering values.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700345 if (is_scattering_applicable) {
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700346 UpdateScatteringResult scatter_result;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700347 scattering_status = UpdateScattering(ec, state, error, &scatter_result,
348 update_state);
349 if (scattering_status == EvalStatus::kFailed) {
350 return EvalStatus::kFailed;
351 } else {
352 result->scatter_wait_period = scatter_result.wait_period;
353 result->scatter_check_threshold = scatter_result.check_threshold;
354 if (scattering_status == EvalStatus::kAskMeAgainLater ||
355 scatter_result.is_scattering)
356 is_scattering_active = true;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700357 }
358 }
359
Gilad Arnoldef8d0872014-10-03 14:14:06 -0700360 // Determine whether use of P2P is allowed by policy. Even if P2P is not
361 // explicitly allowed, we allow it if the device is enterprise enrolled
362 // (that is, missing or empty owner string).
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700363 const bool* policy_au_p2p_enabled_p = ec->GetValue(
364 dp_provider->var_au_p2p_enabled());
365 if (policy_au_p2p_enabled_p) {
366 result->p2p_sharing_allowed = *policy_au_p2p_enabled_p;
367 } else {
368 const string* policy_owner_p = ec->GetValue(dp_provider->var_owner());
369 if (!policy_owner_p || policy_owner_p->empty())
370 result->p2p_sharing_allowed = true;
Gilad Arnoldef8d0872014-10-03 14:14:06 -0700371 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700372 }
373
Gilad Arnoldef8d0872014-10-03 14:14:06 -0700374 // Enable P2P, if so mandated by the updater configuration. This is additive
375 // to whether or not P2P is allowed per device policy (see above).
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700376 if (!result->p2p_sharing_allowed) {
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700377 const bool* updater_p2p_enabled_p = ec->GetValue(
378 state->updater_provider()->var_p2p_enabled());
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700379 result->p2p_sharing_allowed =
380 updater_p2p_enabled_p && *updater_p2p_enabled_p;
381 }
382
383 // Finally, download via P2P is enabled iff P2P is enabled (sharing allowed),
384 // an update is not interactive, and other limits haven't been reached.
385 if (result->p2p_sharing_allowed) {
386 if (update_state.is_interactive) {
387 LOG(INFO) << "Blocked P2P download because update is interactive.";
388 } else if (update_state.p2p_num_attempts >= kMaxP2PAttempts) {
389 LOG(INFO) << "Blocked P2P download as it was attempted too many times.";
390 } else if (!update_state.p2p_first_attempted.is_null() &&
391 ec->IsWallclockTimeGreaterThan(
392 update_state.p2p_first_attempted +
393 TimeDelta::FromSeconds(kMaxP2PAttemptsPeriodInSeconds))) {
394 LOG(INFO) << "Blocked P2P download as its usage timespan exceeds limit.";
395 } else {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700396 // P2P download is allowed; if backoff or scattering are active, be sure
397 // to suppress them, yet prevent any download URL from being used.
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700398 result->p2p_downloading_allowed = true;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700399 if (is_backoff_active || is_scattering_active) {
400 is_backoff_active = is_scattering_active = false;
401 result->download_url_allowed = false;
402 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700403 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700404 }
405
Gilad Arnold14a9e702014-10-08 08:09:09 -0700406 // Check for various deterrents.
407 if (is_check_due) {
408 result->cannot_start_reason = UpdateCannotStartReason::kCheckDue;
409 return EvalStatus::kSucceeded;
410 }
411 if (is_backoff_active) {
412 result->cannot_start_reason = UpdateCannotStartReason::kBackoff;
413 return backoff_url_status;
414 }
415 if (is_scattering_active) {
416 result->cannot_start_reason = UpdateCannotStartReason::kScattering;
417 return scattering_status;
418 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700419 if (result->download_url_idx < 0 && !result->p2p_downloading_allowed) {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700420 result->cannot_start_reason = UpdateCannotStartReason::kCannotDownload;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700421 return EvalStatus::kSucceeded;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700422 }
423
Gilad Arnold14a9e702014-10-08 08:09:09 -0700424 // Update is good to go.
425 result->update_can_start = true;
Gilad Arnoldaf2f6ae2014-04-28 14:14:52 -0700426 return EvalStatus::kSucceeded;
427}
428
Gilad Arnolda8262e22014-06-02 13:54:27 -0700429// TODO(garnold) Logic in this method is based on
430// ConnectionManager::IsUpdateAllowedOver(); be sure to deprecate the latter.
431//
432// TODO(garnold) The current logic generally treats the list of allowed
433// connections coming from the device policy as a whitelist, meaning that it
434// can only be used for enabling connections, but not disable them. Further,
435// certain connection types (like Bluetooth) cannot be enabled even by policy.
436// In effect, the only thing that device policy can change is to enable
437// updates over a cellular network (disabled by default). We may want to
438// revisit this semantics, allowing greater flexibility in defining specific
439// permissions over all types of networks.
Gilad Arnold684219d2014-07-07 14:54:57 -0700440EvalStatus ChromeOSPolicy::UpdateDownloadAllowed(
Gilad Arnolda8262e22014-06-02 13:54:27 -0700441 EvaluationContext* ec,
442 State* state,
443 string* error,
444 bool* result) const {
445 // Get the current connection type.
446 ShillProvider* const shill_provider = state->shill_provider();
447 const ConnectionType* conn_type_p = ec->GetValue(
448 shill_provider->var_conn_type());
449 POLICY_CHECK_VALUE_AND_FAIL(conn_type_p, error);
450 ConnectionType conn_type = *conn_type_p;
451
452 // If we're tethering, treat it as a cellular connection.
453 if (conn_type != ConnectionType::kCellular) {
454 const ConnectionTethering* conn_tethering_p = ec->GetValue(
455 shill_provider->var_conn_tethering());
456 POLICY_CHECK_VALUE_AND_FAIL(conn_tethering_p, error);
457 if (*conn_tethering_p == ConnectionTethering::kConfirmed)
458 conn_type = ConnectionType::kCellular;
459 }
460
461 // By default, we allow updates for all connection types, with exceptions as
462 // noted below. This also determines whether a device policy can override the
463 // default.
464 *result = true;
465 bool device_policy_can_override = false;
466 switch (conn_type) {
467 case ConnectionType::kBluetooth:
468 *result = false;
469 break;
470
471 case ConnectionType::kCellular:
472 *result = false;
473 device_policy_can_override = true;
474 break;
475
476 case ConnectionType::kUnknown:
477 if (error)
478 *error = "Unknown connection type";
479 return EvalStatus::kFailed;
480
481 default:
482 break; // Nothing to do.
483 }
484
485 // If update is allowed, we're done.
486 if (*result)
487 return EvalStatus::kSucceeded;
488
489 // Check whether the device policy specifically allows this connection.
Gilad Arnolda8262e22014-06-02 13:54:27 -0700490 if (device_policy_can_override) {
491 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
492 const bool* device_policy_is_loaded_p = ec->GetValue(
493 dp_provider->var_device_policy_is_loaded());
494 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
495 const set<ConnectionType>* allowed_conn_types_p = ec->GetValue(
496 dp_provider->var_allowed_connection_types_for_update());
497 if (allowed_conn_types_p) {
498 if (allowed_conn_types_p->count(conn_type)) {
499 *result = true;
500 return EvalStatus::kSucceeded;
501 }
Gilad Arnold28d6be62014-06-30 14:04:04 -0700502 } else if (conn_type == ConnectionType::kCellular) {
503 // Local user settings can allow updates over cellular iff a policy was
504 // loaded but no allowed connections were specified in it.
505 const bool* update_over_cellular_allowed_p = ec->GetValue(
506 state->updater_provider()->var_cellular_enabled());
507 if (update_over_cellular_allowed_p && *update_over_cellular_allowed_p)
508 *result = true;
Gilad Arnolda8262e22014-06-02 13:54:27 -0700509 }
510 }
511 }
512
Gilad Arnold28d6be62014-06-30 14:04:04 -0700513 return (*result ? EvalStatus::kSucceeded : EvalStatus::kAskMeAgainLater);
Gilad Arnolda8262e22014-06-02 13:54:27 -0700514}
515
Alex Deymo0d11c602014-04-23 20:12:20 -0700516EvalStatus ChromeOSPolicy::NextUpdateCheckTime(EvaluationContext* ec,
517 State* state, string* error,
518 Time* next_update_check) const {
Gilad Arnolda0258a52014-07-10 16:21:19 -0700519 UpdaterProvider* const updater_provider = state->updater_provider();
520
Alex Deymo0d11c602014-04-23 20:12:20 -0700521 // Don't check for updates too often. We limit the update checks to once every
522 // some interval. The interval is kTimeoutInitialInterval the first time and
523 // kTimeoutPeriodicInterval for the subsequent update checks. If the update
524 // check fails, we increase the interval between the update checks
525 // exponentially until kTimeoutMaxBackoffInterval. Finally, to avoid having
526 // many chromebooks running update checks at the exact same time, we add some
527 // fuzz to the interval.
528 const Time* updater_started_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700529 ec->GetValue(updater_provider->var_updater_started_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700530 POLICY_CHECK_VALUE_AND_FAIL(updater_started_time, error);
531
Alex Deymof329b932014-10-30 01:37:48 -0700532 const Time* last_checked_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700533 ec->GetValue(updater_provider->var_last_checked_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700534
535 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
536 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
537
538 PRNG prng(*seed);
539
Gilad Arnold38b14022014-07-09 12:45:56 -0700540 // If this is the first attempt, compute and return an initial value.
Alex Deymo0d11c602014-04-23 20:12:20 -0700541 if (!last_checked_time || *last_checked_time < *updater_started_time) {
Alex Deymo0d11c602014-04-23 20:12:20 -0700542 *next_update_check = *updater_started_time + FuzzedInterval(
543 &prng, kTimeoutInitialInterval, kTimeoutRegularFuzz);
544 return EvalStatus::kSucceeded;
545 }
Gilad Arnold38b14022014-07-09 12:45:56 -0700546
Gilad Arnolda0258a52014-07-10 16:21:19 -0700547 // Check whether the server is enforcing a poll interval; if not, this value
548 // will be zero.
549 const unsigned int* server_dictated_poll_interval = ec->GetValue(
550 updater_provider->var_server_dictated_poll_interval());
551 POLICY_CHECK_VALUE_AND_FAIL(server_dictated_poll_interval, error);
Alex Deymo0d11c602014-04-23 20:12:20 -0700552
Gilad Arnolda0258a52014-07-10 16:21:19 -0700553 int interval = *server_dictated_poll_interval;
554 int fuzz = 0;
555
Alex Vakulenko072359c2014-07-18 11:41:07 -0700556 // If no poll interval was dictated by server compute a back-off period,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700557 // starting from a predetermined base periodic interval and increasing
558 // exponentially by the number of consecutive failed attempts.
559 if (interval == 0) {
560 const unsigned int* consecutive_failed_update_checks = ec->GetValue(
561 updater_provider->var_consecutive_failed_update_checks());
562 POLICY_CHECK_VALUE_AND_FAIL(consecutive_failed_update_checks, error);
563
564 interval = kTimeoutPeriodicInterval;
565 unsigned int num_failures = *consecutive_failed_update_checks;
566 while (interval < kTimeoutMaxBackoffInterval && num_failures) {
567 interval *= 2;
568 num_failures--;
Alex Deymo0d11c602014-04-23 20:12:20 -0700569 }
570 }
571
Alex Vakulenko072359c2014-07-18 11:41:07 -0700572 // We cannot back off longer than the predetermined maximum interval.
Gilad Arnolda0258a52014-07-10 16:21:19 -0700573 if (interval > kTimeoutMaxBackoffInterval)
574 interval = kTimeoutMaxBackoffInterval;
575
Alex Vakulenko072359c2014-07-18 11:41:07 -0700576 // We cannot back off shorter than the predetermined periodic interval. Also,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700577 // in this case set the fuzz to a predetermined regular value.
578 if (interval <= kTimeoutPeriodicInterval) {
579 interval = kTimeoutPeriodicInterval;
580 fuzz = kTimeoutRegularFuzz;
581 }
582
583 // If not otherwise determined, defer to a fuzz of +/-(interval / 2).
Gilad Arnold38b14022014-07-09 12:45:56 -0700584 if (fuzz == 0)
585 fuzz = interval;
586
Alex Deymo0d11c602014-04-23 20:12:20 -0700587 *next_update_check = *last_checked_time + FuzzedInterval(
Gilad Arnold38b14022014-07-09 12:45:56 -0700588 &prng, interval, fuzz);
Alex Deymo0d11c602014-04-23 20:12:20 -0700589 return EvalStatus::kSucceeded;
590}
591
592TimeDelta ChromeOSPolicy::FuzzedInterval(PRNG* prng, int interval, int fuzz) {
Gilad Arnolde1218812014-05-07 12:21:36 -0700593 DCHECK_GE(interval, 0);
594 DCHECK_GE(fuzz, 0);
Alex Deymo0d11c602014-04-23 20:12:20 -0700595 int half_fuzz = fuzz / 2;
Alex Deymo0d11c602014-04-23 20:12:20 -0700596 // This guarantees the output interval is non negative.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700597 int interval_min = max(interval - half_fuzz, 0);
Gilad Arnolde1218812014-05-07 12:21:36 -0700598 int interval_max = interval + half_fuzz;
599 return TimeDelta::FromSeconds(prng->RandMinMax(interval_min, interval_max));
Alex Deymo0d11c602014-04-23 20:12:20 -0700600}
601
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700602EvalStatus ChromeOSPolicy::UpdateBackoffAndDownloadUrl(
Alex Deymof329b932014-10-30 01:37:48 -0700603 EvaluationContext* ec, State* state, string* error,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700604 UpdateBackoffAndDownloadUrlResult* result,
605 const UpdateState& update_state) const {
606 // Sanity checks.
607 DCHECK_GE(update_state.download_errors_max, 0);
608
609 // Set default result values.
610 result->do_increment_failures = false;
611 result->backoff_expiry = update_state.backoff_expiry;
612 result->url_idx = -1;
613 result->url_num_errors = 0;
614
615 const bool* is_official_build_p = ec->GetValue(
616 state->system_provider()->var_is_official_build());
617 bool is_official_build = (is_official_build_p ? *is_official_build_p : true);
618
619 // Check whether backoff is enabled.
620 bool may_backoff = false;
621 if (update_state.is_backoff_disabled) {
622 LOG(INFO) << "Backoff disabled by Omaha.";
623 } else if (update_state.is_interactive) {
624 LOG(INFO) << "No backoff for interactive updates.";
625 } else if (update_state.is_delta_payload) {
626 LOG(INFO) << "No backoff for delta payloads.";
627 } else if (!is_official_build) {
628 LOG(INFO) << "No backoff for unofficial builds.";
629 } else {
630 may_backoff = true;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700631 }
632
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700633 // If previous backoff still in effect, block.
634 if (may_backoff && !update_state.backoff_expiry.is_null() &&
635 !ec->IsWallclockTimeGreaterThan(update_state.backoff_expiry)) {
636 LOG(INFO) << "Previous backoff has not expired, waiting.";
637 return EvalStatus::kAskMeAgainLater;
638 }
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700639
640 // Determine whether HTTP downloads are forbidden by policy. This only
641 // applies to official system builds; otherwise, HTTP is always enabled.
642 bool http_allowed = true;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700643 if (is_official_build) {
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700644 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
645 const bool* device_policy_is_loaded_p = ec->GetValue(
646 dp_provider->var_device_policy_is_loaded());
647 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
648 const bool* policy_http_downloads_enabled_p = ec->GetValue(
649 dp_provider->var_http_downloads_enabled());
650 http_allowed = (!policy_http_downloads_enabled_p ||
651 *policy_http_downloads_enabled_p);
652 }
653 }
654
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700655 int url_idx = update_state.last_download_url_idx;
656 if (url_idx < 0)
657 url_idx = -1;
658 bool do_advance_url = false;
659 bool is_failure_occurred = false;
660 Time err_time;
661
662 // Scan the relevant part of the download error log, tracking which URLs are
663 // being used, and accounting the number of errors for each URL. Note that
664 // this process may not traverse all errors provided, as it may decide to bail
665 // out midway depending on the particular errors exhibited, the number of
666 // failures allowed, etc. When this ends, |url_idx| will point to the last URL
667 // used (-1 if starting fresh), |do_advance_url| will determine whether the
668 // URL needs to be advanced, and |err_time| the point in time when the last
669 // reported error occurred. Additionally, if the error log indicates that an
670 // update attempt has failed (abnormal), then |is_failure_occurred| will be
671 // set to true.
672 const int num_urls = update_state.download_urls.size();
673 int prev_url_idx = -1;
674 int url_num_errors = update_state.last_download_url_num_errors;
675 Time prev_err_time;
676 bool is_first = true;
677 for (const auto& err_tuple : update_state.download_errors) {
678 // Do some sanity checks.
679 int used_url_idx = get<0>(err_tuple);
680 if (is_first && url_idx >= 0 && used_url_idx != url_idx) {
681 LOG(WARNING) << "First URL in error log (" << used_url_idx
682 << ") not as expected (" << url_idx << ")";
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700683 }
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700684 is_first = false;
685 url_idx = used_url_idx;
686 if (url_idx < 0 || url_idx >= num_urls) {
687 LOG(ERROR) << "Download error log contains an invalid URL index ("
688 << url_idx << ")";
689 return EvalStatus::kFailed;
690 }
691 err_time = get<2>(err_tuple);
692 if (!(prev_err_time.is_null() || err_time >= prev_err_time)) {
693 // TODO(garnold) Monotonicity cannot really be assumed when dealing with
694 // wallclock-based timestamps. However, we're making a simplifying
695 // assumption so as to keep the policy implementation straightforward, for
696 // now. In general, we should convert all timestamp handling in the
697 // UpdateManager to use monotonic time (instead of wallclock), including
698 // the computation of various expiration times (backoff, scattering, etc).
699 // The client will do whatever conversions necessary when
700 // persisting/retrieving these values across reboots. See chromium:408794.
701 LOG(ERROR) << "Download error timestamps not monotonically increasing.";
702 return EvalStatus::kFailed;
703 }
704 prev_err_time = err_time;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700705
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700706 // Ignore errors that happened before the last known failed attempt.
707 if (!update_state.failures_last_updated.is_null() &&
708 err_time <= update_state.failures_last_updated)
709 continue;
710
711 if (prev_url_idx >= 0) {
712 if (url_idx < prev_url_idx) {
713 LOG(ERROR) << "The URLs in the download error log have wrapped around ("
714 << prev_url_idx << "->" << url_idx
715 << "). This should not have happened and means that there's "
716 "a bug. To be conservative, we record a failed attempt "
717 "(invalidating the rest of the error log) and resume "
718 "download from the first usable URL.";
719 url_idx = -1;
720 is_failure_occurred = true;
721 break;
722 }
723
724 if (url_idx > prev_url_idx) {
725 url_num_errors = 0;
726 do_advance_url = false;
727 }
728 }
729
730 if (HandleErrorCode(get<1>(err_tuple), &url_num_errors) ||
731 url_num_errors > update_state.download_errors_max)
732 do_advance_url = true;
733
734 prev_url_idx = url_idx;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700735 }
736
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700737 // If required, advance to the next usable URL. If the URLs wraparound, we
738 // mark an update attempt failure. Also be sure to set the download error
739 // count to zero.
740 if (url_idx < 0 || do_advance_url) {
741 url_num_errors = 0;
742 int start_url_idx = -1;
743 do {
744 if (++url_idx == num_urls) {
745 url_idx = 0;
746 // We only mark failure if an actual advancing of a URL was required.
747 if (do_advance_url)
748 is_failure_occurred = true;
749 }
750
751 if (start_url_idx < 0)
752 start_url_idx = url_idx;
753 else if (url_idx == start_url_idx)
754 url_idx = -1; // No usable URL.
755 } while (url_idx >= 0 &&
756 !IsUrlUsable(update_state.download_urls[url_idx], http_allowed));
757 }
758
759 // If we have a download URL but a failure was observed, compute a new backoff
760 // expiry (if allowed). The backoff period is generally 2 ^ (num_failures - 1)
761 // days, bounded by the size of int and kAttemptBackoffMaxIntervalInDays, and
762 // fuzzed by kAttemptBackoffFuzzInHours hours. Backoff expiry is computed from
763 // the latest recorded time of error.
764 Time backoff_expiry;
765 if (url_idx >= 0 && is_failure_occurred && may_backoff) {
766 CHECK(!err_time.is_null())
767 << "We must have an error timestamp if a failure occurred!";
768 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
769 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
770 PRNG prng(*seed);
Alex Deymof329b932014-10-30 01:37:48 -0700771 int exp = min(update_state.num_failures,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700772 static_cast<int>(sizeof(int)) * 8 - 2);
773 TimeDelta backoff_interval = TimeDelta::FromDays(
Alex Deymof329b932014-10-30 01:37:48 -0700774 min(1 << exp, kAttemptBackoffMaxIntervalInDays));
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700775 TimeDelta backoff_fuzz = TimeDelta::FromHours(kAttemptBackoffFuzzInHours);
776 TimeDelta wait_period = FuzzedInterval(&prng, backoff_interval.InSeconds(),
777 backoff_fuzz.InSeconds());
778 backoff_expiry = err_time + wait_period;
779
780 // If the newly computed backoff already expired, nullify it.
781 if (ec->IsWallclockTimeGreaterThan(backoff_expiry))
782 backoff_expiry = Time();
783 }
784
785 result->do_increment_failures = is_failure_occurred;
786 result->backoff_expiry = backoff_expiry;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700787 result->url_idx = url_idx;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700788 result->url_num_errors = url_num_errors;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700789 return EvalStatus::kSucceeded;
790}
791
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700792EvalStatus ChromeOSPolicy::UpdateScattering(
793 EvaluationContext* ec,
794 State* state,
795 string* error,
796 UpdateScatteringResult* result,
797 const UpdateState& update_state) const {
798 // Preconditions. These stem from the postconditions and usage contract.
799 DCHECK(update_state.scatter_wait_period >= kZeroInterval);
800 DCHECK_GE(update_state.scatter_check_threshold, 0);
801
802 // Set default result values.
803 result->is_scattering = false;
804 result->wait_period = kZeroInterval;
805 result->check_threshold = 0;
806
807 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
808
809 // Ensure that a device policy is loaded.
810 const bool* device_policy_is_loaded_p = ec->GetValue(
811 dp_provider->var_device_policy_is_loaded());
812 if (!(device_policy_is_loaded_p && *device_policy_is_loaded_p))
813 return EvalStatus::kSucceeded;
814
815 // Is scattering enabled by policy?
816 const TimeDelta* scatter_factor_p = ec->GetValue(
817 dp_provider->var_scatter_factor());
818 if (!scatter_factor_p || *scatter_factor_p == kZeroInterval)
819 return EvalStatus::kSucceeded;
820
821 // Obtain a pseudo-random number generator.
822 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
823 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
824 PRNG prng(*seed);
825
826 // Step 1: Maintain the scattering wait period.
827 //
828 // If no wait period was previously determined, or it no longer fits in the
829 // scatter factor, then generate a new one. Otherwise, keep the one we have.
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700830 TimeDelta wait_period = update_state.scatter_wait_period;
831 if (wait_period == kZeroInterval || wait_period > *scatter_factor_p) {
832 wait_period = TimeDelta::FromSeconds(
833 prng.RandMinMax(1, scatter_factor_p->InSeconds()));
834 }
835
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700836 // If we surpassed the wait period or the max scatter period associated with
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700837 // the update, then no wait is needed.
838 Time wait_expires = (update_state.first_seen +
839 min(wait_period, update_state.scatter_wait_period_max));
Gilad Arnolda65fced2014-07-23 09:01:31 -0700840 if (ec->IsWallclockTimeGreaterThan(wait_expires))
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700841 wait_period = kZeroInterval;
842
843 // Step 2: Maintain the update check threshold count.
844 //
845 // If an update check threshold is not specified then generate a new
846 // one.
847 int check_threshold = update_state.scatter_check_threshold;
848 if (check_threshold == 0) {
849 check_threshold = prng.RandMinMax(
850 update_state.scatter_check_threshold_min,
851 update_state.scatter_check_threshold_max);
852 }
853
854 // If the update check threshold is not within allowed range then nullify it.
855 // TODO(garnold) This is compliant with current logic found in
856 // OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied(). We may want
857 // to change it so that it behaves similarly to the wait period case, namely
858 // if the current value exceeds the maximum, we set a new one within range.
859 if (check_threshold > update_state.scatter_check_threshold_max)
860 check_threshold = 0;
861
862 // If the update check threshold is non-zero and satisfied, then nullify it.
863 if (check_threshold > 0 && update_state.num_checks >= check_threshold)
864 check_threshold = 0;
865
866 bool is_scattering = (wait_period != kZeroInterval || check_threshold);
867 EvalStatus ret = EvalStatus::kSucceeded;
868 if (is_scattering && wait_period == update_state.scatter_wait_period &&
869 check_threshold == update_state.scatter_check_threshold)
870 ret = EvalStatus::kAskMeAgainLater;
871 result->is_scattering = is_scattering;
872 result->wait_period = wait_period;
873 result->check_threshold = check_threshold;
874 return ret;
875}
876
Alex Deymo63784a52014-05-28 10:46:14 -0700877} // namespace chromeos_update_manager