blob: fa3217540ab5dda81d909c0f834444d2c77cf723 [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;
Gilad Arnoldb3b05442014-05-30 14:25:05 -070036using chromeos_update_engine::ErrorCode;
Gilad Arnolddc4bb262014-07-23 10:45:19 -070037using std::get;
Gilad Arnoldb3b05442014-05-30 14:25:05 -070038using std::max;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070039using std::min;
Gilad Arnold0adbc942014-05-12 10:35:43 -070040using std::set;
Alex Deymoc705cc82014-02-19 11:15:00 -080041using std::string;
42
Gilad Arnoldb3b05442014-05-30 14:25:05 -070043namespace {
44
Gilad Arnolddc4bb262014-07-23 10:45:19 -070045// Examines |err_code| and decides whether the URL index needs to be advanced,
46// the error count for the URL incremented, or none of the above. In the first
47// case, returns true; in the second case, increments |*url_num_error_p| and
48// returns false; otherwise just returns false.
Gilad Arnoldb3b05442014-05-30 14:25:05 -070049//
50// TODO(garnold) Adapted from PayloadState::UpdateFailed() (to be retired).
Gilad Arnolddc4bb262014-07-23 10:45:19 -070051bool HandleErrorCode(ErrorCode err_code, int* url_num_error_p) {
Gilad Arnoldb3b05442014-05-30 14:25:05 -070052 err_code = chromeos_update_engine::utils::GetBaseErrorCode(err_code);
53 switch (err_code) {
54 // Errors which are good indicators of a problem with a particular URL or
55 // the protocol used in the URL or entities in the communication channel
56 // (e.g. proxies). We should try the next available URL in the next update
57 // check to quickly recover from these errors.
58 case ErrorCode::kPayloadHashMismatchError:
59 case ErrorCode::kPayloadSizeMismatchError:
60 case ErrorCode::kDownloadPayloadVerificationError:
61 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
62 case ErrorCode::kSignedDeltaPayloadExpectedError:
63 case ErrorCode::kDownloadInvalidMetadataMagicString:
64 case ErrorCode::kDownloadSignatureMissingInManifest:
65 case ErrorCode::kDownloadManifestParseError:
66 case ErrorCode::kDownloadMetadataSignatureError:
67 case ErrorCode::kDownloadMetadataSignatureVerificationError:
68 case ErrorCode::kDownloadMetadataSignatureMismatch:
69 case ErrorCode::kDownloadOperationHashVerificationError:
70 case ErrorCode::kDownloadOperationExecutionError:
71 case ErrorCode::kDownloadOperationHashMismatch:
72 case ErrorCode::kDownloadInvalidMetadataSize:
73 case ErrorCode::kDownloadInvalidMetadataSignature:
74 case ErrorCode::kDownloadOperationHashMissingError:
75 case ErrorCode::kDownloadMetadataSignatureMissingError:
76 case ErrorCode::kPayloadMismatchedType:
77 case ErrorCode::kUnsupportedMajorPayloadVersion:
78 case ErrorCode::kUnsupportedMinorPayloadVersion:
79 LOG(INFO) << "Advancing download URL due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -080080 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -070081 << " (" << static_cast<int>(err_code) << ")";
Gilad Arnoldb3b05442014-05-30 14:25:05 -070082 return true;
83
84 // Errors which seem to be just transient network/communication related
85 // failures and do not indicate any inherent problem with the URL itself.
86 // So, we should keep the current URL but just increment the
87 // failure count to give it more chances. This way, while we maximize our
88 // chances of downloading from the URLs that appear earlier in the response
89 // (because download from a local server URL that appears earlier in a
90 // response is preferable than downloading from the next URL which could be
Alex Vakulenko072359c2014-07-18 11:41:07 -070091 // an Internet URL and thus could be more expensive).
Gilad Arnoldb3b05442014-05-30 14:25:05 -070092 case ErrorCode::kError:
93 case ErrorCode::kDownloadTransferError:
94 case ErrorCode::kDownloadWriteError:
95 case ErrorCode::kDownloadStateInitializationError:
Gilad Arnold684219d2014-07-07 14:54:57 -070096 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Gilad Arnoldb3b05442014-05-30 14:25:05 -070097 LOG(INFO) << "Incrementing URL failure count due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -080098 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -070099 << " (" << static_cast<int>(err_code) << ")";
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700100 *url_num_error_p += 1;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700101 return false;
102
103 // Errors which are not specific to a URL and hence shouldn't result in
104 // the URL being penalized. This can happen in two cases:
105 // 1. We haven't started downloading anything: These errors don't cost us
106 // anything in terms of actual payload bytes, so we should just do the
107 // regular retries at the next update check.
108 // 2. We have successfully downloaded the payload: In this case, the
109 // payload attempt number would have been incremented and would take care
Alex Vakulenko072359c2014-07-18 11:41:07 -0700110 // of the back-off at the next update check.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700111 // In either case, there's no need to update URL index or failure count.
112 case ErrorCode::kOmahaRequestError:
113 case ErrorCode::kOmahaResponseHandlerError:
114 case ErrorCode::kPostinstallRunnerError:
115 case ErrorCode::kFilesystemCopierError:
116 case ErrorCode::kInstallDeviceOpenError:
117 case ErrorCode::kKernelDeviceOpenError:
118 case ErrorCode::kDownloadNewPartitionInfoError:
119 case ErrorCode::kNewRootfsVerificationError:
120 case ErrorCode::kNewKernelVerificationError:
121 case ErrorCode::kPostinstallBootedFromFirmwareB:
122 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
123 case ErrorCode::kOmahaRequestEmptyResponseError:
124 case ErrorCode::kOmahaRequestXMLParseError:
125 case ErrorCode::kOmahaResponseInvalid:
126 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
127 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
128 case ErrorCode::kOmahaUpdateDeferredForBackoff:
129 case ErrorCode::kPostinstallPowerwashError:
130 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400131 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700132 case ErrorCode::kFilesystemVerifierError:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800133 case ErrorCode::kUserCanceled:
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700134 LOG(INFO) << "Not changing URL index or failure count due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800135 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700136 << " (" << static_cast<int>(err_code) << ")";
137 return false;
138
139 case ErrorCode::kSuccess: // success code
140 case ErrorCode::kUmaReportedMax: // not an error code
141 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800142 case ErrorCode::kDevModeFlag: // not an error code
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700143 case ErrorCode::kResumedFlag: // not an error code
144 case ErrorCode::kTestImageFlag: // not an error code
145 case ErrorCode::kTestOmahaUrlFlag: // not an error code
146 case ErrorCode::kSpecialFlags: // not an error code
147 // These shouldn't happen. Enumerating these explicitly here so that we
148 // can let the compiler warn about new error codes that are added to
149 // action_processor.h but not added here.
150 LOG(WARNING) << "Unexpected error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800151 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700152 << " (" << static_cast<int>(err_code) << ")";
153 // Note: Not adding a default here so as to let the compiler warn us of
154 // any new enums that were added in the .h but not listed in this switch.
155 }
156 return false;
157}
158
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700159// Checks whether |url| can be used under given download restrictions.
160bool IsUrlUsable(const string& url, bool http_allowed) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800161 return http_allowed ||
162 !base::StartsWith(url, "http://",
163 base::CompareCase::INSENSITIVE_ASCII);
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700164}
165
166} // namespace
167
Alex Deymo63784a52014-05-28 10:46:14 -0700168namespace chromeos_update_manager {
Alex Deymoc705cc82014-02-19 11:15:00 -0800169
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700170const int ChromeOSPolicy::kTimeoutInitialInterval = 7 * 60;
Alex Deymo14e7dde2015-10-20 14:46:33 -0700171
172// TODO(deymo): Split the update_manager policies for Brillo and ChromeOS and
173// make the update check periodic interval configurable.
174#ifdef __ANDROID__
175const int ChromeOSPolicy::kTimeoutPeriodicInterval = 5 * 60 * 60;
Alex Deymodbe13b42015-11-06 11:15:08 -0800176const int ChromeOSPolicy::kTimeoutMaxBackoffInterval = 26 * 60 * 60;
Alex Deymo14e7dde2015-10-20 14:46:33 -0700177#else
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700178const int ChromeOSPolicy::kTimeoutPeriodicInterval = 45 * 60;
Alex Deymodbe13b42015-11-06 11:15:08 -0800179const int ChromeOSPolicy::kTimeoutMaxBackoffInterval = 4 * 60 * 60;
Alex Deymo14e7dde2015-10-20 14:46:33 -0700180#endif // __ANDROID__
181
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700182const int ChromeOSPolicy::kTimeoutRegularFuzz = 10 * 60;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700183const int ChromeOSPolicy::kAttemptBackoffMaxIntervalInDays = 16;
184const int ChromeOSPolicy::kAttemptBackoffFuzzInHours = 12;
Gilad Arnold349ac832014-10-06 14:20:28 -0700185const int ChromeOSPolicy::kMaxP2PAttempts = 10;
186const int ChromeOSPolicy::kMaxP2PAttemptsPeriodInSeconds = 5 * 24 * 60 * 60;
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700187
Alex Deymo0d11c602014-04-23 20:12:20 -0700188EvalStatus ChromeOSPolicy::UpdateCheckAllowed(
189 EvaluationContext* ec, State* state, string* error,
190 UpdateCheckParams* result) const {
Gilad Arnold42f253b2014-06-25 12:39:17 -0700191 // Set the default return values.
192 result->updates_enabled = true;
193 result->target_channel.clear();
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700194 result->target_version_prefix.clear();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700195 result->is_interactive = false;
Gilad Arnold42f253b2014-06-25 12:39:17 -0700196
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700197 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700198 UpdaterProvider* const updater_provider = state->updater_provider();
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700199 SystemProvider* const system_provider = state->system_provider();
200
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700201 // Do not perform any updates if booted from removable device. This decision
202 // is final.
Alex Deymo763e7db2015-08-27 21:08:08 -0700203 const unsigned int* num_slots_p = ec->GetValue(
204 system_provider->var_num_slots());
205 if (!num_slots_p || *num_slots_p < 2) {
206 LOG(INFO) << "Not enough slots for A/B updates, disabling update checks.";
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700207 result->updates_enabled = false;
208 return EvalStatus::kSucceeded;
209 }
210
Gilad Arnold42f253b2014-06-25 12:39:17 -0700211 const bool* device_policy_is_loaded_p = ec->GetValue(
212 dp_provider->var_device_policy_is_loaded());
213 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Xiyuan Xia6e30bc52016-02-24 15:35:42 -0800214 bool kiosk_app_control_chrome_version = false;
215
Gilad Arnold42f253b2014-06-25 12:39:17 -0700216 // Check whether updates are disabled by policy.
217 const bool* update_disabled_p = ec->GetValue(
218 dp_provider->var_update_disabled());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700219 if (update_disabled_p && *update_disabled_p) {
Xiyuan Xia6e30bc52016-02-24 15:35:42 -0800220 // Check whether allow kiosk app to control chrome version policy. This
221 // policy is only effective when AU is disabled by admin.
222 const bool* allow_kiosk_app_control_chrome_version_p = ec->GetValue(
223 dp_provider->var_allow_kiosk_app_control_chrome_version());
224 kiosk_app_control_chrome_version =
225 allow_kiosk_app_control_chrome_version_p &&
226 *allow_kiosk_app_control_chrome_version_p;
227 if (!kiosk_app_control_chrome_version) {
228 // No kiosk pin chrome version policy. AU is really disabled.
229 LOG(INFO) << "Updates disabled by policy, blocking update checks.";
230 return EvalStatus::kAskMeAgainLater;
231 }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700232 }
Gilad Arnold42f253b2014-06-25 12:39:17 -0700233
Xiyuan Xia6e30bc52016-02-24 15:35:42 -0800234 if (kiosk_app_control_chrome_version) {
235 // Get the required platform version from Chrome.
236 const string* kiosk_required_platform_version_p =
237 ec->GetValue(system_provider->var_kiosk_required_platform_version());
238 if (kiosk_required_platform_version_p)
239 result->target_version_prefix = *kiosk_required_platform_version_p;
240 LOG(INFO) << "Allow kiosk app to control Chrome version policy is set,"
241 << ", target version is "
242 << (kiosk_required_platform_version_p
243 ? *kiosk_required_platform_version_p
244 : std::string("latest"));
245 } else {
246 // Determine whether a target version prefix is dictated by policy.
247 const string* target_version_prefix_p = ec->GetValue(
248 dp_provider->var_target_version_prefix());
249 if (target_version_prefix_p)
250 result->target_version_prefix = *target_version_prefix_p;
251 }
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700252
Gilad Arnold42f253b2014-06-25 12:39:17 -0700253 // Determine whether a target channel is dictated by policy.
254 const bool* release_channel_delegated_p = ec->GetValue(
255 dp_provider->var_release_channel_delegated());
256 if (release_channel_delegated_p && !(*release_channel_delegated_p)) {
257 const string* release_channel_p = ec->GetValue(
258 dp_provider->var_release_channel());
259 if (release_channel_p)
260 result->target_channel = *release_channel_p;
261 }
262 }
263
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700264 // First, check to see if an interactive update was requested.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700265 const UpdateRequestStatus* forced_update_requested_p = ec->GetValue(
266 updater_provider->var_forced_update_requested());
267 if (forced_update_requested_p &&
268 *forced_update_requested_p != UpdateRequestStatus::kNone) {
269 result->is_interactive =
270 (*forced_update_requested_p == UpdateRequestStatus::kInteractive);
271 LOG(INFO) << "Forced update signaled ("
272 << (result->is_interactive ? "interactive" : "periodic")
273 << "), allowing update check.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700274 return EvalStatus::kSucceeded;
275 }
276
277 // The logic thereafter applies to periodic updates. Bear in mind that we
278 // should not return a final "no" if any of these criteria are not satisfied,
279 // because the system may still update due to an interactive update request.
280
281 // Unofficial builds should not perform periodic update checks.
282 const bool* is_official_build_p = ec->GetValue(
283 system_provider->var_is_official_build());
284 if (is_official_build_p && !(*is_official_build_p)) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700285 LOG(INFO) << "Unofficial build, blocking periodic update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700286 return EvalStatus::kAskMeAgainLater;
287 }
288
289 // If OOBE is enabled, wait until it is completed.
290 const bool* is_oobe_enabled_p = ec->GetValue(
291 state->config_provider()->var_is_oobe_enabled());
292 if (is_oobe_enabled_p && *is_oobe_enabled_p) {
293 const bool* is_oobe_complete_p = ec->GetValue(
294 system_provider->var_is_oobe_complete());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700295 if (is_oobe_complete_p && !(*is_oobe_complete_p)) {
296 LOG(INFO) << "OOBE not completed, blocking update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700297 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700298 }
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700299 }
300
301 // Ensure that periodic update checks are timed properly.
Alex Deymo0d11c602014-04-23 20:12:20 -0700302 Time next_update_check;
303 if (NextUpdateCheckTime(ec, state, error, &next_update_check) !=
304 EvalStatus::kSucceeded) {
305 return EvalStatus::kFailed;
306 }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700307 if (!ec->IsWallclockTimeGreaterThan(next_update_check)) {
308 LOG(INFO) << "Periodic check interval not satisfied, blocking until "
309 << chromeos_update_engine::utils::ToString(next_update_check);
Alex Deymo0d11c602014-04-23 20:12:20 -0700310 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700311 }
Alex Deymo0d11c602014-04-23 20:12:20 -0700312
313 // It is time to check for an update.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700314 LOG(INFO) << "Allowing update check.";
Alex Deymoe636c3c2014-03-11 19:02:08 -0700315 return EvalStatus::kSucceeded;
Alex Deymoc705cc82014-02-19 11:15:00 -0800316}
317
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700318EvalStatus ChromeOSPolicy::UpdateCanStart(
319 EvaluationContext* ec,
320 State* state,
321 string* error,
Gilad Arnold42f253b2014-06-25 12:39:17 -0700322 UpdateDownloadParams* result,
Gilad Arnoldd78caf92014-09-24 09:28:14 -0700323 const UpdateState update_state) const {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700324 // Set the default return values. Note that we set persisted values (backoff,
325 // scattering) to the same values presented in the update state. The reason is
326 // that preemptive returns, such as the case where an update check is due,
327 // should not clear off the said values; rather, it is the deliberate
328 // inference of new values that should cause them to be reset.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700329 result->update_can_start = false;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700330 result->cannot_start_reason = UpdateCannotStartReason::kUndefined;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700331 result->download_url_idx = -1;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700332 result->download_url_allowed = true;
333 result->download_url_num_errors = 0;
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700334 result->p2p_downloading_allowed = false;
335 result->p2p_sharing_allowed = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700336 result->do_increment_failures = false;
337 result->backoff_expiry = update_state.backoff_expiry;
338 result->scatter_wait_period = update_state.scatter_wait_period;
339 result->scatter_check_threshold = update_state.scatter_check_threshold;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700340
341 // Make sure that we're not due for an update check.
342 UpdateCheckParams check_result;
343 EvalStatus check_status = UpdateCheckAllowed(ec, state, error, &check_result);
344 if (check_status == EvalStatus::kFailed)
345 return EvalStatus::kFailed;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700346 bool is_check_due = (check_status == EvalStatus::kSucceeded &&
347 check_result.updates_enabled == true);
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700348
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700349 // Check whether backoff applies, and if not then which URL can be used for
350 // downloading. These require scanning the download error log, and so they are
351 // done together.
352 UpdateBackoffAndDownloadUrlResult backoff_url_result;
353 EvalStatus backoff_url_status = UpdateBackoffAndDownloadUrl(
354 ec, state, error, &backoff_url_result, update_state);
Gilad Arnold14a9e702014-10-08 08:09:09 -0700355 if (backoff_url_status == EvalStatus::kFailed)
356 return EvalStatus::kFailed;
357 result->download_url_idx = backoff_url_result.url_idx;
358 result->download_url_num_errors = backoff_url_result.url_num_errors;
359 result->do_increment_failures = backoff_url_result.do_increment_failures;
360 result->backoff_expiry = backoff_url_result.backoff_expiry;
361 bool is_backoff_active =
362 (backoff_url_status == EvalStatus::kAskMeAgainLater) ||
363 !backoff_url_result.backoff_expiry.is_null();
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700364
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700365 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold14a9e702014-10-08 08:09:09 -0700366 bool is_scattering_active = false;
367 EvalStatus scattering_status = EvalStatus::kSucceeded;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700368
369 const bool* device_policy_is_loaded_p = ec->GetValue(
370 dp_provider->var_device_policy_is_loaded());
371 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700372 // Check whether scattering applies to this update attempt. We should not be
373 // scattering if this is an interactive update check, or if OOBE is enabled
374 // but not completed.
375 //
376 // Note: current code further suppresses scattering if a "deadline"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700377 // attribute is found in the Omaha response. However, it appears that the
Gilad Arnold76a11f62014-05-20 09:02:12 -0700378 // presence of this attribute is merely indicative of an OOBE update, during
379 // which we suppress scattering anyway.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700380 bool is_scattering_applicable = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700381 result->scatter_wait_period = kZeroInterval;
382 result->scatter_check_threshold = 0;
383 if (!update_state.is_interactive) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700384 const bool* is_oobe_enabled_p = ec->GetValue(
385 state->config_provider()->var_is_oobe_enabled());
386 if (is_oobe_enabled_p && !(*is_oobe_enabled_p)) {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700387 is_scattering_applicable = true;
Gilad Arnold76a11f62014-05-20 09:02:12 -0700388 } else {
389 const bool* is_oobe_complete_p = ec->GetValue(
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700390 state->system_provider()->var_is_oobe_complete());
Gilad Arnold14a9e702014-10-08 08:09:09 -0700391 is_scattering_applicable = (is_oobe_complete_p && *is_oobe_complete_p);
Gilad Arnold76a11f62014-05-20 09:02:12 -0700392 }
393 }
394
395 // Compute scattering values.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700396 if (is_scattering_applicable) {
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700397 UpdateScatteringResult scatter_result;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700398 scattering_status = UpdateScattering(ec, state, error, &scatter_result,
399 update_state);
400 if (scattering_status == EvalStatus::kFailed) {
401 return EvalStatus::kFailed;
402 } else {
403 result->scatter_wait_period = scatter_result.wait_period;
404 result->scatter_check_threshold = scatter_result.check_threshold;
405 if (scattering_status == EvalStatus::kAskMeAgainLater ||
406 scatter_result.is_scattering)
407 is_scattering_active = true;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700408 }
409 }
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700410 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700411
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700412 // Find out whether P2P is globally enabled.
413 bool p2p_enabled;
414 EvalStatus p2p_enabled_status = P2PEnabled(ec, state, error, &p2p_enabled);
415 if (p2p_enabled_status != EvalStatus::kSucceeded)
416 return EvalStatus::kFailed;
417
418 // Is P2P is enabled, consider allowing it for downloading and/or sharing.
419 if (p2p_enabled) {
420 // Sharing via P2P is allowed if not disabled by Omaha.
421 if (update_state.p2p_sharing_disabled) {
422 LOG(INFO) << "Blocked P2P sharing because it is disabled by Omaha.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700423 } else {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700424 result->p2p_sharing_allowed = true;
Gilad Arnoldef8d0872014-10-03 14:14:06 -0700425 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700426
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700427 // Downloading via P2P is allowed if not disabled by Omaha, an update is not
428 // interactive, and other limits haven't been reached.
429 if (update_state.p2p_downloading_disabled) {
430 LOG(INFO) << "Blocked P2P downloading because it is disabled by Omaha.";
431 } else if (update_state.is_interactive) {
432 LOG(INFO) << "Blocked P2P downloading because update is interactive.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700433 } else if (update_state.p2p_num_attempts >= kMaxP2PAttempts) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700434 LOG(INFO) << "Blocked P2P downloading as it was attempted too many "
435 "times.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700436 } else if (!update_state.p2p_first_attempted.is_null() &&
437 ec->IsWallclockTimeGreaterThan(
438 update_state.p2p_first_attempted +
439 TimeDelta::FromSeconds(kMaxP2PAttemptsPeriodInSeconds))) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700440 LOG(INFO) << "Blocked P2P downloading as its usage timespan exceeds "
441 "limit.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700442 } else {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700443 // P2P download is allowed; if backoff or scattering are active, be sure
444 // to suppress them, yet prevent any download URL from being used.
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700445 result->p2p_downloading_allowed = true;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700446 if (is_backoff_active || is_scattering_active) {
447 is_backoff_active = is_scattering_active = false;
448 result->download_url_allowed = false;
449 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700450 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700451 }
452
Gilad Arnold14a9e702014-10-08 08:09:09 -0700453 // Check for various deterrents.
454 if (is_check_due) {
455 result->cannot_start_reason = UpdateCannotStartReason::kCheckDue;
456 return EvalStatus::kSucceeded;
457 }
458 if (is_backoff_active) {
459 result->cannot_start_reason = UpdateCannotStartReason::kBackoff;
460 return backoff_url_status;
461 }
462 if (is_scattering_active) {
463 result->cannot_start_reason = UpdateCannotStartReason::kScattering;
464 return scattering_status;
465 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700466 if (result->download_url_idx < 0 && !result->p2p_downloading_allowed) {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700467 result->cannot_start_reason = UpdateCannotStartReason::kCannotDownload;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700468 return EvalStatus::kSucceeded;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700469 }
470
Gilad Arnold14a9e702014-10-08 08:09:09 -0700471 // Update is good to go.
472 result->update_can_start = true;
Gilad Arnoldaf2f6ae2014-04-28 14:14:52 -0700473 return EvalStatus::kSucceeded;
474}
475
Gilad Arnolda8262e22014-06-02 13:54:27 -0700476// TODO(garnold) Logic in this method is based on
477// ConnectionManager::IsUpdateAllowedOver(); be sure to deprecate the latter.
478//
479// TODO(garnold) The current logic generally treats the list of allowed
480// connections coming from the device policy as a whitelist, meaning that it
481// can only be used for enabling connections, but not disable them. Further,
482// certain connection types (like Bluetooth) cannot be enabled even by policy.
483// In effect, the only thing that device policy can change is to enable
484// updates over a cellular network (disabled by default). We may want to
485// revisit this semantics, allowing greater flexibility in defining specific
486// permissions over all types of networks.
Gilad Arnold684219d2014-07-07 14:54:57 -0700487EvalStatus ChromeOSPolicy::UpdateDownloadAllowed(
Gilad Arnolda8262e22014-06-02 13:54:27 -0700488 EvaluationContext* ec,
489 State* state,
490 string* error,
491 bool* result) const {
492 // Get the current connection type.
493 ShillProvider* const shill_provider = state->shill_provider();
494 const ConnectionType* conn_type_p = ec->GetValue(
495 shill_provider->var_conn_type());
496 POLICY_CHECK_VALUE_AND_FAIL(conn_type_p, error);
497 ConnectionType conn_type = *conn_type_p;
498
499 // If we're tethering, treat it as a cellular connection.
500 if (conn_type != ConnectionType::kCellular) {
501 const ConnectionTethering* conn_tethering_p = ec->GetValue(
502 shill_provider->var_conn_tethering());
503 POLICY_CHECK_VALUE_AND_FAIL(conn_tethering_p, error);
504 if (*conn_tethering_p == ConnectionTethering::kConfirmed)
505 conn_type = ConnectionType::kCellular;
506 }
507
508 // By default, we allow updates for all connection types, with exceptions as
509 // noted below. This also determines whether a device policy can override the
510 // default.
511 *result = true;
512 bool device_policy_can_override = false;
513 switch (conn_type) {
514 case ConnectionType::kBluetooth:
515 *result = false;
516 break;
517
518 case ConnectionType::kCellular:
519 *result = false;
520 device_policy_can_override = true;
521 break;
522
523 case ConnectionType::kUnknown:
524 if (error)
525 *error = "Unknown connection type";
526 return EvalStatus::kFailed;
527
528 default:
529 break; // Nothing to do.
530 }
531
532 // If update is allowed, we're done.
533 if (*result)
534 return EvalStatus::kSucceeded;
535
536 // Check whether the device policy specifically allows this connection.
Gilad Arnolda8262e22014-06-02 13:54:27 -0700537 if (device_policy_can_override) {
538 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
539 const bool* device_policy_is_loaded_p = ec->GetValue(
540 dp_provider->var_device_policy_is_loaded());
541 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
542 const set<ConnectionType>* allowed_conn_types_p = ec->GetValue(
543 dp_provider->var_allowed_connection_types_for_update());
544 if (allowed_conn_types_p) {
545 if (allowed_conn_types_p->count(conn_type)) {
546 *result = true;
547 return EvalStatus::kSucceeded;
548 }
Gilad Arnold28d6be62014-06-30 14:04:04 -0700549 } else if (conn_type == ConnectionType::kCellular) {
550 // Local user settings can allow updates over cellular iff a policy was
551 // loaded but no allowed connections were specified in it.
552 const bool* update_over_cellular_allowed_p = ec->GetValue(
553 state->updater_provider()->var_cellular_enabled());
554 if (update_over_cellular_allowed_p && *update_over_cellular_allowed_p)
555 *result = true;
Gilad Arnolda8262e22014-06-02 13:54:27 -0700556 }
557 }
558 }
559
Gilad Arnold28d6be62014-06-30 14:04:04 -0700560 return (*result ? EvalStatus::kSucceeded : EvalStatus::kAskMeAgainLater);
Gilad Arnolda8262e22014-06-02 13:54:27 -0700561}
562
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700563EvalStatus ChromeOSPolicy::P2PEnabled(EvaluationContext* ec,
564 State* state,
Alex Deymo39910dc2015-11-09 17:04:30 -0800565 string* error,
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700566 bool* result) const {
567 bool enabled = false;
568
569 // Determine whether use of P2P is allowed by policy. Even if P2P is not
570 // explicitly allowed, we allow it if the device is enterprise enrolled (that
571 // is, missing or empty owner string).
572 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
573 const bool* device_policy_is_loaded_p = ec->GetValue(
574 dp_provider->var_device_policy_is_loaded());
575 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
576 const bool* policy_au_p2p_enabled_p = ec->GetValue(
577 dp_provider->var_au_p2p_enabled());
578 if (policy_au_p2p_enabled_p) {
579 enabled = *policy_au_p2p_enabled_p;
580 } else {
581 const string* policy_owner_p = ec->GetValue(dp_provider->var_owner());
582 if (!policy_owner_p || policy_owner_p->empty())
583 enabled = true;
584 }
585 }
586
587 // Enable P2P, if so mandated by the updater configuration. This is additive
588 // to whether or not P2P is enabled by device policy.
589 if (!enabled) {
590 const bool* updater_p2p_enabled_p = ec->GetValue(
591 state->updater_provider()->var_p2p_enabled());
592 enabled = updater_p2p_enabled_p && *updater_p2p_enabled_p;
593 }
594
595 *result = enabled;
596 return EvalStatus::kSucceeded;
597}
598
599EvalStatus ChromeOSPolicy::P2PEnabledChanged(EvaluationContext* ec,
600 State* state,
Alex Deymo39910dc2015-11-09 17:04:30 -0800601 string* error,
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700602 bool* result,
603 bool prev_result) const {
604 EvalStatus status = P2PEnabled(ec, state, error, result);
605 if (status == EvalStatus::kSucceeded && *result == prev_result)
606 return EvalStatus::kAskMeAgainLater;
607 return status;
608}
609
Alex Deymo0d11c602014-04-23 20:12:20 -0700610EvalStatus ChromeOSPolicy::NextUpdateCheckTime(EvaluationContext* ec,
611 State* state, string* error,
612 Time* next_update_check) const {
Gilad Arnolda0258a52014-07-10 16:21:19 -0700613 UpdaterProvider* const updater_provider = state->updater_provider();
614
Alex Deymo0d11c602014-04-23 20:12:20 -0700615 // Don't check for updates too often. We limit the update checks to once every
616 // some interval. The interval is kTimeoutInitialInterval the first time and
617 // kTimeoutPeriodicInterval for the subsequent update checks. If the update
618 // check fails, we increase the interval between the update checks
619 // exponentially until kTimeoutMaxBackoffInterval. Finally, to avoid having
620 // many chromebooks running update checks at the exact same time, we add some
621 // fuzz to the interval.
622 const Time* updater_started_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700623 ec->GetValue(updater_provider->var_updater_started_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700624 POLICY_CHECK_VALUE_AND_FAIL(updater_started_time, error);
625
Alex Deymof329b932014-10-30 01:37:48 -0700626 const Time* last_checked_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700627 ec->GetValue(updater_provider->var_last_checked_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700628
629 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
630 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
631
632 PRNG prng(*seed);
633
Gilad Arnold38b14022014-07-09 12:45:56 -0700634 // If this is the first attempt, compute and return an initial value.
Alex Deymo0d11c602014-04-23 20:12:20 -0700635 if (!last_checked_time || *last_checked_time < *updater_started_time) {
Alex Deymo0d11c602014-04-23 20:12:20 -0700636 *next_update_check = *updater_started_time + FuzzedInterval(
637 &prng, kTimeoutInitialInterval, kTimeoutRegularFuzz);
638 return EvalStatus::kSucceeded;
639 }
Gilad Arnold38b14022014-07-09 12:45:56 -0700640
Gilad Arnolda0258a52014-07-10 16:21:19 -0700641 // Check whether the server is enforcing a poll interval; if not, this value
642 // will be zero.
643 const unsigned int* server_dictated_poll_interval = ec->GetValue(
644 updater_provider->var_server_dictated_poll_interval());
645 POLICY_CHECK_VALUE_AND_FAIL(server_dictated_poll_interval, error);
Alex Deymo0d11c602014-04-23 20:12:20 -0700646
Gilad Arnolda0258a52014-07-10 16:21:19 -0700647 int interval = *server_dictated_poll_interval;
648 int fuzz = 0;
649
Alex Vakulenko072359c2014-07-18 11:41:07 -0700650 // If no poll interval was dictated by server compute a back-off period,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700651 // starting from a predetermined base periodic interval and increasing
652 // exponentially by the number of consecutive failed attempts.
653 if (interval == 0) {
654 const unsigned int* consecutive_failed_update_checks = ec->GetValue(
655 updater_provider->var_consecutive_failed_update_checks());
656 POLICY_CHECK_VALUE_AND_FAIL(consecutive_failed_update_checks, error);
657
658 interval = kTimeoutPeriodicInterval;
659 unsigned int num_failures = *consecutive_failed_update_checks;
660 while (interval < kTimeoutMaxBackoffInterval && num_failures) {
661 interval *= 2;
662 num_failures--;
Alex Deymo0d11c602014-04-23 20:12:20 -0700663 }
664 }
665
Alex Vakulenko072359c2014-07-18 11:41:07 -0700666 // We cannot back off longer than the predetermined maximum interval.
Gilad Arnolda0258a52014-07-10 16:21:19 -0700667 if (interval > kTimeoutMaxBackoffInterval)
668 interval = kTimeoutMaxBackoffInterval;
669
Alex Vakulenko072359c2014-07-18 11:41:07 -0700670 // We cannot back off shorter than the predetermined periodic interval. Also,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700671 // in this case set the fuzz to a predetermined regular value.
672 if (interval <= kTimeoutPeriodicInterval) {
673 interval = kTimeoutPeriodicInterval;
674 fuzz = kTimeoutRegularFuzz;
675 }
676
677 // If not otherwise determined, defer to a fuzz of +/-(interval / 2).
Gilad Arnold38b14022014-07-09 12:45:56 -0700678 if (fuzz == 0)
679 fuzz = interval;
680
Alex Deymo0d11c602014-04-23 20:12:20 -0700681 *next_update_check = *last_checked_time + FuzzedInterval(
Gilad Arnold38b14022014-07-09 12:45:56 -0700682 &prng, interval, fuzz);
Alex Deymo0d11c602014-04-23 20:12:20 -0700683 return EvalStatus::kSucceeded;
684}
685
686TimeDelta ChromeOSPolicy::FuzzedInterval(PRNG* prng, int interval, int fuzz) {
Gilad Arnolde1218812014-05-07 12:21:36 -0700687 DCHECK_GE(interval, 0);
688 DCHECK_GE(fuzz, 0);
Alex Deymo0d11c602014-04-23 20:12:20 -0700689 int half_fuzz = fuzz / 2;
Alex Deymo0d11c602014-04-23 20:12:20 -0700690 // This guarantees the output interval is non negative.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700691 int interval_min = max(interval - half_fuzz, 0);
Gilad Arnolde1218812014-05-07 12:21:36 -0700692 int interval_max = interval + half_fuzz;
693 return TimeDelta::FromSeconds(prng->RandMinMax(interval_min, interval_max));
Alex Deymo0d11c602014-04-23 20:12:20 -0700694}
695
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700696EvalStatus ChromeOSPolicy::UpdateBackoffAndDownloadUrl(
Alex Deymof329b932014-10-30 01:37:48 -0700697 EvaluationContext* ec, State* state, string* error,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700698 UpdateBackoffAndDownloadUrlResult* result,
699 const UpdateState& update_state) const {
700 // Sanity checks.
701 DCHECK_GE(update_state.download_errors_max, 0);
702
703 // Set default result values.
704 result->do_increment_failures = false;
705 result->backoff_expiry = update_state.backoff_expiry;
706 result->url_idx = -1;
707 result->url_num_errors = 0;
708
709 const bool* is_official_build_p = ec->GetValue(
710 state->system_provider()->var_is_official_build());
711 bool is_official_build = (is_official_build_p ? *is_official_build_p : true);
712
713 // Check whether backoff is enabled.
714 bool may_backoff = false;
715 if (update_state.is_backoff_disabled) {
716 LOG(INFO) << "Backoff disabled by Omaha.";
717 } else if (update_state.is_interactive) {
718 LOG(INFO) << "No backoff for interactive updates.";
719 } else if (update_state.is_delta_payload) {
720 LOG(INFO) << "No backoff for delta payloads.";
721 } else if (!is_official_build) {
722 LOG(INFO) << "No backoff for unofficial builds.";
723 } else {
724 may_backoff = true;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700725 }
726
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700727 // If previous backoff still in effect, block.
728 if (may_backoff && !update_state.backoff_expiry.is_null() &&
729 !ec->IsWallclockTimeGreaterThan(update_state.backoff_expiry)) {
730 LOG(INFO) << "Previous backoff has not expired, waiting.";
731 return EvalStatus::kAskMeAgainLater;
732 }
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700733
734 // Determine whether HTTP downloads are forbidden by policy. This only
735 // applies to official system builds; otherwise, HTTP is always enabled.
736 bool http_allowed = true;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700737 if (is_official_build) {
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700738 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
739 const bool* device_policy_is_loaded_p = ec->GetValue(
740 dp_provider->var_device_policy_is_loaded());
741 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
742 const bool* policy_http_downloads_enabled_p = ec->GetValue(
743 dp_provider->var_http_downloads_enabled());
744 http_allowed = (!policy_http_downloads_enabled_p ||
745 *policy_http_downloads_enabled_p);
746 }
747 }
748
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700749 int url_idx = update_state.last_download_url_idx;
750 if (url_idx < 0)
751 url_idx = -1;
752 bool do_advance_url = false;
753 bool is_failure_occurred = false;
754 Time err_time;
755
756 // Scan the relevant part of the download error log, tracking which URLs are
757 // being used, and accounting the number of errors for each URL. Note that
758 // this process may not traverse all errors provided, as it may decide to bail
759 // out midway depending on the particular errors exhibited, the number of
760 // failures allowed, etc. When this ends, |url_idx| will point to the last URL
761 // used (-1 if starting fresh), |do_advance_url| will determine whether the
762 // URL needs to be advanced, and |err_time| the point in time when the last
763 // reported error occurred. Additionally, if the error log indicates that an
764 // update attempt has failed (abnormal), then |is_failure_occurred| will be
765 // set to true.
766 const int num_urls = update_state.download_urls.size();
767 int prev_url_idx = -1;
768 int url_num_errors = update_state.last_download_url_num_errors;
769 Time prev_err_time;
770 bool is_first = true;
771 for (const auto& err_tuple : update_state.download_errors) {
772 // Do some sanity checks.
773 int used_url_idx = get<0>(err_tuple);
774 if (is_first && url_idx >= 0 && used_url_idx != url_idx) {
775 LOG(WARNING) << "First URL in error log (" << used_url_idx
776 << ") not as expected (" << url_idx << ")";
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700777 }
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700778 is_first = false;
779 url_idx = used_url_idx;
780 if (url_idx < 0 || url_idx >= num_urls) {
781 LOG(ERROR) << "Download error log contains an invalid URL index ("
782 << url_idx << ")";
783 return EvalStatus::kFailed;
784 }
785 err_time = get<2>(err_tuple);
786 if (!(prev_err_time.is_null() || err_time >= prev_err_time)) {
787 // TODO(garnold) Monotonicity cannot really be assumed when dealing with
788 // wallclock-based timestamps. However, we're making a simplifying
789 // assumption so as to keep the policy implementation straightforward, for
790 // now. In general, we should convert all timestamp handling in the
791 // UpdateManager to use monotonic time (instead of wallclock), including
792 // the computation of various expiration times (backoff, scattering, etc).
793 // The client will do whatever conversions necessary when
794 // persisting/retrieving these values across reboots. See chromium:408794.
795 LOG(ERROR) << "Download error timestamps not monotonically increasing.";
796 return EvalStatus::kFailed;
797 }
798 prev_err_time = err_time;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700799
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700800 // Ignore errors that happened before the last known failed attempt.
801 if (!update_state.failures_last_updated.is_null() &&
802 err_time <= update_state.failures_last_updated)
803 continue;
804
805 if (prev_url_idx >= 0) {
806 if (url_idx < prev_url_idx) {
807 LOG(ERROR) << "The URLs in the download error log have wrapped around ("
808 << prev_url_idx << "->" << url_idx
809 << "). This should not have happened and means that there's "
810 "a bug. To be conservative, we record a failed attempt "
811 "(invalidating the rest of the error log) and resume "
812 "download from the first usable URL.";
813 url_idx = -1;
814 is_failure_occurred = true;
815 break;
816 }
817
818 if (url_idx > prev_url_idx) {
819 url_num_errors = 0;
820 do_advance_url = false;
821 }
822 }
823
824 if (HandleErrorCode(get<1>(err_tuple), &url_num_errors) ||
825 url_num_errors > update_state.download_errors_max)
826 do_advance_url = true;
827
828 prev_url_idx = url_idx;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700829 }
830
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700831 // If required, advance to the next usable URL. If the URLs wraparound, we
832 // mark an update attempt failure. Also be sure to set the download error
833 // count to zero.
834 if (url_idx < 0 || do_advance_url) {
835 url_num_errors = 0;
836 int start_url_idx = -1;
837 do {
838 if (++url_idx == num_urls) {
839 url_idx = 0;
840 // We only mark failure if an actual advancing of a URL was required.
841 if (do_advance_url)
842 is_failure_occurred = true;
843 }
844
845 if (start_url_idx < 0)
846 start_url_idx = url_idx;
847 else if (url_idx == start_url_idx)
848 url_idx = -1; // No usable URL.
849 } while (url_idx >= 0 &&
850 !IsUrlUsable(update_state.download_urls[url_idx], http_allowed));
851 }
852
853 // If we have a download URL but a failure was observed, compute a new backoff
854 // expiry (if allowed). The backoff period is generally 2 ^ (num_failures - 1)
855 // days, bounded by the size of int and kAttemptBackoffMaxIntervalInDays, and
856 // fuzzed by kAttemptBackoffFuzzInHours hours. Backoff expiry is computed from
857 // the latest recorded time of error.
858 Time backoff_expiry;
859 if (url_idx >= 0 && is_failure_occurred && may_backoff) {
860 CHECK(!err_time.is_null())
861 << "We must have an error timestamp if a failure occurred!";
862 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
863 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
864 PRNG prng(*seed);
Alex Deymof329b932014-10-30 01:37:48 -0700865 int exp = min(update_state.num_failures,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700866 static_cast<int>(sizeof(int)) * 8 - 2);
867 TimeDelta backoff_interval = TimeDelta::FromDays(
Alex Deymof329b932014-10-30 01:37:48 -0700868 min(1 << exp, kAttemptBackoffMaxIntervalInDays));
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700869 TimeDelta backoff_fuzz = TimeDelta::FromHours(kAttemptBackoffFuzzInHours);
870 TimeDelta wait_period = FuzzedInterval(&prng, backoff_interval.InSeconds(),
871 backoff_fuzz.InSeconds());
872 backoff_expiry = err_time + wait_period;
873
874 // If the newly computed backoff already expired, nullify it.
875 if (ec->IsWallclockTimeGreaterThan(backoff_expiry))
876 backoff_expiry = Time();
877 }
878
879 result->do_increment_failures = is_failure_occurred;
880 result->backoff_expiry = backoff_expiry;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700881 result->url_idx = url_idx;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700882 result->url_num_errors = url_num_errors;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700883 return EvalStatus::kSucceeded;
884}
885
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700886EvalStatus ChromeOSPolicy::UpdateScattering(
887 EvaluationContext* ec,
888 State* state,
889 string* error,
890 UpdateScatteringResult* result,
891 const UpdateState& update_state) const {
892 // Preconditions. These stem from the postconditions and usage contract.
893 DCHECK(update_state.scatter_wait_period >= kZeroInterval);
894 DCHECK_GE(update_state.scatter_check_threshold, 0);
895
896 // Set default result values.
897 result->is_scattering = false;
898 result->wait_period = kZeroInterval;
899 result->check_threshold = 0;
900
901 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
902
903 // Ensure that a device policy is loaded.
904 const bool* device_policy_is_loaded_p = ec->GetValue(
905 dp_provider->var_device_policy_is_loaded());
906 if (!(device_policy_is_loaded_p && *device_policy_is_loaded_p))
907 return EvalStatus::kSucceeded;
908
909 // Is scattering enabled by policy?
910 const TimeDelta* scatter_factor_p = ec->GetValue(
911 dp_provider->var_scatter_factor());
912 if (!scatter_factor_p || *scatter_factor_p == kZeroInterval)
913 return EvalStatus::kSucceeded;
914
915 // Obtain a pseudo-random number generator.
916 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
917 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
918 PRNG prng(*seed);
919
920 // Step 1: Maintain the scattering wait period.
921 //
922 // If no wait period was previously determined, or it no longer fits in the
923 // scatter factor, then generate a new one. Otherwise, keep the one we have.
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700924 TimeDelta wait_period = update_state.scatter_wait_period;
925 if (wait_period == kZeroInterval || wait_period > *scatter_factor_p) {
926 wait_period = TimeDelta::FromSeconds(
927 prng.RandMinMax(1, scatter_factor_p->InSeconds()));
928 }
929
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700930 // If we surpassed the wait period or the max scatter period associated with
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700931 // the update, then no wait is needed.
932 Time wait_expires = (update_state.first_seen +
933 min(wait_period, update_state.scatter_wait_period_max));
Gilad Arnolda65fced2014-07-23 09:01:31 -0700934 if (ec->IsWallclockTimeGreaterThan(wait_expires))
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700935 wait_period = kZeroInterval;
936
937 // Step 2: Maintain the update check threshold count.
938 //
939 // If an update check threshold is not specified then generate a new
940 // one.
941 int check_threshold = update_state.scatter_check_threshold;
942 if (check_threshold == 0) {
943 check_threshold = prng.RandMinMax(
944 update_state.scatter_check_threshold_min,
945 update_state.scatter_check_threshold_max);
946 }
947
948 // If the update check threshold is not within allowed range then nullify it.
949 // TODO(garnold) This is compliant with current logic found in
950 // OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied(). We may want
951 // to change it so that it behaves similarly to the wait period case, namely
952 // if the current value exceeds the maximum, we set a new one within range.
953 if (check_threshold > update_state.scatter_check_threshold_max)
954 check_threshold = 0;
955
956 // If the update check threshold is non-zero and satisfied, then nullify it.
957 if (check_threshold > 0 && update_state.num_checks >= check_threshold)
958 check_threshold = 0;
959
960 bool is_scattering = (wait_period != kZeroInterval || check_threshold);
961 EvalStatus ret = EvalStatus::kSucceeded;
962 if (is_scattering && wait_period == update_state.scatter_wait_period &&
963 check_threshold == update_state.scatter_check_threshold)
964 ret = EvalStatus::kAskMeAgainLater;
965 result->is_scattering = is_scattering;
966 result->wait_period = wait_period;
967 result->check_threshold = check_threshold;
968 return ret;
969}
970
Alex Deymo63784a52014-05-28 10:46:14 -0700971} // namespace chromeos_update_manager