blob: 2acccaf256ca116c0925cfd01691a7d402e0e944 [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:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700119 case ErrorCode::kFilesystemVerifierError:
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700120 LOG(INFO) << "Not changing URL index or failure count due to error "
121 << chromeos_update_engine::utils::CodeToString(err_code)
122 << " (" << static_cast<int>(err_code) << ")";
123 return false;
124
125 case ErrorCode::kSuccess: // success code
126 case ErrorCode::kUmaReportedMax: // not an error code
127 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
128 case ErrorCode::kDevModeFlag: // not an error code
129 case ErrorCode::kResumedFlag: // not an error code
130 case ErrorCode::kTestImageFlag: // not an error code
131 case ErrorCode::kTestOmahaUrlFlag: // not an error code
132 case ErrorCode::kSpecialFlags: // not an error code
133 // These shouldn't happen. Enumerating these explicitly here so that we
134 // can let the compiler warn about new error codes that are added to
135 // action_processor.h but not added here.
136 LOG(WARNING) << "Unexpected error "
137 << chromeos_update_engine::utils::CodeToString(err_code)
138 << " (" << static_cast<int>(err_code) << ")";
139 // Note: Not adding a default here so as to let the compiler warn us of
140 // any new enums that were added in the .h but not listed in this switch.
141 }
142 return false;
143}
144
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700145// Checks whether |url| can be used under given download restrictions.
146bool IsUrlUsable(const string& url, bool http_allowed) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700147 return http_allowed || !base::StartsWithASCII(url, "http://", false);
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700148}
149
150} // namespace
151
Alex Deymo63784a52014-05-28 10:46:14 -0700152namespace chromeos_update_manager {
Alex Deymoc705cc82014-02-19 11:15:00 -0800153
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700154const int ChromeOSPolicy::kTimeoutInitialInterval = 7 * 60;
155const int ChromeOSPolicy::kTimeoutPeriodicInterval = 45 * 60;
156const int ChromeOSPolicy::kTimeoutMaxBackoffInterval = 4 * 60 * 60;
157const int ChromeOSPolicy::kTimeoutRegularFuzz = 10 * 60;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700158const int ChromeOSPolicy::kAttemptBackoffMaxIntervalInDays = 16;
159const int ChromeOSPolicy::kAttemptBackoffFuzzInHours = 12;
Gilad Arnold349ac832014-10-06 14:20:28 -0700160const int ChromeOSPolicy::kMaxP2PAttempts = 10;
161const int ChromeOSPolicy::kMaxP2PAttemptsPeriodInSeconds = 5 * 24 * 60 * 60;
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700162
Alex Deymo0d11c602014-04-23 20:12:20 -0700163EvalStatus ChromeOSPolicy::UpdateCheckAllowed(
164 EvaluationContext* ec, State* state, string* error,
165 UpdateCheckParams* result) const {
Gilad Arnold42f253b2014-06-25 12:39:17 -0700166 // Set the default return values.
167 result->updates_enabled = true;
168 result->target_channel.clear();
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700169 result->target_version_prefix.clear();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700170 result->is_interactive = false;
Gilad Arnold42f253b2014-06-25 12:39:17 -0700171
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700172 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700173 UpdaterProvider* const updater_provider = state->updater_provider();
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700174 SystemProvider* const system_provider = state->system_provider();
175
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700176 // Do not perform any updates if booted from removable device. This decision
177 // is final.
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700178 const bool* is_boot_device_removable_p = ec->GetValue(
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700179 system_provider->var_is_boot_device_removable());
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700180 if (is_boot_device_removable_p && *is_boot_device_removable_p) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700181 LOG(INFO) << "Booted from removable device, disabling update checks.";
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700182 result->updates_enabled = false;
183 return EvalStatus::kSucceeded;
184 }
185
Gilad Arnold42f253b2014-06-25 12:39:17 -0700186 const bool* device_policy_is_loaded_p = ec->GetValue(
187 dp_provider->var_device_policy_is_loaded());
188 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
189 // Check whether updates are disabled by policy.
190 const bool* update_disabled_p = ec->GetValue(
191 dp_provider->var_update_disabled());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700192 if (update_disabled_p && *update_disabled_p) {
193 LOG(INFO) << "Updates disabled by policy, blocking update checks.";
Gilad Arnold42f253b2014-06-25 12:39:17 -0700194 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700195 }
Gilad Arnold42f253b2014-06-25 12:39:17 -0700196
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700197 // Determine whether a target version prefix is dictated by policy.
198 const string* target_version_prefix_p = ec->GetValue(
199 dp_provider->var_target_version_prefix());
200 if (target_version_prefix_p)
201 result->target_version_prefix = *target_version_prefix_p;
202
Gilad Arnold42f253b2014-06-25 12:39:17 -0700203 // Determine whether a target channel is dictated by policy.
204 const bool* release_channel_delegated_p = ec->GetValue(
205 dp_provider->var_release_channel_delegated());
206 if (release_channel_delegated_p && !(*release_channel_delegated_p)) {
207 const string* release_channel_p = ec->GetValue(
208 dp_provider->var_release_channel());
209 if (release_channel_p)
210 result->target_channel = *release_channel_p;
211 }
212 }
213
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700214 // First, check to see if an interactive update was requested.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700215 const UpdateRequestStatus* forced_update_requested_p = ec->GetValue(
216 updater_provider->var_forced_update_requested());
217 if (forced_update_requested_p &&
218 *forced_update_requested_p != UpdateRequestStatus::kNone) {
219 result->is_interactive =
220 (*forced_update_requested_p == UpdateRequestStatus::kInteractive);
221 LOG(INFO) << "Forced update signaled ("
222 << (result->is_interactive ? "interactive" : "periodic")
223 << "), allowing update check.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700224 return EvalStatus::kSucceeded;
225 }
226
227 // The logic thereafter applies to periodic updates. Bear in mind that we
228 // should not return a final "no" if any of these criteria are not satisfied,
229 // because the system may still update due to an interactive update request.
230
231 // Unofficial builds should not perform periodic update checks.
232 const bool* is_official_build_p = ec->GetValue(
233 system_provider->var_is_official_build());
234 if (is_official_build_p && !(*is_official_build_p)) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700235 LOG(INFO) << "Unofficial build, blocking periodic update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700236 return EvalStatus::kAskMeAgainLater;
237 }
238
239 // If OOBE is enabled, wait until it is completed.
240 const bool* is_oobe_enabled_p = ec->GetValue(
241 state->config_provider()->var_is_oobe_enabled());
242 if (is_oobe_enabled_p && *is_oobe_enabled_p) {
243 const bool* is_oobe_complete_p = ec->GetValue(
244 system_provider->var_is_oobe_complete());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700245 if (is_oobe_complete_p && !(*is_oobe_complete_p)) {
246 LOG(INFO) << "OOBE not completed, blocking update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700247 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700248 }
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700249 }
250
251 // Ensure that periodic update checks are timed properly.
Alex Deymo0d11c602014-04-23 20:12:20 -0700252 Time next_update_check;
253 if (NextUpdateCheckTime(ec, state, error, &next_update_check) !=
254 EvalStatus::kSucceeded) {
255 return EvalStatus::kFailed;
256 }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700257 if (!ec->IsWallclockTimeGreaterThan(next_update_check)) {
258 LOG(INFO) << "Periodic check interval not satisfied, blocking until "
259 << chromeos_update_engine::utils::ToString(next_update_check);
Alex Deymo0d11c602014-04-23 20:12:20 -0700260 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700261 }
Alex Deymo0d11c602014-04-23 20:12:20 -0700262
263 // It is time to check for an update.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700264 LOG(INFO) << "Allowing update check.";
Alex Deymoe636c3c2014-03-11 19:02:08 -0700265 return EvalStatus::kSucceeded;
Alex Deymoc705cc82014-02-19 11:15:00 -0800266}
267
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700268EvalStatus ChromeOSPolicy::UpdateCanStart(
269 EvaluationContext* ec,
270 State* state,
271 string* error,
Gilad Arnold42f253b2014-06-25 12:39:17 -0700272 UpdateDownloadParams* result,
Gilad Arnoldd78caf92014-09-24 09:28:14 -0700273 const UpdateState update_state) const {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700274 // Set the default return values. Note that we set persisted values (backoff,
275 // scattering) to the same values presented in the update state. The reason is
276 // that preemptive returns, such as the case where an update check is due,
277 // should not clear off the said values; rather, it is the deliberate
278 // inference of new values that should cause them to be reset.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700279 result->update_can_start = false;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700280 result->cannot_start_reason = UpdateCannotStartReason::kUndefined;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700281 result->download_url_idx = -1;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700282 result->download_url_allowed = true;
283 result->download_url_num_errors = 0;
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700284 result->p2p_downloading_allowed = false;
285 result->p2p_sharing_allowed = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700286 result->do_increment_failures = false;
287 result->backoff_expiry = update_state.backoff_expiry;
288 result->scatter_wait_period = update_state.scatter_wait_period;
289 result->scatter_check_threshold = update_state.scatter_check_threshold;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700290
291 // Make sure that we're not due for an update check.
292 UpdateCheckParams check_result;
293 EvalStatus check_status = UpdateCheckAllowed(ec, state, error, &check_result);
294 if (check_status == EvalStatus::kFailed)
295 return EvalStatus::kFailed;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700296 bool is_check_due = (check_status == EvalStatus::kSucceeded &&
297 check_result.updates_enabled == true);
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700298
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700299 // Check whether backoff applies, and if not then which URL can be used for
300 // downloading. These require scanning the download error log, and so they are
301 // done together.
302 UpdateBackoffAndDownloadUrlResult backoff_url_result;
303 EvalStatus backoff_url_status = UpdateBackoffAndDownloadUrl(
304 ec, state, error, &backoff_url_result, update_state);
Gilad Arnold14a9e702014-10-08 08:09:09 -0700305 if (backoff_url_status == EvalStatus::kFailed)
306 return EvalStatus::kFailed;
307 result->download_url_idx = backoff_url_result.url_idx;
308 result->download_url_num_errors = backoff_url_result.url_num_errors;
309 result->do_increment_failures = backoff_url_result.do_increment_failures;
310 result->backoff_expiry = backoff_url_result.backoff_expiry;
311 bool is_backoff_active =
312 (backoff_url_status == EvalStatus::kAskMeAgainLater) ||
313 !backoff_url_result.backoff_expiry.is_null();
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700314
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700315 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold14a9e702014-10-08 08:09:09 -0700316 bool is_scattering_active = false;
317 EvalStatus scattering_status = EvalStatus::kSucceeded;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700318
319 const bool* device_policy_is_loaded_p = ec->GetValue(
320 dp_provider->var_device_policy_is_loaded());
321 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700322 // Check whether scattering applies to this update attempt. We should not be
323 // scattering if this is an interactive update check, or if OOBE is enabled
324 // but not completed.
325 //
326 // Note: current code further suppresses scattering if a "deadline"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700327 // attribute is found in the Omaha response. However, it appears that the
Gilad Arnold76a11f62014-05-20 09:02:12 -0700328 // presence of this attribute is merely indicative of an OOBE update, during
329 // which we suppress scattering anyway.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700330 bool is_scattering_applicable = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700331 result->scatter_wait_period = kZeroInterval;
332 result->scatter_check_threshold = 0;
333 if (!update_state.is_interactive) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700334 const bool* is_oobe_enabled_p = ec->GetValue(
335 state->config_provider()->var_is_oobe_enabled());
336 if (is_oobe_enabled_p && !(*is_oobe_enabled_p)) {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700337 is_scattering_applicable = true;
Gilad Arnold76a11f62014-05-20 09:02:12 -0700338 } else {
339 const bool* is_oobe_complete_p = ec->GetValue(
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700340 state->system_provider()->var_is_oobe_complete());
Gilad Arnold14a9e702014-10-08 08:09:09 -0700341 is_scattering_applicable = (is_oobe_complete_p && *is_oobe_complete_p);
Gilad Arnold76a11f62014-05-20 09:02:12 -0700342 }
343 }
344
345 // Compute scattering values.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700346 if (is_scattering_applicable) {
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700347 UpdateScatteringResult scatter_result;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700348 scattering_status = UpdateScattering(ec, state, error, &scatter_result,
349 update_state);
350 if (scattering_status == EvalStatus::kFailed) {
351 return EvalStatus::kFailed;
352 } else {
353 result->scatter_wait_period = scatter_result.wait_period;
354 result->scatter_check_threshold = scatter_result.check_threshold;
355 if (scattering_status == EvalStatus::kAskMeAgainLater ||
356 scatter_result.is_scattering)
357 is_scattering_active = true;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700358 }
359 }
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700360 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700361
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700362 // Find out whether P2P is globally enabled.
363 bool p2p_enabled;
364 EvalStatus p2p_enabled_status = P2PEnabled(ec, state, error, &p2p_enabled);
365 if (p2p_enabled_status != EvalStatus::kSucceeded)
366 return EvalStatus::kFailed;
367
368 // Is P2P is enabled, consider allowing it for downloading and/or sharing.
369 if (p2p_enabled) {
370 // Sharing via P2P is allowed if not disabled by Omaha.
371 if (update_state.p2p_sharing_disabled) {
372 LOG(INFO) << "Blocked P2P sharing because it is disabled by Omaha.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700373 } else {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700374 result->p2p_sharing_allowed = true;
Gilad Arnoldef8d0872014-10-03 14:14:06 -0700375 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700376
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700377 // Downloading via P2P is allowed if not disabled by Omaha, an update is not
378 // interactive, and other limits haven't been reached.
379 if (update_state.p2p_downloading_disabled) {
380 LOG(INFO) << "Blocked P2P downloading because it is disabled by Omaha.";
381 } else if (update_state.is_interactive) {
382 LOG(INFO) << "Blocked P2P downloading because update is interactive.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700383 } else if (update_state.p2p_num_attempts >= kMaxP2PAttempts) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700384 LOG(INFO) << "Blocked P2P downloading as it was attempted too many "
385 "times.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700386 } else if (!update_state.p2p_first_attempted.is_null() &&
387 ec->IsWallclockTimeGreaterThan(
388 update_state.p2p_first_attempted +
389 TimeDelta::FromSeconds(kMaxP2PAttemptsPeriodInSeconds))) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700390 LOG(INFO) << "Blocked P2P downloading as its usage timespan exceeds "
391 "limit.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700392 } else {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700393 // P2P download is allowed; if backoff or scattering are active, be sure
394 // to suppress them, yet prevent any download URL from being used.
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700395 result->p2p_downloading_allowed = true;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700396 if (is_backoff_active || is_scattering_active) {
397 is_backoff_active = is_scattering_active = false;
398 result->download_url_allowed = false;
399 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700400 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700401 }
402
Gilad Arnold14a9e702014-10-08 08:09:09 -0700403 // Check for various deterrents.
404 if (is_check_due) {
405 result->cannot_start_reason = UpdateCannotStartReason::kCheckDue;
406 return EvalStatus::kSucceeded;
407 }
408 if (is_backoff_active) {
409 result->cannot_start_reason = UpdateCannotStartReason::kBackoff;
410 return backoff_url_status;
411 }
412 if (is_scattering_active) {
413 result->cannot_start_reason = UpdateCannotStartReason::kScattering;
414 return scattering_status;
415 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700416 if (result->download_url_idx < 0 && !result->p2p_downloading_allowed) {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700417 result->cannot_start_reason = UpdateCannotStartReason::kCannotDownload;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700418 return EvalStatus::kSucceeded;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700419 }
420
Gilad Arnold14a9e702014-10-08 08:09:09 -0700421 // Update is good to go.
422 result->update_can_start = true;
Gilad Arnoldaf2f6ae2014-04-28 14:14:52 -0700423 return EvalStatus::kSucceeded;
424}
425
Gilad Arnolda8262e22014-06-02 13:54:27 -0700426// TODO(garnold) Logic in this method is based on
427// ConnectionManager::IsUpdateAllowedOver(); be sure to deprecate the latter.
428//
429// TODO(garnold) The current logic generally treats the list of allowed
430// connections coming from the device policy as a whitelist, meaning that it
431// can only be used for enabling connections, but not disable them. Further,
432// certain connection types (like Bluetooth) cannot be enabled even by policy.
433// In effect, the only thing that device policy can change is to enable
434// updates over a cellular network (disabled by default). We may want to
435// revisit this semantics, allowing greater flexibility in defining specific
436// permissions over all types of networks.
Gilad Arnold684219d2014-07-07 14:54:57 -0700437EvalStatus ChromeOSPolicy::UpdateDownloadAllowed(
Gilad Arnolda8262e22014-06-02 13:54:27 -0700438 EvaluationContext* ec,
439 State* state,
440 string* error,
441 bool* result) const {
442 // Get the current connection type.
443 ShillProvider* const shill_provider = state->shill_provider();
444 const ConnectionType* conn_type_p = ec->GetValue(
445 shill_provider->var_conn_type());
446 POLICY_CHECK_VALUE_AND_FAIL(conn_type_p, error);
447 ConnectionType conn_type = *conn_type_p;
448
449 // If we're tethering, treat it as a cellular connection.
450 if (conn_type != ConnectionType::kCellular) {
451 const ConnectionTethering* conn_tethering_p = ec->GetValue(
452 shill_provider->var_conn_tethering());
453 POLICY_CHECK_VALUE_AND_FAIL(conn_tethering_p, error);
454 if (*conn_tethering_p == ConnectionTethering::kConfirmed)
455 conn_type = ConnectionType::kCellular;
456 }
457
458 // By default, we allow updates for all connection types, with exceptions as
459 // noted below. This also determines whether a device policy can override the
460 // default.
461 *result = true;
462 bool device_policy_can_override = false;
463 switch (conn_type) {
464 case ConnectionType::kBluetooth:
465 *result = false;
466 break;
467
468 case ConnectionType::kCellular:
469 *result = false;
470 device_policy_can_override = true;
471 break;
472
473 case ConnectionType::kUnknown:
474 if (error)
475 *error = "Unknown connection type";
476 return EvalStatus::kFailed;
477
478 default:
479 break; // Nothing to do.
480 }
481
482 // If update is allowed, we're done.
483 if (*result)
484 return EvalStatus::kSucceeded;
485
486 // Check whether the device policy specifically allows this connection.
Gilad Arnolda8262e22014-06-02 13:54:27 -0700487 if (device_policy_can_override) {
488 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
489 const bool* device_policy_is_loaded_p = ec->GetValue(
490 dp_provider->var_device_policy_is_loaded());
491 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
492 const set<ConnectionType>* allowed_conn_types_p = ec->GetValue(
493 dp_provider->var_allowed_connection_types_for_update());
494 if (allowed_conn_types_p) {
495 if (allowed_conn_types_p->count(conn_type)) {
496 *result = true;
497 return EvalStatus::kSucceeded;
498 }
Gilad Arnold28d6be62014-06-30 14:04:04 -0700499 } else if (conn_type == ConnectionType::kCellular) {
500 // Local user settings can allow updates over cellular iff a policy was
501 // loaded but no allowed connections were specified in it.
502 const bool* update_over_cellular_allowed_p = ec->GetValue(
503 state->updater_provider()->var_cellular_enabled());
504 if (update_over_cellular_allowed_p && *update_over_cellular_allowed_p)
505 *result = true;
Gilad Arnolda8262e22014-06-02 13:54:27 -0700506 }
507 }
508 }
509
Gilad Arnold28d6be62014-06-30 14:04:04 -0700510 return (*result ? EvalStatus::kSucceeded : EvalStatus::kAskMeAgainLater);
Gilad Arnolda8262e22014-06-02 13:54:27 -0700511}
512
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700513EvalStatus ChromeOSPolicy::P2PEnabled(EvaluationContext* ec,
514 State* state,
515 std::string* error,
516 bool* result) const {
517 bool enabled = false;
518
519 // Determine whether use of P2P is allowed by policy. Even if P2P is not
520 // explicitly allowed, we allow it if the device is enterprise enrolled (that
521 // is, missing or empty owner string).
522 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
523 const bool* device_policy_is_loaded_p = ec->GetValue(
524 dp_provider->var_device_policy_is_loaded());
525 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
526 const bool* policy_au_p2p_enabled_p = ec->GetValue(
527 dp_provider->var_au_p2p_enabled());
528 if (policy_au_p2p_enabled_p) {
529 enabled = *policy_au_p2p_enabled_p;
530 } else {
531 const string* policy_owner_p = ec->GetValue(dp_provider->var_owner());
532 if (!policy_owner_p || policy_owner_p->empty())
533 enabled = true;
534 }
535 }
536
537 // Enable P2P, if so mandated by the updater configuration. This is additive
538 // to whether or not P2P is enabled by device policy.
539 if (!enabled) {
540 const bool* updater_p2p_enabled_p = ec->GetValue(
541 state->updater_provider()->var_p2p_enabled());
542 enabled = updater_p2p_enabled_p && *updater_p2p_enabled_p;
543 }
544
545 *result = enabled;
546 return EvalStatus::kSucceeded;
547}
548
549EvalStatus ChromeOSPolicy::P2PEnabledChanged(EvaluationContext* ec,
550 State* state,
551 std::string* error,
552 bool* result,
553 bool prev_result) const {
554 EvalStatus status = P2PEnabled(ec, state, error, result);
555 if (status == EvalStatus::kSucceeded && *result == prev_result)
556 return EvalStatus::kAskMeAgainLater;
557 return status;
558}
559
Alex Deymo0d11c602014-04-23 20:12:20 -0700560EvalStatus ChromeOSPolicy::NextUpdateCheckTime(EvaluationContext* ec,
561 State* state, string* error,
562 Time* next_update_check) const {
Gilad Arnolda0258a52014-07-10 16:21:19 -0700563 UpdaterProvider* const updater_provider = state->updater_provider();
564
Alex Deymo0d11c602014-04-23 20:12:20 -0700565 // Don't check for updates too often. We limit the update checks to once every
566 // some interval. The interval is kTimeoutInitialInterval the first time and
567 // kTimeoutPeriodicInterval for the subsequent update checks. If the update
568 // check fails, we increase the interval between the update checks
569 // exponentially until kTimeoutMaxBackoffInterval. Finally, to avoid having
570 // many chromebooks running update checks at the exact same time, we add some
571 // fuzz to the interval.
572 const Time* updater_started_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700573 ec->GetValue(updater_provider->var_updater_started_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700574 POLICY_CHECK_VALUE_AND_FAIL(updater_started_time, error);
575
Alex Deymof329b932014-10-30 01:37:48 -0700576 const Time* last_checked_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700577 ec->GetValue(updater_provider->var_last_checked_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700578
579 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
580 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
581
582 PRNG prng(*seed);
583
Gilad Arnold38b14022014-07-09 12:45:56 -0700584 // If this is the first attempt, compute and return an initial value.
Alex Deymo0d11c602014-04-23 20:12:20 -0700585 if (!last_checked_time || *last_checked_time < *updater_started_time) {
Alex Deymo0d11c602014-04-23 20:12:20 -0700586 *next_update_check = *updater_started_time + FuzzedInterval(
587 &prng, kTimeoutInitialInterval, kTimeoutRegularFuzz);
588 return EvalStatus::kSucceeded;
589 }
Gilad Arnold38b14022014-07-09 12:45:56 -0700590
Gilad Arnolda0258a52014-07-10 16:21:19 -0700591 // Check whether the server is enforcing a poll interval; if not, this value
592 // will be zero.
593 const unsigned int* server_dictated_poll_interval = ec->GetValue(
594 updater_provider->var_server_dictated_poll_interval());
595 POLICY_CHECK_VALUE_AND_FAIL(server_dictated_poll_interval, error);
Alex Deymo0d11c602014-04-23 20:12:20 -0700596
Gilad Arnolda0258a52014-07-10 16:21:19 -0700597 int interval = *server_dictated_poll_interval;
598 int fuzz = 0;
599
Alex Vakulenko072359c2014-07-18 11:41:07 -0700600 // If no poll interval was dictated by server compute a back-off period,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700601 // starting from a predetermined base periodic interval and increasing
602 // exponentially by the number of consecutive failed attempts.
603 if (interval == 0) {
604 const unsigned int* consecutive_failed_update_checks = ec->GetValue(
605 updater_provider->var_consecutive_failed_update_checks());
606 POLICY_CHECK_VALUE_AND_FAIL(consecutive_failed_update_checks, error);
607
608 interval = kTimeoutPeriodicInterval;
609 unsigned int num_failures = *consecutive_failed_update_checks;
610 while (interval < kTimeoutMaxBackoffInterval && num_failures) {
611 interval *= 2;
612 num_failures--;
Alex Deymo0d11c602014-04-23 20:12:20 -0700613 }
614 }
615
Alex Vakulenko072359c2014-07-18 11:41:07 -0700616 // We cannot back off longer than the predetermined maximum interval.
Gilad Arnolda0258a52014-07-10 16:21:19 -0700617 if (interval > kTimeoutMaxBackoffInterval)
618 interval = kTimeoutMaxBackoffInterval;
619
Alex Vakulenko072359c2014-07-18 11:41:07 -0700620 // We cannot back off shorter than the predetermined periodic interval. Also,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700621 // in this case set the fuzz to a predetermined regular value.
622 if (interval <= kTimeoutPeriodicInterval) {
623 interval = kTimeoutPeriodicInterval;
624 fuzz = kTimeoutRegularFuzz;
625 }
626
627 // If not otherwise determined, defer to a fuzz of +/-(interval / 2).
Gilad Arnold38b14022014-07-09 12:45:56 -0700628 if (fuzz == 0)
629 fuzz = interval;
630
Alex Deymo0d11c602014-04-23 20:12:20 -0700631 *next_update_check = *last_checked_time + FuzzedInterval(
Gilad Arnold38b14022014-07-09 12:45:56 -0700632 &prng, interval, fuzz);
Alex Deymo0d11c602014-04-23 20:12:20 -0700633 return EvalStatus::kSucceeded;
634}
635
636TimeDelta ChromeOSPolicy::FuzzedInterval(PRNG* prng, int interval, int fuzz) {
Gilad Arnolde1218812014-05-07 12:21:36 -0700637 DCHECK_GE(interval, 0);
638 DCHECK_GE(fuzz, 0);
Alex Deymo0d11c602014-04-23 20:12:20 -0700639 int half_fuzz = fuzz / 2;
Alex Deymo0d11c602014-04-23 20:12:20 -0700640 // This guarantees the output interval is non negative.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700641 int interval_min = max(interval - half_fuzz, 0);
Gilad Arnolde1218812014-05-07 12:21:36 -0700642 int interval_max = interval + half_fuzz;
643 return TimeDelta::FromSeconds(prng->RandMinMax(interval_min, interval_max));
Alex Deymo0d11c602014-04-23 20:12:20 -0700644}
645
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700646EvalStatus ChromeOSPolicy::UpdateBackoffAndDownloadUrl(
Alex Deymof329b932014-10-30 01:37:48 -0700647 EvaluationContext* ec, State* state, string* error,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700648 UpdateBackoffAndDownloadUrlResult* result,
649 const UpdateState& update_state) const {
650 // Sanity checks.
651 DCHECK_GE(update_state.download_errors_max, 0);
652
653 // Set default result values.
654 result->do_increment_failures = false;
655 result->backoff_expiry = update_state.backoff_expiry;
656 result->url_idx = -1;
657 result->url_num_errors = 0;
658
659 const bool* is_official_build_p = ec->GetValue(
660 state->system_provider()->var_is_official_build());
661 bool is_official_build = (is_official_build_p ? *is_official_build_p : true);
662
663 // Check whether backoff is enabled.
664 bool may_backoff = false;
665 if (update_state.is_backoff_disabled) {
666 LOG(INFO) << "Backoff disabled by Omaha.";
667 } else if (update_state.is_interactive) {
668 LOG(INFO) << "No backoff for interactive updates.";
669 } else if (update_state.is_delta_payload) {
670 LOG(INFO) << "No backoff for delta payloads.";
671 } else if (!is_official_build) {
672 LOG(INFO) << "No backoff for unofficial builds.";
673 } else {
674 may_backoff = true;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700675 }
676
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700677 // If previous backoff still in effect, block.
678 if (may_backoff && !update_state.backoff_expiry.is_null() &&
679 !ec->IsWallclockTimeGreaterThan(update_state.backoff_expiry)) {
680 LOG(INFO) << "Previous backoff has not expired, waiting.";
681 return EvalStatus::kAskMeAgainLater;
682 }
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700683
684 // Determine whether HTTP downloads are forbidden by policy. This only
685 // applies to official system builds; otherwise, HTTP is always enabled.
686 bool http_allowed = true;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700687 if (is_official_build) {
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700688 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
689 const bool* device_policy_is_loaded_p = ec->GetValue(
690 dp_provider->var_device_policy_is_loaded());
691 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
692 const bool* policy_http_downloads_enabled_p = ec->GetValue(
693 dp_provider->var_http_downloads_enabled());
694 http_allowed = (!policy_http_downloads_enabled_p ||
695 *policy_http_downloads_enabled_p);
696 }
697 }
698
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700699 int url_idx = update_state.last_download_url_idx;
700 if (url_idx < 0)
701 url_idx = -1;
702 bool do_advance_url = false;
703 bool is_failure_occurred = false;
704 Time err_time;
705
706 // Scan the relevant part of the download error log, tracking which URLs are
707 // being used, and accounting the number of errors for each URL. Note that
708 // this process may not traverse all errors provided, as it may decide to bail
709 // out midway depending on the particular errors exhibited, the number of
710 // failures allowed, etc. When this ends, |url_idx| will point to the last URL
711 // used (-1 if starting fresh), |do_advance_url| will determine whether the
712 // URL needs to be advanced, and |err_time| the point in time when the last
713 // reported error occurred. Additionally, if the error log indicates that an
714 // update attempt has failed (abnormal), then |is_failure_occurred| will be
715 // set to true.
716 const int num_urls = update_state.download_urls.size();
717 int prev_url_idx = -1;
718 int url_num_errors = update_state.last_download_url_num_errors;
719 Time prev_err_time;
720 bool is_first = true;
721 for (const auto& err_tuple : update_state.download_errors) {
722 // Do some sanity checks.
723 int used_url_idx = get<0>(err_tuple);
724 if (is_first && url_idx >= 0 && used_url_idx != url_idx) {
725 LOG(WARNING) << "First URL in error log (" << used_url_idx
726 << ") not as expected (" << url_idx << ")";
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700727 }
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700728 is_first = false;
729 url_idx = used_url_idx;
730 if (url_idx < 0 || url_idx >= num_urls) {
731 LOG(ERROR) << "Download error log contains an invalid URL index ("
732 << url_idx << ")";
733 return EvalStatus::kFailed;
734 }
735 err_time = get<2>(err_tuple);
736 if (!(prev_err_time.is_null() || err_time >= prev_err_time)) {
737 // TODO(garnold) Monotonicity cannot really be assumed when dealing with
738 // wallclock-based timestamps. However, we're making a simplifying
739 // assumption so as to keep the policy implementation straightforward, for
740 // now. In general, we should convert all timestamp handling in the
741 // UpdateManager to use monotonic time (instead of wallclock), including
742 // the computation of various expiration times (backoff, scattering, etc).
743 // The client will do whatever conversions necessary when
744 // persisting/retrieving these values across reboots. See chromium:408794.
745 LOG(ERROR) << "Download error timestamps not monotonically increasing.";
746 return EvalStatus::kFailed;
747 }
748 prev_err_time = err_time;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700749
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700750 // Ignore errors that happened before the last known failed attempt.
751 if (!update_state.failures_last_updated.is_null() &&
752 err_time <= update_state.failures_last_updated)
753 continue;
754
755 if (prev_url_idx >= 0) {
756 if (url_idx < prev_url_idx) {
757 LOG(ERROR) << "The URLs in the download error log have wrapped around ("
758 << prev_url_idx << "->" << url_idx
759 << "). This should not have happened and means that there's "
760 "a bug. To be conservative, we record a failed attempt "
761 "(invalidating the rest of the error log) and resume "
762 "download from the first usable URL.";
763 url_idx = -1;
764 is_failure_occurred = true;
765 break;
766 }
767
768 if (url_idx > prev_url_idx) {
769 url_num_errors = 0;
770 do_advance_url = false;
771 }
772 }
773
774 if (HandleErrorCode(get<1>(err_tuple), &url_num_errors) ||
775 url_num_errors > update_state.download_errors_max)
776 do_advance_url = true;
777
778 prev_url_idx = url_idx;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700779 }
780
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700781 // If required, advance to the next usable URL. If the URLs wraparound, we
782 // mark an update attempt failure. Also be sure to set the download error
783 // count to zero.
784 if (url_idx < 0 || do_advance_url) {
785 url_num_errors = 0;
786 int start_url_idx = -1;
787 do {
788 if (++url_idx == num_urls) {
789 url_idx = 0;
790 // We only mark failure if an actual advancing of a URL was required.
791 if (do_advance_url)
792 is_failure_occurred = true;
793 }
794
795 if (start_url_idx < 0)
796 start_url_idx = url_idx;
797 else if (url_idx == start_url_idx)
798 url_idx = -1; // No usable URL.
799 } while (url_idx >= 0 &&
800 !IsUrlUsable(update_state.download_urls[url_idx], http_allowed));
801 }
802
803 // If we have a download URL but a failure was observed, compute a new backoff
804 // expiry (if allowed). The backoff period is generally 2 ^ (num_failures - 1)
805 // days, bounded by the size of int and kAttemptBackoffMaxIntervalInDays, and
806 // fuzzed by kAttemptBackoffFuzzInHours hours. Backoff expiry is computed from
807 // the latest recorded time of error.
808 Time backoff_expiry;
809 if (url_idx >= 0 && is_failure_occurred && may_backoff) {
810 CHECK(!err_time.is_null())
811 << "We must have an error timestamp if a failure occurred!";
812 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
813 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
814 PRNG prng(*seed);
Alex Deymof329b932014-10-30 01:37:48 -0700815 int exp = min(update_state.num_failures,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700816 static_cast<int>(sizeof(int)) * 8 - 2);
817 TimeDelta backoff_interval = TimeDelta::FromDays(
Alex Deymof329b932014-10-30 01:37:48 -0700818 min(1 << exp, kAttemptBackoffMaxIntervalInDays));
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700819 TimeDelta backoff_fuzz = TimeDelta::FromHours(kAttemptBackoffFuzzInHours);
820 TimeDelta wait_period = FuzzedInterval(&prng, backoff_interval.InSeconds(),
821 backoff_fuzz.InSeconds());
822 backoff_expiry = err_time + wait_period;
823
824 // If the newly computed backoff already expired, nullify it.
825 if (ec->IsWallclockTimeGreaterThan(backoff_expiry))
826 backoff_expiry = Time();
827 }
828
829 result->do_increment_failures = is_failure_occurred;
830 result->backoff_expiry = backoff_expiry;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700831 result->url_idx = url_idx;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700832 result->url_num_errors = url_num_errors;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700833 return EvalStatus::kSucceeded;
834}
835
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700836EvalStatus ChromeOSPolicy::UpdateScattering(
837 EvaluationContext* ec,
838 State* state,
839 string* error,
840 UpdateScatteringResult* result,
841 const UpdateState& update_state) const {
842 // Preconditions. These stem from the postconditions and usage contract.
843 DCHECK(update_state.scatter_wait_period >= kZeroInterval);
844 DCHECK_GE(update_state.scatter_check_threshold, 0);
845
846 // Set default result values.
847 result->is_scattering = false;
848 result->wait_period = kZeroInterval;
849 result->check_threshold = 0;
850
851 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
852
853 // Ensure that a device policy is loaded.
854 const bool* device_policy_is_loaded_p = ec->GetValue(
855 dp_provider->var_device_policy_is_loaded());
856 if (!(device_policy_is_loaded_p && *device_policy_is_loaded_p))
857 return EvalStatus::kSucceeded;
858
859 // Is scattering enabled by policy?
860 const TimeDelta* scatter_factor_p = ec->GetValue(
861 dp_provider->var_scatter_factor());
862 if (!scatter_factor_p || *scatter_factor_p == kZeroInterval)
863 return EvalStatus::kSucceeded;
864
865 // Obtain a pseudo-random number generator.
866 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
867 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
868 PRNG prng(*seed);
869
870 // Step 1: Maintain the scattering wait period.
871 //
872 // If no wait period was previously determined, or it no longer fits in the
873 // scatter factor, then generate a new one. Otherwise, keep the one we have.
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700874 TimeDelta wait_period = update_state.scatter_wait_period;
875 if (wait_period == kZeroInterval || wait_period > *scatter_factor_p) {
876 wait_period = TimeDelta::FromSeconds(
877 prng.RandMinMax(1, scatter_factor_p->InSeconds()));
878 }
879
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700880 // If we surpassed the wait period or the max scatter period associated with
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700881 // the update, then no wait is needed.
882 Time wait_expires = (update_state.first_seen +
883 min(wait_period, update_state.scatter_wait_period_max));
Gilad Arnolda65fced2014-07-23 09:01:31 -0700884 if (ec->IsWallclockTimeGreaterThan(wait_expires))
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700885 wait_period = kZeroInterval;
886
887 // Step 2: Maintain the update check threshold count.
888 //
889 // If an update check threshold is not specified then generate a new
890 // one.
891 int check_threshold = update_state.scatter_check_threshold;
892 if (check_threshold == 0) {
893 check_threshold = prng.RandMinMax(
894 update_state.scatter_check_threshold_min,
895 update_state.scatter_check_threshold_max);
896 }
897
898 // If the update check threshold is not within allowed range then nullify it.
899 // TODO(garnold) This is compliant with current logic found in
900 // OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied(). We may want
901 // to change it so that it behaves similarly to the wait period case, namely
902 // if the current value exceeds the maximum, we set a new one within range.
903 if (check_threshold > update_state.scatter_check_threshold_max)
904 check_threshold = 0;
905
906 // If the update check threshold is non-zero and satisfied, then nullify it.
907 if (check_threshold > 0 && update_state.num_checks >= check_threshold)
908 check_threshold = 0;
909
910 bool is_scattering = (wait_period != kZeroInterval || check_threshold);
911 EvalStatus ret = EvalStatus::kSucceeded;
912 if (is_scattering && wait_period == update_state.scatter_wait_period &&
913 check_threshold == update_state.scatter_check_threshold)
914 ret = EvalStatus::kAskMeAgainLater;
915 result->is_scattering = is_scattering;
916 result->wait_period = wait_period;
917 result->check_threshold = check_threshold;
918 return ret;
919}
920
Alex Deymo63784a52014-05-28 10:46:14 -0700921} // namespace chromeos_update_manager