blob: 655ec820e24d617eb20701343486a540d019faac [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:
Sen Jiang3978ddd2018-03-22 18:05:44 -0700146 case ErrorCode::kNoUpdate:
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700147 LOG(INFO) << "Not changing URL index or failure count due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800148 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700149 << " (" << static_cast<int>(err_code) << ")";
150 return false;
151
152 case ErrorCode::kSuccess: // success code
153 case ErrorCode::kUmaReportedMax: // not an error code
154 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800155 case ErrorCode::kDevModeFlag: // not an error code
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700156 case ErrorCode::kResumedFlag: // not an error code
157 case ErrorCode::kTestImageFlag: // not an error code
158 case ErrorCode::kTestOmahaUrlFlag: // not an error code
159 case ErrorCode::kSpecialFlags: // not an error code
160 // These shouldn't happen. Enumerating these explicitly here so that we
161 // can let the compiler warn about new error codes that are added to
162 // action_processor.h but not added here.
163 LOG(WARNING) << "Unexpected error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800164 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700165 << " (" << static_cast<int>(err_code) << ")";
166 // Note: Not adding a default here so as to let the compiler warn us of
167 // any new enums that were added in the .h but not listed in this switch.
168 }
169 return false;
170}
171
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700172// Checks whether |url| can be used under given download restrictions.
173bool IsUrlUsable(const string& url, bool http_allowed) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800174 return http_allowed ||
175 !base::StartsWith(url, "http://",
176 base::CompareCase::INSENSITIVE_ASCII);
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700177}
178
179} // namespace
180
Alex Deymo63784a52014-05-28 10:46:14 -0700181namespace chromeos_update_manager {
Alex Deymoc705cc82014-02-19 11:15:00 -0800182
Amin Hassani186ff6a2018-02-27 11:06:03 -0800183const NextUpdateCheckPolicyConstants
184 ChromeOSPolicy::kNextUpdateCheckPolicyConstants = {
185 .timeout_initial_interval = 7 * 60,
186 .timeout_periodic_interval = 45 * 60,
187 .timeout_max_backoff_interval = 4 * 60 * 60,
188 .timeout_regular_fuzz = 10 * 60,
189 .attempt_backoff_max_interval_in_days = 16,
190 .attempt_backoff_fuzz_in_hours = 12,
191};
Alex Deymo14e7dde2015-10-20 14:46:33 -0700192
Gilad Arnold349ac832014-10-06 14:20:28 -0700193const int ChromeOSPolicy::kMaxP2PAttempts = 10;
194const int ChromeOSPolicy::kMaxP2PAttemptsPeriodInSeconds = 5 * 24 * 60 * 60;
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700195
Alex Deymo0d11c602014-04-23 20:12:20 -0700196EvalStatus ChromeOSPolicy::UpdateCheckAllowed(
197 EvaluationContext* ec, State* state, string* error,
198 UpdateCheckParams* result) const {
Gilad Arnold42f253b2014-06-25 12:39:17 -0700199 // Set the default return values.
200 result->updates_enabled = true;
201 result->target_channel.clear();
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700202 result->target_version_prefix.clear();
Marton Hunyadyba51c3f2018-04-25 15:18:10 +0200203 result->rollback_allowed = false;
Marton Hunyady0e0e3542018-02-21 18:51:39 +0100204 result->rollback_allowed_milestones = -1;
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700205 result->is_interactive = false;
Gilad Arnold42f253b2014-06-25 12:39:17 -0700206
Amin Hassani186ff6a2018-02-27 11:06:03 -0800207 EnoughSlotsAbUpdatesPolicyImpl enough_slots_ab_updates_policy;
208 EnterpriseDevicePolicyImpl enterprise_device_policy;
209 OnlyUpdateOfficialBuildsPolicyImpl only_update_official_builds_policy;
210 InteractiveUpdatePolicyImpl interactive_update_policy;
211 OobePolicyImpl oobe_policy;
212 NextUpdateCheckTimePolicyImpl next_update_check_time_policy(
213 kNextUpdateCheckPolicyConstants);
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700214
Amin Hassani186ff6a2018-02-27 11:06:03 -0800215 vector<Policy const*> policies_to_consult = {
216 // Do not perform any updates if there are not enough slots to do A/B
217 // updates.
218 &enough_slots_ab_updates_policy,
219
220 // Check to see if Enterprise-managed (has DevicePolicy) and/or
221 // Kiosk-mode. If so, then defer to those settings.
222 &enterprise_device_policy,
223
224 // Check to see if an interactive update was requested.
225 &interactive_update_policy,
226
227 // Unofficial builds should not perform periodic update checks.
228 &only_update_official_builds_policy,
229
230 // If OOBE is enabled, wait until it is completed.
231 &oobe_policy,
232
233 // Ensure that periodic update checks are timed properly.
234 &next_update_check_time_policy,
235 };
236
237 // Now that the list of policy implementations, and the order to consult them,
238 // has been setup, consult the policies. If none of the policies make a
239 // definitive decisions about whether or not to check for updates, then allow
240 // the update check to happen.
241 EvalStatus status = ConsultPolicies(policies_to_consult,
242 &Policy::UpdateCheckAllowed,
243 ec,
244 state,
245 error,
246 result);
247 if (EvalStatus::kContinue != status) {
248 return status;
249 } else {
250 // It is time to check for an update.
251 LOG(INFO) << "Allowing update check.";
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700252 return EvalStatus::kSucceeded;
253 }
Alex Deymoc705cc82014-02-19 11:15:00 -0800254}
255
Aaron Wood23bd3392017-10-06 14:48:25 -0700256EvalStatus ChromeOSPolicy::UpdateCanBeApplied(EvaluationContext* ec,
257 State* state,
258 std::string* error,
259 ErrorCode* result,
260 InstallPlan* install_plan) const {
261 *result = ErrorCode::kSuccess;
262 return EvalStatus::kSucceeded;
263}
264
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700265EvalStatus ChromeOSPolicy::UpdateCanStart(
266 EvaluationContext* ec,
267 State* state,
268 string* error,
Gilad Arnold42f253b2014-06-25 12:39:17 -0700269 UpdateDownloadParams* result,
Gilad Arnoldd78caf92014-09-24 09:28:14 -0700270 const UpdateState update_state) const {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700271 // Set the default return values. Note that we set persisted values (backoff,
272 // scattering) to the same values presented in the update state. The reason is
273 // that preemptive returns, such as the case where an update check is due,
274 // should not clear off the said values; rather, it is the deliberate
275 // inference of new values that should cause them to be reset.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700276 result->update_can_start = false;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700277 result->cannot_start_reason = UpdateCannotStartReason::kUndefined;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700278 result->download_url_idx = -1;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700279 result->download_url_allowed = true;
280 result->download_url_num_errors = 0;
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700281 result->p2p_downloading_allowed = false;
282 result->p2p_sharing_allowed = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700283 result->do_increment_failures = false;
284 result->backoff_expiry = update_state.backoff_expiry;
285 result->scatter_wait_period = update_state.scatter_wait_period;
286 result->scatter_check_threshold = update_state.scatter_check_threshold;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700287
288 // Make sure that we're not due for an update check.
289 UpdateCheckParams check_result;
290 EvalStatus check_status = UpdateCheckAllowed(ec, state, error, &check_result);
291 if (check_status == EvalStatus::kFailed)
292 return EvalStatus::kFailed;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700293 bool is_check_due = (check_status == EvalStatus::kSucceeded &&
294 check_result.updates_enabled == true);
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700295
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700296 // Check whether backoff applies, and if not then which URL can be used for
297 // downloading. These require scanning the download error log, and so they are
298 // done together.
299 UpdateBackoffAndDownloadUrlResult backoff_url_result;
300 EvalStatus backoff_url_status = UpdateBackoffAndDownloadUrl(
301 ec, state, error, &backoff_url_result, update_state);
Gilad Arnold14a9e702014-10-08 08:09:09 -0700302 if (backoff_url_status == EvalStatus::kFailed)
303 return EvalStatus::kFailed;
304 result->download_url_idx = backoff_url_result.url_idx;
305 result->download_url_num_errors = backoff_url_result.url_num_errors;
306 result->do_increment_failures = backoff_url_result.do_increment_failures;
307 result->backoff_expiry = backoff_url_result.backoff_expiry;
308 bool is_backoff_active =
309 (backoff_url_status == EvalStatus::kAskMeAgainLater) ||
310 !backoff_url_result.backoff_expiry.is_null();
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700311
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700312 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold14a9e702014-10-08 08:09:09 -0700313 bool is_scattering_active = false;
314 EvalStatus scattering_status = EvalStatus::kSucceeded;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700315
316 const bool* device_policy_is_loaded_p = ec->GetValue(
317 dp_provider->var_device_policy_is_loaded());
318 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700319 // Check whether scattering applies to this update attempt. We should not be
320 // scattering if this is an interactive update check, or if OOBE is enabled
321 // but not completed.
322 //
323 // Note: current code further suppresses scattering if a "deadline"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700324 // attribute is found in the Omaha response. However, it appears that the
Gilad Arnold76a11f62014-05-20 09:02:12 -0700325 // presence of this attribute is merely indicative of an OOBE update, during
326 // which we suppress scattering anyway.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700327 bool is_scattering_applicable = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700328 result->scatter_wait_period = kZeroInterval;
329 result->scatter_check_threshold = 0;
330 if (!update_state.is_interactive) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700331 const bool* is_oobe_enabled_p = ec->GetValue(
332 state->config_provider()->var_is_oobe_enabled());
333 if (is_oobe_enabled_p && !(*is_oobe_enabled_p)) {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700334 is_scattering_applicable = true;
Gilad Arnold76a11f62014-05-20 09:02:12 -0700335 } else {
336 const bool* is_oobe_complete_p = ec->GetValue(
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700337 state->system_provider()->var_is_oobe_complete());
Gilad Arnold14a9e702014-10-08 08:09:09 -0700338 is_scattering_applicable = (is_oobe_complete_p && *is_oobe_complete_p);
Gilad Arnold76a11f62014-05-20 09:02:12 -0700339 }
340 }
341
342 // Compute scattering values.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700343 if (is_scattering_applicable) {
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700344 UpdateScatteringResult scatter_result;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700345 scattering_status = UpdateScattering(ec, state, error, &scatter_result,
346 update_state);
347 if (scattering_status == EvalStatus::kFailed) {
348 return EvalStatus::kFailed;
349 } else {
350 result->scatter_wait_period = scatter_result.wait_period;
351 result->scatter_check_threshold = scatter_result.check_threshold;
352 if (scattering_status == EvalStatus::kAskMeAgainLater ||
353 scatter_result.is_scattering)
354 is_scattering_active = true;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700355 }
356 }
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700357 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700358
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700359 // Find out whether P2P is globally enabled.
360 bool p2p_enabled;
361 EvalStatus p2p_enabled_status = P2PEnabled(ec, state, error, &p2p_enabled);
362 if (p2p_enabled_status != EvalStatus::kSucceeded)
363 return EvalStatus::kFailed;
364
365 // Is P2P is enabled, consider allowing it for downloading and/or sharing.
366 if (p2p_enabled) {
367 // Sharing via P2P is allowed if not disabled by Omaha.
368 if (update_state.p2p_sharing_disabled) {
369 LOG(INFO) << "Blocked P2P sharing because it is disabled by Omaha.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700370 } else {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700371 result->p2p_sharing_allowed = true;
Gilad Arnoldef8d0872014-10-03 14:14:06 -0700372 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700373
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700374 // Downloading via P2P is allowed if not disabled by Omaha, an update is not
375 // interactive, and other limits haven't been reached.
376 if (update_state.p2p_downloading_disabled) {
377 LOG(INFO) << "Blocked P2P downloading because it is disabled by Omaha.";
378 } else if (update_state.is_interactive) {
379 LOG(INFO) << "Blocked P2P downloading because update is interactive.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700380 } else if (update_state.p2p_num_attempts >= kMaxP2PAttempts) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700381 LOG(INFO) << "Blocked P2P downloading as it was attempted too many "
382 "times.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700383 } else if (!update_state.p2p_first_attempted.is_null() &&
384 ec->IsWallclockTimeGreaterThan(
385 update_state.p2p_first_attempted +
386 TimeDelta::FromSeconds(kMaxP2PAttemptsPeriodInSeconds))) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700387 LOG(INFO) << "Blocked P2P downloading as its usage timespan exceeds "
388 "limit.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700389 } else {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700390 // P2P download is allowed; if backoff or scattering are active, be sure
391 // to suppress them, yet prevent any download URL from being used.
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700392 result->p2p_downloading_allowed = true;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700393 if (is_backoff_active || is_scattering_active) {
394 is_backoff_active = is_scattering_active = false;
395 result->download_url_allowed = false;
396 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700397 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700398 }
399
Gilad Arnold14a9e702014-10-08 08:09:09 -0700400 // Check for various deterrents.
401 if (is_check_due) {
402 result->cannot_start_reason = UpdateCannotStartReason::kCheckDue;
403 return EvalStatus::kSucceeded;
404 }
405 if (is_backoff_active) {
406 result->cannot_start_reason = UpdateCannotStartReason::kBackoff;
407 return backoff_url_status;
408 }
409 if (is_scattering_active) {
410 result->cannot_start_reason = UpdateCannotStartReason::kScattering;
411 return scattering_status;
412 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700413 if (result->download_url_idx < 0 && !result->p2p_downloading_allowed) {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700414 result->cannot_start_reason = UpdateCannotStartReason::kCannotDownload;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700415 return EvalStatus::kSucceeded;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700416 }
417
Gilad Arnold14a9e702014-10-08 08:09:09 -0700418 // Update is good to go.
419 result->update_can_start = true;
Gilad Arnoldaf2f6ae2014-04-28 14:14:52 -0700420 return EvalStatus::kSucceeded;
421}
422
Gilad Arnolda8262e22014-06-02 13:54:27 -0700423// TODO(garnold) Logic in this method is based on
424// ConnectionManager::IsUpdateAllowedOver(); be sure to deprecate the latter.
425//
426// TODO(garnold) The current logic generally treats the list of allowed
427// connections coming from the device policy as a whitelist, meaning that it
428// can only be used for enabling connections, but not disable them. Further,
429// certain connection types (like Bluetooth) cannot be enabled even by policy.
430// In effect, the only thing that device policy can change is to enable
431// updates over a cellular network (disabled by default). We may want to
432// revisit this semantics, allowing greater flexibility in defining specific
433// permissions over all types of networks.
Gilad Arnold684219d2014-07-07 14:54:57 -0700434EvalStatus ChromeOSPolicy::UpdateDownloadAllowed(
Gilad Arnolda8262e22014-06-02 13:54:27 -0700435 EvaluationContext* ec,
436 State* state,
437 string* error,
438 bool* result) const {
439 // Get the current connection type.
440 ShillProvider* const shill_provider = state->shill_provider();
441 const ConnectionType* conn_type_p = ec->GetValue(
442 shill_provider->var_conn_type());
443 POLICY_CHECK_VALUE_AND_FAIL(conn_type_p, error);
444 ConnectionType conn_type = *conn_type_p;
445
446 // If we're tethering, treat it as a cellular connection.
447 if (conn_type != ConnectionType::kCellular) {
448 const ConnectionTethering* conn_tethering_p = ec->GetValue(
449 shill_provider->var_conn_tethering());
450 POLICY_CHECK_VALUE_AND_FAIL(conn_tethering_p, error);
451 if (*conn_tethering_p == ConnectionTethering::kConfirmed)
452 conn_type = ConnectionType::kCellular;
453 }
454
455 // By default, we allow updates for all connection types, with exceptions as
456 // noted below. This also determines whether a device policy can override the
457 // default.
458 *result = true;
459 bool device_policy_can_override = false;
460 switch (conn_type) {
461 case ConnectionType::kBluetooth:
462 *result = false;
463 break;
464
465 case ConnectionType::kCellular:
466 *result = false;
467 device_policy_can_override = true;
468 break;
469
470 case ConnectionType::kUnknown:
471 if (error)
472 *error = "Unknown connection type";
473 return EvalStatus::kFailed;
474
475 default:
476 break; // Nothing to do.
477 }
478
479 // If update is allowed, we're done.
480 if (*result)
481 return EvalStatus::kSucceeded;
482
483 // Check whether the device policy specifically allows this connection.
Gilad Arnolda8262e22014-06-02 13:54:27 -0700484 if (device_policy_can_override) {
485 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
486 const bool* device_policy_is_loaded_p = ec->GetValue(
487 dp_provider->var_device_policy_is_loaded());
488 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
489 const set<ConnectionType>* allowed_conn_types_p = ec->GetValue(
490 dp_provider->var_allowed_connection_types_for_update());
491 if (allowed_conn_types_p) {
492 if (allowed_conn_types_p->count(conn_type)) {
493 *result = true;
494 return EvalStatus::kSucceeded;
495 }
Gilad Arnold28d6be62014-06-30 14:04:04 -0700496 } else if (conn_type == ConnectionType::kCellular) {
497 // Local user settings can allow updates over cellular iff a policy was
498 // loaded but no allowed connections were specified in it.
499 const bool* update_over_cellular_allowed_p = ec->GetValue(
500 state->updater_provider()->var_cellular_enabled());
501 if (update_over_cellular_allowed_p && *update_over_cellular_allowed_p)
502 *result = true;
Gilad Arnolda8262e22014-06-02 13:54:27 -0700503 }
504 }
505 }
506
Gilad Arnold28d6be62014-06-30 14:04:04 -0700507 return (*result ? EvalStatus::kSucceeded : EvalStatus::kAskMeAgainLater);
Gilad Arnolda8262e22014-06-02 13:54:27 -0700508}
509
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700510EvalStatus ChromeOSPolicy::P2PEnabled(EvaluationContext* ec,
511 State* state,
Alex Deymo39910dc2015-11-09 17:04:30 -0800512 string* error,
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700513 bool* result) const {
514 bool enabled = false;
515
516 // Determine whether use of P2P is allowed by policy. Even if P2P is not
517 // explicitly allowed, we allow it if the device is enterprise enrolled (that
518 // is, missing or empty owner string).
519 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
520 const bool* device_policy_is_loaded_p = ec->GetValue(
521 dp_provider->var_device_policy_is_loaded());
522 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
523 const bool* policy_au_p2p_enabled_p = ec->GetValue(
524 dp_provider->var_au_p2p_enabled());
525 if (policy_au_p2p_enabled_p) {
526 enabled = *policy_au_p2p_enabled_p;
527 } else {
528 const string* policy_owner_p = ec->GetValue(dp_provider->var_owner());
529 if (!policy_owner_p || policy_owner_p->empty())
530 enabled = true;
531 }
532 }
533
534 // Enable P2P, if so mandated by the updater configuration. This is additive
535 // to whether or not P2P is enabled by device policy.
536 if (!enabled) {
537 const bool* updater_p2p_enabled_p = ec->GetValue(
538 state->updater_provider()->var_p2p_enabled());
539 enabled = updater_p2p_enabled_p && *updater_p2p_enabled_p;
540 }
541
542 *result = enabled;
543 return EvalStatus::kSucceeded;
544}
545
546EvalStatus ChromeOSPolicy::P2PEnabledChanged(EvaluationContext* ec,
547 State* state,
Alex Deymo39910dc2015-11-09 17:04:30 -0800548 string* error,
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700549 bool* result,
550 bool prev_result) const {
551 EvalStatus status = P2PEnabled(ec, state, error, result);
552 if (status == EvalStatus::kSucceeded && *result == prev_result)
553 return EvalStatus::kAskMeAgainLater;
554 return status;
555}
556
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700557EvalStatus ChromeOSPolicy::UpdateBackoffAndDownloadUrl(
Alex Deymof329b932014-10-30 01:37:48 -0700558 EvaluationContext* ec, State* state, string* error,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700559 UpdateBackoffAndDownloadUrlResult* result,
560 const UpdateState& update_state) const {
561 // Sanity checks.
562 DCHECK_GE(update_state.download_errors_max, 0);
563
564 // Set default result values.
565 result->do_increment_failures = false;
566 result->backoff_expiry = update_state.backoff_expiry;
567 result->url_idx = -1;
568 result->url_num_errors = 0;
569
570 const bool* is_official_build_p = ec->GetValue(
571 state->system_provider()->var_is_official_build());
572 bool is_official_build = (is_official_build_p ? *is_official_build_p : true);
573
574 // Check whether backoff is enabled.
575 bool may_backoff = false;
576 if (update_state.is_backoff_disabled) {
577 LOG(INFO) << "Backoff disabled by Omaha.";
578 } else if (update_state.is_interactive) {
579 LOG(INFO) << "No backoff for interactive updates.";
580 } else if (update_state.is_delta_payload) {
581 LOG(INFO) << "No backoff for delta payloads.";
582 } else if (!is_official_build) {
583 LOG(INFO) << "No backoff for unofficial builds.";
584 } else {
585 may_backoff = true;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700586 }
587
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700588 // If previous backoff still in effect, block.
589 if (may_backoff && !update_state.backoff_expiry.is_null() &&
590 !ec->IsWallclockTimeGreaterThan(update_state.backoff_expiry)) {
591 LOG(INFO) << "Previous backoff has not expired, waiting.";
592 return EvalStatus::kAskMeAgainLater;
593 }
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700594
595 // Determine whether HTTP downloads are forbidden by policy. This only
596 // applies to official system builds; otherwise, HTTP is always enabled.
597 bool http_allowed = true;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700598 if (is_official_build) {
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700599 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
600 const bool* device_policy_is_loaded_p = ec->GetValue(
601 dp_provider->var_device_policy_is_loaded());
602 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
603 const bool* policy_http_downloads_enabled_p = ec->GetValue(
604 dp_provider->var_http_downloads_enabled());
605 http_allowed = (!policy_http_downloads_enabled_p ||
606 *policy_http_downloads_enabled_p);
607 }
608 }
609
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700610 int url_idx = update_state.last_download_url_idx;
611 if (url_idx < 0)
612 url_idx = -1;
613 bool do_advance_url = false;
614 bool is_failure_occurred = false;
615 Time err_time;
616
617 // Scan the relevant part of the download error log, tracking which URLs are
618 // being used, and accounting the number of errors for each URL. Note that
619 // this process may not traverse all errors provided, as it may decide to bail
620 // out midway depending on the particular errors exhibited, the number of
621 // failures allowed, etc. When this ends, |url_idx| will point to the last URL
622 // used (-1 if starting fresh), |do_advance_url| will determine whether the
623 // URL needs to be advanced, and |err_time| the point in time when the last
624 // reported error occurred. Additionally, if the error log indicates that an
625 // update attempt has failed (abnormal), then |is_failure_occurred| will be
626 // set to true.
627 const int num_urls = update_state.download_urls.size();
628 int prev_url_idx = -1;
629 int url_num_errors = update_state.last_download_url_num_errors;
630 Time prev_err_time;
631 bool is_first = true;
632 for (const auto& err_tuple : update_state.download_errors) {
633 // Do some sanity checks.
634 int used_url_idx = get<0>(err_tuple);
635 if (is_first && url_idx >= 0 && used_url_idx != url_idx) {
636 LOG(WARNING) << "First URL in error log (" << used_url_idx
637 << ") not as expected (" << url_idx << ")";
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700638 }
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700639 is_first = false;
640 url_idx = used_url_idx;
641 if (url_idx < 0 || url_idx >= num_urls) {
642 LOG(ERROR) << "Download error log contains an invalid URL index ("
643 << url_idx << ")";
644 return EvalStatus::kFailed;
645 }
646 err_time = get<2>(err_tuple);
647 if (!(prev_err_time.is_null() || err_time >= prev_err_time)) {
648 // TODO(garnold) Monotonicity cannot really be assumed when dealing with
649 // wallclock-based timestamps. However, we're making a simplifying
650 // assumption so as to keep the policy implementation straightforward, for
651 // now. In general, we should convert all timestamp handling in the
652 // UpdateManager to use monotonic time (instead of wallclock), including
653 // the computation of various expiration times (backoff, scattering, etc).
654 // The client will do whatever conversions necessary when
655 // persisting/retrieving these values across reboots. See chromium:408794.
656 LOG(ERROR) << "Download error timestamps not monotonically increasing.";
657 return EvalStatus::kFailed;
658 }
659 prev_err_time = err_time;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700660
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700661 // Ignore errors that happened before the last known failed attempt.
662 if (!update_state.failures_last_updated.is_null() &&
663 err_time <= update_state.failures_last_updated)
664 continue;
665
666 if (prev_url_idx >= 0) {
667 if (url_idx < prev_url_idx) {
668 LOG(ERROR) << "The URLs in the download error log have wrapped around ("
669 << prev_url_idx << "->" << url_idx
670 << "). This should not have happened and means that there's "
671 "a bug. To be conservative, we record a failed attempt "
672 "(invalidating the rest of the error log) and resume "
673 "download from the first usable URL.";
674 url_idx = -1;
675 is_failure_occurred = true;
676 break;
677 }
678
679 if (url_idx > prev_url_idx) {
680 url_num_errors = 0;
681 do_advance_url = false;
682 }
683 }
684
685 if (HandleErrorCode(get<1>(err_tuple), &url_num_errors) ||
686 url_num_errors > update_state.download_errors_max)
687 do_advance_url = true;
688
689 prev_url_idx = url_idx;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700690 }
691
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700692 // If required, advance to the next usable URL. If the URLs wraparound, we
693 // mark an update attempt failure. Also be sure to set the download error
694 // count to zero.
695 if (url_idx < 0 || do_advance_url) {
696 url_num_errors = 0;
697 int start_url_idx = -1;
698 do {
699 if (++url_idx == num_urls) {
700 url_idx = 0;
701 // We only mark failure if an actual advancing of a URL was required.
702 if (do_advance_url)
703 is_failure_occurred = true;
704 }
705
706 if (start_url_idx < 0)
707 start_url_idx = url_idx;
708 else if (url_idx == start_url_idx)
709 url_idx = -1; // No usable URL.
710 } while (url_idx >= 0 &&
711 !IsUrlUsable(update_state.download_urls[url_idx], http_allowed));
712 }
713
714 // If we have a download URL but a failure was observed, compute a new backoff
715 // expiry (if allowed). The backoff period is generally 2 ^ (num_failures - 1)
716 // days, bounded by the size of int and kAttemptBackoffMaxIntervalInDays, and
717 // fuzzed by kAttemptBackoffFuzzInHours hours. Backoff expiry is computed from
718 // the latest recorded time of error.
719 Time backoff_expiry;
720 if (url_idx >= 0 && is_failure_occurred && may_backoff) {
721 CHECK(!err_time.is_null())
722 << "We must have an error timestamp if a failure occurred!";
723 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
724 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
725 PRNG prng(*seed);
Alex Deymof329b932014-10-30 01:37:48 -0700726 int exp = min(update_state.num_failures,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700727 static_cast<int>(sizeof(int)) * 8 - 2);
Amin Hassani186ff6a2018-02-27 11:06:03 -0800728 TimeDelta backoff_interval = TimeDelta::FromDays(min(
729 1 << exp,
730 kNextUpdateCheckPolicyConstants.attempt_backoff_max_interval_in_days));
731 TimeDelta backoff_fuzz = TimeDelta::FromHours(
732 kNextUpdateCheckPolicyConstants.attempt_backoff_fuzz_in_hours);
733 TimeDelta wait_period = NextUpdateCheckTimePolicyImpl::FuzzedInterval(
734 &prng, backoff_interval.InSeconds(), backoff_fuzz.InSeconds());
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700735 backoff_expiry = err_time + wait_period;
736
737 // If the newly computed backoff already expired, nullify it.
738 if (ec->IsWallclockTimeGreaterThan(backoff_expiry))
739 backoff_expiry = Time();
740 }
741
742 result->do_increment_failures = is_failure_occurred;
743 result->backoff_expiry = backoff_expiry;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700744 result->url_idx = url_idx;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700745 result->url_num_errors = url_num_errors;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700746 return EvalStatus::kSucceeded;
747}
748
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700749EvalStatus ChromeOSPolicy::UpdateScattering(
750 EvaluationContext* ec,
751 State* state,
752 string* error,
753 UpdateScatteringResult* result,
754 const UpdateState& update_state) const {
755 // Preconditions. These stem from the postconditions and usage contract.
756 DCHECK(update_state.scatter_wait_period >= kZeroInterval);
757 DCHECK_GE(update_state.scatter_check_threshold, 0);
758
759 // Set default result values.
760 result->is_scattering = false;
761 result->wait_period = kZeroInterval;
762 result->check_threshold = 0;
763
764 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
765
766 // Ensure that a device policy is loaded.
767 const bool* device_policy_is_loaded_p = ec->GetValue(
768 dp_provider->var_device_policy_is_loaded());
769 if (!(device_policy_is_loaded_p && *device_policy_is_loaded_p))
770 return EvalStatus::kSucceeded;
771
772 // Is scattering enabled by policy?
773 const TimeDelta* scatter_factor_p = ec->GetValue(
774 dp_provider->var_scatter_factor());
775 if (!scatter_factor_p || *scatter_factor_p == kZeroInterval)
776 return EvalStatus::kSucceeded;
777
778 // Obtain a pseudo-random number generator.
779 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
780 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
781 PRNG prng(*seed);
782
783 // Step 1: Maintain the scattering wait period.
784 //
785 // If no wait period was previously determined, or it no longer fits in the
786 // scatter factor, then generate a new one. Otherwise, keep the one we have.
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700787 TimeDelta wait_period = update_state.scatter_wait_period;
788 if (wait_period == kZeroInterval || wait_period > *scatter_factor_p) {
789 wait_period = TimeDelta::FromSeconds(
790 prng.RandMinMax(1, scatter_factor_p->InSeconds()));
791 }
792
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700793 // If we surpassed the wait period or the max scatter period associated with
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700794 // the update, then no wait is needed.
795 Time wait_expires = (update_state.first_seen +
796 min(wait_period, update_state.scatter_wait_period_max));
Gilad Arnolda65fced2014-07-23 09:01:31 -0700797 if (ec->IsWallclockTimeGreaterThan(wait_expires))
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700798 wait_period = kZeroInterval;
799
800 // Step 2: Maintain the update check threshold count.
801 //
802 // If an update check threshold is not specified then generate a new
803 // one.
804 int check_threshold = update_state.scatter_check_threshold;
805 if (check_threshold == 0) {
806 check_threshold = prng.RandMinMax(
807 update_state.scatter_check_threshold_min,
808 update_state.scatter_check_threshold_max);
809 }
810
811 // If the update check threshold is not within allowed range then nullify it.
812 // TODO(garnold) This is compliant with current logic found in
813 // OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied(). We may want
814 // to change it so that it behaves similarly to the wait period case, namely
815 // if the current value exceeds the maximum, we set a new one within range.
816 if (check_threshold > update_state.scatter_check_threshold_max)
817 check_threshold = 0;
818
819 // If the update check threshold is non-zero and satisfied, then nullify it.
820 if (check_threshold > 0 && update_state.num_checks >= check_threshold)
821 check_threshold = 0;
822
823 bool is_scattering = (wait_period != kZeroInterval || check_threshold);
824 EvalStatus ret = EvalStatus::kSucceeded;
825 if (is_scattering && wait_period == update_state.scatter_wait_period &&
826 check_threshold == update_state.scatter_check_threshold)
827 ret = EvalStatus::kAskMeAgainLater;
828 result->is_scattering = is_scattering;
829 result->wait_period = wait_period;
830 result->check_threshold = check_threshold;
831 return ret;
832}
833
Alex Deymo63784a52014-05-28 10:46:14 -0700834} // namespace chromeos_update_manager