blob: 585ea197e4bf256715cb57eddeabeca1abc33a59 [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"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070039
Alex Deymo0d11c602014-04-23 20:12:20 -070040using base::Time;
41using base::TimeDelta;
Sen Jiang255e22b2016-05-20 16:15:29 -070042using chromeos_update_engine::ConnectionTethering;
43using chromeos_update_engine::ConnectionType;
Gilad Arnoldb3b05442014-05-30 14:25:05 -070044using chromeos_update_engine::ErrorCode;
Aaron Wood23bd3392017-10-06 14:48:25 -070045using chromeos_update_engine::InstallPlan;
Gilad Arnolddc4bb262014-07-23 10:45:19 -070046using std::get;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070047using std::min;
Gilad Arnold0adbc942014-05-12 10:35:43 -070048using std::set;
Alex Deymoc705cc82014-02-19 11:15:00 -080049using std::string;
Amin Hassani186ff6a2018-02-27 11:06:03 -080050using std::vector;
Alex Deymoc705cc82014-02-19 11:15:00 -080051
Gilad Arnoldb3b05442014-05-30 14:25:05 -070052namespace {
53
Gilad Arnolddc4bb262014-07-23 10:45:19 -070054// Examines |err_code| and decides whether the URL index needs to be advanced,
55// the error count for the URL incremented, or none of the above. In the first
56// case, returns true; in the second case, increments |*url_num_error_p| and
57// returns false; otherwise just returns false.
Gilad Arnoldb3b05442014-05-30 14:25:05 -070058//
59// TODO(garnold) Adapted from PayloadState::UpdateFailed() (to be retired).
Gilad Arnolddc4bb262014-07-23 10:45:19 -070060bool HandleErrorCode(ErrorCode err_code, int* url_num_error_p) {
Gilad Arnoldb3b05442014-05-30 14:25:05 -070061 err_code = chromeos_update_engine::utils::GetBaseErrorCode(err_code);
62 switch (err_code) {
63 // Errors which are good indicators of a problem with a particular URL or
64 // the protocol used in the URL or entities in the communication channel
65 // (e.g. proxies). We should try the next available URL in the next update
66 // check to quickly recover from these errors.
67 case ErrorCode::kPayloadHashMismatchError:
68 case ErrorCode::kPayloadSizeMismatchError:
69 case ErrorCode::kDownloadPayloadVerificationError:
70 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
71 case ErrorCode::kSignedDeltaPayloadExpectedError:
72 case ErrorCode::kDownloadInvalidMetadataMagicString:
73 case ErrorCode::kDownloadSignatureMissingInManifest:
74 case ErrorCode::kDownloadManifestParseError:
75 case ErrorCode::kDownloadMetadataSignatureError:
76 case ErrorCode::kDownloadMetadataSignatureVerificationError:
77 case ErrorCode::kDownloadMetadataSignatureMismatch:
78 case ErrorCode::kDownloadOperationHashVerificationError:
79 case ErrorCode::kDownloadOperationExecutionError:
80 case ErrorCode::kDownloadOperationHashMismatch:
81 case ErrorCode::kDownloadInvalidMetadataSize:
82 case ErrorCode::kDownloadInvalidMetadataSignature:
83 case ErrorCode::kDownloadOperationHashMissingError:
84 case ErrorCode::kDownloadMetadataSignatureMissingError:
85 case ErrorCode::kPayloadMismatchedType:
86 case ErrorCode::kUnsupportedMajorPayloadVersion:
87 case ErrorCode::kUnsupportedMinorPayloadVersion:
88 LOG(INFO) << "Advancing download URL due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -080089 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -070090 << " (" << static_cast<int>(err_code) << ")";
Gilad Arnoldb3b05442014-05-30 14:25:05 -070091 return true;
92
93 // Errors which seem to be just transient network/communication related
94 // failures and do not indicate any inherent problem with the URL itself.
95 // So, we should keep the current URL but just increment the
96 // failure count to give it more chances. This way, while we maximize our
97 // chances of downloading from the URLs that appear earlier in the response
98 // (because download from a local server URL that appears earlier in a
99 // response is preferable than downloading from the next URL which could be
Alex Vakulenko072359c2014-07-18 11:41:07 -0700100 // an Internet URL and thus could be more expensive).
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700101 case ErrorCode::kError:
102 case ErrorCode::kDownloadTransferError:
103 case ErrorCode::kDownloadWriteError:
104 case ErrorCode::kDownloadStateInitializationError:
Gilad Arnold684219d2014-07-07 14:54:57 -0700105 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700106 LOG(INFO) << "Incrementing URL failure count due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800107 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700108 << " (" << static_cast<int>(err_code) << ")";
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700109 *url_num_error_p += 1;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700110 return false;
111
112 // Errors which are not specific to a URL and hence shouldn't result in
113 // the URL being penalized. This can happen in two cases:
114 // 1. We haven't started downloading anything: These errors don't cost us
115 // anything in terms of actual payload bytes, so we should just do the
116 // regular retries at the next update check.
117 // 2. We have successfully downloaded the payload: In this case, the
118 // payload attempt number would have been incremented and would take care
Alex Vakulenko072359c2014-07-18 11:41:07 -0700119 // of the back-off at the next update check.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700120 // In either case, there's no need to update URL index or failure count.
121 case ErrorCode::kOmahaRequestError:
122 case ErrorCode::kOmahaResponseHandlerError:
123 case ErrorCode::kPostinstallRunnerError:
124 case ErrorCode::kFilesystemCopierError:
125 case ErrorCode::kInstallDeviceOpenError:
126 case ErrorCode::kKernelDeviceOpenError:
127 case ErrorCode::kDownloadNewPartitionInfoError:
128 case ErrorCode::kNewRootfsVerificationError:
129 case ErrorCode::kNewKernelVerificationError:
130 case ErrorCode::kPostinstallBootedFromFirmwareB:
131 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
132 case ErrorCode::kOmahaRequestEmptyResponseError:
133 case ErrorCode::kOmahaRequestXMLParseError:
134 case ErrorCode::kOmahaResponseInvalid:
135 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
136 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
Kevin Cernekee2494e282016-03-29 18:03:53 -0700137 case ErrorCode::kNonCriticalUpdateInOOBE:
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700138 case ErrorCode::kOmahaUpdateDeferredForBackoff:
139 case ErrorCode::kPostinstallPowerwashError:
140 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400141 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700142 case ErrorCode::kFilesystemVerifierError:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800143 case ErrorCode::kUserCanceled:
Weidong Guo421ff332017-04-17 10:08:38 -0700144 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
Sen Jiang02c49422017-10-31 15:14:11 -0700145 case ErrorCode::kUpdatedButNotActive:
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700146 LOG(INFO) << "Not changing URL index or failure count due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800147 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700148 << " (" << static_cast<int>(err_code) << ")";
149 return false;
150
151 case ErrorCode::kSuccess: // success code
152 case ErrorCode::kUmaReportedMax: // not an error code
153 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800154 case ErrorCode::kDevModeFlag: // not an error code
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700155 case ErrorCode::kResumedFlag: // not an error code
156 case ErrorCode::kTestImageFlag: // not an error code
157 case ErrorCode::kTestOmahaUrlFlag: // not an error code
158 case ErrorCode::kSpecialFlags: // not an error code
159 // These shouldn't happen. Enumerating these explicitly here so that we
160 // can let the compiler warn about new error codes that are added to
161 // action_processor.h but not added here.
162 LOG(WARNING) << "Unexpected error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800163 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700164 << " (" << static_cast<int>(err_code) << ")";
165 // Note: Not adding a default here so as to let the compiler warn us of
166 // any new enums that were added in the .h but not listed in this switch.
167 }
168 return false;
169}
170
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700171// Checks whether |url| can be used under given download restrictions.
172bool IsUrlUsable(const string& url, bool http_allowed) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800173 return http_allowed ||
174 !base::StartsWith(url, "http://",
175 base::CompareCase::INSENSITIVE_ASCII);
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700176}
177
178} // namespace
179
Alex Deymo63784a52014-05-28 10:46:14 -0700180namespace chromeos_update_manager {
Alex Deymoc705cc82014-02-19 11:15:00 -0800181
Amin Hassani186ff6a2018-02-27 11:06:03 -0800182const NextUpdateCheckPolicyConstants
183 ChromeOSPolicy::kNextUpdateCheckPolicyConstants = {
184 .timeout_initial_interval = 7 * 60,
185 .timeout_periodic_interval = 45 * 60,
186 .timeout_max_backoff_interval = 4 * 60 * 60,
187 .timeout_regular_fuzz = 10 * 60,
188 .attempt_backoff_max_interval_in_days = 16,
189 .attempt_backoff_fuzz_in_hours = 12,
190};
Alex Deymo14e7dde2015-10-20 14:46:33 -0700191
Gilad Arnold349ac832014-10-06 14:20:28 -0700192const int ChromeOSPolicy::kMaxP2PAttempts = 10;
193const int ChromeOSPolicy::kMaxP2PAttemptsPeriodInSeconds = 5 * 24 * 60 * 60;
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700194
Alex Deymo0d11c602014-04-23 20:12:20 -0700195EvalStatus ChromeOSPolicy::UpdateCheckAllowed(
196 EvaluationContext* ec, State* state, string* error,
197 UpdateCheckParams* result) const {
Gilad Arnold42f253b2014-06-25 12:39:17 -0700198 // Set the default return values.
199 result->updates_enabled = true;
200 result->target_channel.clear();
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700201 result->target_version_prefix.clear();
Marton Hunyady0e0e3542018-02-21 18:51:39 +0100202 result->rollback_to_target_version = RollbackToTargetVersion::kUnspecified;
203 result->rollback_allowed_milestones = -1;
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700204 result->is_interactive = false;
Gilad Arnold42f253b2014-06-25 12:39:17 -0700205
Amin Hassani186ff6a2018-02-27 11:06:03 -0800206 EnoughSlotsAbUpdatesPolicyImpl enough_slots_ab_updates_policy;
207 EnterpriseDevicePolicyImpl enterprise_device_policy;
208 OnlyUpdateOfficialBuildsPolicyImpl only_update_official_builds_policy;
209 InteractiveUpdatePolicyImpl interactive_update_policy;
210 OobePolicyImpl oobe_policy;
211 NextUpdateCheckTimePolicyImpl next_update_check_time_policy(
212 kNextUpdateCheckPolicyConstants);
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700213
Amin Hassani186ff6a2018-02-27 11:06:03 -0800214 vector<Policy const*> policies_to_consult = {
215 // Do not perform any updates if there are not enough slots to do A/B
216 // updates.
217 &enough_slots_ab_updates_policy,
218
219 // Check to see if Enterprise-managed (has DevicePolicy) and/or
220 // Kiosk-mode. If so, then defer to those settings.
221 &enterprise_device_policy,
222
223 // Check to see if an interactive update was requested.
224 &interactive_update_policy,
225
226 // Unofficial builds should not perform periodic update checks.
227 &only_update_official_builds_policy,
228
229 // If OOBE is enabled, wait until it is completed.
230 &oobe_policy,
231
232 // Ensure that periodic update checks are timed properly.
233 &next_update_check_time_policy,
234 };
235
236 // Now that the list of policy implementations, and the order to consult them,
237 // has been setup, consult the policies. If none of the policies make a
238 // definitive decisions about whether or not to check for updates, then allow
239 // the update check to happen.
240 EvalStatus status = ConsultPolicies(policies_to_consult,
241 &Policy::UpdateCheckAllowed,
242 ec,
243 state,
244 error,
245 result);
246 if (EvalStatus::kContinue != status) {
247 return status;
248 } else {
249 // It is time to check for an update.
250 LOG(INFO) << "Allowing update check.";
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700251 return EvalStatus::kSucceeded;
252 }
Alex Deymoc705cc82014-02-19 11:15:00 -0800253}
254
Aaron Wood23bd3392017-10-06 14:48:25 -0700255EvalStatus ChromeOSPolicy::UpdateCanBeApplied(EvaluationContext* ec,
256 State* state,
257 std::string* error,
258 ErrorCode* result,
259 InstallPlan* install_plan) const {
260 *result = ErrorCode::kSuccess;
261 return EvalStatus::kSucceeded;
262}
263
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700264EvalStatus ChromeOSPolicy::UpdateCanStart(
265 EvaluationContext* ec,
266 State* state,
267 string* error,
Gilad Arnold42f253b2014-06-25 12:39:17 -0700268 UpdateDownloadParams* result,
Gilad Arnoldd78caf92014-09-24 09:28:14 -0700269 const UpdateState update_state) const {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700270 // Set the default return values. Note that we set persisted values (backoff,
271 // scattering) to the same values presented in the update state. The reason is
272 // that preemptive returns, such as the case where an update check is due,
273 // should not clear off the said values; rather, it is the deliberate
274 // inference of new values that should cause them to be reset.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700275 result->update_can_start = false;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700276 result->cannot_start_reason = UpdateCannotStartReason::kUndefined;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700277 result->download_url_idx = -1;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700278 result->download_url_allowed = true;
279 result->download_url_num_errors = 0;
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700280 result->p2p_downloading_allowed = false;
281 result->p2p_sharing_allowed = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700282 result->do_increment_failures = false;
283 result->backoff_expiry = update_state.backoff_expiry;
284 result->scatter_wait_period = update_state.scatter_wait_period;
285 result->scatter_check_threshold = update_state.scatter_check_threshold;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700286
287 // Make sure that we're not due for an update check.
288 UpdateCheckParams check_result;
289 EvalStatus check_status = UpdateCheckAllowed(ec, state, error, &check_result);
290 if (check_status == EvalStatus::kFailed)
291 return EvalStatus::kFailed;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700292 bool is_check_due = (check_status == EvalStatus::kSucceeded &&
293 check_result.updates_enabled == true);
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700294
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700295 // Check whether backoff applies, and if not then which URL can be used for
296 // downloading. These require scanning the download error log, and so they are
297 // done together.
298 UpdateBackoffAndDownloadUrlResult backoff_url_result;
299 EvalStatus backoff_url_status = UpdateBackoffAndDownloadUrl(
300 ec, state, error, &backoff_url_result, update_state);
Gilad Arnold14a9e702014-10-08 08:09:09 -0700301 if (backoff_url_status == EvalStatus::kFailed)
302 return EvalStatus::kFailed;
303 result->download_url_idx = backoff_url_result.url_idx;
304 result->download_url_num_errors = backoff_url_result.url_num_errors;
305 result->do_increment_failures = backoff_url_result.do_increment_failures;
306 result->backoff_expiry = backoff_url_result.backoff_expiry;
307 bool is_backoff_active =
308 (backoff_url_status == EvalStatus::kAskMeAgainLater) ||
309 !backoff_url_result.backoff_expiry.is_null();
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700310
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700311 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold14a9e702014-10-08 08:09:09 -0700312 bool is_scattering_active = false;
313 EvalStatus scattering_status = EvalStatus::kSucceeded;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700314
315 const bool* device_policy_is_loaded_p = ec->GetValue(
316 dp_provider->var_device_policy_is_loaded());
317 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700318 // Check whether scattering applies to this update attempt. We should not be
319 // scattering if this is an interactive update check, or if OOBE is enabled
320 // but not completed.
321 //
322 // Note: current code further suppresses scattering if a "deadline"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700323 // attribute is found in the Omaha response. However, it appears that the
Gilad Arnold76a11f62014-05-20 09:02:12 -0700324 // presence of this attribute is merely indicative of an OOBE update, during
325 // which we suppress scattering anyway.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700326 bool is_scattering_applicable = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700327 result->scatter_wait_period = kZeroInterval;
328 result->scatter_check_threshold = 0;
329 if (!update_state.is_interactive) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700330 const bool* is_oobe_enabled_p = ec->GetValue(
331 state->config_provider()->var_is_oobe_enabled());
332 if (is_oobe_enabled_p && !(*is_oobe_enabled_p)) {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700333 is_scattering_applicable = true;
Gilad Arnold76a11f62014-05-20 09:02:12 -0700334 } else {
335 const bool* is_oobe_complete_p = ec->GetValue(
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700336 state->system_provider()->var_is_oobe_complete());
Gilad Arnold14a9e702014-10-08 08:09:09 -0700337 is_scattering_applicable = (is_oobe_complete_p && *is_oobe_complete_p);
Gilad Arnold76a11f62014-05-20 09:02:12 -0700338 }
339 }
340
341 // Compute scattering values.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700342 if (is_scattering_applicable) {
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700343 UpdateScatteringResult scatter_result;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700344 scattering_status = UpdateScattering(ec, state, error, &scatter_result,
345 update_state);
346 if (scattering_status == EvalStatus::kFailed) {
347 return EvalStatus::kFailed;
348 } else {
349 result->scatter_wait_period = scatter_result.wait_period;
350 result->scatter_check_threshold = scatter_result.check_threshold;
351 if (scattering_status == EvalStatus::kAskMeAgainLater ||
352 scatter_result.is_scattering)
353 is_scattering_active = true;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700354 }
355 }
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700356 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700357
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700358 // Find out whether P2P is globally enabled.
359 bool p2p_enabled;
360 EvalStatus p2p_enabled_status = P2PEnabled(ec, state, error, &p2p_enabled);
361 if (p2p_enabled_status != EvalStatus::kSucceeded)
362 return EvalStatus::kFailed;
363
364 // Is P2P is enabled, consider allowing it for downloading and/or sharing.
365 if (p2p_enabled) {
366 // Sharing via P2P is allowed if not disabled by Omaha.
367 if (update_state.p2p_sharing_disabled) {
368 LOG(INFO) << "Blocked P2P sharing because it is disabled by Omaha.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700369 } else {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700370 result->p2p_sharing_allowed = true;
Gilad Arnoldef8d0872014-10-03 14:14:06 -0700371 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700372
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700373 // Downloading via P2P is allowed if not disabled by Omaha, an update is not
374 // interactive, and other limits haven't been reached.
375 if (update_state.p2p_downloading_disabled) {
376 LOG(INFO) << "Blocked P2P downloading because it is disabled by Omaha.";
377 } else if (update_state.is_interactive) {
378 LOG(INFO) << "Blocked P2P downloading because update is interactive.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700379 } else if (update_state.p2p_num_attempts >= kMaxP2PAttempts) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700380 LOG(INFO) << "Blocked P2P downloading as it was attempted too many "
381 "times.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700382 } else if (!update_state.p2p_first_attempted.is_null() &&
383 ec->IsWallclockTimeGreaterThan(
384 update_state.p2p_first_attempted +
385 TimeDelta::FromSeconds(kMaxP2PAttemptsPeriodInSeconds))) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700386 LOG(INFO) << "Blocked P2P downloading as its usage timespan exceeds "
387 "limit.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700388 } else {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700389 // P2P download is allowed; if backoff or scattering are active, be sure
390 // to suppress them, yet prevent any download URL from being used.
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700391 result->p2p_downloading_allowed = true;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700392 if (is_backoff_active || is_scattering_active) {
393 is_backoff_active = is_scattering_active = false;
394 result->download_url_allowed = false;
395 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700396 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700397 }
398
Gilad Arnold14a9e702014-10-08 08:09:09 -0700399 // Check for various deterrents.
400 if (is_check_due) {
401 result->cannot_start_reason = UpdateCannotStartReason::kCheckDue;
402 return EvalStatus::kSucceeded;
403 }
404 if (is_backoff_active) {
405 result->cannot_start_reason = UpdateCannotStartReason::kBackoff;
406 return backoff_url_status;
407 }
408 if (is_scattering_active) {
409 result->cannot_start_reason = UpdateCannotStartReason::kScattering;
410 return scattering_status;
411 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700412 if (result->download_url_idx < 0 && !result->p2p_downloading_allowed) {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700413 result->cannot_start_reason = UpdateCannotStartReason::kCannotDownload;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700414 return EvalStatus::kSucceeded;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700415 }
416
Gilad Arnold14a9e702014-10-08 08:09:09 -0700417 // Update is good to go.
418 result->update_can_start = true;
Gilad Arnoldaf2f6ae2014-04-28 14:14:52 -0700419 return EvalStatus::kSucceeded;
420}
421
Gilad Arnolda8262e22014-06-02 13:54:27 -0700422// TODO(garnold) Logic in this method is based on
423// ConnectionManager::IsUpdateAllowedOver(); be sure to deprecate the latter.
424//
425// TODO(garnold) The current logic generally treats the list of allowed
426// connections coming from the device policy as a whitelist, meaning that it
427// can only be used for enabling connections, but not disable them. Further,
428// certain connection types (like Bluetooth) cannot be enabled even by policy.
429// In effect, the only thing that device policy can change is to enable
430// updates over a cellular network (disabled by default). We may want to
431// revisit this semantics, allowing greater flexibility in defining specific
432// permissions over all types of networks.
Gilad Arnold684219d2014-07-07 14:54:57 -0700433EvalStatus ChromeOSPolicy::UpdateDownloadAllowed(
Gilad Arnolda8262e22014-06-02 13:54:27 -0700434 EvaluationContext* ec,
435 State* state,
436 string* error,
437 bool* result) const {
438 // Get the current connection type.
439 ShillProvider* const shill_provider = state->shill_provider();
440 const ConnectionType* conn_type_p = ec->GetValue(
441 shill_provider->var_conn_type());
442 POLICY_CHECK_VALUE_AND_FAIL(conn_type_p, error);
443 ConnectionType conn_type = *conn_type_p;
444
445 // If we're tethering, treat it as a cellular connection.
446 if (conn_type != ConnectionType::kCellular) {
447 const ConnectionTethering* conn_tethering_p = ec->GetValue(
448 shill_provider->var_conn_tethering());
449 POLICY_CHECK_VALUE_AND_FAIL(conn_tethering_p, error);
450 if (*conn_tethering_p == ConnectionTethering::kConfirmed)
451 conn_type = ConnectionType::kCellular;
452 }
453
454 // By default, we allow updates for all connection types, with exceptions as
455 // noted below. This also determines whether a device policy can override the
456 // default.
457 *result = true;
458 bool device_policy_can_override = false;
459 switch (conn_type) {
460 case ConnectionType::kBluetooth:
461 *result = false;
462 break;
463
464 case ConnectionType::kCellular:
465 *result = false;
466 device_policy_can_override = true;
467 break;
468
469 case ConnectionType::kUnknown:
470 if (error)
471 *error = "Unknown connection type";
472 return EvalStatus::kFailed;
473
474 default:
475 break; // Nothing to do.
476 }
477
478 // If update is allowed, we're done.
479 if (*result)
480 return EvalStatus::kSucceeded;
481
482 // Check whether the device policy specifically allows this connection.
Gilad Arnolda8262e22014-06-02 13:54:27 -0700483 if (device_policy_can_override) {
484 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
485 const bool* device_policy_is_loaded_p = ec->GetValue(
486 dp_provider->var_device_policy_is_loaded());
487 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
488 const set<ConnectionType>* allowed_conn_types_p = ec->GetValue(
489 dp_provider->var_allowed_connection_types_for_update());
490 if (allowed_conn_types_p) {
491 if (allowed_conn_types_p->count(conn_type)) {
492 *result = true;
493 return EvalStatus::kSucceeded;
494 }
Gilad Arnold28d6be62014-06-30 14:04:04 -0700495 } else if (conn_type == ConnectionType::kCellular) {
496 // Local user settings can allow updates over cellular iff a policy was
497 // loaded but no allowed connections were specified in it.
498 const bool* update_over_cellular_allowed_p = ec->GetValue(
499 state->updater_provider()->var_cellular_enabled());
500 if (update_over_cellular_allowed_p && *update_over_cellular_allowed_p)
501 *result = true;
Gilad Arnolda8262e22014-06-02 13:54:27 -0700502 }
503 }
504 }
505
Gilad Arnold28d6be62014-06-30 14:04:04 -0700506 return (*result ? EvalStatus::kSucceeded : EvalStatus::kAskMeAgainLater);
Gilad Arnolda8262e22014-06-02 13:54:27 -0700507}
508
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700509EvalStatus ChromeOSPolicy::P2PEnabled(EvaluationContext* ec,
510 State* state,
Alex Deymo39910dc2015-11-09 17:04:30 -0800511 string* error,
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700512 bool* result) const {
513 bool enabled = false;
514
515 // Determine whether use of P2P is allowed by policy. Even if P2P is not
516 // explicitly allowed, we allow it if the device is enterprise enrolled (that
517 // is, missing or empty owner string).
518 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
519 const bool* device_policy_is_loaded_p = ec->GetValue(
520 dp_provider->var_device_policy_is_loaded());
521 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
522 const bool* policy_au_p2p_enabled_p = ec->GetValue(
523 dp_provider->var_au_p2p_enabled());
524 if (policy_au_p2p_enabled_p) {
525 enabled = *policy_au_p2p_enabled_p;
526 } else {
527 const string* policy_owner_p = ec->GetValue(dp_provider->var_owner());
528 if (!policy_owner_p || policy_owner_p->empty())
529 enabled = true;
530 }
531 }
532
533 // Enable P2P, if so mandated by the updater configuration. This is additive
534 // to whether or not P2P is enabled by device policy.
535 if (!enabled) {
536 const bool* updater_p2p_enabled_p = ec->GetValue(
537 state->updater_provider()->var_p2p_enabled());
538 enabled = updater_p2p_enabled_p && *updater_p2p_enabled_p;
539 }
540
541 *result = enabled;
542 return EvalStatus::kSucceeded;
543}
544
545EvalStatus ChromeOSPolicy::P2PEnabledChanged(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,
549 bool prev_result) const {
550 EvalStatus status = P2PEnabled(ec, state, error, result);
551 if (status == EvalStatus::kSucceeded && *result == prev_result)
552 return EvalStatus::kAskMeAgainLater;
553 return status;
554}
555
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700556EvalStatus ChromeOSPolicy::UpdateBackoffAndDownloadUrl(
Alex Deymof329b932014-10-30 01:37:48 -0700557 EvaluationContext* ec, State* state, string* error,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700558 UpdateBackoffAndDownloadUrlResult* result,
559 const UpdateState& update_state) const {
560 // Sanity checks.
561 DCHECK_GE(update_state.download_errors_max, 0);
562
563 // Set default result values.
564 result->do_increment_failures = false;
565 result->backoff_expiry = update_state.backoff_expiry;
566 result->url_idx = -1;
567 result->url_num_errors = 0;
568
569 const bool* is_official_build_p = ec->GetValue(
570 state->system_provider()->var_is_official_build());
571 bool is_official_build = (is_official_build_p ? *is_official_build_p : true);
572
573 // Check whether backoff is enabled.
574 bool may_backoff = false;
575 if (update_state.is_backoff_disabled) {
576 LOG(INFO) << "Backoff disabled by Omaha.";
577 } else if (update_state.is_interactive) {
578 LOG(INFO) << "No backoff for interactive updates.";
579 } else if (update_state.is_delta_payload) {
580 LOG(INFO) << "No backoff for delta payloads.";
581 } else if (!is_official_build) {
582 LOG(INFO) << "No backoff for unofficial builds.";
583 } else {
584 may_backoff = true;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700585 }
586
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700587 // If previous backoff still in effect, block.
588 if (may_backoff && !update_state.backoff_expiry.is_null() &&
589 !ec->IsWallclockTimeGreaterThan(update_state.backoff_expiry)) {
590 LOG(INFO) << "Previous backoff has not expired, waiting.";
591 return EvalStatus::kAskMeAgainLater;
592 }
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700593
594 // Determine whether HTTP downloads are forbidden by policy. This only
595 // applies to official system builds; otherwise, HTTP is always enabled.
596 bool http_allowed = true;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700597 if (is_official_build) {
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700598 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
599 const bool* device_policy_is_loaded_p = ec->GetValue(
600 dp_provider->var_device_policy_is_loaded());
601 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
602 const bool* policy_http_downloads_enabled_p = ec->GetValue(
603 dp_provider->var_http_downloads_enabled());
604 http_allowed = (!policy_http_downloads_enabled_p ||
605 *policy_http_downloads_enabled_p);
606 }
607 }
608
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700609 int url_idx = update_state.last_download_url_idx;
610 if (url_idx < 0)
611 url_idx = -1;
612 bool do_advance_url = false;
613 bool is_failure_occurred = false;
614 Time err_time;
615
616 // Scan the relevant part of the download error log, tracking which URLs are
617 // being used, and accounting the number of errors for each URL. Note that
618 // this process may not traverse all errors provided, as it may decide to bail
619 // out midway depending on the particular errors exhibited, the number of
620 // failures allowed, etc. When this ends, |url_idx| will point to the last URL
621 // used (-1 if starting fresh), |do_advance_url| will determine whether the
622 // URL needs to be advanced, and |err_time| the point in time when the last
623 // reported error occurred. Additionally, if the error log indicates that an
624 // update attempt has failed (abnormal), then |is_failure_occurred| will be
625 // set to true.
626 const int num_urls = update_state.download_urls.size();
627 int prev_url_idx = -1;
628 int url_num_errors = update_state.last_download_url_num_errors;
629 Time prev_err_time;
630 bool is_first = true;
631 for (const auto& err_tuple : update_state.download_errors) {
632 // Do some sanity checks.
633 int used_url_idx = get<0>(err_tuple);
634 if (is_first && url_idx >= 0 && used_url_idx != url_idx) {
635 LOG(WARNING) << "First URL in error log (" << used_url_idx
636 << ") not as expected (" << url_idx << ")";
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700637 }
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700638 is_first = false;
639 url_idx = used_url_idx;
640 if (url_idx < 0 || url_idx >= num_urls) {
641 LOG(ERROR) << "Download error log contains an invalid URL index ("
642 << url_idx << ")";
643 return EvalStatus::kFailed;
644 }
645 err_time = get<2>(err_tuple);
646 if (!(prev_err_time.is_null() || err_time >= prev_err_time)) {
647 // TODO(garnold) Monotonicity cannot really be assumed when dealing with
648 // wallclock-based timestamps. However, we're making a simplifying
649 // assumption so as to keep the policy implementation straightforward, for
650 // now. In general, we should convert all timestamp handling in the
651 // UpdateManager to use monotonic time (instead of wallclock), including
652 // the computation of various expiration times (backoff, scattering, etc).
653 // The client will do whatever conversions necessary when
654 // persisting/retrieving these values across reboots. See chromium:408794.
655 LOG(ERROR) << "Download error timestamps not monotonically increasing.";
656 return EvalStatus::kFailed;
657 }
658 prev_err_time = err_time;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700659
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700660 // Ignore errors that happened before the last known failed attempt.
661 if (!update_state.failures_last_updated.is_null() &&
662 err_time <= update_state.failures_last_updated)
663 continue;
664
665 if (prev_url_idx >= 0) {
666 if (url_idx < prev_url_idx) {
667 LOG(ERROR) << "The URLs in the download error log have wrapped around ("
668 << prev_url_idx << "->" << url_idx
669 << "). This should not have happened and means that there's "
670 "a bug. To be conservative, we record a failed attempt "
671 "(invalidating the rest of the error log) and resume "
672 "download from the first usable URL.";
673 url_idx = -1;
674 is_failure_occurred = true;
675 break;
676 }
677
678 if (url_idx > prev_url_idx) {
679 url_num_errors = 0;
680 do_advance_url = false;
681 }
682 }
683
684 if (HandleErrorCode(get<1>(err_tuple), &url_num_errors) ||
685 url_num_errors > update_state.download_errors_max)
686 do_advance_url = true;
687
688 prev_url_idx = url_idx;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700689 }
690
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700691 // If required, advance to the next usable URL. If the URLs wraparound, we
692 // mark an update attempt failure. Also be sure to set the download error
693 // count to zero.
694 if (url_idx < 0 || do_advance_url) {
695 url_num_errors = 0;
696 int start_url_idx = -1;
697 do {
698 if (++url_idx == num_urls) {
699 url_idx = 0;
700 // We only mark failure if an actual advancing of a URL was required.
701 if (do_advance_url)
702 is_failure_occurred = true;
703 }
704
705 if (start_url_idx < 0)
706 start_url_idx = url_idx;
707 else if (url_idx == start_url_idx)
708 url_idx = -1; // No usable URL.
709 } while (url_idx >= 0 &&
710 !IsUrlUsable(update_state.download_urls[url_idx], http_allowed));
711 }
712
713 // If we have a download URL but a failure was observed, compute a new backoff
714 // expiry (if allowed). The backoff period is generally 2 ^ (num_failures - 1)
715 // days, bounded by the size of int and kAttemptBackoffMaxIntervalInDays, and
716 // fuzzed by kAttemptBackoffFuzzInHours hours. Backoff expiry is computed from
717 // the latest recorded time of error.
718 Time backoff_expiry;
719 if (url_idx >= 0 && is_failure_occurred && may_backoff) {
720 CHECK(!err_time.is_null())
721 << "We must have an error timestamp if a failure occurred!";
722 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
723 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
724 PRNG prng(*seed);
Alex Deymof329b932014-10-30 01:37:48 -0700725 int exp = min(update_state.num_failures,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700726 static_cast<int>(sizeof(int)) * 8 - 2);
Amin Hassani186ff6a2018-02-27 11:06:03 -0800727 TimeDelta backoff_interval = TimeDelta::FromDays(min(
728 1 << exp,
729 kNextUpdateCheckPolicyConstants.attempt_backoff_max_interval_in_days));
730 TimeDelta backoff_fuzz = TimeDelta::FromHours(
731 kNextUpdateCheckPolicyConstants.attempt_backoff_fuzz_in_hours);
732 TimeDelta wait_period = NextUpdateCheckTimePolicyImpl::FuzzedInterval(
733 &prng, backoff_interval.InSeconds(), backoff_fuzz.InSeconds());
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700734 backoff_expiry = err_time + wait_period;
735
736 // If the newly computed backoff already expired, nullify it.
737 if (ec->IsWallclockTimeGreaterThan(backoff_expiry))
738 backoff_expiry = Time();
739 }
740
741 result->do_increment_failures = is_failure_occurred;
742 result->backoff_expiry = backoff_expiry;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700743 result->url_idx = url_idx;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700744 result->url_num_errors = url_num_errors;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700745 return EvalStatus::kSucceeded;
746}
747
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700748EvalStatus ChromeOSPolicy::UpdateScattering(
749 EvaluationContext* ec,
750 State* state,
751 string* error,
752 UpdateScatteringResult* result,
753 const UpdateState& update_state) const {
754 // Preconditions. These stem from the postconditions and usage contract.
755 DCHECK(update_state.scatter_wait_period >= kZeroInterval);
756 DCHECK_GE(update_state.scatter_check_threshold, 0);
757
758 // Set default result values.
759 result->is_scattering = false;
760 result->wait_period = kZeroInterval;
761 result->check_threshold = 0;
762
763 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
764
765 // Ensure that a device policy is loaded.
766 const bool* device_policy_is_loaded_p = ec->GetValue(
767 dp_provider->var_device_policy_is_loaded());
768 if (!(device_policy_is_loaded_p && *device_policy_is_loaded_p))
769 return EvalStatus::kSucceeded;
770
771 // Is scattering enabled by policy?
772 const TimeDelta* scatter_factor_p = ec->GetValue(
773 dp_provider->var_scatter_factor());
774 if (!scatter_factor_p || *scatter_factor_p == kZeroInterval)
775 return EvalStatus::kSucceeded;
776
777 // Obtain a pseudo-random number generator.
778 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
779 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
780 PRNG prng(*seed);
781
782 // Step 1: Maintain the scattering wait period.
783 //
784 // If no wait period was previously determined, or it no longer fits in the
785 // scatter factor, then generate a new one. Otherwise, keep the one we have.
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700786 TimeDelta wait_period = update_state.scatter_wait_period;
787 if (wait_period == kZeroInterval || wait_period > *scatter_factor_p) {
788 wait_period = TimeDelta::FromSeconds(
789 prng.RandMinMax(1, scatter_factor_p->InSeconds()));
790 }
791
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700792 // If we surpassed the wait period or the max scatter period associated with
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700793 // the update, then no wait is needed.
794 Time wait_expires = (update_state.first_seen +
795 min(wait_period, update_state.scatter_wait_period_max));
Gilad Arnolda65fced2014-07-23 09:01:31 -0700796 if (ec->IsWallclockTimeGreaterThan(wait_expires))
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700797 wait_period = kZeroInterval;
798
799 // Step 2: Maintain the update check threshold count.
800 //
801 // If an update check threshold is not specified then generate a new
802 // one.
803 int check_threshold = update_state.scatter_check_threshold;
804 if (check_threshold == 0) {
805 check_threshold = prng.RandMinMax(
806 update_state.scatter_check_threshold_min,
807 update_state.scatter_check_threshold_max);
808 }
809
810 // If the update check threshold is not within allowed range then nullify it.
811 // TODO(garnold) This is compliant with current logic found in
812 // OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied(). We may want
813 // to change it so that it behaves similarly to the wait period case, namely
814 // if the current value exceeds the maximum, we set a new one within range.
815 if (check_threshold > update_state.scatter_check_threshold_max)
816 check_threshold = 0;
817
818 // If the update check threshold is non-zero and satisfied, then nullify it.
819 if (check_threshold > 0 && update_state.num_checks >= check_threshold)
820 check_threshold = 0;
821
822 bool is_scattering = (wait_period != kZeroInterval || check_threshold);
823 EvalStatus ret = EvalStatus::kSucceeded;
824 if (is_scattering && wait_period == update_state.scatter_wait_period &&
825 check_threshold == update_state.scatter_check_threshold)
826 ret = EvalStatus::kAskMeAgainLater;
827 result->is_scattering = is_scattering;
828 result->wait_period = wait_period;
829 result->check_threshold = check_threshold;
830 return ret;
831}
832
Alex Deymo63784a52014-05-28 10:46:14 -0700833} // namespace chromeos_update_manager