blob: 12f417c1d987b7266e5e8c25afdeae6f2566497a [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>
22
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070023#include <base/logging.h>
Gilad Arnoldb3b05442014-05-30 14:25:05 -070024#include <base/strings/string_util.h>
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070025#include <base/time/time.h>
26
Alex Deymo39910dc2015-11-09 17:04:30 -080027#include "update_engine/common/error_code.h"
Alex Deymoe88e9fe2016-02-03 16:38:00 -080028#include "update_engine/common/error_code_utils.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080029#include "update_engine/common/utils.h"
Alex Deymo63784a52014-05-28 10:46:14 -070030#include "update_engine/update_manager/device_policy_provider.h"
31#include "update_engine/update_manager/policy_utils.h"
32#include "update_engine/update_manager/shill_provider.h"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070033
Alex Deymo0d11c602014-04-23 20:12:20 -070034using base::Time;
35using base::TimeDelta;
Sen Jiang255e22b2016-05-20 16:15:29 -070036using chromeos_update_engine::ConnectionTethering;
37using chromeos_update_engine::ConnectionType;
Gilad Arnoldb3b05442014-05-30 14:25:05 -070038using chromeos_update_engine::ErrorCode;
Aaron Wood23bd3392017-10-06 14:48:25 -070039using chromeos_update_engine::InstallPlan;
Gilad Arnolddc4bb262014-07-23 10:45:19 -070040using std::get;
Gilad Arnoldb3b05442014-05-30 14:25:05 -070041using std::max;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070042using std::min;
Gilad Arnold0adbc942014-05-12 10:35:43 -070043using std::set;
Alex Deymoc705cc82014-02-19 11:15:00 -080044using std::string;
45
Gilad Arnoldb3b05442014-05-30 14:25:05 -070046namespace {
47
Gilad Arnolddc4bb262014-07-23 10:45:19 -070048// Examines |err_code| and decides whether the URL index needs to be advanced,
49// the error count for the URL incremented, or none of the above. In the first
50// case, returns true; in the second case, increments |*url_num_error_p| and
51// returns false; otherwise just returns false.
Gilad Arnoldb3b05442014-05-30 14:25:05 -070052//
53// TODO(garnold) Adapted from PayloadState::UpdateFailed() (to be retired).
Gilad Arnolddc4bb262014-07-23 10:45:19 -070054bool HandleErrorCode(ErrorCode err_code, int* url_num_error_p) {
Gilad Arnoldb3b05442014-05-30 14:25:05 -070055 err_code = chromeos_update_engine::utils::GetBaseErrorCode(err_code);
56 switch (err_code) {
57 // Errors which are good indicators of a problem with a particular URL or
58 // the protocol used in the URL or entities in the communication channel
59 // (e.g. proxies). We should try the next available URL in the next update
60 // check to quickly recover from these errors.
61 case ErrorCode::kPayloadHashMismatchError:
62 case ErrorCode::kPayloadSizeMismatchError:
63 case ErrorCode::kDownloadPayloadVerificationError:
64 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
65 case ErrorCode::kSignedDeltaPayloadExpectedError:
66 case ErrorCode::kDownloadInvalidMetadataMagicString:
67 case ErrorCode::kDownloadSignatureMissingInManifest:
68 case ErrorCode::kDownloadManifestParseError:
69 case ErrorCode::kDownloadMetadataSignatureError:
70 case ErrorCode::kDownloadMetadataSignatureVerificationError:
71 case ErrorCode::kDownloadMetadataSignatureMismatch:
72 case ErrorCode::kDownloadOperationHashVerificationError:
73 case ErrorCode::kDownloadOperationExecutionError:
74 case ErrorCode::kDownloadOperationHashMismatch:
75 case ErrorCode::kDownloadInvalidMetadataSize:
76 case ErrorCode::kDownloadInvalidMetadataSignature:
77 case ErrorCode::kDownloadOperationHashMissingError:
78 case ErrorCode::kDownloadMetadataSignatureMissingError:
79 case ErrorCode::kPayloadMismatchedType:
80 case ErrorCode::kUnsupportedMajorPayloadVersion:
81 case ErrorCode::kUnsupportedMinorPayloadVersion:
82 LOG(INFO) << "Advancing download URL due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -080083 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -070084 << " (" << static_cast<int>(err_code) << ")";
Gilad Arnoldb3b05442014-05-30 14:25:05 -070085 return true;
86
87 // Errors which seem to be just transient network/communication related
88 // failures and do not indicate any inherent problem with the URL itself.
89 // So, we should keep the current URL but just increment the
90 // failure count to give it more chances. This way, while we maximize our
91 // chances of downloading from the URLs that appear earlier in the response
92 // (because download from a local server URL that appears earlier in a
93 // response is preferable than downloading from the next URL which could be
Alex Vakulenko072359c2014-07-18 11:41:07 -070094 // an Internet URL and thus could be more expensive).
Gilad Arnoldb3b05442014-05-30 14:25:05 -070095 case ErrorCode::kError:
96 case ErrorCode::kDownloadTransferError:
97 case ErrorCode::kDownloadWriteError:
98 case ErrorCode::kDownloadStateInitializationError:
Gilad Arnold684219d2014-07-07 14:54:57 -070099 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700100 LOG(INFO) << "Incrementing URL failure count due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800101 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700102 << " (" << static_cast<int>(err_code) << ")";
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700103 *url_num_error_p += 1;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700104 return false;
105
106 // Errors which are not specific to a URL and hence shouldn't result in
107 // the URL being penalized. This can happen in two cases:
108 // 1. We haven't started downloading anything: These errors don't cost us
109 // anything in terms of actual payload bytes, so we should just do the
110 // regular retries at the next update check.
111 // 2. We have successfully downloaded the payload: In this case, the
112 // payload attempt number would have been incremented and would take care
Alex Vakulenko072359c2014-07-18 11:41:07 -0700113 // of the back-off at the next update check.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700114 // In either case, there's no need to update URL index or failure count.
115 case ErrorCode::kOmahaRequestError:
116 case ErrorCode::kOmahaResponseHandlerError:
117 case ErrorCode::kPostinstallRunnerError:
118 case ErrorCode::kFilesystemCopierError:
119 case ErrorCode::kInstallDeviceOpenError:
120 case ErrorCode::kKernelDeviceOpenError:
121 case ErrorCode::kDownloadNewPartitionInfoError:
122 case ErrorCode::kNewRootfsVerificationError:
123 case ErrorCode::kNewKernelVerificationError:
124 case ErrorCode::kPostinstallBootedFromFirmwareB:
125 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
126 case ErrorCode::kOmahaRequestEmptyResponseError:
127 case ErrorCode::kOmahaRequestXMLParseError:
128 case ErrorCode::kOmahaResponseInvalid:
129 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
130 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
Kevin Cernekee2494e282016-03-29 18:03:53 -0700131 case ErrorCode::kNonCriticalUpdateInOOBE:
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700132 case ErrorCode::kOmahaUpdateDeferredForBackoff:
133 case ErrorCode::kPostinstallPowerwashError:
134 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400135 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700136 case ErrorCode::kFilesystemVerifierError:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800137 case ErrorCode::kUserCanceled:
Sen Jiang02c49422017-10-31 15:14:11 -0700138 case ErrorCode::kUpdatedButNotActive:
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700139 LOG(INFO) << "Not changing URL index or failure count due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800140 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700141 << " (" << static_cast<int>(err_code) << ")";
142 return false;
143
144 case ErrorCode::kSuccess: // success code
145 case ErrorCode::kUmaReportedMax: // not an error code
146 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800147 case ErrorCode::kDevModeFlag: // not an error code
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700148 case ErrorCode::kResumedFlag: // not an error code
149 case ErrorCode::kTestImageFlag: // not an error code
150 case ErrorCode::kTestOmahaUrlFlag: // not an error code
151 case ErrorCode::kSpecialFlags: // not an error code
152 // These shouldn't happen. Enumerating these explicitly here so that we
153 // can let the compiler warn about new error codes that are added to
154 // action_processor.h but not added here.
155 LOG(WARNING) << "Unexpected error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800156 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700157 << " (" << static_cast<int>(err_code) << ")";
158 // Note: Not adding a default here so as to let the compiler warn us of
159 // any new enums that were added in the .h but not listed in this switch.
160 }
161 return false;
162}
163
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700164// Checks whether |url| can be used under given download restrictions.
165bool IsUrlUsable(const string& url, bool http_allowed) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800166 return http_allowed ||
167 !base::StartsWith(url, "http://",
168 base::CompareCase::INSENSITIVE_ASCII);
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700169}
170
171} // namespace
172
Alex Deymo63784a52014-05-28 10:46:14 -0700173namespace chromeos_update_manager {
Alex Deymoc705cc82014-02-19 11:15:00 -0800174
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700175const int ChromeOSPolicy::kTimeoutInitialInterval = 7 * 60;
Alex Deymo14e7dde2015-10-20 14:46:33 -0700176
177// TODO(deymo): Split the update_manager policies for Brillo and ChromeOS and
178// make the update check periodic interval configurable.
179#ifdef __ANDROID__
180const int ChromeOSPolicy::kTimeoutPeriodicInterval = 5 * 60 * 60;
Alex Deymodbe13b42015-11-06 11:15:08 -0800181const int ChromeOSPolicy::kTimeoutMaxBackoffInterval = 26 * 60 * 60;
Alex Deymo14e7dde2015-10-20 14:46:33 -0700182#else
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700183const int ChromeOSPolicy::kTimeoutPeriodicInterval = 45 * 60;
Alex Deymodbe13b42015-11-06 11:15:08 -0800184const int ChromeOSPolicy::kTimeoutMaxBackoffInterval = 4 * 60 * 60;
Alex Deymo14e7dde2015-10-20 14:46:33 -0700185#endif // __ANDROID__
186
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700187const int ChromeOSPolicy::kTimeoutRegularFuzz = 10 * 60;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700188const int ChromeOSPolicy::kAttemptBackoffMaxIntervalInDays = 16;
189const int ChromeOSPolicy::kAttemptBackoffFuzzInHours = 12;
Gilad Arnold349ac832014-10-06 14:20:28 -0700190const int ChromeOSPolicy::kMaxP2PAttempts = 10;
191const int ChromeOSPolicy::kMaxP2PAttemptsPeriodInSeconds = 5 * 24 * 60 * 60;
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700192
Alex Deymo0d11c602014-04-23 20:12:20 -0700193EvalStatus ChromeOSPolicy::UpdateCheckAllowed(
194 EvaluationContext* ec, State* state, string* error,
195 UpdateCheckParams* result) const {
Gilad Arnold42f253b2014-06-25 12:39:17 -0700196 // Set the default return values.
197 result->updates_enabled = true;
198 result->target_channel.clear();
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700199 result->target_version_prefix.clear();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700200 result->is_interactive = false;
Gilad Arnold42f253b2014-06-25 12:39:17 -0700201
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700202 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700203 UpdaterProvider* const updater_provider = state->updater_provider();
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700204 SystemProvider* const system_provider = state->system_provider();
205
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700206 // Do not perform any updates if booted from removable device. This decision
207 // is final.
Alex Deymo763e7db2015-08-27 21:08:08 -0700208 const unsigned int* num_slots_p = ec->GetValue(
209 system_provider->var_num_slots());
210 if (!num_slots_p || *num_slots_p < 2) {
211 LOG(INFO) << "Not enough slots for A/B updates, disabling update checks.";
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700212 result->updates_enabled = false;
213 return EvalStatus::kSucceeded;
214 }
215
Gilad Arnold42f253b2014-06-25 12:39:17 -0700216 const bool* device_policy_is_loaded_p = ec->GetValue(
217 dp_provider->var_device_policy_is_loaded());
218 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Xiyuan Xia6e30bc52016-02-24 15:35:42 -0800219 bool kiosk_app_control_chrome_version = false;
220
Gilad Arnold42f253b2014-06-25 12:39:17 -0700221 // Check whether updates are disabled by policy.
222 const bool* update_disabled_p = ec->GetValue(
223 dp_provider->var_update_disabled());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700224 if (update_disabled_p && *update_disabled_p) {
Xiyuan Xia6e30bc52016-02-24 15:35:42 -0800225 // Check whether allow kiosk app to control chrome version policy. This
226 // policy is only effective when AU is disabled by admin.
227 const bool* allow_kiosk_app_control_chrome_version_p = ec->GetValue(
228 dp_provider->var_allow_kiosk_app_control_chrome_version());
229 kiosk_app_control_chrome_version =
230 allow_kiosk_app_control_chrome_version_p &&
231 *allow_kiosk_app_control_chrome_version_p;
232 if (!kiosk_app_control_chrome_version) {
233 // No kiosk pin chrome version policy. AU is really disabled.
234 LOG(INFO) << "Updates disabled by policy, blocking update checks.";
235 return EvalStatus::kAskMeAgainLater;
236 }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700237 }
Gilad Arnold42f253b2014-06-25 12:39:17 -0700238
Xiyuan Xia6e30bc52016-02-24 15:35:42 -0800239 if (kiosk_app_control_chrome_version) {
240 // Get the required platform version from Chrome.
241 const string* kiosk_required_platform_version_p =
242 ec->GetValue(system_provider->var_kiosk_required_platform_version());
Xiyuan Xiaed9bd922016-04-07 14:45:16 -0700243 if (!kiosk_required_platform_version_p) {
244 LOG(INFO) << "Kiosk app required platform version is not fetched, "
245 "blocking update checks";
246 return EvalStatus::kAskMeAgainLater;
247 }
248
249 result->target_version_prefix = *kiosk_required_platform_version_p;
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -0800250 LOG(INFO) << "Allow kiosk app to control Chrome version policy is set, "
251 << "target version is "
252 << (!kiosk_required_platform_version_p->empty()
Xiyuan Xia6e30bc52016-02-24 15:35:42 -0800253 ? *kiosk_required_platform_version_p
254 : std::string("latest"));
255 } else {
256 // Determine whether a target version prefix is dictated by policy.
257 const string* target_version_prefix_p = ec->GetValue(
258 dp_provider->var_target_version_prefix());
259 if (target_version_prefix_p)
260 result->target_version_prefix = *target_version_prefix_p;
261 }
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700262
Gilad Arnold42f253b2014-06-25 12:39:17 -0700263 // Determine whether a target channel is dictated by policy.
264 const bool* release_channel_delegated_p = ec->GetValue(
265 dp_provider->var_release_channel_delegated());
266 if (release_channel_delegated_p && !(*release_channel_delegated_p)) {
267 const string* release_channel_p = ec->GetValue(
268 dp_provider->var_release_channel());
269 if (release_channel_p)
270 result->target_channel = *release_channel_p;
271 }
272 }
273
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700274 // First, check to see if an interactive update was requested.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700275 const UpdateRequestStatus* forced_update_requested_p = ec->GetValue(
276 updater_provider->var_forced_update_requested());
277 if (forced_update_requested_p &&
278 *forced_update_requested_p != UpdateRequestStatus::kNone) {
279 result->is_interactive =
280 (*forced_update_requested_p == UpdateRequestStatus::kInteractive);
281 LOG(INFO) << "Forced update signaled ("
282 << (result->is_interactive ? "interactive" : "periodic")
283 << "), allowing update check.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700284 return EvalStatus::kSucceeded;
285 }
286
287 // The logic thereafter applies to periodic updates. Bear in mind that we
288 // should not return a final "no" if any of these criteria are not satisfied,
289 // because the system may still update due to an interactive update request.
290
291 // Unofficial builds should not perform periodic update checks.
292 const bool* is_official_build_p = ec->GetValue(
293 system_provider->var_is_official_build());
294 if (is_official_build_p && !(*is_official_build_p)) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700295 LOG(INFO) << "Unofficial build, blocking periodic update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700296 return EvalStatus::kAskMeAgainLater;
297 }
298
299 // If OOBE is enabled, wait until it is completed.
300 const bool* is_oobe_enabled_p = ec->GetValue(
301 state->config_provider()->var_is_oobe_enabled());
302 if (is_oobe_enabled_p && *is_oobe_enabled_p) {
303 const bool* is_oobe_complete_p = ec->GetValue(
304 system_provider->var_is_oobe_complete());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700305 if (is_oobe_complete_p && !(*is_oobe_complete_p)) {
306 LOG(INFO) << "OOBE not completed, blocking update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700307 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700308 }
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700309 }
310
311 // Ensure that periodic update checks are timed properly.
Alex Deymo0d11c602014-04-23 20:12:20 -0700312 Time next_update_check;
313 if (NextUpdateCheckTime(ec, state, error, &next_update_check) !=
314 EvalStatus::kSucceeded) {
315 return EvalStatus::kFailed;
316 }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700317 if (!ec->IsWallclockTimeGreaterThan(next_update_check)) {
318 LOG(INFO) << "Periodic check interval not satisfied, blocking until "
319 << chromeos_update_engine::utils::ToString(next_update_check);
Alex Deymo0d11c602014-04-23 20:12:20 -0700320 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700321 }
Alex Deymo0d11c602014-04-23 20:12:20 -0700322
323 // It is time to check for an update.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700324 LOG(INFO) << "Allowing update check.";
Alex Deymoe636c3c2014-03-11 19:02:08 -0700325 return EvalStatus::kSucceeded;
Alex Deymoc705cc82014-02-19 11:15:00 -0800326}
327
Aaron Wood23bd3392017-10-06 14:48:25 -0700328EvalStatus ChromeOSPolicy::UpdateCanBeApplied(EvaluationContext* ec,
329 State* state,
330 std::string* error,
331 ErrorCode* result,
332 InstallPlan* install_plan) const {
333 *result = ErrorCode::kSuccess;
334 return EvalStatus::kSucceeded;
335}
336
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700337EvalStatus ChromeOSPolicy::UpdateCanStart(
338 EvaluationContext* ec,
339 State* state,
340 string* error,
Gilad Arnold42f253b2014-06-25 12:39:17 -0700341 UpdateDownloadParams* result,
Gilad Arnoldd78caf92014-09-24 09:28:14 -0700342 const UpdateState update_state) const {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700343 // Set the default return values. Note that we set persisted values (backoff,
344 // scattering) to the same values presented in the update state. The reason is
345 // that preemptive returns, such as the case where an update check is due,
346 // should not clear off the said values; rather, it is the deliberate
347 // inference of new values that should cause them to be reset.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700348 result->update_can_start = false;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700349 result->cannot_start_reason = UpdateCannotStartReason::kUndefined;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700350 result->download_url_idx = -1;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700351 result->download_url_allowed = true;
352 result->download_url_num_errors = 0;
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700353 result->p2p_downloading_allowed = false;
354 result->p2p_sharing_allowed = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700355 result->do_increment_failures = false;
356 result->backoff_expiry = update_state.backoff_expiry;
357 result->scatter_wait_period = update_state.scatter_wait_period;
358 result->scatter_check_threshold = update_state.scatter_check_threshold;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700359
360 // Make sure that we're not due for an update check.
361 UpdateCheckParams check_result;
362 EvalStatus check_status = UpdateCheckAllowed(ec, state, error, &check_result);
363 if (check_status == EvalStatus::kFailed)
364 return EvalStatus::kFailed;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700365 bool is_check_due = (check_status == EvalStatus::kSucceeded &&
366 check_result.updates_enabled == true);
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700367
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700368 // Check whether backoff applies, and if not then which URL can be used for
369 // downloading. These require scanning the download error log, and so they are
370 // done together.
371 UpdateBackoffAndDownloadUrlResult backoff_url_result;
372 EvalStatus backoff_url_status = UpdateBackoffAndDownloadUrl(
373 ec, state, error, &backoff_url_result, update_state);
Gilad Arnold14a9e702014-10-08 08:09:09 -0700374 if (backoff_url_status == EvalStatus::kFailed)
375 return EvalStatus::kFailed;
376 result->download_url_idx = backoff_url_result.url_idx;
377 result->download_url_num_errors = backoff_url_result.url_num_errors;
378 result->do_increment_failures = backoff_url_result.do_increment_failures;
379 result->backoff_expiry = backoff_url_result.backoff_expiry;
380 bool is_backoff_active =
381 (backoff_url_status == EvalStatus::kAskMeAgainLater) ||
382 !backoff_url_result.backoff_expiry.is_null();
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700383
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700384 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold14a9e702014-10-08 08:09:09 -0700385 bool is_scattering_active = false;
386 EvalStatus scattering_status = EvalStatus::kSucceeded;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700387
388 const bool* device_policy_is_loaded_p = ec->GetValue(
389 dp_provider->var_device_policy_is_loaded());
390 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700391 // Check whether scattering applies to this update attempt. We should not be
392 // scattering if this is an interactive update check, or if OOBE is enabled
393 // but not completed.
394 //
395 // Note: current code further suppresses scattering if a "deadline"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700396 // attribute is found in the Omaha response. However, it appears that the
Gilad Arnold76a11f62014-05-20 09:02:12 -0700397 // presence of this attribute is merely indicative of an OOBE update, during
398 // which we suppress scattering anyway.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700399 bool is_scattering_applicable = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700400 result->scatter_wait_period = kZeroInterval;
401 result->scatter_check_threshold = 0;
402 if (!update_state.is_interactive) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700403 const bool* is_oobe_enabled_p = ec->GetValue(
404 state->config_provider()->var_is_oobe_enabled());
405 if (is_oobe_enabled_p && !(*is_oobe_enabled_p)) {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700406 is_scattering_applicable = true;
Gilad Arnold76a11f62014-05-20 09:02:12 -0700407 } else {
408 const bool* is_oobe_complete_p = ec->GetValue(
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700409 state->system_provider()->var_is_oobe_complete());
Gilad Arnold14a9e702014-10-08 08:09:09 -0700410 is_scattering_applicable = (is_oobe_complete_p && *is_oobe_complete_p);
Gilad Arnold76a11f62014-05-20 09:02:12 -0700411 }
412 }
413
414 // Compute scattering values.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700415 if (is_scattering_applicable) {
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700416 UpdateScatteringResult scatter_result;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700417 scattering_status = UpdateScattering(ec, state, error, &scatter_result,
418 update_state);
419 if (scattering_status == EvalStatus::kFailed) {
420 return EvalStatus::kFailed;
421 } else {
422 result->scatter_wait_period = scatter_result.wait_period;
423 result->scatter_check_threshold = scatter_result.check_threshold;
424 if (scattering_status == EvalStatus::kAskMeAgainLater ||
425 scatter_result.is_scattering)
426 is_scattering_active = true;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700427 }
428 }
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700429 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700430
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700431 // Find out whether P2P is globally enabled.
432 bool p2p_enabled;
433 EvalStatus p2p_enabled_status = P2PEnabled(ec, state, error, &p2p_enabled);
434 if (p2p_enabled_status != EvalStatus::kSucceeded)
435 return EvalStatus::kFailed;
436
437 // Is P2P is enabled, consider allowing it for downloading and/or sharing.
438 if (p2p_enabled) {
439 // Sharing via P2P is allowed if not disabled by Omaha.
440 if (update_state.p2p_sharing_disabled) {
441 LOG(INFO) << "Blocked P2P sharing because it is disabled by Omaha.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700442 } else {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700443 result->p2p_sharing_allowed = true;
Gilad Arnoldef8d0872014-10-03 14:14:06 -0700444 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700445
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700446 // Downloading via P2P is allowed if not disabled by Omaha, an update is not
447 // interactive, and other limits haven't been reached.
448 if (update_state.p2p_downloading_disabled) {
449 LOG(INFO) << "Blocked P2P downloading because it is disabled by Omaha.";
450 } else if (update_state.is_interactive) {
451 LOG(INFO) << "Blocked P2P downloading because update is interactive.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700452 } else if (update_state.p2p_num_attempts >= kMaxP2PAttempts) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700453 LOG(INFO) << "Blocked P2P downloading as it was attempted too many "
454 "times.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700455 } else if (!update_state.p2p_first_attempted.is_null() &&
456 ec->IsWallclockTimeGreaterThan(
457 update_state.p2p_first_attempted +
458 TimeDelta::FromSeconds(kMaxP2PAttemptsPeriodInSeconds))) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700459 LOG(INFO) << "Blocked P2P downloading as its usage timespan exceeds "
460 "limit.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700461 } else {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700462 // P2P download is allowed; if backoff or scattering are active, be sure
463 // to suppress them, yet prevent any download URL from being used.
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700464 result->p2p_downloading_allowed = true;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700465 if (is_backoff_active || is_scattering_active) {
466 is_backoff_active = is_scattering_active = false;
467 result->download_url_allowed = false;
468 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700469 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700470 }
471
Gilad Arnold14a9e702014-10-08 08:09:09 -0700472 // Check for various deterrents.
473 if (is_check_due) {
474 result->cannot_start_reason = UpdateCannotStartReason::kCheckDue;
475 return EvalStatus::kSucceeded;
476 }
477 if (is_backoff_active) {
478 result->cannot_start_reason = UpdateCannotStartReason::kBackoff;
479 return backoff_url_status;
480 }
481 if (is_scattering_active) {
482 result->cannot_start_reason = UpdateCannotStartReason::kScattering;
483 return scattering_status;
484 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700485 if (result->download_url_idx < 0 && !result->p2p_downloading_allowed) {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700486 result->cannot_start_reason = UpdateCannotStartReason::kCannotDownload;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700487 return EvalStatus::kSucceeded;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700488 }
489
Gilad Arnold14a9e702014-10-08 08:09:09 -0700490 // Update is good to go.
491 result->update_can_start = true;
Gilad Arnoldaf2f6ae2014-04-28 14:14:52 -0700492 return EvalStatus::kSucceeded;
493}
494
Gilad Arnolda8262e22014-06-02 13:54:27 -0700495// TODO(garnold) Logic in this method is based on
496// ConnectionManager::IsUpdateAllowedOver(); be sure to deprecate the latter.
497//
498// TODO(garnold) The current logic generally treats the list of allowed
499// connections coming from the device policy as a whitelist, meaning that it
500// can only be used for enabling connections, but not disable them. Further,
501// certain connection types (like Bluetooth) cannot be enabled even by policy.
502// In effect, the only thing that device policy can change is to enable
503// updates over a cellular network (disabled by default). We may want to
504// revisit this semantics, allowing greater flexibility in defining specific
505// permissions over all types of networks.
Gilad Arnold684219d2014-07-07 14:54:57 -0700506EvalStatus ChromeOSPolicy::UpdateDownloadAllowed(
Gilad Arnolda8262e22014-06-02 13:54:27 -0700507 EvaluationContext* ec,
508 State* state,
509 string* error,
510 bool* result) const {
511 // Get the current connection type.
512 ShillProvider* const shill_provider = state->shill_provider();
513 const ConnectionType* conn_type_p = ec->GetValue(
514 shill_provider->var_conn_type());
515 POLICY_CHECK_VALUE_AND_FAIL(conn_type_p, error);
516 ConnectionType conn_type = *conn_type_p;
517
518 // If we're tethering, treat it as a cellular connection.
519 if (conn_type != ConnectionType::kCellular) {
520 const ConnectionTethering* conn_tethering_p = ec->GetValue(
521 shill_provider->var_conn_tethering());
522 POLICY_CHECK_VALUE_AND_FAIL(conn_tethering_p, error);
523 if (*conn_tethering_p == ConnectionTethering::kConfirmed)
524 conn_type = ConnectionType::kCellular;
525 }
526
527 // By default, we allow updates for all connection types, with exceptions as
528 // noted below. This also determines whether a device policy can override the
529 // default.
530 *result = true;
531 bool device_policy_can_override = false;
532 switch (conn_type) {
533 case ConnectionType::kBluetooth:
534 *result = false;
535 break;
536
537 case ConnectionType::kCellular:
538 *result = false;
539 device_policy_can_override = true;
540 break;
541
542 case ConnectionType::kUnknown:
543 if (error)
544 *error = "Unknown connection type";
545 return EvalStatus::kFailed;
546
547 default:
548 break; // Nothing to do.
549 }
550
551 // If update is allowed, we're done.
552 if (*result)
553 return EvalStatus::kSucceeded;
554
555 // Check whether the device policy specifically allows this connection.
Gilad Arnolda8262e22014-06-02 13:54:27 -0700556 if (device_policy_can_override) {
557 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
558 const bool* device_policy_is_loaded_p = ec->GetValue(
559 dp_provider->var_device_policy_is_loaded());
560 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
561 const set<ConnectionType>* allowed_conn_types_p = ec->GetValue(
562 dp_provider->var_allowed_connection_types_for_update());
563 if (allowed_conn_types_p) {
564 if (allowed_conn_types_p->count(conn_type)) {
565 *result = true;
566 return EvalStatus::kSucceeded;
567 }
Gilad Arnold28d6be62014-06-30 14:04:04 -0700568 } else if (conn_type == ConnectionType::kCellular) {
569 // Local user settings can allow updates over cellular iff a policy was
570 // loaded but no allowed connections were specified in it.
571 const bool* update_over_cellular_allowed_p = ec->GetValue(
572 state->updater_provider()->var_cellular_enabled());
573 if (update_over_cellular_allowed_p && *update_over_cellular_allowed_p)
574 *result = true;
Gilad Arnolda8262e22014-06-02 13:54:27 -0700575 }
576 }
577 }
578
Gilad Arnold28d6be62014-06-30 14:04:04 -0700579 return (*result ? EvalStatus::kSucceeded : EvalStatus::kAskMeAgainLater);
Gilad Arnolda8262e22014-06-02 13:54:27 -0700580}
581
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700582EvalStatus ChromeOSPolicy::P2PEnabled(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) const {
586 bool enabled = false;
587
588 // Determine whether use of P2P is allowed by policy. Even if P2P is not
589 // explicitly allowed, we allow it if the device is enterprise enrolled (that
590 // is, missing or empty owner string).
591 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
592 const bool* device_policy_is_loaded_p = ec->GetValue(
593 dp_provider->var_device_policy_is_loaded());
594 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
595 const bool* policy_au_p2p_enabled_p = ec->GetValue(
596 dp_provider->var_au_p2p_enabled());
597 if (policy_au_p2p_enabled_p) {
598 enabled = *policy_au_p2p_enabled_p;
599 } else {
600 const string* policy_owner_p = ec->GetValue(dp_provider->var_owner());
601 if (!policy_owner_p || policy_owner_p->empty())
602 enabled = true;
603 }
604 }
605
606 // Enable P2P, if so mandated by the updater configuration. This is additive
607 // to whether or not P2P is enabled by device policy.
608 if (!enabled) {
609 const bool* updater_p2p_enabled_p = ec->GetValue(
610 state->updater_provider()->var_p2p_enabled());
611 enabled = updater_p2p_enabled_p && *updater_p2p_enabled_p;
612 }
613
614 *result = enabled;
615 return EvalStatus::kSucceeded;
616}
617
618EvalStatus ChromeOSPolicy::P2PEnabledChanged(EvaluationContext* ec,
619 State* state,
Alex Deymo39910dc2015-11-09 17:04:30 -0800620 string* error,
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700621 bool* result,
622 bool prev_result) const {
623 EvalStatus status = P2PEnabled(ec, state, error, result);
624 if (status == EvalStatus::kSucceeded && *result == prev_result)
625 return EvalStatus::kAskMeAgainLater;
626 return status;
627}
628
Alex Deymo0d11c602014-04-23 20:12:20 -0700629EvalStatus ChromeOSPolicy::NextUpdateCheckTime(EvaluationContext* ec,
630 State* state, string* error,
631 Time* next_update_check) const {
Gilad Arnolda0258a52014-07-10 16:21:19 -0700632 UpdaterProvider* const updater_provider = state->updater_provider();
633
Alex Deymo0d11c602014-04-23 20:12:20 -0700634 // Don't check for updates too often. We limit the update checks to once every
635 // some interval. The interval is kTimeoutInitialInterval the first time and
636 // kTimeoutPeriodicInterval for the subsequent update checks. If the update
637 // check fails, we increase the interval between the update checks
638 // exponentially until kTimeoutMaxBackoffInterval. Finally, to avoid having
639 // many chromebooks running update checks at the exact same time, we add some
640 // fuzz to the interval.
641 const Time* updater_started_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700642 ec->GetValue(updater_provider->var_updater_started_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700643 POLICY_CHECK_VALUE_AND_FAIL(updater_started_time, error);
644
Alex Deymof329b932014-10-30 01:37:48 -0700645 const Time* last_checked_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700646 ec->GetValue(updater_provider->var_last_checked_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700647
648 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
649 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
650
651 PRNG prng(*seed);
652
Gilad Arnold38b14022014-07-09 12:45:56 -0700653 // If this is the first attempt, compute and return an initial value.
Alex Deymo0d11c602014-04-23 20:12:20 -0700654 if (!last_checked_time || *last_checked_time < *updater_started_time) {
Alex Deymo0d11c602014-04-23 20:12:20 -0700655 *next_update_check = *updater_started_time + FuzzedInterval(
656 &prng, kTimeoutInitialInterval, kTimeoutRegularFuzz);
657 return EvalStatus::kSucceeded;
658 }
Gilad Arnold38b14022014-07-09 12:45:56 -0700659
Gilad Arnolda0258a52014-07-10 16:21:19 -0700660 // Check whether the server is enforcing a poll interval; if not, this value
661 // will be zero.
662 const unsigned int* server_dictated_poll_interval = ec->GetValue(
663 updater_provider->var_server_dictated_poll_interval());
664 POLICY_CHECK_VALUE_AND_FAIL(server_dictated_poll_interval, error);
Alex Deymo0d11c602014-04-23 20:12:20 -0700665
Gilad Arnolda0258a52014-07-10 16:21:19 -0700666 int interval = *server_dictated_poll_interval;
667 int fuzz = 0;
668
Alex Vakulenko072359c2014-07-18 11:41:07 -0700669 // If no poll interval was dictated by server compute a back-off period,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700670 // starting from a predetermined base periodic interval and increasing
671 // exponentially by the number of consecutive failed attempts.
672 if (interval == 0) {
673 const unsigned int* consecutive_failed_update_checks = ec->GetValue(
674 updater_provider->var_consecutive_failed_update_checks());
675 POLICY_CHECK_VALUE_AND_FAIL(consecutive_failed_update_checks, error);
676
677 interval = kTimeoutPeriodicInterval;
678 unsigned int num_failures = *consecutive_failed_update_checks;
679 while (interval < kTimeoutMaxBackoffInterval && num_failures) {
680 interval *= 2;
681 num_failures--;
Alex Deymo0d11c602014-04-23 20:12:20 -0700682 }
683 }
684
Alex Vakulenko072359c2014-07-18 11:41:07 -0700685 // We cannot back off longer than the predetermined maximum interval.
Gilad Arnolda0258a52014-07-10 16:21:19 -0700686 if (interval > kTimeoutMaxBackoffInterval)
687 interval = kTimeoutMaxBackoffInterval;
688
Alex Vakulenko072359c2014-07-18 11:41:07 -0700689 // We cannot back off shorter than the predetermined periodic interval. Also,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700690 // in this case set the fuzz to a predetermined regular value.
691 if (interval <= kTimeoutPeriodicInterval) {
692 interval = kTimeoutPeriodicInterval;
693 fuzz = kTimeoutRegularFuzz;
694 }
695
696 // If not otherwise determined, defer to a fuzz of +/-(interval / 2).
Gilad Arnold38b14022014-07-09 12:45:56 -0700697 if (fuzz == 0)
698 fuzz = interval;
699
Alex Deymo0d11c602014-04-23 20:12:20 -0700700 *next_update_check = *last_checked_time + FuzzedInterval(
Gilad Arnold38b14022014-07-09 12:45:56 -0700701 &prng, interval, fuzz);
Alex Deymo0d11c602014-04-23 20:12:20 -0700702 return EvalStatus::kSucceeded;
703}
704
705TimeDelta ChromeOSPolicy::FuzzedInterval(PRNG* prng, int interval, int fuzz) {
Gilad Arnolde1218812014-05-07 12:21:36 -0700706 DCHECK_GE(interval, 0);
707 DCHECK_GE(fuzz, 0);
Alex Deymo0d11c602014-04-23 20:12:20 -0700708 int half_fuzz = fuzz / 2;
Alex Deymo0d11c602014-04-23 20:12:20 -0700709 // This guarantees the output interval is non negative.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700710 int interval_min = max(interval - half_fuzz, 0);
Gilad Arnolde1218812014-05-07 12:21:36 -0700711 int interval_max = interval + half_fuzz;
712 return TimeDelta::FromSeconds(prng->RandMinMax(interval_min, interval_max));
Alex Deymo0d11c602014-04-23 20:12:20 -0700713}
714
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700715EvalStatus ChromeOSPolicy::UpdateBackoffAndDownloadUrl(
Alex Deymof329b932014-10-30 01:37:48 -0700716 EvaluationContext* ec, State* state, string* error,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700717 UpdateBackoffAndDownloadUrlResult* result,
718 const UpdateState& update_state) const {
719 // Sanity checks.
720 DCHECK_GE(update_state.download_errors_max, 0);
721
722 // Set default result values.
723 result->do_increment_failures = false;
724 result->backoff_expiry = update_state.backoff_expiry;
725 result->url_idx = -1;
726 result->url_num_errors = 0;
727
728 const bool* is_official_build_p = ec->GetValue(
729 state->system_provider()->var_is_official_build());
730 bool is_official_build = (is_official_build_p ? *is_official_build_p : true);
731
732 // Check whether backoff is enabled.
733 bool may_backoff = false;
734 if (update_state.is_backoff_disabled) {
735 LOG(INFO) << "Backoff disabled by Omaha.";
736 } else if (update_state.is_interactive) {
737 LOG(INFO) << "No backoff for interactive updates.";
738 } else if (update_state.is_delta_payload) {
739 LOG(INFO) << "No backoff for delta payloads.";
740 } else if (!is_official_build) {
741 LOG(INFO) << "No backoff for unofficial builds.";
742 } else {
743 may_backoff = true;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700744 }
745
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700746 // If previous backoff still in effect, block.
747 if (may_backoff && !update_state.backoff_expiry.is_null() &&
748 !ec->IsWallclockTimeGreaterThan(update_state.backoff_expiry)) {
749 LOG(INFO) << "Previous backoff has not expired, waiting.";
750 return EvalStatus::kAskMeAgainLater;
751 }
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700752
753 // Determine whether HTTP downloads are forbidden by policy. This only
754 // applies to official system builds; otherwise, HTTP is always enabled.
755 bool http_allowed = true;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700756 if (is_official_build) {
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700757 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
758 const bool* device_policy_is_loaded_p = ec->GetValue(
759 dp_provider->var_device_policy_is_loaded());
760 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
761 const bool* policy_http_downloads_enabled_p = ec->GetValue(
762 dp_provider->var_http_downloads_enabled());
763 http_allowed = (!policy_http_downloads_enabled_p ||
764 *policy_http_downloads_enabled_p);
765 }
766 }
767
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700768 int url_idx = update_state.last_download_url_idx;
769 if (url_idx < 0)
770 url_idx = -1;
771 bool do_advance_url = false;
772 bool is_failure_occurred = false;
773 Time err_time;
774
775 // Scan the relevant part of the download error log, tracking which URLs are
776 // being used, and accounting the number of errors for each URL. Note that
777 // this process may not traverse all errors provided, as it may decide to bail
778 // out midway depending on the particular errors exhibited, the number of
779 // failures allowed, etc. When this ends, |url_idx| will point to the last URL
780 // used (-1 if starting fresh), |do_advance_url| will determine whether the
781 // URL needs to be advanced, and |err_time| the point in time when the last
782 // reported error occurred. Additionally, if the error log indicates that an
783 // update attempt has failed (abnormal), then |is_failure_occurred| will be
784 // set to true.
785 const int num_urls = update_state.download_urls.size();
786 int prev_url_idx = -1;
787 int url_num_errors = update_state.last_download_url_num_errors;
788 Time prev_err_time;
789 bool is_first = true;
790 for (const auto& err_tuple : update_state.download_errors) {
791 // Do some sanity checks.
792 int used_url_idx = get<0>(err_tuple);
793 if (is_first && url_idx >= 0 && used_url_idx != url_idx) {
794 LOG(WARNING) << "First URL in error log (" << used_url_idx
795 << ") not as expected (" << url_idx << ")";
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700796 }
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700797 is_first = false;
798 url_idx = used_url_idx;
799 if (url_idx < 0 || url_idx >= num_urls) {
800 LOG(ERROR) << "Download error log contains an invalid URL index ("
801 << url_idx << ")";
802 return EvalStatus::kFailed;
803 }
804 err_time = get<2>(err_tuple);
805 if (!(prev_err_time.is_null() || err_time >= prev_err_time)) {
806 // TODO(garnold) Monotonicity cannot really be assumed when dealing with
807 // wallclock-based timestamps. However, we're making a simplifying
808 // assumption so as to keep the policy implementation straightforward, for
809 // now. In general, we should convert all timestamp handling in the
810 // UpdateManager to use monotonic time (instead of wallclock), including
811 // the computation of various expiration times (backoff, scattering, etc).
812 // The client will do whatever conversions necessary when
813 // persisting/retrieving these values across reboots. See chromium:408794.
814 LOG(ERROR) << "Download error timestamps not monotonically increasing.";
815 return EvalStatus::kFailed;
816 }
817 prev_err_time = err_time;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700818
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700819 // Ignore errors that happened before the last known failed attempt.
820 if (!update_state.failures_last_updated.is_null() &&
821 err_time <= update_state.failures_last_updated)
822 continue;
823
824 if (prev_url_idx >= 0) {
825 if (url_idx < prev_url_idx) {
826 LOG(ERROR) << "The URLs in the download error log have wrapped around ("
827 << prev_url_idx << "->" << url_idx
828 << "). This should not have happened and means that there's "
829 "a bug. To be conservative, we record a failed attempt "
830 "(invalidating the rest of the error log) and resume "
831 "download from the first usable URL.";
832 url_idx = -1;
833 is_failure_occurred = true;
834 break;
835 }
836
837 if (url_idx > prev_url_idx) {
838 url_num_errors = 0;
839 do_advance_url = false;
840 }
841 }
842
843 if (HandleErrorCode(get<1>(err_tuple), &url_num_errors) ||
844 url_num_errors > update_state.download_errors_max)
845 do_advance_url = true;
846
847 prev_url_idx = url_idx;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700848 }
849
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700850 // If required, advance to the next usable URL. If the URLs wraparound, we
851 // mark an update attempt failure. Also be sure to set the download error
852 // count to zero.
853 if (url_idx < 0 || do_advance_url) {
854 url_num_errors = 0;
855 int start_url_idx = -1;
856 do {
857 if (++url_idx == num_urls) {
858 url_idx = 0;
859 // We only mark failure if an actual advancing of a URL was required.
860 if (do_advance_url)
861 is_failure_occurred = true;
862 }
863
864 if (start_url_idx < 0)
865 start_url_idx = url_idx;
866 else if (url_idx == start_url_idx)
867 url_idx = -1; // No usable URL.
868 } while (url_idx >= 0 &&
869 !IsUrlUsable(update_state.download_urls[url_idx], http_allowed));
870 }
871
872 // If we have a download URL but a failure was observed, compute a new backoff
873 // expiry (if allowed). The backoff period is generally 2 ^ (num_failures - 1)
874 // days, bounded by the size of int and kAttemptBackoffMaxIntervalInDays, and
875 // fuzzed by kAttemptBackoffFuzzInHours hours. Backoff expiry is computed from
876 // the latest recorded time of error.
877 Time backoff_expiry;
878 if (url_idx >= 0 && is_failure_occurred && may_backoff) {
879 CHECK(!err_time.is_null())
880 << "We must have an error timestamp if a failure occurred!";
881 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
882 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
883 PRNG prng(*seed);
Alex Deymof329b932014-10-30 01:37:48 -0700884 int exp = min(update_state.num_failures,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700885 static_cast<int>(sizeof(int)) * 8 - 2);
886 TimeDelta backoff_interval = TimeDelta::FromDays(
Alex Deymof329b932014-10-30 01:37:48 -0700887 min(1 << exp, kAttemptBackoffMaxIntervalInDays));
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700888 TimeDelta backoff_fuzz = TimeDelta::FromHours(kAttemptBackoffFuzzInHours);
889 TimeDelta wait_period = FuzzedInterval(&prng, backoff_interval.InSeconds(),
890 backoff_fuzz.InSeconds());
891 backoff_expiry = err_time + wait_period;
892
893 // If the newly computed backoff already expired, nullify it.
894 if (ec->IsWallclockTimeGreaterThan(backoff_expiry))
895 backoff_expiry = Time();
896 }
897
898 result->do_increment_failures = is_failure_occurred;
899 result->backoff_expiry = backoff_expiry;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700900 result->url_idx = url_idx;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700901 result->url_num_errors = url_num_errors;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700902 return EvalStatus::kSucceeded;
903}
904
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700905EvalStatus ChromeOSPolicy::UpdateScattering(
906 EvaluationContext* ec,
907 State* state,
908 string* error,
909 UpdateScatteringResult* result,
910 const UpdateState& update_state) const {
911 // Preconditions. These stem from the postconditions and usage contract.
912 DCHECK(update_state.scatter_wait_period >= kZeroInterval);
913 DCHECK_GE(update_state.scatter_check_threshold, 0);
914
915 // Set default result values.
916 result->is_scattering = false;
917 result->wait_period = kZeroInterval;
918 result->check_threshold = 0;
919
920 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
921
922 // Ensure that a device policy is loaded.
923 const bool* device_policy_is_loaded_p = ec->GetValue(
924 dp_provider->var_device_policy_is_loaded());
925 if (!(device_policy_is_loaded_p && *device_policy_is_loaded_p))
926 return EvalStatus::kSucceeded;
927
928 // Is scattering enabled by policy?
929 const TimeDelta* scatter_factor_p = ec->GetValue(
930 dp_provider->var_scatter_factor());
931 if (!scatter_factor_p || *scatter_factor_p == kZeroInterval)
932 return EvalStatus::kSucceeded;
933
934 // Obtain a pseudo-random number generator.
935 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
936 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
937 PRNG prng(*seed);
938
939 // Step 1: Maintain the scattering wait period.
940 //
941 // If no wait period was previously determined, or it no longer fits in the
942 // scatter factor, then generate a new one. Otherwise, keep the one we have.
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700943 TimeDelta wait_period = update_state.scatter_wait_period;
944 if (wait_period == kZeroInterval || wait_period > *scatter_factor_p) {
945 wait_period = TimeDelta::FromSeconds(
946 prng.RandMinMax(1, scatter_factor_p->InSeconds()));
947 }
948
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700949 // If we surpassed the wait period or the max scatter period associated with
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700950 // the update, then no wait is needed.
951 Time wait_expires = (update_state.first_seen +
952 min(wait_period, update_state.scatter_wait_period_max));
Gilad Arnolda65fced2014-07-23 09:01:31 -0700953 if (ec->IsWallclockTimeGreaterThan(wait_expires))
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700954 wait_period = kZeroInterval;
955
956 // Step 2: Maintain the update check threshold count.
957 //
958 // If an update check threshold is not specified then generate a new
959 // one.
960 int check_threshold = update_state.scatter_check_threshold;
961 if (check_threshold == 0) {
962 check_threshold = prng.RandMinMax(
963 update_state.scatter_check_threshold_min,
964 update_state.scatter_check_threshold_max);
965 }
966
967 // If the update check threshold is not within allowed range then nullify it.
968 // TODO(garnold) This is compliant with current logic found in
969 // OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied(). We may want
970 // to change it so that it behaves similarly to the wait period case, namely
971 // if the current value exceeds the maximum, we set a new one within range.
972 if (check_threshold > update_state.scatter_check_threshold_max)
973 check_threshold = 0;
974
975 // If the update check threshold is non-zero and satisfied, then nullify it.
976 if (check_threshold > 0 && update_state.num_checks >= check_threshold)
977 check_threshold = 0;
978
979 bool is_scattering = (wait_period != kZeroInterval || check_threshold);
980 EvalStatus ret = EvalStatus::kSucceeded;
981 if (is_scattering && wait_period == update_state.scatter_wait_period &&
982 check_threshold == update_state.scatter_check_threshold)
983 ret = EvalStatus::kAskMeAgainLater;
984 result->is_scattering = is_scattering;
985 result->wait_period = wait_period;
986 result->check_threshold = check_threshold;
987 return ret;
988}
989
Alex Deymo63784a52014-05-28 10:46:14 -0700990} // namespace chromeos_update_manager