blob: dd6cc8d64bd56f958f4c2f2c508e7f64b8a1b0a0 [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>
Amin Hassanifbb600f2019-08-14 19:52:30 -070020#include <memory>
Gilad Arnold0adbc942014-05-12 10:35:43 -070021#include <set>
Alex Deymoc705cc82014-02-19 11:15:00 -080022#include <string>
Amin Hassani186ff6a2018-02-27 11:06:03 -080023#include <vector>
Alex Deymoc705cc82014-02-19 11:15:00 -080024
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070025#include <base/logging.h>
Gilad Arnoldb3b05442014-05-30 14:25:05 -070026#include <base/strings/string_util.h>
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070027#include <base/time/time.h>
28
Alex Deymo39910dc2015-11-09 17:04:30 -080029#include "update_engine/common/error_code.h"
Alex Deymoe88e9fe2016-02-03 16:38:00 -080030#include "update_engine/common/error_code_utils.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080031#include "update_engine/common/utils.h"
Alex Deymo63784a52014-05-28 10:46:14 -070032#include "update_engine/update_manager/device_policy_provider.h"
Amin Hassani186ff6a2018-02-27 11:06:03 -080033#include "update_engine/update_manager/enough_slots_ab_updates_policy_impl.h"
34#include "update_engine/update_manager/enterprise_device_policy_impl.h"
35#include "update_engine/update_manager/interactive_update_policy_impl.h"
36#include "update_engine/update_manager/official_build_check_policy_impl.h"
37#include "update_engine/update_manager/out_of_box_experience_policy_impl.h"
Alex Deymo63784a52014-05-28 10:46:14 -070038#include "update_engine/update_manager/policy_utils.h"
39#include "update_engine/update_manager/shill_provider.h"
Adolfo Victoria94ffe132018-06-28 16:14:56 -070040#include "update_engine/update_manager/update_time_restrictions_policy_impl.h"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070041
Alex Deymo0d11c602014-04-23 20:12:20 -070042using base::Time;
43using base::TimeDelta;
Sen Jiang255e22b2016-05-20 16:15:29 -070044using chromeos_update_engine::ConnectionTethering;
45using chromeos_update_engine::ConnectionType;
Gilad Arnoldb3b05442014-05-30 14:25:05 -070046using chromeos_update_engine::ErrorCode;
Aaron Wood23bd3392017-10-06 14:48:25 -070047using chromeos_update_engine::InstallPlan;
Gilad Arnolddc4bb262014-07-23 10:45:19 -070048using std::get;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070049using std::min;
Gilad Arnold0adbc942014-05-12 10:35:43 -070050using std::set;
Alex Deymoc705cc82014-02-19 11:15:00 -080051using std::string;
Amin Hassanifbb600f2019-08-14 19:52:30 -070052using std::unique_ptr;
Amin Hassani186ff6a2018-02-27 11:06:03 -080053using std::vector;
Alex Deymoc705cc82014-02-19 11:15:00 -080054
Gilad Arnoldb3b05442014-05-30 14:25:05 -070055namespace {
56
Gilad Arnolddc4bb262014-07-23 10:45:19 -070057// Examines |err_code| and decides whether the URL index needs to be advanced,
58// the error count for the URL incremented, or none of the above. In the first
59// case, returns true; in the second case, increments |*url_num_error_p| and
60// returns false; otherwise just returns false.
Gilad Arnoldb3b05442014-05-30 14:25:05 -070061//
62// TODO(garnold) Adapted from PayloadState::UpdateFailed() (to be retired).
Gilad Arnolddc4bb262014-07-23 10:45:19 -070063bool HandleErrorCode(ErrorCode err_code, int* url_num_error_p) {
Gilad Arnoldb3b05442014-05-30 14:25:05 -070064 err_code = chromeos_update_engine::utils::GetBaseErrorCode(err_code);
65 switch (err_code) {
66 // Errors which are good indicators of a problem with a particular URL or
67 // the protocol used in the URL or entities in the communication channel
68 // (e.g. proxies). We should try the next available URL in the next update
69 // check to quickly recover from these errors.
70 case ErrorCode::kPayloadHashMismatchError:
71 case ErrorCode::kPayloadSizeMismatchError:
72 case ErrorCode::kDownloadPayloadVerificationError:
73 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
74 case ErrorCode::kSignedDeltaPayloadExpectedError:
75 case ErrorCode::kDownloadInvalidMetadataMagicString:
76 case ErrorCode::kDownloadSignatureMissingInManifest:
77 case ErrorCode::kDownloadManifestParseError:
78 case ErrorCode::kDownloadMetadataSignatureError:
79 case ErrorCode::kDownloadMetadataSignatureVerificationError:
80 case ErrorCode::kDownloadMetadataSignatureMismatch:
81 case ErrorCode::kDownloadOperationHashVerificationError:
82 case ErrorCode::kDownloadOperationExecutionError:
83 case ErrorCode::kDownloadOperationHashMismatch:
84 case ErrorCode::kDownloadInvalidMetadataSize:
85 case ErrorCode::kDownloadInvalidMetadataSignature:
86 case ErrorCode::kDownloadOperationHashMissingError:
87 case ErrorCode::kDownloadMetadataSignatureMissingError:
88 case ErrorCode::kPayloadMismatchedType:
89 case ErrorCode::kUnsupportedMajorPayloadVersion:
90 case ErrorCode::kUnsupportedMinorPayloadVersion:
Sen Jiang8e768e92017-06-28 17:13:19 -070091 case ErrorCode::kPayloadTimestampError:
Sen Jiang57f91802017-11-14 17:42:13 -080092 case ErrorCode::kVerityCalculationError:
Gilad Arnoldb3b05442014-05-30 14:25:05 -070093 LOG(INFO) << "Advancing download URL due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -080094 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -070095 << " (" << static_cast<int>(err_code) << ")";
Gilad Arnoldb3b05442014-05-30 14:25:05 -070096 return true;
97
98 // Errors which seem to be just transient network/communication related
99 // failures and do not indicate any inherent problem with the URL itself.
100 // So, we should keep the current URL but just increment the
101 // failure count to give it more chances. This way, while we maximize our
102 // chances of downloading from the URLs that appear earlier in the response
103 // (because download from a local server URL that appears earlier in a
104 // response is preferable than downloading from the next URL which could be
Alex Vakulenko072359c2014-07-18 11:41:07 -0700105 // an Internet URL and thus could be more expensive).
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700106 case ErrorCode::kError:
107 case ErrorCode::kDownloadTransferError:
108 case ErrorCode::kDownloadWriteError:
109 case ErrorCode::kDownloadStateInitializationError:
Gilad Arnold684219d2014-07-07 14:54:57 -0700110 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700111 LOG(INFO) << "Incrementing URL failure count due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800112 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700113 << " (" << static_cast<int>(err_code) << ")";
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700114 *url_num_error_p += 1;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700115 return false;
116
117 // Errors which are not specific to a URL and hence shouldn't result in
118 // the URL being penalized. This can happen in two cases:
119 // 1. We haven't started downloading anything: These errors don't cost us
120 // anything in terms of actual payload bytes, so we should just do the
121 // regular retries at the next update check.
122 // 2. We have successfully downloaded the payload: In this case, the
123 // payload attempt number would have been incremented and would take care
Alex Vakulenko072359c2014-07-18 11:41:07 -0700124 // of the back-off at the next update check.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700125 // In either case, there's no need to update URL index or failure count.
126 case ErrorCode::kOmahaRequestError:
127 case ErrorCode::kOmahaResponseHandlerError:
128 case ErrorCode::kPostinstallRunnerError:
129 case ErrorCode::kFilesystemCopierError:
130 case ErrorCode::kInstallDeviceOpenError:
131 case ErrorCode::kKernelDeviceOpenError:
132 case ErrorCode::kDownloadNewPartitionInfoError:
133 case ErrorCode::kNewRootfsVerificationError:
134 case ErrorCode::kNewKernelVerificationError:
135 case ErrorCode::kPostinstallBootedFromFirmwareB:
136 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
137 case ErrorCode::kOmahaRequestEmptyResponseError:
138 case ErrorCode::kOmahaRequestXMLParseError:
139 case ErrorCode::kOmahaResponseInvalid:
140 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
141 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
Kevin Cernekee2494e282016-03-29 18:03:53 -0700142 case ErrorCode::kNonCriticalUpdateInOOBE:
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700143 case ErrorCode::kOmahaUpdateDeferredForBackoff:
144 case ErrorCode::kPostinstallPowerwashError:
145 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400146 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700147 case ErrorCode::kFilesystemVerifierError:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800148 case ErrorCode::kUserCanceled:
Weidong Guo421ff332017-04-17 10:08:38 -0700149 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
Sen Jiangfe522822017-10-31 15:14:11 -0700150 case ErrorCode::kUpdatedButNotActive:
Sen Jiang89e24c12018-03-22 18:05:44 -0700151 case ErrorCode::kNoUpdate:
Marton Hunyady199152d2018-05-07 19:08:48 +0200152 case ErrorCode::kRollbackNotPossible:
Amin Hassani80f4d4c2018-05-16 13:34:00 -0700153 case ErrorCode::kFirstActiveOmahaPingSentPersistenceError:
Amin Hassanid3d84212019-08-17 00:27:44 -0700154 case ErrorCode::kInternalLibCurlError:
155 case ErrorCode::kUnresolvedHostError:
156 case ErrorCode::kUnresolvedHostRecovered:
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700157 LOG(INFO) << "Not changing URL index or failure count due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800158 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700159 << " (" << static_cast<int>(err_code) << ")";
160 return false;
161
Amin Hassani4b717432019-01-14 16:24:20 -0800162 case ErrorCode::kSuccess: // success code
163 case ErrorCode::kUmaReportedMax: // not an error code
164 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
165 case ErrorCode::kDevModeFlag: // not an error code
166 case ErrorCode::kResumedFlag: // not an error code
167 case ErrorCode::kTestImageFlag: // not an error code
168 case ErrorCode::kTestOmahaUrlFlag: // not an error code
169 case ErrorCode::kSpecialFlags: // not an error code
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700170 // These shouldn't happen. Enumerating these explicitly here so that we
171 // can let the compiler warn about new error codes that are added to
172 // action_processor.h but not added here.
173 LOG(WARNING) << "Unexpected error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800174 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700175 << " (" << static_cast<int>(err_code) << ")";
Amin Hassani4b717432019-01-14 16:24:20 -0800176 // Note: Not adding a default here so as to let the compiler warn us of
177 // any new enums that were added in the .h but not listed in this switch.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700178 }
179 return false;
180}
181
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700182// Checks whether |url| can be used under given download restrictions.
183bool IsUrlUsable(const string& url, bool http_allowed) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800184 return http_allowed ||
Amin Hassani4b717432019-01-14 16:24:20 -0800185 !base::StartsWith(
186 url, "http://", base::CompareCase::INSENSITIVE_ASCII);
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700187}
188
189} // namespace
190
Alex Deymo63784a52014-05-28 10:46:14 -0700191namespace chromeos_update_manager {
Alex Deymoc705cc82014-02-19 11:15:00 -0800192
Amin Hassanifbb600f2019-08-14 19:52:30 -0700193unique_ptr<Policy> GetSystemPolicy() {
194 return std::make_unique<ChromeOSPolicy>();
195}
196
Amin Hassani186ff6a2018-02-27 11:06:03 -0800197const NextUpdateCheckPolicyConstants
198 ChromeOSPolicy::kNextUpdateCheckPolicyConstants = {
199 .timeout_initial_interval = 7 * 60,
200 .timeout_periodic_interval = 45 * 60,
201 .timeout_max_backoff_interval = 4 * 60 * 60,
202 .timeout_regular_fuzz = 10 * 60,
203 .attempt_backoff_max_interval_in_days = 16,
204 .attempt_backoff_fuzz_in_hours = 12,
205};
Alex Deymo14e7dde2015-10-20 14:46:33 -0700206
Gilad Arnold349ac832014-10-06 14:20:28 -0700207const int ChromeOSPolicy::kMaxP2PAttempts = 10;
208const int ChromeOSPolicy::kMaxP2PAttemptsPeriodInSeconds = 5 * 24 * 60 * 60;
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700209
Amin Hassani4b717432019-01-14 16:24:20 -0800210EvalStatus ChromeOSPolicy::UpdateCheckAllowed(EvaluationContext* ec,
211 State* state,
212 string* error,
213 UpdateCheckParams* result) const {
Gilad Arnold42f253b2014-06-25 12:39:17 -0700214 // Set the default return values.
215 result->updates_enabled = true;
216 result->target_channel.clear();
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700217 result->target_version_prefix.clear();
Marton Hunyadyba51c3f2018-04-25 15:18:10 +0200218 result->rollback_allowed = false;
Marton Hunyady0e0e3542018-02-21 18:51:39 +0100219 result->rollback_allowed_milestones = -1;
Amin Hassanied37d682018-04-06 13:22:00 -0700220 result->interactive = false;
Gilad Arnold42f253b2014-06-25 12:39:17 -0700221
Amin Hassani186ff6a2018-02-27 11:06:03 -0800222 EnoughSlotsAbUpdatesPolicyImpl enough_slots_ab_updates_policy;
223 EnterpriseDevicePolicyImpl enterprise_device_policy;
224 OnlyUpdateOfficialBuildsPolicyImpl only_update_official_builds_policy;
225 InteractiveUpdatePolicyImpl interactive_update_policy;
226 OobePolicyImpl oobe_policy;
227 NextUpdateCheckTimePolicyImpl next_update_check_time_policy(
228 kNextUpdateCheckPolicyConstants);
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700229
Amin Hassani186ff6a2018-02-27 11:06:03 -0800230 vector<Policy const*> policies_to_consult = {
231 // Do not perform any updates if there are not enough slots to do A/B
232 // updates.
233 &enough_slots_ab_updates_policy,
234
235 // Check to see if Enterprise-managed (has DevicePolicy) and/or
236 // Kiosk-mode. If so, then defer to those settings.
237 &enterprise_device_policy,
238
239 // Check to see if an interactive update was requested.
240 &interactive_update_policy,
241
242 // Unofficial builds should not perform periodic update checks.
243 &only_update_official_builds_policy,
244
245 // If OOBE is enabled, wait until it is completed.
246 &oobe_policy,
247
248 // Ensure that periodic update checks are timed properly.
249 &next_update_check_time_policy,
250 };
251
252 // Now that the list of policy implementations, and the order to consult them,
253 // has been setup, consult the policies. If none of the policies make a
254 // definitive decisions about whether or not to check for updates, then allow
255 // the update check to happen.
256 EvalStatus status = ConsultPolicies(policies_to_consult,
257 &Policy::UpdateCheckAllowed,
258 ec,
259 state,
260 error,
261 result);
262 if (EvalStatus::kContinue != status) {
263 return status;
264 } else {
265 // It is time to check for an update.
266 LOG(INFO) << "Allowing update check.";
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700267 return EvalStatus::kSucceeded;
268 }
Alex Deymoc705cc82014-02-19 11:15:00 -0800269}
270
Aaron Wood23bd3392017-10-06 14:48:25 -0700271EvalStatus ChromeOSPolicy::UpdateCanBeApplied(EvaluationContext* ec,
272 State* state,
273 std::string* error,
274 ErrorCode* result,
275 InstallPlan* install_plan) const {
Adolfo Victoria0dbf1f92018-07-19 14:18:11 -0700276 UpdateTimeRestrictionsPolicyImpl update_time_restrictions_policy;
277 InteractiveUpdatePolicyImpl interactive_update_policy;
278
279 vector<Policy const*> policies_to_consult = {
280 // Check to see if an interactive update has been requested.
281 &interactive_update_policy,
282
283 // Do not apply or download an update if we are inside one of the
284 // restricted times.
285 &update_time_restrictions_policy,
286 };
287
288 EvalStatus status = ConsultPolicies(policies_to_consult,
289 &Policy::UpdateCanBeApplied,
290 ec,
291 state,
292 error,
293 result,
294 install_plan);
295 if (EvalStatus::kContinue != status) {
296 return status;
297 } else {
298 // The update can proceed.
299 LOG(INFO) << "Allowing update to be applied.";
300 *result = ErrorCode::kSuccess;
301 return EvalStatus::kSucceeded;
302 }
Aaron Wood23bd3392017-10-06 14:48:25 -0700303}
304
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700305EvalStatus ChromeOSPolicy::UpdateCanStart(
306 EvaluationContext* ec,
307 State* state,
308 string* error,
Gilad Arnold42f253b2014-06-25 12:39:17 -0700309 UpdateDownloadParams* result,
Gilad Arnoldd78caf92014-09-24 09:28:14 -0700310 const UpdateState update_state) const {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700311 // Set the default return values. Note that we set persisted values (backoff,
312 // scattering) to the same values presented in the update state. The reason is
313 // that preemptive returns, such as the case where an update check is due,
314 // should not clear off the said values; rather, it is the deliberate
315 // inference of new values that should cause them to be reset.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700316 result->update_can_start = false;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700317 result->cannot_start_reason = UpdateCannotStartReason::kUndefined;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700318 result->download_url_idx = -1;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700319 result->download_url_allowed = true;
320 result->download_url_num_errors = 0;
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700321 result->p2p_downloading_allowed = false;
322 result->p2p_sharing_allowed = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700323 result->do_increment_failures = false;
324 result->backoff_expiry = update_state.backoff_expiry;
325 result->scatter_wait_period = update_state.scatter_wait_period;
326 result->scatter_check_threshold = update_state.scatter_check_threshold;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700327
328 // Make sure that we're not due for an update check.
329 UpdateCheckParams check_result;
330 EvalStatus check_status = UpdateCheckAllowed(ec, state, error, &check_result);
331 if (check_status == EvalStatus::kFailed)
332 return EvalStatus::kFailed;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700333 bool is_check_due = (check_status == EvalStatus::kSucceeded &&
334 check_result.updates_enabled == true);
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700335
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700336 // Check whether backoff applies, and if not then which URL can be used for
337 // downloading. These require scanning the download error log, and so they are
338 // done together.
339 UpdateBackoffAndDownloadUrlResult backoff_url_result;
340 EvalStatus backoff_url_status = UpdateBackoffAndDownloadUrl(
341 ec, state, error, &backoff_url_result, update_state);
Gilad Arnold14a9e702014-10-08 08:09:09 -0700342 if (backoff_url_status == EvalStatus::kFailed)
343 return EvalStatus::kFailed;
344 result->download_url_idx = backoff_url_result.url_idx;
345 result->download_url_num_errors = backoff_url_result.url_num_errors;
346 result->do_increment_failures = backoff_url_result.do_increment_failures;
347 result->backoff_expiry = backoff_url_result.backoff_expiry;
348 bool is_backoff_active =
349 (backoff_url_status == EvalStatus::kAskMeAgainLater) ||
350 !backoff_url_result.backoff_expiry.is_null();
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700351
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700352 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold14a9e702014-10-08 08:09:09 -0700353 bool is_scattering_active = false;
354 EvalStatus scattering_status = EvalStatus::kSucceeded;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700355
Amin Hassani4b717432019-01-14 16:24:20 -0800356 const bool* device_policy_is_loaded_p =
357 ec->GetValue(dp_provider->var_device_policy_is_loaded());
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700358 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700359 // Check whether scattering applies to this update attempt. We should not be
360 // scattering if this is an interactive update check, or if OOBE is enabled
361 // but not completed.
362 //
363 // Note: current code further suppresses scattering if a "deadline"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700364 // attribute is found in the Omaha response. However, it appears that the
Gilad Arnold76a11f62014-05-20 09:02:12 -0700365 // presence of this attribute is merely indicative of an OOBE update, during
366 // which we suppress scattering anyway.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700367 bool is_scattering_applicable = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700368 result->scatter_wait_period = kZeroInterval;
369 result->scatter_check_threshold = 0;
Amin Hassanied37d682018-04-06 13:22:00 -0700370 if (!update_state.interactive) {
Amin Hassani4b717432019-01-14 16:24:20 -0800371 const bool* is_oobe_enabled_p =
372 ec->GetValue(state->config_provider()->var_is_oobe_enabled());
Gilad Arnold76a11f62014-05-20 09:02:12 -0700373 if (is_oobe_enabled_p && !(*is_oobe_enabled_p)) {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700374 is_scattering_applicable = true;
Gilad Arnold76a11f62014-05-20 09:02:12 -0700375 } else {
Amin Hassani4b717432019-01-14 16:24:20 -0800376 const bool* is_oobe_complete_p =
377 ec->GetValue(state->system_provider()->var_is_oobe_complete());
Gilad Arnold14a9e702014-10-08 08:09:09 -0700378 is_scattering_applicable = (is_oobe_complete_p && *is_oobe_complete_p);
Gilad Arnold76a11f62014-05-20 09:02:12 -0700379 }
380 }
381
382 // Compute scattering values.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700383 if (is_scattering_applicable) {
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700384 UpdateScatteringResult scatter_result;
Amin Hassani4b717432019-01-14 16:24:20 -0800385 scattering_status =
386 UpdateScattering(ec, state, error, &scatter_result, update_state);
Gilad Arnold14a9e702014-10-08 08:09:09 -0700387 if (scattering_status == EvalStatus::kFailed) {
388 return EvalStatus::kFailed;
389 } else {
390 result->scatter_wait_period = scatter_result.wait_period;
391 result->scatter_check_threshold = scatter_result.check_threshold;
392 if (scattering_status == EvalStatus::kAskMeAgainLater ||
393 scatter_result.is_scattering)
394 is_scattering_active = true;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700395 }
396 }
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700397 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700398
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700399 // Find out whether P2P is globally enabled.
400 bool p2p_enabled;
401 EvalStatus p2p_enabled_status = P2PEnabled(ec, state, error, &p2p_enabled);
402 if (p2p_enabled_status != EvalStatus::kSucceeded)
403 return EvalStatus::kFailed;
404
405 // Is P2P is enabled, consider allowing it for downloading and/or sharing.
406 if (p2p_enabled) {
407 // Sharing via P2P is allowed if not disabled by Omaha.
408 if (update_state.p2p_sharing_disabled) {
409 LOG(INFO) << "Blocked P2P sharing because it is disabled by Omaha.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700410 } else {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700411 result->p2p_sharing_allowed = true;
Gilad Arnoldef8d0872014-10-03 14:14:06 -0700412 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700413
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700414 // Downloading via P2P is allowed if not disabled by Omaha, an update is not
415 // interactive, and other limits haven't been reached.
416 if (update_state.p2p_downloading_disabled) {
417 LOG(INFO) << "Blocked P2P downloading because it is disabled by Omaha.";
Amin Hassanied37d682018-04-06 13:22:00 -0700418 } else if (update_state.interactive) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700419 LOG(INFO) << "Blocked P2P downloading because update is interactive.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700420 } else if (update_state.p2p_num_attempts >= kMaxP2PAttempts) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700421 LOG(INFO) << "Blocked P2P downloading as it was attempted too many "
422 "times.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700423 } else if (!update_state.p2p_first_attempted.is_null() &&
424 ec->IsWallclockTimeGreaterThan(
425 update_state.p2p_first_attempted +
426 TimeDelta::FromSeconds(kMaxP2PAttemptsPeriodInSeconds))) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700427 LOG(INFO) << "Blocked P2P downloading as its usage timespan exceeds "
428 "limit.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700429 } else {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700430 // P2P download is allowed; if backoff or scattering are active, be sure
431 // to suppress them, yet prevent any download URL from being used.
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700432 result->p2p_downloading_allowed = true;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700433 if (is_backoff_active || is_scattering_active) {
434 is_backoff_active = is_scattering_active = false;
435 result->download_url_allowed = false;
436 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700437 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700438 }
439
Gilad Arnold14a9e702014-10-08 08:09:09 -0700440 // Check for various deterrents.
441 if (is_check_due) {
442 result->cannot_start_reason = UpdateCannotStartReason::kCheckDue;
443 return EvalStatus::kSucceeded;
444 }
445 if (is_backoff_active) {
446 result->cannot_start_reason = UpdateCannotStartReason::kBackoff;
447 return backoff_url_status;
448 }
449 if (is_scattering_active) {
450 result->cannot_start_reason = UpdateCannotStartReason::kScattering;
451 return scattering_status;
452 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700453 if (result->download_url_idx < 0 && !result->p2p_downloading_allowed) {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700454 result->cannot_start_reason = UpdateCannotStartReason::kCannotDownload;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700455 return EvalStatus::kSucceeded;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700456 }
457
Gilad Arnold14a9e702014-10-08 08:09:09 -0700458 // Update is good to go.
459 result->update_can_start = true;
Gilad Arnoldaf2f6ae2014-04-28 14:14:52 -0700460 return EvalStatus::kSucceeded;
461}
462
Gilad Arnolda8262e22014-06-02 13:54:27 -0700463// TODO(garnold) Logic in this method is based on
464// ConnectionManager::IsUpdateAllowedOver(); be sure to deprecate the latter.
465//
466// TODO(garnold) The current logic generally treats the list of allowed
467// connections coming from the device policy as a whitelist, meaning that it
468// can only be used for enabling connections, but not disable them. Further,
Alex Khouderchahbfa82262019-08-13 15:00:34 -0700469// certain connection types cannot be enabled even by policy.
Gilad Arnolda8262e22014-06-02 13:54:27 -0700470// In effect, the only thing that device policy can change is to enable
471// updates over a cellular network (disabled by default). We may want to
472// revisit this semantics, allowing greater flexibility in defining specific
473// permissions over all types of networks.
Amin Hassani4b717432019-01-14 16:24:20 -0800474EvalStatus ChromeOSPolicy::UpdateDownloadAllowed(EvaluationContext* ec,
475 State* state,
476 string* error,
477 bool* result) const {
Gilad Arnolda8262e22014-06-02 13:54:27 -0700478 // Get the current connection type.
479 ShillProvider* const shill_provider = state->shill_provider();
Amin Hassani4b717432019-01-14 16:24:20 -0800480 const ConnectionType* conn_type_p =
481 ec->GetValue(shill_provider->var_conn_type());
Gilad Arnolda8262e22014-06-02 13:54:27 -0700482 POLICY_CHECK_VALUE_AND_FAIL(conn_type_p, error);
483 ConnectionType conn_type = *conn_type_p;
484
485 // If we're tethering, treat it as a cellular connection.
486 if (conn_type != ConnectionType::kCellular) {
Amin Hassani4b717432019-01-14 16:24:20 -0800487 const ConnectionTethering* conn_tethering_p =
488 ec->GetValue(shill_provider->var_conn_tethering());
Gilad Arnolda8262e22014-06-02 13:54:27 -0700489 POLICY_CHECK_VALUE_AND_FAIL(conn_tethering_p, error);
490 if (*conn_tethering_p == ConnectionTethering::kConfirmed)
491 conn_type = ConnectionType::kCellular;
492 }
493
494 // By default, we allow updates for all connection types, with exceptions as
495 // noted below. This also determines whether a device policy can override the
496 // default.
497 *result = true;
498 bool device_policy_can_override = false;
499 switch (conn_type) {
Gilad Arnolda8262e22014-06-02 13:54:27 -0700500 case ConnectionType::kCellular:
501 *result = false;
502 device_policy_can_override = true;
503 break;
504
505 case ConnectionType::kUnknown:
506 if (error)
507 *error = "Unknown connection type";
508 return EvalStatus::kFailed;
509
510 default:
511 break; // Nothing to do.
512 }
513
514 // If update is allowed, we're done.
515 if (*result)
516 return EvalStatus::kSucceeded;
517
518 // Check whether the device policy specifically allows this connection.
Gilad Arnolda8262e22014-06-02 13:54:27 -0700519 if (device_policy_can_override) {
520 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Amin Hassani4b717432019-01-14 16:24:20 -0800521 const bool* device_policy_is_loaded_p =
522 ec->GetValue(dp_provider->var_device_policy_is_loaded());
Gilad Arnolda8262e22014-06-02 13:54:27 -0700523 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Amin Hassani4b717432019-01-14 16:24:20 -0800524 const set<ConnectionType>* allowed_conn_types_p =
525 ec->GetValue(dp_provider->var_allowed_connection_types_for_update());
Gilad Arnolda8262e22014-06-02 13:54:27 -0700526 if (allowed_conn_types_p) {
527 if (allowed_conn_types_p->count(conn_type)) {
528 *result = true;
529 return EvalStatus::kSucceeded;
530 }
Gilad Arnold28d6be62014-06-30 14:04:04 -0700531 } else if (conn_type == ConnectionType::kCellular) {
532 // Local user settings can allow updates over cellular iff a policy was
533 // loaded but no allowed connections were specified in it.
Amin Hassani4b717432019-01-14 16:24:20 -0800534 const bool* update_over_cellular_allowed_p =
535 ec->GetValue(state->updater_provider()->var_cellular_enabled());
Gilad Arnold28d6be62014-06-30 14:04:04 -0700536 if (update_over_cellular_allowed_p && *update_over_cellular_allowed_p)
537 *result = true;
Gilad Arnolda8262e22014-06-02 13:54:27 -0700538 }
539 }
540 }
541
Gilad Arnold28d6be62014-06-30 14:04:04 -0700542 return (*result ? EvalStatus::kSucceeded : EvalStatus::kAskMeAgainLater);
Gilad Arnolda8262e22014-06-02 13:54:27 -0700543}
544
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700545EvalStatus ChromeOSPolicy::P2PEnabled(EvaluationContext* ec,
546 State* state,
Alex Deymo39910dc2015-11-09 17:04:30 -0800547 string* error,
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700548 bool* result) const {
549 bool enabled = false;
550
551 // Determine whether use of P2P is allowed by policy. Even if P2P is not
552 // explicitly allowed, we allow it if the device is enterprise enrolled (that
553 // is, missing or empty owner string).
554 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Amin Hassani4b717432019-01-14 16:24:20 -0800555 const bool* device_policy_is_loaded_p =
556 ec->GetValue(dp_provider->var_device_policy_is_loaded());
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700557 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Amin Hassani4b717432019-01-14 16:24:20 -0800558 const bool* policy_au_p2p_enabled_p =
559 ec->GetValue(dp_provider->var_au_p2p_enabled());
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700560 if (policy_au_p2p_enabled_p) {
561 enabled = *policy_au_p2p_enabled_p;
562 } else {
Jae Hoon Kim9d9492f2019-06-17 14:52:48 -0700563 const bool* policy_has_owner_p =
564 ec->GetValue(dp_provider->var_has_owner());
565 if (!policy_has_owner_p || !*policy_has_owner_p)
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700566 enabled = true;
567 }
568 }
569
570 // Enable P2P, if so mandated by the updater configuration. This is additive
571 // to whether or not P2P is enabled by device policy.
572 if (!enabled) {
Amin Hassani4b717432019-01-14 16:24:20 -0800573 const bool* updater_p2p_enabled_p =
574 ec->GetValue(state->updater_provider()->var_p2p_enabled());
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700575 enabled = updater_p2p_enabled_p && *updater_p2p_enabled_p;
576 }
577
578 *result = enabled;
579 return EvalStatus::kSucceeded;
580}
581
582EvalStatus ChromeOSPolicy::P2PEnabledChanged(EvaluationContext* ec,
583 State* state,
Alex Deymo39910dc2015-11-09 17:04:30 -0800584 string* error,
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700585 bool* result,
586 bool prev_result) const {
587 EvalStatus status = P2PEnabled(ec, state, error, result);
588 if (status == EvalStatus::kSucceeded && *result == prev_result)
589 return EvalStatus::kAskMeAgainLater;
590 return status;
591}
592
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700593EvalStatus ChromeOSPolicy::UpdateBackoffAndDownloadUrl(
Amin Hassani4b717432019-01-14 16:24:20 -0800594 EvaluationContext* ec,
595 State* state,
596 string* error,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700597 UpdateBackoffAndDownloadUrlResult* result,
598 const UpdateState& update_state) const {
599 // Sanity checks.
600 DCHECK_GE(update_state.download_errors_max, 0);
601
602 // Set default result values.
603 result->do_increment_failures = false;
604 result->backoff_expiry = update_state.backoff_expiry;
605 result->url_idx = -1;
606 result->url_num_errors = 0;
607
Amin Hassani4b717432019-01-14 16:24:20 -0800608 const bool* is_official_build_p =
609 ec->GetValue(state->system_provider()->var_is_official_build());
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700610 bool is_official_build = (is_official_build_p ? *is_official_build_p : true);
611
612 // Check whether backoff is enabled.
613 bool may_backoff = false;
614 if (update_state.is_backoff_disabled) {
615 LOG(INFO) << "Backoff disabled by Omaha.";
Amin Hassanied37d682018-04-06 13:22:00 -0700616 } else if (update_state.interactive) {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700617 LOG(INFO) << "No backoff for interactive updates.";
618 } else if (update_state.is_delta_payload) {
619 LOG(INFO) << "No backoff for delta payloads.";
620 } else if (!is_official_build) {
621 LOG(INFO) << "No backoff for unofficial builds.";
622 } else {
623 may_backoff = true;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700624 }
625
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700626 // If previous backoff still in effect, block.
627 if (may_backoff && !update_state.backoff_expiry.is_null() &&
628 !ec->IsWallclockTimeGreaterThan(update_state.backoff_expiry)) {
629 LOG(INFO) << "Previous backoff has not expired, waiting.";
630 return EvalStatus::kAskMeAgainLater;
631 }
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700632
633 // Determine whether HTTP downloads are forbidden by policy. This only
634 // applies to official system builds; otherwise, HTTP is always enabled.
635 bool http_allowed = true;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700636 if (is_official_build) {
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700637 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Amin Hassani4b717432019-01-14 16:24:20 -0800638 const bool* device_policy_is_loaded_p =
639 ec->GetValue(dp_provider->var_device_policy_is_loaded());
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700640 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Amin Hassani4b717432019-01-14 16:24:20 -0800641 const bool* policy_http_downloads_enabled_p =
642 ec->GetValue(dp_provider->var_http_downloads_enabled());
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700643 http_allowed = (!policy_http_downloads_enabled_p ||
644 *policy_http_downloads_enabled_p);
645 }
646 }
647
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700648 int url_idx = update_state.last_download_url_idx;
649 if (url_idx < 0)
650 url_idx = -1;
651 bool do_advance_url = false;
652 bool is_failure_occurred = false;
653 Time err_time;
654
655 // Scan the relevant part of the download error log, tracking which URLs are
656 // being used, and accounting the number of errors for each URL. Note that
657 // this process may not traverse all errors provided, as it may decide to bail
658 // out midway depending on the particular errors exhibited, the number of
659 // failures allowed, etc. When this ends, |url_idx| will point to the last URL
660 // used (-1 if starting fresh), |do_advance_url| will determine whether the
661 // URL needs to be advanced, and |err_time| the point in time when the last
662 // reported error occurred. Additionally, if the error log indicates that an
663 // update attempt has failed (abnormal), then |is_failure_occurred| will be
664 // set to true.
665 const int num_urls = update_state.download_urls.size();
666 int prev_url_idx = -1;
667 int url_num_errors = update_state.last_download_url_num_errors;
668 Time prev_err_time;
669 bool is_first = true;
670 for (const auto& err_tuple : update_state.download_errors) {
671 // Do some sanity checks.
672 int used_url_idx = get<0>(err_tuple);
673 if (is_first && url_idx >= 0 && used_url_idx != url_idx) {
674 LOG(WARNING) << "First URL in error log (" << used_url_idx
675 << ") not as expected (" << url_idx << ")";
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700676 }
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700677 is_first = false;
678 url_idx = used_url_idx;
679 if (url_idx < 0 || url_idx >= num_urls) {
680 LOG(ERROR) << "Download error log contains an invalid URL index ("
681 << url_idx << ")";
682 return EvalStatus::kFailed;
683 }
684 err_time = get<2>(err_tuple);
685 if (!(prev_err_time.is_null() || err_time >= prev_err_time)) {
686 // TODO(garnold) Monotonicity cannot really be assumed when dealing with
687 // wallclock-based timestamps. However, we're making a simplifying
688 // assumption so as to keep the policy implementation straightforward, for
689 // now. In general, we should convert all timestamp handling in the
690 // UpdateManager to use monotonic time (instead of wallclock), including
691 // the computation of various expiration times (backoff, scattering, etc).
692 // The client will do whatever conversions necessary when
693 // persisting/retrieving these values across reboots. See chromium:408794.
694 LOG(ERROR) << "Download error timestamps not monotonically increasing.";
695 return EvalStatus::kFailed;
696 }
697 prev_err_time = err_time;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700698
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700699 // Ignore errors that happened before the last known failed attempt.
700 if (!update_state.failures_last_updated.is_null() &&
701 err_time <= update_state.failures_last_updated)
702 continue;
703
704 if (prev_url_idx >= 0) {
705 if (url_idx < prev_url_idx) {
706 LOG(ERROR) << "The URLs in the download error log have wrapped around ("
707 << prev_url_idx << "->" << url_idx
708 << "). This should not have happened and means that there's "
709 "a bug. To be conservative, we record a failed attempt "
710 "(invalidating the rest of the error log) and resume "
711 "download from the first usable URL.";
712 url_idx = -1;
713 is_failure_occurred = true;
714 break;
715 }
716
717 if (url_idx > prev_url_idx) {
718 url_num_errors = 0;
719 do_advance_url = false;
720 }
721 }
722
723 if (HandleErrorCode(get<1>(err_tuple), &url_num_errors) ||
724 url_num_errors > update_state.download_errors_max)
725 do_advance_url = true;
726
727 prev_url_idx = url_idx;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700728 }
729
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700730 // If required, advance to the next usable URL. If the URLs wraparound, we
731 // mark an update attempt failure. Also be sure to set the download error
732 // count to zero.
733 if (url_idx < 0 || do_advance_url) {
734 url_num_errors = 0;
735 int start_url_idx = -1;
736 do {
737 if (++url_idx == num_urls) {
738 url_idx = 0;
739 // We only mark failure if an actual advancing of a URL was required.
740 if (do_advance_url)
741 is_failure_occurred = true;
742 }
743
744 if (start_url_idx < 0)
745 start_url_idx = url_idx;
746 else if (url_idx == start_url_idx)
747 url_idx = -1; // No usable URL.
748 } while (url_idx >= 0 &&
749 !IsUrlUsable(update_state.download_urls[url_idx], http_allowed));
750 }
751
752 // If we have a download URL but a failure was observed, compute a new backoff
753 // expiry (if allowed). The backoff period is generally 2 ^ (num_failures - 1)
754 // days, bounded by the size of int and kAttemptBackoffMaxIntervalInDays, and
755 // fuzzed by kAttemptBackoffFuzzInHours hours. Backoff expiry is computed from
756 // the latest recorded time of error.
757 Time backoff_expiry;
758 if (url_idx >= 0 && is_failure_occurred && may_backoff) {
759 CHECK(!err_time.is_null())
760 << "We must have an error timestamp if a failure occurred!";
761 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
762 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
763 PRNG prng(*seed);
Amin Hassani4b717432019-01-14 16:24:20 -0800764 int exp =
765 min(update_state.num_failures, static_cast<int>(sizeof(int)) * 8 - 2);
Amin Hassani186ff6a2018-02-27 11:06:03 -0800766 TimeDelta backoff_interval = TimeDelta::FromDays(min(
767 1 << exp,
768 kNextUpdateCheckPolicyConstants.attempt_backoff_max_interval_in_days));
769 TimeDelta backoff_fuzz = TimeDelta::FromHours(
770 kNextUpdateCheckPolicyConstants.attempt_backoff_fuzz_in_hours);
771 TimeDelta wait_period = NextUpdateCheckTimePolicyImpl::FuzzedInterval(
772 &prng, backoff_interval.InSeconds(), backoff_fuzz.InSeconds());
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700773 backoff_expiry = err_time + wait_period;
774
775 // If the newly computed backoff already expired, nullify it.
776 if (ec->IsWallclockTimeGreaterThan(backoff_expiry))
777 backoff_expiry = Time();
778 }
779
780 result->do_increment_failures = is_failure_occurred;
781 result->backoff_expiry = backoff_expiry;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700782 result->url_idx = url_idx;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700783 result->url_num_errors = url_num_errors;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700784 return EvalStatus::kSucceeded;
785}
786
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700787EvalStatus ChromeOSPolicy::UpdateScattering(
788 EvaluationContext* ec,
789 State* state,
790 string* error,
791 UpdateScatteringResult* result,
792 const UpdateState& update_state) const {
793 // Preconditions. These stem from the postconditions and usage contract.
794 DCHECK(update_state.scatter_wait_period >= kZeroInterval);
795 DCHECK_GE(update_state.scatter_check_threshold, 0);
796
797 // Set default result values.
798 result->is_scattering = false;
799 result->wait_period = kZeroInterval;
800 result->check_threshold = 0;
801
802 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
803
804 // Ensure that a device policy is loaded.
Amin Hassani4b717432019-01-14 16:24:20 -0800805 const bool* device_policy_is_loaded_p =
806 ec->GetValue(dp_provider->var_device_policy_is_loaded());
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700807 if (!(device_policy_is_loaded_p && *device_policy_is_loaded_p))
808 return EvalStatus::kSucceeded;
809
810 // Is scattering enabled by policy?
Amin Hassani4b717432019-01-14 16:24:20 -0800811 const TimeDelta* scatter_factor_p =
812 ec->GetValue(dp_provider->var_scatter_factor());
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700813 if (!scatter_factor_p || *scatter_factor_p == kZeroInterval)
814 return EvalStatus::kSucceeded;
815
816 // Obtain a pseudo-random number generator.
817 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
818 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
819 PRNG prng(*seed);
820
821 // Step 1: Maintain the scattering wait period.
822 //
823 // If no wait period was previously determined, or it no longer fits in the
824 // scatter factor, then generate a new one. Otherwise, keep the one we have.
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700825 TimeDelta wait_period = update_state.scatter_wait_period;
826 if (wait_period == kZeroInterval || wait_period > *scatter_factor_p) {
827 wait_period = TimeDelta::FromSeconds(
828 prng.RandMinMax(1, scatter_factor_p->InSeconds()));
829 }
830
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700831 // If we surpassed the wait period or the max scatter period associated with
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700832 // the update, then no wait is needed.
833 Time wait_expires = (update_state.first_seen +
834 min(wait_period, update_state.scatter_wait_period_max));
Gilad Arnolda65fced2014-07-23 09:01:31 -0700835 if (ec->IsWallclockTimeGreaterThan(wait_expires))
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700836 wait_period = kZeroInterval;
837
838 // Step 2: Maintain the update check threshold count.
839 //
840 // If an update check threshold is not specified then generate a new
841 // one.
842 int check_threshold = update_state.scatter_check_threshold;
843 if (check_threshold == 0) {
Amin Hassani4b717432019-01-14 16:24:20 -0800844 check_threshold = prng.RandMinMax(update_state.scatter_check_threshold_min,
845 update_state.scatter_check_threshold_max);
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700846 }
847
848 // If the update check threshold is not within allowed range then nullify it.
849 // TODO(garnold) This is compliant with current logic found in
850 // OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied(). We may want
851 // to change it so that it behaves similarly to the wait period case, namely
852 // if the current value exceeds the maximum, we set a new one within range.
853 if (check_threshold > update_state.scatter_check_threshold_max)
854 check_threshold = 0;
855
856 // If the update check threshold is non-zero and satisfied, then nullify it.
857 if (check_threshold > 0 && update_state.num_checks >= check_threshold)
858 check_threshold = 0;
859
860 bool is_scattering = (wait_period != kZeroInterval || check_threshold);
861 EvalStatus ret = EvalStatus::kSucceeded;
862 if (is_scattering && wait_period == update_state.scatter_wait_period &&
863 check_threshold == update_state.scatter_check_threshold)
864 ret = EvalStatus::kAskMeAgainLater;
865 result->is_scattering = is_scattering;
866 result->wait_period = wait_period;
867 result->check_threshold = check_threshold;
868 return ret;
869}
870
Alex Deymo63784a52014-05-28 10:46:14 -0700871} // namespace chromeos_update_manager