blob: 3fb680a8bc3e5b21458b68a5ed49bc3feacb2286 [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:
Kevin Cernekee2494e282016-03-29 18:03:53 -0700128 case ErrorCode::kNonCriticalUpdateInOOBE:
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700129 case ErrorCode::kOmahaUpdateDeferredForBackoff:
130 case ErrorCode::kPostinstallPowerwashError:
131 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400132 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700133 case ErrorCode::kFilesystemVerifierError:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800134 case ErrorCode::kUserCanceled:
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700135 LOG(INFO) << "Not changing URL index or failure count due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800136 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700137 << " (" << static_cast<int>(err_code) << ")";
138 return false;
139
140 case ErrorCode::kSuccess: // success code
141 case ErrorCode::kUmaReportedMax: // not an error code
142 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800143 case ErrorCode::kDevModeFlag: // not an error code
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700144 case ErrorCode::kResumedFlag: // not an error code
145 case ErrorCode::kTestImageFlag: // not an error code
146 case ErrorCode::kTestOmahaUrlFlag: // not an error code
147 case ErrorCode::kSpecialFlags: // not an error code
148 // These shouldn't happen. Enumerating these explicitly here so that we
149 // can let the compiler warn about new error codes that are added to
150 // action_processor.h but not added here.
151 LOG(WARNING) << "Unexpected error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800152 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700153 << " (" << static_cast<int>(err_code) << ")";
154 // Note: Not adding a default here so as to let the compiler warn us of
155 // any new enums that were added in the .h but not listed in this switch.
156 }
157 return false;
158}
159
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700160// Checks whether |url| can be used under given download restrictions.
161bool IsUrlUsable(const string& url, bool http_allowed) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800162 return http_allowed ||
163 !base::StartsWith(url, "http://",
164 base::CompareCase::INSENSITIVE_ASCII);
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700165}
166
167} // namespace
168
Alex Deymo63784a52014-05-28 10:46:14 -0700169namespace chromeos_update_manager {
Alex Deymoc705cc82014-02-19 11:15:00 -0800170
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700171const int ChromeOSPolicy::kTimeoutInitialInterval = 7 * 60;
Alex Deymo14e7dde2015-10-20 14:46:33 -0700172
173// TODO(deymo): Split the update_manager policies for Brillo and ChromeOS and
174// make the update check periodic interval configurable.
175#ifdef __ANDROID__
176const int ChromeOSPolicy::kTimeoutPeriodicInterval = 5 * 60 * 60;
Alex Deymodbe13b42015-11-06 11:15:08 -0800177const int ChromeOSPolicy::kTimeoutMaxBackoffInterval = 26 * 60 * 60;
Alex Deymo14e7dde2015-10-20 14:46:33 -0700178#else
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700179const int ChromeOSPolicy::kTimeoutPeriodicInterval = 45 * 60;
Alex Deymodbe13b42015-11-06 11:15:08 -0800180const int ChromeOSPolicy::kTimeoutMaxBackoffInterval = 4 * 60 * 60;
Alex Deymo14e7dde2015-10-20 14:46:33 -0700181#endif // __ANDROID__
182
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700183const int ChromeOSPolicy::kTimeoutRegularFuzz = 10 * 60;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700184const int ChromeOSPolicy::kAttemptBackoffMaxIntervalInDays = 16;
185const int ChromeOSPolicy::kAttemptBackoffFuzzInHours = 12;
Gilad Arnold349ac832014-10-06 14:20:28 -0700186const int ChromeOSPolicy::kMaxP2PAttempts = 10;
187const int ChromeOSPolicy::kMaxP2PAttemptsPeriodInSeconds = 5 * 24 * 60 * 60;
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700188
Alex Deymo0d11c602014-04-23 20:12:20 -0700189EvalStatus ChromeOSPolicy::UpdateCheckAllowed(
190 EvaluationContext* ec, State* state, string* error,
191 UpdateCheckParams* result) const {
Gilad Arnold42f253b2014-06-25 12:39:17 -0700192 // Set the default return values.
193 result->updates_enabled = true;
194 result->target_channel.clear();
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700195 result->target_version_prefix.clear();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700196 result->is_interactive = false;
Gilad Arnold42f253b2014-06-25 12:39:17 -0700197
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700198 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700199 UpdaterProvider* const updater_provider = state->updater_provider();
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700200 SystemProvider* const system_provider = state->system_provider();
201
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700202 // Do not perform any updates if booted from removable device. This decision
203 // is final.
Alex Deymo763e7db2015-08-27 21:08:08 -0700204 const unsigned int* num_slots_p = ec->GetValue(
205 system_provider->var_num_slots());
206 if (!num_slots_p || *num_slots_p < 2) {
207 LOG(INFO) << "Not enough slots for A/B updates, disabling update checks.";
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700208 result->updates_enabled = false;
209 return EvalStatus::kSucceeded;
210 }
211
Gilad Arnold42f253b2014-06-25 12:39:17 -0700212 const bool* device_policy_is_loaded_p = ec->GetValue(
213 dp_provider->var_device_policy_is_loaded());
214 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Xiyuan Xia6e30bc52016-02-24 15:35:42 -0800215 bool kiosk_app_control_chrome_version = false;
216
Gilad Arnold42f253b2014-06-25 12:39:17 -0700217 // Check whether updates are disabled by policy.
218 const bool* update_disabled_p = ec->GetValue(
219 dp_provider->var_update_disabled());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700220 if (update_disabled_p && *update_disabled_p) {
Xiyuan Xia6e30bc52016-02-24 15:35:42 -0800221 // Check whether allow kiosk app to control chrome version policy. This
222 // policy is only effective when AU is disabled by admin.
223 const bool* allow_kiosk_app_control_chrome_version_p = ec->GetValue(
224 dp_provider->var_allow_kiosk_app_control_chrome_version());
225 kiosk_app_control_chrome_version =
226 allow_kiosk_app_control_chrome_version_p &&
227 *allow_kiosk_app_control_chrome_version_p;
228 if (!kiosk_app_control_chrome_version) {
229 // No kiosk pin chrome version policy. AU is really disabled.
230 LOG(INFO) << "Updates disabled by policy, blocking update checks.";
231 return EvalStatus::kAskMeAgainLater;
232 }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700233 }
Gilad Arnold42f253b2014-06-25 12:39:17 -0700234
Xiyuan Xia6e30bc52016-02-24 15:35:42 -0800235 if (kiosk_app_control_chrome_version) {
236 // Get the required platform version from Chrome.
237 const string* kiosk_required_platform_version_p =
238 ec->GetValue(system_provider->var_kiosk_required_platform_version());
239 if (kiosk_required_platform_version_p)
240 result->target_version_prefix = *kiosk_required_platform_version_p;
241 LOG(INFO) << "Allow kiosk app to control Chrome version policy is set,"
242 << ", target version is "
243 << (kiosk_required_platform_version_p
244 ? *kiosk_required_platform_version_p
245 : std::string("latest"));
246 } else {
247 // Determine whether a target version prefix is dictated by policy.
248 const string* target_version_prefix_p = ec->GetValue(
249 dp_provider->var_target_version_prefix());
250 if (target_version_prefix_p)
251 result->target_version_prefix = *target_version_prefix_p;
252 }
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700253
Gilad Arnold42f253b2014-06-25 12:39:17 -0700254 // Determine whether a target channel is dictated by policy.
255 const bool* release_channel_delegated_p = ec->GetValue(
256 dp_provider->var_release_channel_delegated());
257 if (release_channel_delegated_p && !(*release_channel_delegated_p)) {
258 const string* release_channel_p = ec->GetValue(
259 dp_provider->var_release_channel());
260 if (release_channel_p)
261 result->target_channel = *release_channel_p;
262 }
263 }
264
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700265 // First, check to see if an interactive update was requested.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700266 const UpdateRequestStatus* forced_update_requested_p = ec->GetValue(
267 updater_provider->var_forced_update_requested());
268 if (forced_update_requested_p &&
269 *forced_update_requested_p != UpdateRequestStatus::kNone) {
270 result->is_interactive =
271 (*forced_update_requested_p == UpdateRequestStatus::kInteractive);
272 LOG(INFO) << "Forced update signaled ("
273 << (result->is_interactive ? "interactive" : "periodic")
274 << "), allowing update check.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700275 return EvalStatus::kSucceeded;
276 }
277
278 // The logic thereafter applies to periodic updates. Bear in mind that we
279 // should not return a final "no" if any of these criteria are not satisfied,
280 // because the system may still update due to an interactive update request.
281
282 // Unofficial builds should not perform periodic update checks.
283 const bool* is_official_build_p = ec->GetValue(
284 system_provider->var_is_official_build());
285 if (is_official_build_p && !(*is_official_build_p)) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700286 LOG(INFO) << "Unofficial build, blocking periodic update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700287 return EvalStatus::kAskMeAgainLater;
288 }
289
290 // If OOBE is enabled, wait until it is completed.
291 const bool* is_oobe_enabled_p = ec->GetValue(
292 state->config_provider()->var_is_oobe_enabled());
293 if (is_oobe_enabled_p && *is_oobe_enabled_p) {
294 const bool* is_oobe_complete_p = ec->GetValue(
295 system_provider->var_is_oobe_complete());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700296 if (is_oobe_complete_p && !(*is_oobe_complete_p)) {
297 LOG(INFO) << "OOBE not completed, blocking update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700298 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700299 }
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700300 }
301
302 // Ensure that periodic update checks are timed properly.
Alex Deymo0d11c602014-04-23 20:12:20 -0700303 Time next_update_check;
304 if (NextUpdateCheckTime(ec, state, error, &next_update_check) !=
305 EvalStatus::kSucceeded) {
306 return EvalStatus::kFailed;
307 }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700308 if (!ec->IsWallclockTimeGreaterThan(next_update_check)) {
309 LOG(INFO) << "Periodic check interval not satisfied, blocking until "
310 << chromeos_update_engine::utils::ToString(next_update_check);
Alex Deymo0d11c602014-04-23 20:12:20 -0700311 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700312 }
Alex Deymo0d11c602014-04-23 20:12:20 -0700313
314 // It is time to check for an update.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700315 LOG(INFO) << "Allowing update check.";
Alex Deymoe636c3c2014-03-11 19:02:08 -0700316 return EvalStatus::kSucceeded;
Alex Deymoc705cc82014-02-19 11:15:00 -0800317}
318
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700319EvalStatus ChromeOSPolicy::UpdateCanStart(
320 EvaluationContext* ec,
321 State* state,
322 string* error,
Gilad Arnold42f253b2014-06-25 12:39:17 -0700323 UpdateDownloadParams* result,
Gilad Arnoldd78caf92014-09-24 09:28:14 -0700324 const UpdateState update_state) const {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700325 // Set the default return values. Note that we set persisted values (backoff,
326 // scattering) to the same values presented in the update state. The reason is
327 // that preemptive returns, such as the case where an update check is due,
328 // should not clear off the said values; rather, it is the deliberate
329 // inference of new values that should cause them to be reset.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700330 result->update_can_start = false;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700331 result->cannot_start_reason = UpdateCannotStartReason::kUndefined;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700332 result->download_url_idx = -1;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700333 result->download_url_allowed = true;
334 result->download_url_num_errors = 0;
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700335 result->p2p_downloading_allowed = false;
336 result->p2p_sharing_allowed = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700337 result->do_increment_failures = false;
338 result->backoff_expiry = update_state.backoff_expiry;
339 result->scatter_wait_period = update_state.scatter_wait_period;
340 result->scatter_check_threshold = update_state.scatter_check_threshold;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700341
342 // Make sure that we're not due for an update check.
343 UpdateCheckParams check_result;
344 EvalStatus check_status = UpdateCheckAllowed(ec, state, error, &check_result);
345 if (check_status == EvalStatus::kFailed)
346 return EvalStatus::kFailed;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700347 bool is_check_due = (check_status == EvalStatus::kSucceeded &&
348 check_result.updates_enabled == true);
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700349
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700350 // Check whether backoff applies, and if not then which URL can be used for
351 // downloading. These require scanning the download error log, and so they are
352 // done together.
353 UpdateBackoffAndDownloadUrlResult backoff_url_result;
354 EvalStatus backoff_url_status = UpdateBackoffAndDownloadUrl(
355 ec, state, error, &backoff_url_result, update_state);
Gilad Arnold14a9e702014-10-08 08:09:09 -0700356 if (backoff_url_status == EvalStatus::kFailed)
357 return EvalStatus::kFailed;
358 result->download_url_idx = backoff_url_result.url_idx;
359 result->download_url_num_errors = backoff_url_result.url_num_errors;
360 result->do_increment_failures = backoff_url_result.do_increment_failures;
361 result->backoff_expiry = backoff_url_result.backoff_expiry;
362 bool is_backoff_active =
363 (backoff_url_status == EvalStatus::kAskMeAgainLater) ||
364 !backoff_url_result.backoff_expiry.is_null();
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700365
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700366 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold14a9e702014-10-08 08:09:09 -0700367 bool is_scattering_active = false;
368 EvalStatus scattering_status = EvalStatus::kSucceeded;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700369
370 const bool* device_policy_is_loaded_p = ec->GetValue(
371 dp_provider->var_device_policy_is_loaded());
372 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700373 // Check whether scattering applies to this update attempt. We should not be
374 // scattering if this is an interactive update check, or if OOBE is enabled
375 // but not completed.
376 //
377 // Note: current code further suppresses scattering if a "deadline"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700378 // attribute is found in the Omaha response. However, it appears that the
Gilad Arnold76a11f62014-05-20 09:02:12 -0700379 // presence of this attribute is merely indicative of an OOBE update, during
380 // which we suppress scattering anyway.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700381 bool is_scattering_applicable = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700382 result->scatter_wait_period = kZeroInterval;
383 result->scatter_check_threshold = 0;
384 if (!update_state.is_interactive) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700385 const bool* is_oobe_enabled_p = ec->GetValue(
386 state->config_provider()->var_is_oobe_enabled());
387 if (is_oobe_enabled_p && !(*is_oobe_enabled_p)) {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700388 is_scattering_applicable = true;
Gilad Arnold76a11f62014-05-20 09:02:12 -0700389 } else {
390 const bool* is_oobe_complete_p = ec->GetValue(
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700391 state->system_provider()->var_is_oobe_complete());
Gilad Arnold14a9e702014-10-08 08:09:09 -0700392 is_scattering_applicable = (is_oobe_complete_p && *is_oobe_complete_p);
Gilad Arnold76a11f62014-05-20 09:02:12 -0700393 }
394 }
395
396 // Compute scattering values.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700397 if (is_scattering_applicable) {
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700398 UpdateScatteringResult scatter_result;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700399 scattering_status = UpdateScattering(ec, state, error, &scatter_result,
400 update_state);
401 if (scattering_status == EvalStatus::kFailed) {
402 return EvalStatus::kFailed;
403 } else {
404 result->scatter_wait_period = scatter_result.wait_period;
405 result->scatter_check_threshold = scatter_result.check_threshold;
406 if (scattering_status == EvalStatus::kAskMeAgainLater ||
407 scatter_result.is_scattering)
408 is_scattering_active = true;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700409 }
410 }
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700411 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700412
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700413 // Find out whether P2P is globally enabled.
414 bool p2p_enabled;
415 EvalStatus p2p_enabled_status = P2PEnabled(ec, state, error, &p2p_enabled);
416 if (p2p_enabled_status != EvalStatus::kSucceeded)
417 return EvalStatus::kFailed;
418
419 // Is P2P is enabled, consider allowing it for downloading and/or sharing.
420 if (p2p_enabled) {
421 // Sharing via P2P is allowed if not disabled by Omaha.
422 if (update_state.p2p_sharing_disabled) {
423 LOG(INFO) << "Blocked P2P sharing because it is disabled by Omaha.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700424 } else {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700425 result->p2p_sharing_allowed = true;
Gilad Arnoldef8d0872014-10-03 14:14:06 -0700426 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700427
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700428 // Downloading via P2P is allowed if not disabled by Omaha, an update is not
429 // interactive, and other limits haven't been reached.
430 if (update_state.p2p_downloading_disabled) {
431 LOG(INFO) << "Blocked P2P downloading because it is disabled by Omaha.";
432 } else if (update_state.is_interactive) {
433 LOG(INFO) << "Blocked P2P downloading because update is interactive.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700434 } else if (update_state.p2p_num_attempts >= kMaxP2PAttempts) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700435 LOG(INFO) << "Blocked P2P downloading as it was attempted too many "
436 "times.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700437 } else if (!update_state.p2p_first_attempted.is_null() &&
438 ec->IsWallclockTimeGreaterThan(
439 update_state.p2p_first_attempted +
440 TimeDelta::FromSeconds(kMaxP2PAttemptsPeriodInSeconds))) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700441 LOG(INFO) << "Blocked P2P downloading as its usage timespan exceeds "
442 "limit.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700443 } else {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700444 // P2P download is allowed; if backoff or scattering are active, be sure
445 // to suppress them, yet prevent any download URL from being used.
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700446 result->p2p_downloading_allowed = true;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700447 if (is_backoff_active || is_scattering_active) {
448 is_backoff_active = is_scattering_active = false;
449 result->download_url_allowed = false;
450 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700451 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700452 }
453
Gilad Arnold14a9e702014-10-08 08:09:09 -0700454 // Check for various deterrents.
455 if (is_check_due) {
456 result->cannot_start_reason = UpdateCannotStartReason::kCheckDue;
457 return EvalStatus::kSucceeded;
458 }
459 if (is_backoff_active) {
460 result->cannot_start_reason = UpdateCannotStartReason::kBackoff;
461 return backoff_url_status;
462 }
463 if (is_scattering_active) {
464 result->cannot_start_reason = UpdateCannotStartReason::kScattering;
465 return scattering_status;
466 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700467 if (result->download_url_idx < 0 && !result->p2p_downloading_allowed) {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700468 result->cannot_start_reason = UpdateCannotStartReason::kCannotDownload;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700469 return EvalStatus::kSucceeded;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700470 }
471
Gilad Arnold14a9e702014-10-08 08:09:09 -0700472 // Update is good to go.
473 result->update_can_start = true;
Gilad Arnoldaf2f6ae2014-04-28 14:14:52 -0700474 return EvalStatus::kSucceeded;
475}
476
Gilad Arnolda8262e22014-06-02 13:54:27 -0700477// TODO(garnold) Logic in this method is based on
478// ConnectionManager::IsUpdateAllowedOver(); be sure to deprecate the latter.
479//
480// TODO(garnold) The current logic generally treats the list of allowed
481// connections coming from the device policy as a whitelist, meaning that it
482// can only be used for enabling connections, but not disable them. Further,
483// certain connection types (like Bluetooth) cannot be enabled even by policy.
484// In effect, the only thing that device policy can change is to enable
485// updates over a cellular network (disabled by default). We may want to
486// revisit this semantics, allowing greater flexibility in defining specific
487// permissions over all types of networks.
Gilad Arnold684219d2014-07-07 14:54:57 -0700488EvalStatus ChromeOSPolicy::UpdateDownloadAllowed(
Gilad Arnolda8262e22014-06-02 13:54:27 -0700489 EvaluationContext* ec,
490 State* state,
491 string* error,
492 bool* result) const {
493 // Get the current connection type.
494 ShillProvider* const shill_provider = state->shill_provider();
495 const ConnectionType* conn_type_p = ec->GetValue(
496 shill_provider->var_conn_type());
497 POLICY_CHECK_VALUE_AND_FAIL(conn_type_p, error);
498 ConnectionType conn_type = *conn_type_p;
499
500 // If we're tethering, treat it as a cellular connection.
501 if (conn_type != ConnectionType::kCellular) {
502 const ConnectionTethering* conn_tethering_p = ec->GetValue(
503 shill_provider->var_conn_tethering());
504 POLICY_CHECK_VALUE_AND_FAIL(conn_tethering_p, error);
505 if (*conn_tethering_p == ConnectionTethering::kConfirmed)
506 conn_type = ConnectionType::kCellular;
507 }
508
509 // By default, we allow updates for all connection types, with exceptions as
510 // noted below. This also determines whether a device policy can override the
511 // default.
512 *result = true;
513 bool device_policy_can_override = false;
514 switch (conn_type) {
515 case ConnectionType::kBluetooth:
516 *result = false;
517 break;
518
519 case ConnectionType::kCellular:
520 *result = false;
521 device_policy_can_override = true;
522 break;
523
524 case ConnectionType::kUnknown:
525 if (error)
526 *error = "Unknown connection type";
527 return EvalStatus::kFailed;
528
529 default:
530 break; // Nothing to do.
531 }
532
533 // If update is allowed, we're done.
534 if (*result)
535 return EvalStatus::kSucceeded;
536
537 // Check whether the device policy specifically allows this connection.
Gilad Arnolda8262e22014-06-02 13:54:27 -0700538 if (device_policy_can_override) {
539 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
540 const bool* device_policy_is_loaded_p = ec->GetValue(
541 dp_provider->var_device_policy_is_loaded());
542 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
543 const set<ConnectionType>* allowed_conn_types_p = ec->GetValue(
544 dp_provider->var_allowed_connection_types_for_update());
545 if (allowed_conn_types_p) {
546 if (allowed_conn_types_p->count(conn_type)) {
547 *result = true;
548 return EvalStatus::kSucceeded;
549 }
Gilad Arnold28d6be62014-06-30 14:04:04 -0700550 } else if (conn_type == ConnectionType::kCellular) {
551 // Local user settings can allow updates over cellular iff a policy was
552 // loaded but no allowed connections were specified in it.
553 const bool* update_over_cellular_allowed_p = ec->GetValue(
554 state->updater_provider()->var_cellular_enabled());
555 if (update_over_cellular_allowed_p && *update_over_cellular_allowed_p)
556 *result = true;
Gilad Arnolda8262e22014-06-02 13:54:27 -0700557 }
558 }
559 }
560
Gilad Arnold28d6be62014-06-30 14:04:04 -0700561 return (*result ? EvalStatus::kSucceeded : EvalStatus::kAskMeAgainLater);
Gilad Arnolda8262e22014-06-02 13:54:27 -0700562}
563
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700564EvalStatus ChromeOSPolicy::P2PEnabled(EvaluationContext* ec,
565 State* state,
Alex Deymo39910dc2015-11-09 17:04:30 -0800566 string* error,
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700567 bool* result) const {
568 bool enabled = false;
569
570 // Determine whether use of P2P is allowed by policy. Even if P2P is not
571 // explicitly allowed, we allow it if the device is enterprise enrolled (that
572 // is, missing or empty owner string).
573 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
574 const bool* device_policy_is_loaded_p = ec->GetValue(
575 dp_provider->var_device_policy_is_loaded());
576 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
577 const bool* policy_au_p2p_enabled_p = ec->GetValue(
578 dp_provider->var_au_p2p_enabled());
579 if (policy_au_p2p_enabled_p) {
580 enabled = *policy_au_p2p_enabled_p;
581 } else {
582 const string* policy_owner_p = ec->GetValue(dp_provider->var_owner());
583 if (!policy_owner_p || policy_owner_p->empty())
584 enabled = true;
585 }
586 }
587
588 // Enable P2P, if so mandated by the updater configuration. This is additive
589 // to whether or not P2P is enabled by device policy.
590 if (!enabled) {
591 const bool* updater_p2p_enabled_p = ec->GetValue(
592 state->updater_provider()->var_p2p_enabled());
593 enabled = updater_p2p_enabled_p && *updater_p2p_enabled_p;
594 }
595
596 *result = enabled;
597 return EvalStatus::kSucceeded;
598}
599
600EvalStatus ChromeOSPolicy::P2PEnabledChanged(EvaluationContext* ec,
601 State* state,
Alex Deymo39910dc2015-11-09 17:04:30 -0800602 string* error,
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700603 bool* result,
604 bool prev_result) const {
605 EvalStatus status = P2PEnabled(ec, state, error, result);
606 if (status == EvalStatus::kSucceeded && *result == prev_result)
607 return EvalStatus::kAskMeAgainLater;
608 return status;
609}
610
Alex Deymo0d11c602014-04-23 20:12:20 -0700611EvalStatus ChromeOSPolicy::NextUpdateCheckTime(EvaluationContext* ec,
612 State* state, string* error,
613 Time* next_update_check) const {
Gilad Arnolda0258a52014-07-10 16:21:19 -0700614 UpdaterProvider* const updater_provider = state->updater_provider();
615
Alex Deymo0d11c602014-04-23 20:12:20 -0700616 // Don't check for updates too often. We limit the update checks to once every
617 // some interval. The interval is kTimeoutInitialInterval the first time and
618 // kTimeoutPeriodicInterval for the subsequent update checks. If the update
619 // check fails, we increase the interval between the update checks
620 // exponentially until kTimeoutMaxBackoffInterval. Finally, to avoid having
621 // many chromebooks running update checks at the exact same time, we add some
622 // fuzz to the interval.
623 const Time* updater_started_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700624 ec->GetValue(updater_provider->var_updater_started_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700625 POLICY_CHECK_VALUE_AND_FAIL(updater_started_time, error);
626
Alex Deymof329b932014-10-30 01:37:48 -0700627 const Time* last_checked_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700628 ec->GetValue(updater_provider->var_last_checked_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700629
630 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
631 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
632
633 PRNG prng(*seed);
634
Gilad Arnold38b14022014-07-09 12:45:56 -0700635 // If this is the first attempt, compute and return an initial value.
Alex Deymo0d11c602014-04-23 20:12:20 -0700636 if (!last_checked_time || *last_checked_time < *updater_started_time) {
Alex Deymo0d11c602014-04-23 20:12:20 -0700637 *next_update_check = *updater_started_time + FuzzedInterval(
638 &prng, kTimeoutInitialInterval, kTimeoutRegularFuzz);
639 return EvalStatus::kSucceeded;
640 }
Gilad Arnold38b14022014-07-09 12:45:56 -0700641
Gilad Arnolda0258a52014-07-10 16:21:19 -0700642 // Check whether the server is enforcing a poll interval; if not, this value
643 // will be zero.
644 const unsigned int* server_dictated_poll_interval = ec->GetValue(
645 updater_provider->var_server_dictated_poll_interval());
646 POLICY_CHECK_VALUE_AND_FAIL(server_dictated_poll_interval, error);
Alex Deymo0d11c602014-04-23 20:12:20 -0700647
Gilad Arnolda0258a52014-07-10 16:21:19 -0700648 int interval = *server_dictated_poll_interval;
649 int fuzz = 0;
650
Alex Vakulenko072359c2014-07-18 11:41:07 -0700651 // If no poll interval was dictated by server compute a back-off period,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700652 // starting from a predetermined base periodic interval and increasing
653 // exponentially by the number of consecutive failed attempts.
654 if (interval == 0) {
655 const unsigned int* consecutive_failed_update_checks = ec->GetValue(
656 updater_provider->var_consecutive_failed_update_checks());
657 POLICY_CHECK_VALUE_AND_FAIL(consecutive_failed_update_checks, error);
658
659 interval = kTimeoutPeriodicInterval;
660 unsigned int num_failures = *consecutive_failed_update_checks;
661 while (interval < kTimeoutMaxBackoffInterval && num_failures) {
662 interval *= 2;
663 num_failures--;
Alex Deymo0d11c602014-04-23 20:12:20 -0700664 }
665 }
666
Alex Vakulenko072359c2014-07-18 11:41:07 -0700667 // We cannot back off longer than the predetermined maximum interval.
Gilad Arnolda0258a52014-07-10 16:21:19 -0700668 if (interval > kTimeoutMaxBackoffInterval)
669 interval = kTimeoutMaxBackoffInterval;
670
Alex Vakulenko072359c2014-07-18 11:41:07 -0700671 // We cannot back off shorter than the predetermined periodic interval. Also,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700672 // in this case set the fuzz to a predetermined regular value.
673 if (interval <= kTimeoutPeriodicInterval) {
674 interval = kTimeoutPeriodicInterval;
675 fuzz = kTimeoutRegularFuzz;
676 }
677
678 // If not otherwise determined, defer to a fuzz of +/-(interval / 2).
Gilad Arnold38b14022014-07-09 12:45:56 -0700679 if (fuzz == 0)
680 fuzz = interval;
681
Alex Deymo0d11c602014-04-23 20:12:20 -0700682 *next_update_check = *last_checked_time + FuzzedInterval(
Gilad Arnold38b14022014-07-09 12:45:56 -0700683 &prng, interval, fuzz);
Alex Deymo0d11c602014-04-23 20:12:20 -0700684 return EvalStatus::kSucceeded;
685}
686
687TimeDelta ChromeOSPolicy::FuzzedInterval(PRNG* prng, int interval, int fuzz) {
Gilad Arnolde1218812014-05-07 12:21:36 -0700688 DCHECK_GE(interval, 0);
689 DCHECK_GE(fuzz, 0);
Alex Deymo0d11c602014-04-23 20:12:20 -0700690 int half_fuzz = fuzz / 2;
Alex Deymo0d11c602014-04-23 20:12:20 -0700691 // This guarantees the output interval is non negative.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700692 int interval_min = max(interval - half_fuzz, 0);
Gilad Arnolde1218812014-05-07 12:21:36 -0700693 int interval_max = interval + half_fuzz;
694 return TimeDelta::FromSeconds(prng->RandMinMax(interval_min, interval_max));
Alex Deymo0d11c602014-04-23 20:12:20 -0700695}
696
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700697EvalStatus ChromeOSPolicy::UpdateBackoffAndDownloadUrl(
Alex Deymof329b932014-10-30 01:37:48 -0700698 EvaluationContext* ec, State* state, string* error,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700699 UpdateBackoffAndDownloadUrlResult* result,
700 const UpdateState& update_state) const {
701 // Sanity checks.
702 DCHECK_GE(update_state.download_errors_max, 0);
703
704 // Set default result values.
705 result->do_increment_failures = false;
706 result->backoff_expiry = update_state.backoff_expiry;
707 result->url_idx = -1;
708 result->url_num_errors = 0;
709
710 const bool* is_official_build_p = ec->GetValue(
711 state->system_provider()->var_is_official_build());
712 bool is_official_build = (is_official_build_p ? *is_official_build_p : true);
713
714 // Check whether backoff is enabled.
715 bool may_backoff = false;
716 if (update_state.is_backoff_disabled) {
717 LOG(INFO) << "Backoff disabled by Omaha.";
718 } else if (update_state.is_interactive) {
719 LOG(INFO) << "No backoff for interactive updates.";
720 } else if (update_state.is_delta_payload) {
721 LOG(INFO) << "No backoff for delta payloads.";
722 } else if (!is_official_build) {
723 LOG(INFO) << "No backoff for unofficial builds.";
724 } else {
725 may_backoff = true;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700726 }
727
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700728 // If previous backoff still in effect, block.
729 if (may_backoff && !update_state.backoff_expiry.is_null() &&
730 !ec->IsWallclockTimeGreaterThan(update_state.backoff_expiry)) {
731 LOG(INFO) << "Previous backoff has not expired, waiting.";
732 return EvalStatus::kAskMeAgainLater;
733 }
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700734
735 // Determine whether HTTP downloads are forbidden by policy. This only
736 // applies to official system builds; otherwise, HTTP is always enabled.
737 bool http_allowed = true;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700738 if (is_official_build) {
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700739 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
740 const bool* device_policy_is_loaded_p = ec->GetValue(
741 dp_provider->var_device_policy_is_loaded());
742 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
743 const bool* policy_http_downloads_enabled_p = ec->GetValue(
744 dp_provider->var_http_downloads_enabled());
745 http_allowed = (!policy_http_downloads_enabled_p ||
746 *policy_http_downloads_enabled_p);
747 }
748 }
749
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700750 int url_idx = update_state.last_download_url_idx;
751 if (url_idx < 0)
752 url_idx = -1;
753 bool do_advance_url = false;
754 bool is_failure_occurred = false;
755 Time err_time;
756
757 // Scan the relevant part of the download error log, tracking which URLs are
758 // being used, and accounting the number of errors for each URL. Note that
759 // this process may not traverse all errors provided, as it may decide to bail
760 // out midway depending on the particular errors exhibited, the number of
761 // failures allowed, etc. When this ends, |url_idx| will point to the last URL
762 // used (-1 if starting fresh), |do_advance_url| will determine whether the
763 // URL needs to be advanced, and |err_time| the point in time when the last
764 // reported error occurred. Additionally, if the error log indicates that an
765 // update attempt has failed (abnormal), then |is_failure_occurred| will be
766 // set to true.
767 const int num_urls = update_state.download_urls.size();
768 int prev_url_idx = -1;
769 int url_num_errors = update_state.last_download_url_num_errors;
770 Time prev_err_time;
771 bool is_first = true;
772 for (const auto& err_tuple : update_state.download_errors) {
773 // Do some sanity checks.
774 int used_url_idx = get<0>(err_tuple);
775 if (is_first && url_idx >= 0 && used_url_idx != url_idx) {
776 LOG(WARNING) << "First URL in error log (" << used_url_idx
777 << ") not as expected (" << url_idx << ")";
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700778 }
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700779 is_first = false;
780 url_idx = used_url_idx;
781 if (url_idx < 0 || url_idx >= num_urls) {
782 LOG(ERROR) << "Download error log contains an invalid URL index ("
783 << url_idx << ")";
784 return EvalStatus::kFailed;
785 }
786 err_time = get<2>(err_tuple);
787 if (!(prev_err_time.is_null() || err_time >= prev_err_time)) {
788 // TODO(garnold) Monotonicity cannot really be assumed when dealing with
789 // wallclock-based timestamps. However, we're making a simplifying
790 // assumption so as to keep the policy implementation straightforward, for
791 // now. In general, we should convert all timestamp handling in the
792 // UpdateManager to use monotonic time (instead of wallclock), including
793 // the computation of various expiration times (backoff, scattering, etc).
794 // The client will do whatever conversions necessary when
795 // persisting/retrieving these values across reboots. See chromium:408794.
796 LOG(ERROR) << "Download error timestamps not monotonically increasing.";
797 return EvalStatus::kFailed;
798 }
799 prev_err_time = err_time;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700800
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700801 // Ignore errors that happened before the last known failed attempt.
802 if (!update_state.failures_last_updated.is_null() &&
803 err_time <= update_state.failures_last_updated)
804 continue;
805
806 if (prev_url_idx >= 0) {
807 if (url_idx < prev_url_idx) {
808 LOG(ERROR) << "The URLs in the download error log have wrapped around ("
809 << prev_url_idx << "->" << url_idx
810 << "). This should not have happened and means that there's "
811 "a bug. To be conservative, we record a failed attempt "
812 "(invalidating the rest of the error log) and resume "
813 "download from the first usable URL.";
814 url_idx = -1;
815 is_failure_occurred = true;
816 break;
817 }
818
819 if (url_idx > prev_url_idx) {
820 url_num_errors = 0;
821 do_advance_url = false;
822 }
823 }
824
825 if (HandleErrorCode(get<1>(err_tuple), &url_num_errors) ||
826 url_num_errors > update_state.download_errors_max)
827 do_advance_url = true;
828
829 prev_url_idx = url_idx;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700830 }
831
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700832 // If required, advance to the next usable URL. If the URLs wraparound, we
833 // mark an update attempt failure. Also be sure to set the download error
834 // count to zero.
835 if (url_idx < 0 || do_advance_url) {
836 url_num_errors = 0;
837 int start_url_idx = -1;
838 do {
839 if (++url_idx == num_urls) {
840 url_idx = 0;
841 // We only mark failure if an actual advancing of a URL was required.
842 if (do_advance_url)
843 is_failure_occurred = true;
844 }
845
846 if (start_url_idx < 0)
847 start_url_idx = url_idx;
848 else if (url_idx == start_url_idx)
849 url_idx = -1; // No usable URL.
850 } while (url_idx >= 0 &&
851 !IsUrlUsable(update_state.download_urls[url_idx], http_allowed));
852 }
853
854 // If we have a download URL but a failure was observed, compute a new backoff
855 // expiry (if allowed). The backoff period is generally 2 ^ (num_failures - 1)
856 // days, bounded by the size of int and kAttemptBackoffMaxIntervalInDays, and
857 // fuzzed by kAttemptBackoffFuzzInHours hours. Backoff expiry is computed from
858 // the latest recorded time of error.
859 Time backoff_expiry;
860 if (url_idx >= 0 && is_failure_occurred && may_backoff) {
861 CHECK(!err_time.is_null())
862 << "We must have an error timestamp if a failure occurred!";
863 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
864 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
865 PRNG prng(*seed);
Alex Deymof329b932014-10-30 01:37:48 -0700866 int exp = min(update_state.num_failures,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700867 static_cast<int>(sizeof(int)) * 8 - 2);
868 TimeDelta backoff_interval = TimeDelta::FromDays(
Alex Deymof329b932014-10-30 01:37:48 -0700869 min(1 << exp, kAttemptBackoffMaxIntervalInDays));
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700870 TimeDelta backoff_fuzz = TimeDelta::FromHours(kAttemptBackoffFuzzInHours);
871 TimeDelta wait_period = FuzzedInterval(&prng, backoff_interval.InSeconds(),
872 backoff_fuzz.InSeconds());
873 backoff_expiry = err_time + wait_period;
874
875 // If the newly computed backoff already expired, nullify it.
876 if (ec->IsWallclockTimeGreaterThan(backoff_expiry))
877 backoff_expiry = Time();
878 }
879
880 result->do_increment_failures = is_failure_occurred;
881 result->backoff_expiry = backoff_expiry;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700882 result->url_idx = url_idx;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700883 result->url_num_errors = url_num_errors;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700884 return EvalStatus::kSucceeded;
885}
886
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700887EvalStatus ChromeOSPolicy::UpdateScattering(
888 EvaluationContext* ec,
889 State* state,
890 string* error,
891 UpdateScatteringResult* result,
892 const UpdateState& update_state) const {
893 // Preconditions. These stem from the postconditions and usage contract.
894 DCHECK(update_state.scatter_wait_period >= kZeroInterval);
895 DCHECK_GE(update_state.scatter_check_threshold, 0);
896
897 // Set default result values.
898 result->is_scattering = false;
899 result->wait_period = kZeroInterval;
900 result->check_threshold = 0;
901
902 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
903
904 // Ensure that a device policy is loaded.
905 const bool* device_policy_is_loaded_p = ec->GetValue(
906 dp_provider->var_device_policy_is_loaded());
907 if (!(device_policy_is_loaded_p && *device_policy_is_loaded_p))
908 return EvalStatus::kSucceeded;
909
910 // Is scattering enabled by policy?
911 const TimeDelta* scatter_factor_p = ec->GetValue(
912 dp_provider->var_scatter_factor());
913 if (!scatter_factor_p || *scatter_factor_p == kZeroInterval)
914 return EvalStatus::kSucceeded;
915
916 // Obtain a pseudo-random number generator.
917 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
918 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
919 PRNG prng(*seed);
920
921 // Step 1: Maintain the scattering wait period.
922 //
923 // If no wait period was previously determined, or it no longer fits in the
924 // scatter factor, then generate a new one. Otherwise, keep the one we have.
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700925 TimeDelta wait_period = update_state.scatter_wait_period;
926 if (wait_period == kZeroInterval || wait_period > *scatter_factor_p) {
927 wait_period = TimeDelta::FromSeconds(
928 prng.RandMinMax(1, scatter_factor_p->InSeconds()));
929 }
930
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700931 // If we surpassed the wait period or the max scatter period associated with
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700932 // the update, then no wait is needed.
933 Time wait_expires = (update_state.first_seen +
934 min(wait_period, update_state.scatter_wait_period_max));
Gilad Arnolda65fced2014-07-23 09:01:31 -0700935 if (ec->IsWallclockTimeGreaterThan(wait_expires))
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700936 wait_period = kZeroInterval;
937
938 // Step 2: Maintain the update check threshold count.
939 //
940 // If an update check threshold is not specified then generate a new
941 // one.
942 int check_threshold = update_state.scatter_check_threshold;
943 if (check_threshold == 0) {
944 check_threshold = prng.RandMinMax(
945 update_state.scatter_check_threshold_min,
946 update_state.scatter_check_threshold_max);
947 }
948
949 // If the update check threshold is not within allowed range then nullify it.
950 // TODO(garnold) This is compliant with current logic found in
951 // OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied(). We may want
952 // to change it so that it behaves similarly to the wait period case, namely
953 // if the current value exceeds the maximum, we set a new one within range.
954 if (check_threshold > update_state.scatter_check_threshold_max)
955 check_threshold = 0;
956
957 // If the update check threshold is non-zero and satisfied, then nullify it.
958 if (check_threshold > 0 && update_state.num_checks >= check_threshold)
959 check_threshold = 0;
960
961 bool is_scattering = (wait_period != kZeroInterval || check_threshold);
962 EvalStatus ret = EvalStatus::kSucceeded;
963 if (is_scattering && wait_period == update_state.scatter_wait_period &&
964 check_threshold == update_state.scatter_check_threshold)
965 ret = EvalStatus::kAskMeAgainLater;
966 result->is_scattering = is_scattering;
967 result->wait_period = wait_period;
968 result->check_threshold = check_threshold;
969 return ret;
970}
971
Alex Deymo63784a52014-05-28 10:46:14 -0700972} // namespace chromeos_update_manager