blob: 22e5094500fadd977c3c012448e342b1ae09dbda [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2014 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
Alex Deymoc705cc82014-02-19 11:15:00 -080016
Alex Deymo63784a52014-05-28 10:46:14 -070017#include "update_engine/update_manager/chromeos_policy.h"
Alex Deymo0d11c602014-04-23 20:12:20 -070018
Gilad Arnolde1218812014-05-07 12:21:36 -070019#include <algorithm>
Gilad Arnold0adbc942014-05-12 10:35:43 -070020#include <set>
Alex Deymoc705cc82014-02-19 11:15:00 -080021#include <string>
Amin Hassani186ff6a2018-02-27 11:06:03 -080022#include <vector>
Alex Deymoc705cc82014-02-19 11:15:00 -080023
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070024#include <base/logging.h>
Gilad Arnoldb3b05442014-05-30 14:25:05 -070025#include <base/strings/string_util.h>
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070026#include <base/time/time.h>
27
Alex Deymo39910dc2015-11-09 17:04:30 -080028#include "update_engine/common/error_code.h"
Alex Deymoe88e9fe2016-02-03 16:38:00 -080029#include "update_engine/common/error_code_utils.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080030#include "update_engine/common/utils.h"
Alex Deymo63784a52014-05-28 10:46:14 -070031#include "update_engine/update_manager/device_policy_provider.h"
Amin Hassani186ff6a2018-02-27 11:06:03 -080032#include "update_engine/update_manager/enough_slots_ab_updates_policy_impl.h"
33#include "update_engine/update_manager/enterprise_device_policy_impl.h"
34#include "update_engine/update_manager/interactive_update_policy_impl.h"
35#include "update_engine/update_manager/official_build_check_policy_impl.h"
36#include "update_engine/update_manager/out_of_box_experience_policy_impl.h"
Alex Deymo63784a52014-05-28 10:46:14 -070037#include "update_engine/update_manager/policy_utils.h"
38#include "update_engine/update_manager/shill_provider.h"
Adolfo Victoria94ffe132018-06-28 16:14:56 -070039#include "update_engine/update_manager/update_time_restrictions_policy_impl.h"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070040
Alex Deymo0d11c602014-04-23 20:12:20 -070041using base::Time;
42using base::TimeDelta;
Sen Jiang255e22b2016-05-20 16:15:29 -070043using chromeos_update_engine::ConnectionTethering;
44using chromeos_update_engine::ConnectionType;
Gilad Arnoldb3b05442014-05-30 14:25:05 -070045using chromeos_update_engine::ErrorCode;
Aaron Wood23bd3392017-10-06 14:48:25 -070046using chromeos_update_engine::InstallPlan;
Gilad Arnolddc4bb262014-07-23 10:45:19 -070047using std::get;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070048using std::min;
Gilad Arnold0adbc942014-05-12 10:35:43 -070049using std::set;
Alex Deymoc705cc82014-02-19 11:15:00 -080050using std::string;
Amin Hassani186ff6a2018-02-27 11:06:03 -080051using std::vector;
Alex Deymoc705cc82014-02-19 11:15:00 -080052
Gilad Arnoldb3b05442014-05-30 14:25:05 -070053namespace {
54
Gilad Arnolddc4bb262014-07-23 10:45:19 -070055// Examines |err_code| and decides whether the URL index needs to be advanced,
56// the error count for the URL incremented, or none of the above. In the first
57// case, returns true; in the second case, increments |*url_num_error_p| and
58// returns false; otherwise just returns false.
Gilad Arnoldb3b05442014-05-30 14:25:05 -070059//
60// TODO(garnold) Adapted from PayloadState::UpdateFailed() (to be retired).
Gilad Arnolddc4bb262014-07-23 10:45:19 -070061bool HandleErrorCode(ErrorCode err_code, int* url_num_error_p) {
Gilad Arnoldb3b05442014-05-30 14:25:05 -070062 err_code = chromeos_update_engine::utils::GetBaseErrorCode(err_code);
63 switch (err_code) {
64 // Errors which are good indicators of a problem with a particular URL or
65 // the protocol used in the URL or entities in the communication channel
66 // (e.g. proxies). We should try the next available URL in the next update
67 // check to quickly recover from these errors.
68 case ErrorCode::kPayloadHashMismatchError:
69 case ErrorCode::kPayloadSizeMismatchError:
70 case ErrorCode::kDownloadPayloadVerificationError:
71 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
72 case ErrorCode::kSignedDeltaPayloadExpectedError:
73 case ErrorCode::kDownloadInvalidMetadataMagicString:
74 case ErrorCode::kDownloadSignatureMissingInManifest:
75 case ErrorCode::kDownloadManifestParseError:
76 case ErrorCode::kDownloadMetadataSignatureError:
77 case ErrorCode::kDownloadMetadataSignatureVerificationError:
78 case ErrorCode::kDownloadMetadataSignatureMismatch:
79 case ErrorCode::kDownloadOperationHashVerificationError:
80 case ErrorCode::kDownloadOperationExecutionError:
81 case ErrorCode::kDownloadOperationHashMismatch:
82 case ErrorCode::kDownloadInvalidMetadataSize:
83 case ErrorCode::kDownloadInvalidMetadataSignature:
84 case ErrorCode::kDownloadOperationHashMissingError:
85 case ErrorCode::kDownloadMetadataSignatureMissingError:
86 case ErrorCode::kPayloadMismatchedType:
87 case ErrorCode::kUnsupportedMajorPayloadVersion:
88 case ErrorCode::kUnsupportedMinorPayloadVersion:
Sen Jiang8e768e92017-06-28 17:13:19 -070089 case ErrorCode::kPayloadTimestampError:
Sen Jiang57f91802017-11-14 17:42:13 -080090 case ErrorCode::kVerityCalculationError:
Gilad Arnoldb3b05442014-05-30 14:25:05 -070091 LOG(INFO) << "Advancing download URL due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -080092 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -070093 << " (" << static_cast<int>(err_code) << ")";
Gilad Arnoldb3b05442014-05-30 14:25:05 -070094 return true;
95
96 // Errors which seem to be just transient network/communication related
97 // failures and do not indicate any inherent problem with the URL itself.
98 // So, we should keep the current URL but just increment the
99 // failure count to give it more chances. This way, while we maximize our
100 // chances of downloading from the URLs that appear earlier in the response
101 // (because download from a local server URL that appears earlier in a
102 // response is preferable than downloading from the next URL which could be
Alex Vakulenko072359c2014-07-18 11:41:07 -0700103 // an Internet URL and thus could be more expensive).
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700104 case ErrorCode::kError:
105 case ErrorCode::kDownloadTransferError:
106 case ErrorCode::kDownloadWriteError:
107 case ErrorCode::kDownloadStateInitializationError:
Gilad Arnold684219d2014-07-07 14:54:57 -0700108 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700109 LOG(INFO) << "Incrementing URL failure count due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800110 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700111 << " (" << static_cast<int>(err_code) << ")";
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700112 *url_num_error_p += 1;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700113 return false;
114
115 // Errors which are not specific to a URL and hence shouldn't result in
116 // the URL being penalized. This can happen in two cases:
117 // 1. We haven't started downloading anything: These errors don't cost us
118 // anything in terms of actual payload bytes, so we should just do the
119 // regular retries at the next update check.
120 // 2. We have successfully downloaded the payload: In this case, the
121 // payload attempt number would have been incremented and would take care
Alex Vakulenko072359c2014-07-18 11:41:07 -0700122 // of the back-off at the next update check.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700123 // In either case, there's no need to update URL index or failure count.
124 case ErrorCode::kOmahaRequestError:
125 case ErrorCode::kOmahaResponseHandlerError:
126 case ErrorCode::kPostinstallRunnerError:
127 case ErrorCode::kFilesystemCopierError:
128 case ErrorCode::kInstallDeviceOpenError:
129 case ErrorCode::kKernelDeviceOpenError:
130 case ErrorCode::kDownloadNewPartitionInfoError:
131 case ErrorCode::kNewRootfsVerificationError:
132 case ErrorCode::kNewKernelVerificationError:
133 case ErrorCode::kPostinstallBootedFromFirmwareB:
134 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
135 case ErrorCode::kOmahaRequestEmptyResponseError:
136 case ErrorCode::kOmahaRequestXMLParseError:
137 case ErrorCode::kOmahaResponseInvalid:
138 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
139 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
Kevin Cernekee2494e282016-03-29 18:03:53 -0700140 case ErrorCode::kNonCriticalUpdateInOOBE:
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700141 case ErrorCode::kOmahaUpdateDeferredForBackoff:
142 case ErrorCode::kPostinstallPowerwashError:
143 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400144 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700145 case ErrorCode::kFilesystemVerifierError:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800146 case ErrorCode::kUserCanceled:
Weidong Guo421ff332017-04-17 10:08:38 -0700147 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
Sen Jiangfe522822017-10-31 15:14:11 -0700148 case ErrorCode::kUpdatedButNotActive:
Sen Jiang89e24c12018-03-22 18:05:44 -0700149 case ErrorCode::kNoUpdate:
Marton Hunyady199152d2018-05-07 19:08:48 +0200150 case ErrorCode::kRollbackNotPossible:
Amin Hassani80f4d4c2018-05-16 13:34:00 -0700151 case ErrorCode::kFirstActiveOmahaPingSentPersistenceError:
Yifan Hongf6c805a2019-12-13 11:50:43 -0800152 case ErrorCode::kInternalLibCurlError:
153 case ErrorCode::kUnresolvedHostError:
154 case ErrorCode::kUnresolvedHostRecovered:
Yifan Hong46e37d42019-12-13 12:01:42 -0800155 case ErrorCode::kNotEnoughSpace:
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700156 LOG(INFO) << "Not changing URL index or failure count due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800157 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700158 << " (" << static_cast<int>(err_code) << ")";
159 return false;
160
Amin Hassani4b717432019-01-14 16:24:20 -0800161 case ErrorCode::kSuccess: // success code
162 case ErrorCode::kUmaReportedMax: // not an error code
163 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
164 case ErrorCode::kDevModeFlag: // not an error code
165 case ErrorCode::kResumedFlag: // not an error code
166 case ErrorCode::kTestImageFlag: // not an error code
167 case ErrorCode::kTestOmahaUrlFlag: // not an error code
168 case ErrorCode::kSpecialFlags: // not an error code
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700169 // These shouldn't happen. Enumerating these explicitly here so that we
170 // can let the compiler warn about new error codes that are added to
171 // action_processor.h but not added here.
172 LOG(WARNING) << "Unexpected error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800173 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700174 << " (" << static_cast<int>(err_code) << ")";
Amin Hassani4b717432019-01-14 16:24:20 -0800175 // Note: Not adding a default here so as to let the compiler warn us of
176 // any new enums that were added in the .h but not listed in this switch.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700177 }
178 return false;
179}
180
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700181// Checks whether |url| can be used under given download restrictions.
182bool IsUrlUsable(const string& url, bool http_allowed) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800183 return http_allowed ||
Amin Hassani4b717432019-01-14 16:24:20 -0800184 !base::StartsWith(
185 url, "http://", base::CompareCase::INSENSITIVE_ASCII);
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700186}
187
188} // namespace
189
Alex Deymo63784a52014-05-28 10:46:14 -0700190namespace chromeos_update_manager {
Alex Deymoc705cc82014-02-19 11:15:00 -0800191
Amin Hassani186ff6a2018-02-27 11:06:03 -0800192const NextUpdateCheckPolicyConstants
193 ChromeOSPolicy::kNextUpdateCheckPolicyConstants = {
194 .timeout_initial_interval = 7 * 60,
195 .timeout_periodic_interval = 45 * 60,
196 .timeout_max_backoff_interval = 4 * 60 * 60,
197 .timeout_regular_fuzz = 10 * 60,
198 .attempt_backoff_max_interval_in_days = 16,
199 .attempt_backoff_fuzz_in_hours = 12,
200};
Alex Deymo14e7dde2015-10-20 14:46:33 -0700201
Gilad Arnold349ac832014-10-06 14:20:28 -0700202const int ChromeOSPolicy::kMaxP2PAttempts = 10;
203const int ChromeOSPolicy::kMaxP2PAttemptsPeriodInSeconds = 5 * 24 * 60 * 60;
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700204
Amin Hassani4b717432019-01-14 16:24:20 -0800205EvalStatus ChromeOSPolicy::UpdateCheckAllowed(EvaluationContext* ec,
206 State* state,
207 string* error,
208 UpdateCheckParams* result) const {
Gilad Arnold42f253b2014-06-25 12:39:17 -0700209 // Set the default return values.
210 result->updates_enabled = true;
211 result->target_channel.clear();
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700212 result->target_version_prefix.clear();
Marton Hunyadyba51c3f2018-04-25 15:18:10 +0200213 result->rollback_allowed = false;
Marton Hunyady0e0e3542018-02-21 18:51:39 +0100214 result->rollback_allowed_milestones = -1;
Amin Hassanied37d682018-04-06 13:22:00 -0700215 result->interactive = false;
Gilad Arnold42f253b2014-06-25 12:39:17 -0700216
Amin Hassani186ff6a2018-02-27 11:06:03 -0800217 EnoughSlotsAbUpdatesPolicyImpl enough_slots_ab_updates_policy;
218 EnterpriseDevicePolicyImpl enterprise_device_policy;
219 OnlyUpdateOfficialBuildsPolicyImpl only_update_official_builds_policy;
220 InteractiveUpdatePolicyImpl interactive_update_policy;
221 OobePolicyImpl oobe_policy;
222 NextUpdateCheckTimePolicyImpl next_update_check_time_policy(
223 kNextUpdateCheckPolicyConstants);
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700224
Amin Hassani186ff6a2018-02-27 11:06:03 -0800225 vector<Policy const*> policies_to_consult = {
226 // Do not perform any updates if there are not enough slots to do A/B
227 // updates.
228 &enough_slots_ab_updates_policy,
229
230 // Check to see if Enterprise-managed (has DevicePolicy) and/or
231 // Kiosk-mode. If so, then defer to those settings.
232 &enterprise_device_policy,
233
234 // Check to see if an interactive update was requested.
235 &interactive_update_policy,
236
237 // Unofficial builds should not perform periodic update checks.
238 &only_update_official_builds_policy,
239
240 // If OOBE is enabled, wait until it is completed.
241 &oobe_policy,
242
243 // Ensure that periodic update checks are timed properly.
244 &next_update_check_time_policy,
245 };
246
247 // Now that the list of policy implementations, and the order to consult them,
248 // has been setup, consult the policies. If none of the policies make a
249 // definitive decisions about whether or not to check for updates, then allow
250 // the update check to happen.
251 EvalStatus status = ConsultPolicies(policies_to_consult,
252 &Policy::UpdateCheckAllowed,
253 ec,
254 state,
255 error,
256 result);
257 if (EvalStatus::kContinue != status) {
258 return status;
259 } else {
260 // It is time to check for an update.
261 LOG(INFO) << "Allowing update check.";
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700262 return EvalStatus::kSucceeded;
263 }
Alex Deymoc705cc82014-02-19 11:15:00 -0800264}
265
Aaron Wood23bd3392017-10-06 14:48:25 -0700266EvalStatus ChromeOSPolicy::UpdateCanBeApplied(EvaluationContext* ec,
267 State* state,
268 std::string* error,
269 ErrorCode* result,
270 InstallPlan* install_plan) const {
Adolfo Victoria0dbf1f92018-07-19 14:18:11 -0700271 UpdateTimeRestrictionsPolicyImpl update_time_restrictions_policy;
272 InteractiveUpdatePolicyImpl interactive_update_policy;
273
274 vector<Policy const*> policies_to_consult = {
275 // Check to see if an interactive update has been requested.
276 &interactive_update_policy,
277
278 // Do not apply or download an update if we are inside one of the
279 // restricted times.
280 &update_time_restrictions_policy,
281 };
282
283 EvalStatus status = ConsultPolicies(policies_to_consult,
284 &Policy::UpdateCanBeApplied,
285 ec,
286 state,
287 error,
288 result,
289 install_plan);
290 if (EvalStatus::kContinue != status) {
291 return status;
292 } else {
293 // The update can proceed.
294 LOG(INFO) << "Allowing update to be applied.";
295 *result = ErrorCode::kSuccess;
296 return EvalStatus::kSucceeded;
297 }
Aaron Wood23bd3392017-10-06 14:48:25 -0700298}
299
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700300EvalStatus ChromeOSPolicy::UpdateCanStart(
301 EvaluationContext* ec,
302 State* state,
303 string* error,
Gilad Arnold42f253b2014-06-25 12:39:17 -0700304 UpdateDownloadParams* result,
Gilad Arnoldd78caf92014-09-24 09:28:14 -0700305 const UpdateState update_state) const {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700306 // Set the default return values. Note that we set persisted values (backoff,
307 // scattering) to the same values presented in the update state. The reason is
308 // that preemptive returns, such as the case where an update check is due,
309 // should not clear off the said values; rather, it is the deliberate
310 // inference of new values that should cause them to be reset.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700311 result->update_can_start = false;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700312 result->cannot_start_reason = UpdateCannotStartReason::kUndefined;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700313 result->download_url_idx = -1;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700314 result->download_url_allowed = true;
315 result->download_url_num_errors = 0;
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700316 result->p2p_downloading_allowed = false;
317 result->p2p_sharing_allowed = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700318 result->do_increment_failures = false;
319 result->backoff_expiry = update_state.backoff_expiry;
320 result->scatter_wait_period = update_state.scatter_wait_period;
321 result->scatter_check_threshold = update_state.scatter_check_threshold;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700322
323 // Make sure that we're not due for an update check.
324 UpdateCheckParams check_result;
325 EvalStatus check_status = UpdateCheckAllowed(ec, state, error, &check_result);
326 if (check_status == EvalStatus::kFailed)
327 return EvalStatus::kFailed;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700328 bool is_check_due = (check_status == EvalStatus::kSucceeded &&
329 check_result.updates_enabled == true);
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700330
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700331 // Check whether backoff applies, and if not then which URL can be used for
332 // downloading. These require scanning the download error log, and so they are
333 // done together.
334 UpdateBackoffAndDownloadUrlResult backoff_url_result;
335 EvalStatus backoff_url_status = UpdateBackoffAndDownloadUrl(
336 ec, state, error, &backoff_url_result, update_state);
Gilad Arnold14a9e702014-10-08 08:09:09 -0700337 if (backoff_url_status == EvalStatus::kFailed)
338 return EvalStatus::kFailed;
339 result->download_url_idx = backoff_url_result.url_idx;
340 result->download_url_num_errors = backoff_url_result.url_num_errors;
341 result->do_increment_failures = backoff_url_result.do_increment_failures;
342 result->backoff_expiry = backoff_url_result.backoff_expiry;
343 bool is_backoff_active =
344 (backoff_url_status == EvalStatus::kAskMeAgainLater) ||
345 !backoff_url_result.backoff_expiry.is_null();
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700346
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700347 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold14a9e702014-10-08 08:09:09 -0700348 bool is_scattering_active = false;
349 EvalStatus scattering_status = EvalStatus::kSucceeded;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700350
Amin Hassani4b717432019-01-14 16:24:20 -0800351 const bool* device_policy_is_loaded_p =
352 ec->GetValue(dp_provider->var_device_policy_is_loaded());
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700353 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700354 // Check whether scattering applies to this update attempt. We should not be
355 // scattering if this is an interactive update check, or if OOBE is enabled
356 // but not completed.
357 //
358 // Note: current code further suppresses scattering if a "deadline"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700359 // attribute is found in the Omaha response. However, it appears that the
Gilad Arnold76a11f62014-05-20 09:02:12 -0700360 // presence of this attribute is merely indicative of an OOBE update, during
361 // which we suppress scattering anyway.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700362 bool is_scattering_applicable = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700363 result->scatter_wait_period = kZeroInterval;
364 result->scatter_check_threshold = 0;
Amin Hassanied37d682018-04-06 13:22:00 -0700365 if (!update_state.interactive) {
Amin Hassani4b717432019-01-14 16:24:20 -0800366 const bool* is_oobe_enabled_p =
367 ec->GetValue(state->config_provider()->var_is_oobe_enabled());
Gilad Arnold76a11f62014-05-20 09:02:12 -0700368 if (is_oobe_enabled_p && !(*is_oobe_enabled_p)) {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700369 is_scattering_applicable = true;
Gilad Arnold76a11f62014-05-20 09:02:12 -0700370 } else {
Amin Hassani4b717432019-01-14 16:24:20 -0800371 const bool* is_oobe_complete_p =
372 ec->GetValue(state->system_provider()->var_is_oobe_complete());
Gilad Arnold14a9e702014-10-08 08:09:09 -0700373 is_scattering_applicable = (is_oobe_complete_p && *is_oobe_complete_p);
Gilad Arnold76a11f62014-05-20 09:02:12 -0700374 }
375 }
376
377 // Compute scattering values.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700378 if (is_scattering_applicable) {
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700379 UpdateScatteringResult scatter_result;
Amin Hassani4b717432019-01-14 16:24:20 -0800380 scattering_status =
381 UpdateScattering(ec, state, error, &scatter_result, update_state);
Gilad Arnold14a9e702014-10-08 08:09:09 -0700382 if (scattering_status == EvalStatus::kFailed) {
383 return EvalStatus::kFailed;
384 } else {
385 result->scatter_wait_period = scatter_result.wait_period;
386 result->scatter_check_threshold = scatter_result.check_threshold;
387 if (scattering_status == EvalStatus::kAskMeAgainLater ||
388 scatter_result.is_scattering)
389 is_scattering_active = true;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700390 }
391 }
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700392 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700393
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700394 // Find out whether P2P is globally enabled.
395 bool p2p_enabled;
396 EvalStatus p2p_enabled_status = P2PEnabled(ec, state, error, &p2p_enabled);
397 if (p2p_enabled_status != EvalStatus::kSucceeded)
398 return EvalStatus::kFailed;
399
400 // Is P2P is enabled, consider allowing it for downloading and/or sharing.
401 if (p2p_enabled) {
402 // Sharing via P2P is allowed if not disabled by Omaha.
403 if (update_state.p2p_sharing_disabled) {
404 LOG(INFO) << "Blocked P2P sharing because it is disabled by Omaha.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700405 } else {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700406 result->p2p_sharing_allowed = true;
Gilad Arnoldef8d0872014-10-03 14:14:06 -0700407 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700408
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700409 // Downloading via P2P is allowed if not disabled by Omaha, an update is not
410 // interactive, and other limits haven't been reached.
411 if (update_state.p2p_downloading_disabled) {
412 LOG(INFO) << "Blocked P2P downloading because it is disabled by Omaha.";
Amin Hassanied37d682018-04-06 13:22:00 -0700413 } else if (update_state.interactive) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700414 LOG(INFO) << "Blocked P2P downloading because update is interactive.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700415 } else if (update_state.p2p_num_attempts >= kMaxP2PAttempts) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700416 LOG(INFO) << "Blocked P2P downloading as it was attempted too many "
417 "times.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700418 } else if (!update_state.p2p_first_attempted.is_null() &&
419 ec->IsWallclockTimeGreaterThan(
420 update_state.p2p_first_attempted +
421 TimeDelta::FromSeconds(kMaxP2PAttemptsPeriodInSeconds))) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700422 LOG(INFO) << "Blocked P2P downloading as its usage timespan exceeds "
423 "limit.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700424 } else {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700425 // P2P download is allowed; if backoff or scattering are active, be sure
426 // to suppress them, yet prevent any download URL from being used.
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700427 result->p2p_downloading_allowed = true;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700428 if (is_backoff_active || is_scattering_active) {
429 is_backoff_active = is_scattering_active = false;
430 result->download_url_allowed = false;
431 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700432 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700433 }
434
Gilad Arnold14a9e702014-10-08 08:09:09 -0700435 // Check for various deterrents.
436 if (is_check_due) {
437 result->cannot_start_reason = UpdateCannotStartReason::kCheckDue;
438 return EvalStatus::kSucceeded;
439 }
440 if (is_backoff_active) {
441 result->cannot_start_reason = UpdateCannotStartReason::kBackoff;
442 return backoff_url_status;
443 }
444 if (is_scattering_active) {
445 result->cannot_start_reason = UpdateCannotStartReason::kScattering;
446 return scattering_status;
447 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700448 if (result->download_url_idx < 0 && !result->p2p_downloading_allowed) {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700449 result->cannot_start_reason = UpdateCannotStartReason::kCannotDownload;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700450 return EvalStatus::kSucceeded;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700451 }
452
Gilad Arnold14a9e702014-10-08 08:09:09 -0700453 // Update is good to go.
454 result->update_can_start = true;
Gilad Arnoldaf2f6ae2014-04-28 14:14:52 -0700455 return EvalStatus::kSucceeded;
456}
457
Gilad Arnolda8262e22014-06-02 13:54:27 -0700458// TODO(garnold) Logic in this method is based on
459// ConnectionManager::IsUpdateAllowedOver(); be sure to deprecate the latter.
460//
461// TODO(garnold) The current logic generally treats the list of allowed
462// connections coming from the device policy as a whitelist, meaning that it
463// can only be used for enabling connections, but not disable them. Further,
464// certain connection types (like Bluetooth) cannot be enabled even by policy.
465// In effect, the only thing that device policy can change is to enable
466// updates over a cellular network (disabled by default). We may want to
467// revisit this semantics, allowing greater flexibility in defining specific
468// permissions over all types of networks.
Amin Hassani4b717432019-01-14 16:24:20 -0800469EvalStatus ChromeOSPolicy::UpdateDownloadAllowed(EvaluationContext* ec,
470 State* state,
471 string* error,
472 bool* result) const {
Gilad Arnolda8262e22014-06-02 13:54:27 -0700473 // Get the current connection type.
474 ShillProvider* const shill_provider = state->shill_provider();
Amin Hassani4b717432019-01-14 16:24:20 -0800475 const ConnectionType* conn_type_p =
476 ec->GetValue(shill_provider->var_conn_type());
Gilad Arnolda8262e22014-06-02 13:54:27 -0700477 POLICY_CHECK_VALUE_AND_FAIL(conn_type_p, error);
478 ConnectionType conn_type = *conn_type_p;
479
480 // If we're tethering, treat it as a cellular connection.
481 if (conn_type != ConnectionType::kCellular) {
Amin Hassani4b717432019-01-14 16:24:20 -0800482 const ConnectionTethering* conn_tethering_p =
483 ec->GetValue(shill_provider->var_conn_tethering());
Gilad Arnolda8262e22014-06-02 13:54:27 -0700484 POLICY_CHECK_VALUE_AND_FAIL(conn_tethering_p, error);
485 if (*conn_tethering_p == ConnectionTethering::kConfirmed)
486 conn_type = ConnectionType::kCellular;
487 }
488
489 // By default, we allow updates for all connection types, with exceptions as
490 // noted below. This also determines whether a device policy can override the
491 // default.
492 *result = true;
493 bool device_policy_can_override = false;
494 switch (conn_type) {
495 case ConnectionType::kBluetooth:
496 *result = false;
497 break;
498
499 case ConnectionType::kCellular:
500 *result = false;
501 device_policy_can_override = true;
502 break;
503
504 case ConnectionType::kUnknown:
505 if (error)
506 *error = "Unknown connection type";
507 return EvalStatus::kFailed;
508
509 default:
510 break; // Nothing to do.
511 }
512
513 // If update is allowed, we're done.
514 if (*result)
515 return EvalStatus::kSucceeded;
516
517 // Check whether the device policy specifically allows this connection.
Gilad Arnolda8262e22014-06-02 13:54:27 -0700518 if (device_policy_can_override) {
519 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Amin Hassani4b717432019-01-14 16:24:20 -0800520 const bool* device_policy_is_loaded_p =
521 ec->GetValue(dp_provider->var_device_policy_is_loaded());
Gilad Arnolda8262e22014-06-02 13:54:27 -0700522 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Amin Hassani4b717432019-01-14 16:24:20 -0800523 const set<ConnectionType>* allowed_conn_types_p =
524 ec->GetValue(dp_provider->var_allowed_connection_types_for_update());
Gilad Arnolda8262e22014-06-02 13:54:27 -0700525 if (allowed_conn_types_p) {
526 if (allowed_conn_types_p->count(conn_type)) {
527 *result = true;
528 return EvalStatus::kSucceeded;
529 }
Gilad Arnold28d6be62014-06-30 14:04:04 -0700530 } else if (conn_type == ConnectionType::kCellular) {
531 // Local user settings can allow updates over cellular iff a policy was
532 // loaded but no allowed connections were specified in it.
Amin Hassani4b717432019-01-14 16:24:20 -0800533 const bool* update_over_cellular_allowed_p =
534 ec->GetValue(state->updater_provider()->var_cellular_enabled());
Gilad Arnold28d6be62014-06-30 14:04:04 -0700535 if (update_over_cellular_allowed_p && *update_over_cellular_allowed_p)
536 *result = true;
Gilad Arnolda8262e22014-06-02 13:54:27 -0700537 }
538 }
539 }
540
Gilad Arnold28d6be62014-06-30 14:04:04 -0700541 return (*result ? EvalStatus::kSucceeded : EvalStatus::kAskMeAgainLater);
Gilad Arnolda8262e22014-06-02 13:54:27 -0700542}
543
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700544EvalStatus ChromeOSPolicy::P2PEnabled(EvaluationContext* ec,
545 State* state,
Alex Deymo39910dc2015-11-09 17:04:30 -0800546 string* error,
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700547 bool* result) const {
548 bool enabled = false;
549
550 // Determine whether use of P2P is allowed by policy. Even if P2P is not
551 // explicitly allowed, we allow it if the device is enterprise enrolled (that
552 // is, missing or empty owner string).
553 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Amin Hassani4b717432019-01-14 16:24:20 -0800554 const bool* device_policy_is_loaded_p =
555 ec->GetValue(dp_provider->var_device_policy_is_loaded());
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700556 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Amin Hassani4b717432019-01-14 16:24:20 -0800557 const bool* policy_au_p2p_enabled_p =
558 ec->GetValue(dp_provider->var_au_p2p_enabled());
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700559 if (policy_au_p2p_enabled_p) {
560 enabled = *policy_au_p2p_enabled_p;
561 } else {
562 const string* policy_owner_p = ec->GetValue(dp_provider->var_owner());
563 if (!policy_owner_p || policy_owner_p->empty())
564 enabled = true;
565 }
566 }
567
568 // Enable P2P, if so mandated by the updater configuration. This is additive
569 // to whether or not P2P is enabled by device policy.
570 if (!enabled) {
Amin Hassani4b717432019-01-14 16:24:20 -0800571 const bool* updater_p2p_enabled_p =
572 ec->GetValue(state->updater_provider()->var_p2p_enabled());
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700573 enabled = updater_p2p_enabled_p && *updater_p2p_enabled_p;
574 }
575
576 *result = enabled;
577 return EvalStatus::kSucceeded;
578}
579
580EvalStatus ChromeOSPolicy::P2PEnabledChanged(EvaluationContext* ec,
581 State* state,
Alex Deymo39910dc2015-11-09 17:04:30 -0800582 string* error,
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700583 bool* result,
584 bool prev_result) const {
585 EvalStatus status = P2PEnabled(ec, state, error, result);
586 if (status == EvalStatus::kSucceeded && *result == prev_result)
587 return EvalStatus::kAskMeAgainLater;
588 return status;
589}
590
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700591EvalStatus ChromeOSPolicy::UpdateBackoffAndDownloadUrl(
Amin Hassani4b717432019-01-14 16:24:20 -0800592 EvaluationContext* ec,
593 State* state,
594 string* error,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700595 UpdateBackoffAndDownloadUrlResult* result,
596 const UpdateState& update_state) const {
597 // Sanity checks.
598 DCHECK_GE(update_state.download_errors_max, 0);
599
600 // Set default result values.
601 result->do_increment_failures = false;
602 result->backoff_expiry = update_state.backoff_expiry;
603 result->url_idx = -1;
604 result->url_num_errors = 0;
605
Amin Hassani4b717432019-01-14 16:24:20 -0800606 const bool* is_official_build_p =
607 ec->GetValue(state->system_provider()->var_is_official_build());
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700608 bool is_official_build = (is_official_build_p ? *is_official_build_p : true);
609
610 // Check whether backoff is enabled.
611 bool may_backoff = false;
612 if (update_state.is_backoff_disabled) {
613 LOG(INFO) << "Backoff disabled by Omaha.";
Amin Hassanied37d682018-04-06 13:22:00 -0700614 } else if (update_state.interactive) {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700615 LOG(INFO) << "No backoff for interactive updates.";
616 } else if (update_state.is_delta_payload) {
617 LOG(INFO) << "No backoff for delta payloads.";
618 } else if (!is_official_build) {
619 LOG(INFO) << "No backoff for unofficial builds.";
620 } else {
621 may_backoff = true;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700622 }
623
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700624 // If previous backoff still in effect, block.
625 if (may_backoff && !update_state.backoff_expiry.is_null() &&
626 !ec->IsWallclockTimeGreaterThan(update_state.backoff_expiry)) {
627 LOG(INFO) << "Previous backoff has not expired, waiting.";
628 return EvalStatus::kAskMeAgainLater;
629 }
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700630
631 // Determine whether HTTP downloads are forbidden by policy. This only
632 // applies to official system builds; otherwise, HTTP is always enabled.
633 bool http_allowed = true;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700634 if (is_official_build) {
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700635 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Amin Hassani4b717432019-01-14 16:24:20 -0800636 const bool* device_policy_is_loaded_p =
637 ec->GetValue(dp_provider->var_device_policy_is_loaded());
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700638 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Amin Hassani4b717432019-01-14 16:24:20 -0800639 const bool* policy_http_downloads_enabled_p =
640 ec->GetValue(dp_provider->var_http_downloads_enabled());
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700641 http_allowed = (!policy_http_downloads_enabled_p ||
642 *policy_http_downloads_enabled_p);
643 }
644 }
645
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700646 int url_idx = update_state.last_download_url_idx;
647 if (url_idx < 0)
648 url_idx = -1;
649 bool do_advance_url = false;
650 bool is_failure_occurred = false;
651 Time err_time;
652
653 // Scan the relevant part of the download error log, tracking which URLs are
654 // being used, and accounting the number of errors for each URL. Note that
655 // this process may not traverse all errors provided, as it may decide to bail
656 // out midway depending on the particular errors exhibited, the number of
657 // failures allowed, etc. When this ends, |url_idx| will point to the last URL
658 // used (-1 if starting fresh), |do_advance_url| will determine whether the
659 // URL needs to be advanced, and |err_time| the point in time when the last
660 // reported error occurred. Additionally, if the error log indicates that an
661 // update attempt has failed (abnormal), then |is_failure_occurred| will be
662 // set to true.
663 const int num_urls = update_state.download_urls.size();
664 int prev_url_idx = -1;
665 int url_num_errors = update_state.last_download_url_num_errors;
666 Time prev_err_time;
667 bool is_first = true;
668 for (const auto& err_tuple : update_state.download_errors) {
669 // Do some sanity checks.
670 int used_url_idx = get<0>(err_tuple);
671 if (is_first && url_idx >= 0 && used_url_idx != url_idx) {
672 LOG(WARNING) << "First URL in error log (" << used_url_idx
673 << ") not as expected (" << url_idx << ")";
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700674 }
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700675 is_first = false;
676 url_idx = used_url_idx;
677 if (url_idx < 0 || url_idx >= num_urls) {
678 LOG(ERROR) << "Download error log contains an invalid URL index ("
679 << url_idx << ")";
680 return EvalStatus::kFailed;
681 }
682 err_time = get<2>(err_tuple);
683 if (!(prev_err_time.is_null() || err_time >= prev_err_time)) {
684 // TODO(garnold) Monotonicity cannot really be assumed when dealing with
685 // wallclock-based timestamps. However, we're making a simplifying
686 // assumption so as to keep the policy implementation straightforward, for
687 // now. In general, we should convert all timestamp handling in the
688 // UpdateManager to use monotonic time (instead of wallclock), including
689 // the computation of various expiration times (backoff, scattering, etc).
690 // The client will do whatever conversions necessary when
691 // persisting/retrieving these values across reboots. See chromium:408794.
692 LOG(ERROR) << "Download error timestamps not monotonically increasing.";
693 return EvalStatus::kFailed;
694 }
695 prev_err_time = err_time;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700696
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700697 // Ignore errors that happened before the last known failed attempt.
698 if (!update_state.failures_last_updated.is_null() &&
699 err_time <= update_state.failures_last_updated)
700 continue;
701
702 if (prev_url_idx >= 0) {
703 if (url_idx < prev_url_idx) {
704 LOG(ERROR) << "The URLs in the download error log have wrapped around ("
705 << prev_url_idx << "->" << url_idx
706 << "). This should not have happened and means that there's "
707 "a bug. To be conservative, we record a failed attempt "
708 "(invalidating the rest of the error log) and resume "
709 "download from the first usable URL.";
710 url_idx = -1;
711 is_failure_occurred = true;
712 break;
713 }
714
715 if (url_idx > prev_url_idx) {
716 url_num_errors = 0;
717 do_advance_url = false;
718 }
719 }
720
721 if (HandleErrorCode(get<1>(err_tuple), &url_num_errors) ||
722 url_num_errors > update_state.download_errors_max)
723 do_advance_url = true;
724
725 prev_url_idx = url_idx;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700726 }
727
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700728 // If required, advance to the next usable URL. If the URLs wraparound, we
729 // mark an update attempt failure. Also be sure to set the download error
730 // count to zero.
731 if (url_idx < 0 || do_advance_url) {
732 url_num_errors = 0;
733 int start_url_idx = -1;
734 do {
735 if (++url_idx == num_urls) {
736 url_idx = 0;
737 // We only mark failure if an actual advancing of a URL was required.
738 if (do_advance_url)
739 is_failure_occurred = true;
740 }
741
742 if (start_url_idx < 0)
743 start_url_idx = url_idx;
744 else if (url_idx == start_url_idx)
745 url_idx = -1; // No usable URL.
746 } while (url_idx >= 0 &&
747 !IsUrlUsable(update_state.download_urls[url_idx], http_allowed));
748 }
749
750 // If we have a download URL but a failure was observed, compute a new backoff
751 // expiry (if allowed). The backoff period is generally 2 ^ (num_failures - 1)
752 // days, bounded by the size of int and kAttemptBackoffMaxIntervalInDays, and
753 // fuzzed by kAttemptBackoffFuzzInHours hours. Backoff expiry is computed from
754 // the latest recorded time of error.
755 Time backoff_expiry;
756 if (url_idx >= 0 && is_failure_occurred && may_backoff) {
757 CHECK(!err_time.is_null())
758 << "We must have an error timestamp if a failure occurred!";
759 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
760 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
761 PRNG prng(*seed);
Amin Hassani4b717432019-01-14 16:24:20 -0800762 int exp =
763 min(update_state.num_failures, static_cast<int>(sizeof(int)) * 8 - 2);
Amin Hassani186ff6a2018-02-27 11:06:03 -0800764 TimeDelta backoff_interval = TimeDelta::FromDays(min(
765 1 << exp,
766 kNextUpdateCheckPolicyConstants.attempt_backoff_max_interval_in_days));
767 TimeDelta backoff_fuzz = TimeDelta::FromHours(
768 kNextUpdateCheckPolicyConstants.attempt_backoff_fuzz_in_hours);
769 TimeDelta wait_period = NextUpdateCheckTimePolicyImpl::FuzzedInterval(
770 &prng, backoff_interval.InSeconds(), backoff_fuzz.InSeconds());
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700771 backoff_expiry = err_time + wait_period;
772
773 // If the newly computed backoff already expired, nullify it.
774 if (ec->IsWallclockTimeGreaterThan(backoff_expiry))
775 backoff_expiry = Time();
776 }
777
778 result->do_increment_failures = is_failure_occurred;
779 result->backoff_expiry = backoff_expiry;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700780 result->url_idx = url_idx;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700781 result->url_num_errors = url_num_errors;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700782 return EvalStatus::kSucceeded;
783}
784
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700785EvalStatus ChromeOSPolicy::UpdateScattering(
786 EvaluationContext* ec,
787 State* state,
788 string* error,
789 UpdateScatteringResult* result,
790 const UpdateState& update_state) const {
791 // Preconditions. These stem from the postconditions and usage contract.
792 DCHECK(update_state.scatter_wait_period >= kZeroInterval);
793 DCHECK_GE(update_state.scatter_check_threshold, 0);
794
795 // Set default result values.
796 result->is_scattering = false;
797 result->wait_period = kZeroInterval;
798 result->check_threshold = 0;
799
800 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
801
802 // Ensure that a device policy is loaded.
Amin Hassani4b717432019-01-14 16:24:20 -0800803 const bool* device_policy_is_loaded_p =
804 ec->GetValue(dp_provider->var_device_policy_is_loaded());
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700805 if (!(device_policy_is_loaded_p && *device_policy_is_loaded_p))
806 return EvalStatus::kSucceeded;
807
808 // Is scattering enabled by policy?
Amin Hassani4b717432019-01-14 16:24:20 -0800809 const TimeDelta* scatter_factor_p =
810 ec->GetValue(dp_provider->var_scatter_factor());
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700811 if (!scatter_factor_p || *scatter_factor_p == kZeroInterval)
812 return EvalStatus::kSucceeded;
813
814 // Obtain a pseudo-random number generator.
815 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
816 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
817 PRNG prng(*seed);
818
819 // Step 1: Maintain the scattering wait period.
820 //
821 // If no wait period was previously determined, or it no longer fits in the
822 // scatter factor, then generate a new one. Otherwise, keep the one we have.
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700823 TimeDelta wait_period = update_state.scatter_wait_period;
824 if (wait_period == kZeroInterval || wait_period > *scatter_factor_p) {
825 wait_period = TimeDelta::FromSeconds(
826 prng.RandMinMax(1, scatter_factor_p->InSeconds()));
827 }
828
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700829 // If we surpassed the wait period or the max scatter period associated with
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700830 // the update, then no wait is needed.
831 Time wait_expires = (update_state.first_seen +
832 min(wait_period, update_state.scatter_wait_period_max));
Gilad Arnolda65fced2014-07-23 09:01:31 -0700833 if (ec->IsWallclockTimeGreaterThan(wait_expires))
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700834 wait_period = kZeroInterval;
835
836 // Step 2: Maintain the update check threshold count.
837 //
838 // If an update check threshold is not specified then generate a new
839 // one.
840 int check_threshold = update_state.scatter_check_threshold;
841 if (check_threshold == 0) {
Amin Hassani4b717432019-01-14 16:24:20 -0800842 check_threshold = prng.RandMinMax(update_state.scatter_check_threshold_min,
843 update_state.scatter_check_threshold_max);
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700844 }
845
846 // If the update check threshold is not within allowed range then nullify it.
847 // TODO(garnold) This is compliant with current logic found in
848 // OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied(). We may want
849 // to change it so that it behaves similarly to the wait period case, namely
850 // if the current value exceeds the maximum, we set a new one within range.
851 if (check_threshold > update_state.scatter_check_threshold_max)
852 check_threshold = 0;
853
854 // If the update check threshold is non-zero and satisfied, then nullify it.
855 if (check_threshold > 0 && update_state.num_checks >= check_threshold)
856 check_threshold = 0;
857
858 bool is_scattering = (wait_period != kZeroInterval || check_threshold);
859 EvalStatus ret = EvalStatus::kSucceeded;
860 if (is_scattering && wait_period == update_state.scatter_wait_period &&
861 check_threshold == update_state.scatter_check_threshold)
862 ret = EvalStatus::kAskMeAgainLater;
863 result->is_scattering = is_scattering;
864 result->wait_period = wait_period;
865 result->check_threshold = check_threshold;
866 return ret;
867}
868
Alex Deymo63784a52014-05-28 10:46:14 -0700869} // namespace chromeos_update_manager