blob: 3a81059499aa1b9c35a331abb2a768fbf035e634 [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
Gilad Arnoldb3b05442014-05-30 14:25:05 -070027#include "update_engine/error_code.h"
Alex Deymo63784a52014-05-28 10:46:14 -070028#include "update_engine/update_manager/device_policy_provider.h"
29#include "update_engine/update_manager/policy_utils.h"
30#include "update_engine/update_manager/shill_provider.h"
Gilad Arnoldb3b05442014-05-30 14:25:05 -070031#include "update_engine/utils.h"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070032
Alex Deymo0d11c602014-04-23 20:12:20 -070033using base::Time;
34using base::TimeDelta;
Gilad Arnoldb3b05442014-05-30 14:25:05 -070035using chromeos_update_engine::ErrorCode;
Gilad Arnolddc4bb262014-07-23 10:45:19 -070036using std::get;
Gilad Arnoldb3b05442014-05-30 14:25:05 -070037using std::max;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070038using std::min;
Gilad Arnold0adbc942014-05-12 10:35:43 -070039using std::set;
Alex Deymoc705cc82014-02-19 11:15:00 -080040using std::string;
41
Gilad Arnoldb3b05442014-05-30 14:25:05 -070042namespace {
43
Gilad Arnolddc4bb262014-07-23 10:45:19 -070044// Examines |err_code| and decides whether the URL index needs to be advanced,
45// the error count for the URL incremented, or none of the above. In the first
46// case, returns true; in the second case, increments |*url_num_error_p| and
47// returns false; otherwise just returns false.
Gilad Arnoldb3b05442014-05-30 14:25:05 -070048//
49// TODO(garnold) Adapted from PayloadState::UpdateFailed() (to be retired).
Gilad Arnolddc4bb262014-07-23 10:45:19 -070050bool HandleErrorCode(ErrorCode err_code, int* url_num_error_p) {
Gilad Arnoldb3b05442014-05-30 14:25:05 -070051 err_code = chromeos_update_engine::utils::GetBaseErrorCode(err_code);
52 switch (err_code) {
53 // Errors which are good indicators of a problem with a particular URL or
54 // the protocol used in the URL or entities in the communication channel
55 // (e.g. proxies). We should try the next available URL in the next update
56 // check to quickly recover from these errors.
57 case ErrorCode::kPayloadHashMismatchError:
58 case ErrorCode::kPayloadSizeMismatchError:
59 case ErrorCode::kDownloadPayloadVerificationError:
60 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
61 case ErrorCode::kSignedDeltaPayloadExpectedError:
62 case ErrorCode::kDownloadInvalidMetadataMagicString:
63 case ErrorCode::kDownloadSignatureMissingInManifest:
64 case ErrorCode::kDownloadManifestParseError:
65 case ErrorCode::kDownloadMetadataSignatureError:
66 case ErrorCode::kDownloadMetadataSignatureVerificationError:
67 case ErrorCode::kDownloadMetadataSignatureMismatch:
68 case ErrorCode::kDownloadOperationHashVerificationError:
69 case ErrorCode::kDownloadOperationExecutionError:
70 case ErrorCode::kDownloadOperationHashMismatch:
71 case ErrorCode::kDownloadInvalidMetadataSize:
72 case ErrorCode::kDownloadInvalidMetadataSignature:
73 case ErrorCode::kDownloadOperationHashMissingError:
74 case ErrorCode::kDownloadMetadataSignatureMissingError:
75 case ErrorCode::kPayloadMismatchedType:
76 case ErrorCode::kUnsupportedMajorPayloadVersion:
77 case ErrorCode::kUnsupportedMinorPayloadVersion:
78 LOG(INFO) << "Advancing download URL due to error "
79 << chromeos_update_engine::utils::CodeToString(err_code)
80 << " (" << static_cast<int>(err_code) << ")";
Gilad Arnoldb3b05442014-05-30 14:25:05 -070081 return true;
82
83 // Errors which seem to be just transient network/communication related
84 // failures and do not indicate any inherent problem with the URL itself.
85 // So, we should keep the current URL but just increment the
86 // failure count to give it more chances. This way, while we maximize our
87 // chances of downloading from the URLs that appear earlier in the response
88 // (because download from a local server URL that appears earlier in a
89 // response is preferable than downloading from the next URL which could be
Alex Vakulenko072359c2014-07-18 11:41:07 -070090 // an Internet URL and thus could be more expensive).
Gilad Arnoldb3b05442014-05-30 14:25:05 -070091 case ErrorCode::kError:
92 case ErrorCode::kDownloadTransferError:
93 case ErrorCode::kDownloadWriteError:
94 case ErrorCode::kDownloadStateInitializationError:
Gilad Arnold684219d2014-07-07 14:54:57 -070095 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Gilad Arnoldb3b05442014-05-30 14:25:05 -070096 LOG(INFO) << "Incrementing URL failure count due to error "
97 << chromeos_update_engine::utils::CodeToString(err_code)
98 << " (" << static_cast<int>(err_code) << ")";
Gilad Arnolddc4bb262014-07-23 10:45:19 -070099 *url_num_error_p += 1;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700100 return false;
101
102 // Errors which are not specific to a URL and hence shouldn't result in
103 // the URL being penalized. This can happen in two cases:
104 // 1. We haven't started downloading anything: These errors don't cost us
105 // anything in terms of actual payload bytes, so we should just do the
106 // regular retries at the next update check.
107 // 2. We have successfully downloaded the payload: In this case, the
108 // payload attempt number would have been incremented and would take care
Alex Vakulenko072359c2014-07-18 11:41:07 -0700109 // of the back-off at the next update check.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700110 // In either case, there's no need to update URL index or failure count.
111 case ErrorCode::kOmahaRequestError:
112 case ErrorCode::kOmahaResponseHandlerError:
113 case ErrorCode::kPostinstallRunnerError:
114 case ErrorCode::kFilesystemCopierError:
115 case ErrorCode::kInstallDeviceOpenError:
116 case ErrorCode::kKernelDeviceOpenError:
117 case ErrorCode::kDownloadNewPartitionInfoError:
118 case ErrorCode::kNewRootfsVerificationError:
119 case ErrorCode::kNewKernelVerificationError:
120 case ErrorCode::kPostinstallBootedFromFirmwareB:
121 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
122 case ErrorCode::kOmahaRequestEmptyResponseError:
123 case ErrorCode::kOmahaRequestXMLParseError:
124 case ErrorCode::kOmahaResponseInvalid:
125 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
126 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
127 case ErrorCode::kOmahaUpdateDeferredForBackoff:
128 case ErrorCode::kPostinstallPowerwashError:
129 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400130 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700131 case ErrorCode::kFilesystemVerifierError:
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700132 LOG(INFO) << "Not changing URL index or failure count due to error "
133 << chromeos_update_engine::utils::CodeToString(err_code)
134 << " (" << static_cast<int>(err_code) << ")";
135 return false;
136
137 case ErrorCode::kSuccess: // success code
138 case ErrorCode::kUmaReportedMax: // not an error code
139 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
140 case ErrorCode::kDevModeFlag: // not an error code
141 case ErrorCode::kResumedFlag: // not an error code
142 case ErrorCode::kTestImageFlag: // not an error code
143 case ErrorCode::kTestOmahaUrlFlag: // not an error code
144 case ErrorCode::kSpecialFlags: // not an error code
145 // These shouldn't happen. Enumerating these explicitly here so that we
146 // can let the compiler warn about new error codes that are added to
147 // action_processor.h but not added here.
148 LOG(WARNING) << "Unexpected error "
149 << chromeos_update_engine::utils::CodeToString(err_code)
150 << " (" << static_cast<int>(err_code) << ")";
151 // Note: Not adding a default here so as to let the compiler warn us of
152 // any new enums that were added in the .h but not listed in this switch.
153 }
154 return false;
155}
156
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700157// Checks whether |url| can be used under given download restrictions.
158bool IsUrlUsable(const string& url, bool http_allowed) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700159 return http_allowed || !base::StartsWithASCII(url, "http://", false);
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700160}
161
162} // namespace
163
Alex Deymo63784a52014-05-28 10:46:14 -0700164namespace chromeos_update_manager {
Alex Deymoc705cc82014-02-19 11:15:00 -0800165
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700166const int ChromeOSPolicy::kTimeoutInitialInterval = 7 * 60;
Alex Deymo14e7dde2015-10-20 14:46:33 -0700167
168// TODO(deymo): Split the update_manager policies for Brillo and ChromeOS and
169// make the update check periodic interval configurable.
170#ifdef __ANDROID__
171const int ChromeOSPolicy::kTimeoutPeriodicInterval = 5 * 60 * 60;
Alex Deymodbe13b42015-11-06 11:15:08 -0800172const int ChromeOSPolicy::kTimeoutMaxBackoffInterval = 26 * 60 * 60;
Alex Deymo14e7dde2015-10-20 14:46:33 -0700173#else
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700174const int ChromeOSPolicy::kTimeoutPeriodicInterval = 45 * 60;
Alex Deymodbe13b42015-11-06 11:15:08 -0800175const int ChromeOSPolicy::kTimeoutMaxBackoffInterval = 4 * 60 * 60;
Alex Deymo14e7dde2015-10-20 14:46:33 -0700176#endif // __ANDROID__
177
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700178const int ChromeOSPolicy::kTimeoutRegularFuzz = 10 * 60;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700179const int ChromeOSPolicy::kAttemptBackoffMaxIntervalInDays = 16;
180const int ChromeOSPolicy::kAttemptBackoffFuzzInHours = 12;
Gilad Arnold349ac832014-10-06 14:20:28 -0700181const int ChromeOSPolicy::kMaxP2PAttempts = 10;
182const int ChromeOSPolicy::kMaxP2PAttemptsPeriodInSeconds = 5 * 24 * 60 * 60;
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700183
Alex Deymo0d11c602014-04-23 20:12:20 -0700184EvalStatus ChromeOSPolicy::UpdateCheckAllowed(
185 EvaluationContext* ec, State* state, string* error,
186 UpdateCheckParams* result) const {
Gilad Arnold42f253b2014-06-25 12:39:17 -0700187 // Set the default return values.
188 result->updates_enabled = true;
189 result->target_channel.clear();
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700190 result->target_version_prefix.clear();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700191 result->is_interactive = false;
Gilad Arnold42f253b2014-06-25 12:39:17 -0700192
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700193 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700194 UpdaterProvider* const updater_provider = state->updater_provider();
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700195 SystemProvider* const system_provider = state->system_provider();
196
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700197 // Do not perform any updates if booted from removable device. This decision
198 // is final.
Alex Deymo763e7db2015-08-27 21:08:08 -0700199 const unsigned int* num_slots_p = ec->GetValue(
200 system_provider->var_num_slots());
201 if (!num_slots_p || *num_slots_p < 2) {
202 LOG(INFO) << "Not enough slots for A/B updates, disabling update checks.";
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700203 result->updates_enabled = false;
204 return EvalStatus::kSucceeded;
205 }
206
Gilad Arnold42f253b2014-06-25 12:39:17 -0700207 const bool* device_policy_is_loaded_p = ec->GetValue(
208 dp_provider->var_device_policy_is_loaded());
209 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
210 // Check whether updates are disabled by policy.
211 const bool* update_disabled_p = ec->GetValue(
212 dp_provider->var_update_disabled());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700213 if (update_disabled_p && *update_disabled_p) {
214 LOG(INFO) << "Updates disabled by policy, blocking update checks.";
Gilad Arnold42f253b2014-06-25 12:39:17 -0700215 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700216 }
Gilad Arnold42f253b2014-06-25 12:39:17 -0700217
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700218 // Determine whether a target version prefix is dictated by policy.
219 const string* target_version_prefix_p = ec->GetValue(
220 dp_provider->var_target_version_prefix());
221 if (target_version_prefix_p)
222 result->target_version_prefix = *target_version_prefix_p;
223
Gilad Arnold42f253b2014-06-25 12:39:17 -0700224 // Determine whether a target channel is dictated by policy.
225 const bool* release_channel_delegated_p = ec->GetValue(
226 dp_provider->var_release_channel_delegated());
227 if (release_channel_delegated_p && !(*release_channel_delegated_p)) {
228 const string* release_channel_p = ec->GetValue(
229 dp_provider->var_release_channel());
230 if (release_channel_p)
231 result->target_channel = *release_channel_p;
232 }
233 }
234
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700235 // First, check to see if an interactive update was requested.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700236 const UpdateRequestStatus* forced_update_requested_p = ec->GetValue(
237 updater_provider->var_forced_update_requested());
238 if (forced_update_requested_p &&
239 *forced_update_requested_p != UpdateRequestStatus::kNone) {
240 result->is_interactive =
241 (*forced_update_requested_p == UpdateRequestStatus::kInteractive);
242 LOG(INFO) << "Forced update signaled ("
243 << (result->is_interactive ? "interactive" : "periodic")
244 << "), allowing update check.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700245 return EvalStatus::kSucceeded;
246 }
247
248 // The logic thereafter applies to periodic updates. Bear in mind that we
249 // should not return a final "no" if any of these criteria are not satisfied,
250 // because the system may still update due to an interactive update request.
251
252 // Unofficial builds should not perform periodic update checks.
253 const bool* is_official_build_p = ec->GetValue(
254 system_provider->var_is_official_build());
255 if (is_official_build_p && !(*is_official_build_p)) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700256 LOG(INFO) << "Unofficial build, blocking periodic update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700257 return EvalStatus::kAskMeAgainLater;
258 }
259
260 // If OOBE is enabled, wait until it is completed.
261 const bool* is_oobe_enabled_p = ec->GetValue(
262 state->config_provider()->var_is_oobe_enabled());
263 if (is_oobe_enabled_p && *is_oobe_enabled_p) {
264 const bool* is_oobe_complete_p = ec->GetValue(
265 system_provider->var_is_oobe_complete());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700266 if (is_oobe_complete_p && !(*is_oobe_complete_p)) {
267 LOG(INFO) << "OOBE not completed, blocking update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700268 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700269 }
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700270 }
271
272 // Ensure that periodic update checks are timed properly.
Alex Deymo0d11c602014-04-23 20:12:20 -0700273 Time next_update_check;
274 if (NextUpdateCheckTime(ec, state, error, &next_update_check) !=
275 EvalStatus::kSucceeded) {
276 return EvalStatus::kFailed;
277 }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700278 if (!ec->IsWallclockTimeGreaterThan(next_update_check)) {
279 LOG(INFO) << "Periodic check interval not satisfied, blocking until "
280 << chromeos_update_engine::utils::ToString(next_update_check);
Alex Deymo0d11c602014-04-23 20:12:20 -0700281 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700282 }
Alex Deymo0d11c602014-04-23 20:12:20 -0700283
284 // It is time to check for an update.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700285 LOG(INFO) << "Allowing update check.";
Alex Deymoe636c3c2014-03-11 19:02:08 -0700286 return EvalStatus::kSucceeded;
Alex Deymoc705cc82014-02-19 11:15:00 -0800287}
288
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700289EvalStatus ChromeOSPolicy::UpdateCanStart(
290 EvaluationContext* ec,
291 State* state,
292 string* error,
Gilad Arnold42f253b2014-06-25 12:39:17 -0700293 UpdateDownloadParams* result,
Gilad Arnoldd78caf92014-09-24 09:28:14 -0700294 const UpdateState update_state) const {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700295 // Set the default return values. Note that we set persisted values (backoff,
296 // scattering) to the same values presented in the update state. The reason is
297 // that preemptive returns, such as the case where an update check is due,
298 // should not clear off the said values; rather, it is the deliberate
299 // inference of new values that should cause them to be reset.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700300 result->update_can_start = false;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700301 result->cannot_start_reason = UpdateCannotStartReason::kUndefined;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700302 result->download_url_idx = -1;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700303 result->download_url_allowed = true;
304 result->download_url_num_errors = 0;
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700305 result->p2p_downloading_allowed = false;
306 result->p2p_sharing_allowed = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700307 result->do_increment_failures = false;
308 result->backoff_expiry = update_state.backoff_expiry;
309 result->scatter_wait_period = update_state.scatter_wait_period;
310 result->scatter_check_threshold = update_state.scatter_check_threshold;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700311
312 // Make sure that we're not due for an update check.
313 UpdateCheckParams check_result;
314 EvalStatus check_status = UpdateCheckAllowed(ec, state, error, &check_result);
315 if (check_status == EvalStatus::kFailed)
316 return EvalStatus::kFailed;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700317 bool is_check_due = (check_status == EvalStatus::kSucceeded &&
318 check_result.updates_enabled == true);
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700319
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700320 // Check whether backoff applies, and if not then which URL can be used for
321 // downloading. These require scanning the download error log, and so they are
322 // done together.
323 UpdateBackoffAndDownloadUrlResult backoff_url_result;
324 EvalStatus backoff_url_status = UpdateBackoffAndDownloadUrl(
325 ec, state, error, &backoff_url_result, update_state);
Gilad Arnold14a9e702014-10-08 08:09:09 -0700326 if (backoff_url_status == EvalStatus::kFailed)
327 return EvalStatus::kFailed;
328 result->download_url_idx = backoff_url_result.url_idx;
329 result->download_url_num_errors = backoff_url_result.url_num_errors;
330 result->do_increment_failures = backoff_url_result.do_increment_failures;
331 result->backoff_expiry = backoff_url_result.backoff_expiry;
332 bool is_backoff_active =
333 (backoff_url_status == EvalStatus::kAskMeAgainLater) ||
334 !backoff_url_result.backoff_expiry.is_null();
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700335
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700336 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold14a9e702014-10-08 08:09:09 -0700337 bool is_scattering_active = false;
338 EvalStatus scattering_status = EvalStatus::kSucceeded;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700339
340 const bool* device_policy_is_loaded_p = ec->GetValue(
341 dp_provider->var_device_policy_is_loaded());
342 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700343 // Check whether scattering applies to this update attempt. We should not be
344 // scattering if this is an interactive update check, or if OOBE is enabled
345 // but not completed.
346 //
347 // Note: current code further suppresses scattering if a "deadline"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700348 // attribute is found in the Omaha response. However, it appears that the
Gilad Arnold76a11f62014-05-20 09:02:12 -0700349 // presence of this attribute is merely indicative of an OOBE update, during
350 // which we suppress scattering anyway.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700351 bool is_scattering_applicable = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700352 result->scatter_wait_period = kZeroInterval;
353 result->scatter_check_threshold = 0;
354 if (!update_state.is_interactive) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700355 const bool* is_oobe_enabled_p = ec->GetValue(
356 state->config_provider()->var_is_oobe_enabled());
357 if (is_oobe_enabled_p && !(*is_oobe_enabled_p)) {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700358 is_scattering_applicable = true;
Gilad Arnold76a11f62014-05-20 09:02:12 -0700359 } else {
360 const bool* is_oobe_complete_p = ec->GetValue(
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700361 state->system_provider()->var_is_oobe_complete());
Gilad Arnold14a9e702014-10-08 08:09:09 -0700362 is_scattering_applicable = (is_oobe_complete_p && *is_oobe_complete_p);
Gilad Arnold76a11f62014-05-20 09:02:12 -0700363 }
364 }
365
366 // Compute scattering values.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700367 if (is_scattering_applicable) {
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700368 UpdateScatteringResult scatter_result;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700369 scattering_status = UpdateScattering(ec, state, error, &scatter_result,
370 update_state);
371 if (scattering_status == EvalStatus::kFailed) {
372 return EvalStatus::kFailed;
373 } else {
374 result->scatter_wait_period = scatter_result.wait_period;
375 result->scatter_check_threshold = scatter_result.check_threshold;
376 if (scattering_status == EvalStatus::kAskMeAgainLater ||
377 scatter_result.is_scattering)
378 is_scattering_active = true;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700379 }
380 }
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700381 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700382
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700383 // Find out whether P2P is globally enabled.
384 bool p2p_enabled;
385 EvalStatus p2p_enabled_status = P2PEnabled(ec, state, error, &p2p_enabled);
386 if (p2p_enabled_status != EvalStatus::kSucceeded)
387 return EvalStatus::kFailed;
388
389 // Is P2P is enabled, consider allowing it for downloading and/or sharing.
390 if (p2p_enabled) {
391 // Sharing via P2P is allowed if not disabled by Omaha.
392 if (update_state.p2p_sharing_disabled) {
393 LOG(INFO) << "Blocked P2P sharing because it is disabled by Omaha.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700394 } else {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700395 result->p2p_sharing_allowed = true;
Gilad Arnoldef8d0872014-10-03 14:14:06 -0700396 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700397
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700398 // Downloading via P2P is allowed if not disabled by Omaha, an update is not
399 // interactive, and other limits haven't been reached.
400 if (update_state.p2p_downloading_disabled) {
401 LOG(INFO) << "Blocked P2P downloading because it is disabled by Omaha.";
402 } else if (update_state.is_interactive) {
403 LOG(INFO) << "Blocked P2P downloading because update is interactive.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700404 } else if (update_state.p2p_num_attempts >= kMaxP2PAttempts) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700405 LOG(INFO) << "Blocked P2P downloading as it was attempted too many "
406 "times.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700407 } else if (!update_state.p2p_first_attempted.is_null() &&
408 ec->IsWallclockTimeGreaterThan(
409 update_state.p2p_first_attempted +
410 TimeDelta::FromSeconds(kMaxP2PAttemptsPeriodInSeconds))) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700411 LOG(INFO) << "Blocked P2P downloading as its usage timespan exceeds "
412 "limit.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700413 } else {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700414 // P2P download is allowed; if backoff or scattering are active, be sure
415 // to suppress them, yet prevent any download URL from being used.
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700416 result->p2p_downloading_allowed = true;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700417 if (is_backoff_active || is_scattering_active) {
418 is_backoff_active = is_scattering_active = false;
419 result->download_url_allowed = false;
420 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700421 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700422 }
423
Gilad Arnold14a9e702014-10-08 08:09:09 -0700424 // Check for various deterrents.
425 if (is_check_due) {
426 result->cannot_start_reason = UpdateCannotStartReason::kCheckDue;
427 return EvalStatus::kSucceeded;
428 }
429 if (is_backoff_active) {
430 result->cannot_start_reason = UpdateCannotStartReason::kBackoff;
431 return backoff_url_status;
432 }
433 if (is_scattering_active) {
434 result->cannot_start_reason = UpdateCannotStartReason::kScattering;
435 return scattering_status;
436 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700437 if (result->download_url_idx < 0 && !result->p2p_downloading_allowed) {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700438 result->cannot_start_reason = UpdateCannotStartReason::kCannotDownload;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700439 return EvalStatus::kSucceeded;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700440 }
441
Gilad Arnold14a9e702014-10-08 08:09:09 -0700442 // Update is good to go.
443 result->update_can_start = true;
Gilad Arnoldaf2f6ae2014-04-28 14:14:52 -0700444 return EvalStatus::kSucceeded;
445}
446
Gilad Arnolda8262e22014-06-02 13:54:27 -0700447// TODO(garnold) Logic in this method is based on
448// ConnectionManager::IsUpdateAllowedOver(); be sure to deprecate the latter.
449//
450// TODO(garnold) The current logic generally treats the list of allowed
451// connections coming from the device policy as a whitelist, meaning that it
452// can only be used for enabling connections, but not disable them. Further,
453// certain connection types (like Bluetooth) cannot be enabled even by policy.
454// In effect, the only thing that device policy can change is to enable
455// updates over a cellular network (disabled by default). We may want to
456// revisit this semantics, allowing greater flexibility in defining specific
457// permissions over all types of networks.
Gilad Arnold684219d2014-07-07 14:54:57 -0700458EvalStatus ChromeOSPolicy::UpdateDownloadAllowed(
Gilad Arnolda8262e22014-06-02 13:54:27 -0700459 EvaluationContext* ec,
460 State* state,
461 string* error,
462 bool* result) const {
463 // Get the current connection type.
464 ShillProvider* const shill_provider = state->shill_provider();
465 const ConnectionType* conn_type_p = ec->GetValue(
466 shill_provider->var_conn_type());
467 POLICY_CHECK_VALUE_AND_FAIL(conn_type_p, error);
468 ConnectionType conn_type = *conn_type_p;
469
470 // If we're tethering, treat it as a cellular connection.
471 if (conn_type != ConnectionType::kCellular) {
472 const ConnectionTethering* conn_tethering_p = ec->GetValue(
473 shill_provider->var_conn_tethering());
474 POLICY_CHECK_VALUE_AND_FAIL(conn_tethering_p, error);
475 if (*conn_tethering_p == ConnectionTethering::kConfirmed)
476 conn_type = ConnectionType::kCellular;
477 }
478
479 // By default, we allow updates for all connection types, with exceptions as
480 // noted below. This also determines whether a device policy can override the
481 // default.
482 *result = true;
483 bool device_policy_can_override = false;
484 switch (conn_type) {
485 case ConnectionType::kBluetooth:
486 *result = false;
487 break;
488
489 case ConnectionType::kCellular:
490 *result = false;
491 device_policy_can_override = true;
492 break;
493
494 case ConnectionType::kUnknown:
495 if (error)
496 *error = "Unknown connection type";
497 return EvalStatus::kFailed;
498
499 default:
500 break; // Nothing to do.
501 }
502
503 // If update is allowed, we're done.
504 if (*result)
505 return EvalStatus::kSucceeded;
506
507 // Check whether the device policy specifically allows this connection.
Gilad Arnolda8262e22014-06-02 13:54:27 -0700508 if (device_policy_can_override) {
509 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
510 const bool* device_policy_is_loaded_p = ec->GetValue(
511 dp_provider->var_device_policy_is_loaded());
512 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
513 const set<ConnectionType>* allowed_conn_types_p = ec->GetValue(
514 dp_provider->var_allowed_connection_types_for_update());
515 if (allowed_conn_types_p) {
516 if (allowed_conn_types_p->count(conn_type)) {
517 *result = true;
518 return EvalStatus::kSucceeded;
519 }
Gilad Arnold28d6be62014-06-30 14:04:04 -0700520 } else if (conn_type == ConnectionType::kCellular) {
521 // Local user settings can allow updates over cellular iff a policy was
522 // loaded but no allowed connections were specified in it.
523 const bool* update_over_cellular_allowed_p = ec->GetValue(
524 state->updater_provider()->var_cellular_enabled());
525 if (update_over_cellular_allowed_p && *update_over_cellular_allowed_p)
526 *result = true;
Gilad Arnolda8262e22014-06-02 13:54:27 -0700527 }
528 }
529 }
530
Gilad Arnold28d6be62014-06-30 14:04:04 -0700531 return (*result ? EvalStatus::kSucceeded : EvalStatus::kAskMeAgainLater);
Gilad Arnolda8262e22014-06-02 13:54:27 -0700532}
533
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700534EvalStatus ChromeOSPolicy::P2PEnabled(EvaluationContext* ec,
535 State* state,
536 std::string* error,
537 bool* result) const {
538 bool enabled = false;
539
540 // Determine whether use of P2P is allowed by policy. Even if P2P is not
541 // explicitly allowed, we allow it if the device is enterprise enrolled (that
542 // is, missing or empty owner string).
543 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
544 const bool* device_policy_is_loaded_p = ec->GetValue(
545 dp_provider->var_device_policy_is_loaded());
546 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
547 const bool* policy_au_p2p_enabled_p = ec->GetValue(
548 dp_provider->var_au_p2p_enabled());
549 if (policy_au_p2p_enabled_p) {
550 enabled = *policy_au_p2p_enabled_p;
551 } else {
552 const string* policy_owner_p = ec->GetValue(dp_provider->var_owner());
553 if (!policy_owner_p || policy_owner_p->empty())
554 enabled = true;
555 }
556 }
557
558 // Enable P2P, if so mandated by the updater configuration. This is additive
559 // to whether or not P2P is enabled by device policy.
560 if (!enabled) {
561 const bool* updater_p2p_enabled_p = ec->GetValue(
562 state->updater_provider()->var_p2p_enabled());
563 enabled = updater_p2p_enabled_p && *updater_p2p_enabled_p;
564 }
565
566 *result = enabled;
567 return EvalStatus::kSucceeded;
568}
569
570EvalStatus ChromeOSPolicy::P2PEnabledChanged(EvaluationContext* ec,
571 State* state,
572 std::string* error,
573 bool* result,
574 bool prev_result) const {
575 EvalStatus status = P2PEnabled(ec, state, error, result);
576 if (status == EvalStatus::kSucceeded && *result == prev_result)
577 return EvalStatus::kAskMeAgainLater;
578 return status;
579}
580
Alex Deymo0d11c602014-04-23 20:12:20 -0700581EvalStatus ChromeOSPolicy::NextUpdateCheckTime(EvaluationContext* ec,
582 State* state, string* error,
583 Time* next_update_check) const {
Gilad Arnolda0258a52014-07-10 16:21:19 -0700584 UpdaterProvider* const updater_provider = state->updater_provider();
585
Alex Deymo0d11c602014-04-23 20:12:20 -0700586 // Don't check for updates too often. We limit the update checks to once every
587 // some interval. The interval is kTimeoutInitialInterval the first time and
588 // kTimeoutPeriodicInterval for the subsequent update checks. If the update
589 // check fails, we increase the interval between the update checks
590 // exponentially until kTimeoutMaxBackoffInterval. Finally, to avoid having
591 // many chromebooks running update checks at the exact same time, we add some
592 // fuzz to the interval.
593 const Time* updater_started_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700594 ec->GetValue(updater_provider->var_updater_started_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700595 POLICY_CHECK_VALUE_AND_FAIL(updater_started_time, error);
596
Alex Deymof329b932014-10-30 01:37:48 -0700597 const Time* last_checked_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700598 ec->GetValue(updater_provider->var_last_checked_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700599
600 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
601 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
602
603 PRNG prng(*seed);
604
Gilad Arnold38b14022014-07-09 12:45:56 -0700605 // If this is the first attempt, compute and return an initial value.
Alex Deymo0d11c602014-04-23 20:12:20 -0700606 if (!last_checked_time || *last_checked_time < *updater_started_time) {
Alex Deymo0d11c602014-04-23 20:12:20 -0700607 *next_update_check = *updater_started_time + FuzzedInterval(
608 &prng, kTimeoutInitialInterval, kTimeoutRegularFuzz);
609 return EvalStatus::kSucceeded;
610 }
Gilad Arnold38b14022014-07-09 12:45:56 -0700611
Gilad Arnolda0258a52014-07-10 16:21:19 -0700612 // Check whether the server is enforcing a poll interval; if not, this value
613 // will be zero.
614 const unsigned int* server_dictated_poll_interval = ec->GetValue(
615 updater_provider->var_server_dictated_poll_interval());
616 POLICY_CHECK_VALUE_AND_FAIL(server_dictated_poll_interval, error);
Alex Deymo0d11c602014-04-23 20:12:20 -0700617
Gilad Arnolda0258a52014-07-10 16:21:19 -0700618 int interval = *server_dictated_poll_interval;
619 int fuzz = 0;
620
Alex Vakulenko072359c2014-07-18 11:41:07 -0700621 // If no poll interval was dictated by server compute a back-off period,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700622 // starting from a predetermined base periodic interval and increasing
623 // exponentially by the number of consecutive failed attempts.
624 if (interval == 0) {
625 const unsigned int* consecutive_failed_update_checks = ec->GetValue(
626 updater_provider->var_consecutive_failed_update_checks());
627 POLICY_CHECK_VALUE_AND_FAIL(consecutive_failed_update_checks, error);
628
629 interval = kTimeoutPeriodicInterval;
630 unsigned int num_failures = *consecutive_failed_update_checks;
631 while (interval < kTimeoutMaxBackoffInterval && num_failures) {
632 interval *= 2;
633 num_failures--;
Alex Deymo0d11c602014-04-23 20:12:20 -0700634 }
635 }
636
Alex Vakulenko072359c2014-07-18 11:41:07 -0700637 // We cannot back off longer than the predetermined maximum interval.
Gilad Arnolda0258a52014-07-10 16:21:19 -0700638 if (interval > kTimeoutMaxBackoffInterval)
639 interval = kTimeoutMaxBackoffInterval;
640
Alex Vakulenko072359c2014-07-18 11:41:07 -0700641 // We cannot back off shorter than the predetermined periodic interval. Also,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700642 // in this case set the fuzz to a predetermined regular value.
643 if (interval <= kTimeoutPeriodicInterval) {
644 interval = kTimeoutPeriodicInterval;
645 fuzz = kTimeoutRegularFuzz;
646 }
647
648 // If not otherwise determined, defer to a fuzz of +/-(interval / 2).
Gilad Arnold38b14022014-07-09 12:45:56 -0700649 if (fuzz == 0)
650 fuzz = interval;
651
Alex Deymo0d11c602014-04-23 20:12:20 -0700652 *next_update_check = *last_checked_time + FuzzedInterval(
Gilad Arnold38b14022014-07-09 12:45:56 -0700653 &prng, interval, fuzz);
Alex Deymo0d11c602014-04-23 20:12:20 -0700654 return EvalStatus::kSucceeded;
655}
656
657TimeDelta ChromeOSPolicy::FuzzedInterval(PRNG* prng, int interval, int fuzz) {
Gilad Arnolde1218812014-05-07 12:21:36 -0700658 DCHECK_GE(interval, 0);
659 DCHECK_GE(fuzz, 0);
Alex Deymo0d11c602014-04-23 20:12:20 -0700660 int half_fuzz = fuzz / 2;
Alex Deymo0d11c602014-04-23 20:12:20 -0700661 // This guarantees the output interval is non negative.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700662 int interval_min = max(interval - half_fuzz, 0);
Gilad Arnolde1218812014-05-07 12:21:36 -0700663 int interval_max = interval + half_fuzz;
664 return TimeDelta::FromSeconds(prng->RandMinMax(interval_min, interval_max));
Alex Deymo0d11c602014-04-23 20:12:20 -0700665}
666
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700667EvalStatus ChromeOSPolicy::UpdateBackoffAndDownloadUrl(
Alex Deymof329b932014-10-30 01:37:48 -0700668 EvaluationContext* ec, State* state, string* error,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700669 UpdateBackoffAndDownloadUrlResult* result,
670 const UpdateState& update_state) const {
671 // Sanity checks.
672 DCHECK_GE(update_state.download_errors_max, 0);
673
674 // Set default result values.
675 result->do_increment_failures = false;
676 result->backoff_expiry = update_state.backoff_expiry;
677 result->url_idx = -1;
678 result->url_num_errors = 0;
679
680 const bool* is_official_build_p = ec->GetValue(
681 state->system_provider()->var_is_official_build());
682 bool is_official_build = (is_official_build_p ? *is_official_build_p : true);
683
684 // Check whether backoff is enabled.
685 bool may_backoff = false;
686 if (update_state.is_backoff_disabled) {
687 LOG(INFO) << "Backoff disabled by Omaha.";
688 } else if (update_state.is_interactive) {
689 LOG(INFO) << "No backoff for interactive updates.";
690 } else if (update_state.is_delta_payload) {
691 LOG(INFO) << "No backoff for delta payloads.";
692 } else if (!is_official_build) {
693 LOG(INFO) << "No backoff for unofficial builds.";
694 } else {
695 may_backoff = true;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700696 }
697
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700698 // If previous backoff still in effect, block.
699 if (may_backoff && !update_state.backoff_expiry.is_null() &&
700 !ec->IsWallclockTimeGreaterThan(update_state.backoff_expiry)) {
701 LOG(INFO) << "Previous backoff has not expired, waiting.";
702 return EvalStatus::kAskMeAgainLater;
703 }
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700704
705 // Determine whether HTTP downloads are forbidden by policy. This only
706 // applies to official system builds; otherwise, HTTP is always enabled.
707 bool http_allowed = true;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700708 if (is_official_build) {
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700709 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
710 const bool* device_policy_is_loaded_p = ec->GetValue(
711 dp_provider->var_device_policy_is_loaded());
712 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
713 const bool* policy_http_downloads_enabled_p = ec->GetValue(
714 dp_provider->var_http_downloads_enabled());
715 http_allowed = (!policy_http_downloads_enabled_p ||
716 *policy_http_downloads_enabled_p);
717 }
718 }
719
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700720 int url_idx = update_state.last_download_url_idx;
721 if (url_idx < 0)
722 url_idx = -1;
723 bool do_advance_url = false;
724 bool is_failure_occurred = false;
725 Time err_time;
726
727 // Scan the relevant part of the download error log, tracking which URLs are
728 // being used, and accounting the number of errors for each URL. Note that
729 // this process may not traverse all errors provided, as it may decide to bail
730 // out midway depending on the particular errors exhibited, the number of
731 // failures allowed, etc. When this ends, |url_idx| will point to the last URL
732 // used (-1 if starting fresh), |do_advance_url| will determine whether the
733 // URL needs to be advanced, and |err_time| the point in time when the last
734 // reported error occurred. Additionally, if the error log indicates that an
735 // update attempt has failed (abnormal), then |is_failure_occurred| will be
736 // set to true.
737 const int num_urls = update_state.download_urls.size();
738 int prev_url_idx = -1;
739 int url_num_errors = update_state.last_download_url_num_errors;
740 Time prev_err_time;
741 bool is_first = true;
742 for (const auto& err_tuple : update_state.download_errors) {
743 // Do some sanity checks.
744 int used_url_idx = get<0>(err_tuple);
745 if (is_first && url_idx >= 0 && used_url_idx != url_idx) {
746 LOG(WARNING) << "First URL in error log (" << used_url_idx
747 << ") not as expected (" << url_idx << ")";
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700748 }
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700749 is_first = false;
750 url_idx = used_url_idx;
751 if (url_idx < 0 || url_idx >= num_urls) {
752 LOG(ERROR) << "Download error log contains an invalid URL index ("
753 << url_idx << ")";
754 return EvalStatus::kFailed;
755 }
756 err_time = get<2>(err_tuple);
757 if (!(prev_err_time.is_null() || err_time >= prev_err_time)) {
758 // TODO(garnold) Monotonicity cannot really be assumed when dealing with
759 // wallclock-based timestamps. However, we're making a simplifying
760 // assumption so as to keep the policy implementation straightforward, for
761 // now. In general, we should convert all timestamp handling in the
762 // UpdateManager to use monotonic time (instead of wallclock), including
763 // the computation of various expiration times (backoff, scattering, etc).
764 // The client will do whatever conversions necessary when
765 // persisting/retrieving these values across reboots. See chromium:408794.
766 LOG(ERROR) << "Download error timestamps not monotonically increasing.";
767 return EvalStatus::kFailed;
768 }
769 prev_err_time = err_time;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700770
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700771 // Ignore errors that happened before the last known failed attempt.
772 if (!update_state.failures_last_updated.is_null() &&
773 err_time <= update_state.failures_last_updated)
774 continue;
775
776 if (prev_url_idx >= 0) {
777 if (url_idx < prev_url_idx) {
778 LOG(ERROR) << "The URLs in the download error log have wrapped around ("
779 << prev_url_idx << "->" << url_idx
780 << "). This should not have happened and means that there's "
781 "a bug. To be conservative, we record a failed attempt "
782 "(invalidating the rest of the error log) and resume "
783 "download from the first usable URL.";
784 url_idx = -1;
785 is_failure_occurred = true;
786 break;
787 }
788
789 if (url_idx > prev_url_idx) {
790 url_num_errors = 0;
791 do_advance_url = false;
792 }
793 }
794
795 if (HandleErrorCode(get<1>(err_tuple), &url_num_errors) ||
796 url_num_errors > update_state.download_errors_max)
797 do_advance_url = true;
798
799 prev_url_idx = url_idx;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700800 }
801
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700802 // If required, advance to the next usable URL. If the URLs wraparound, we
803 // mark an update attempt failure. Also be sure to set the download error
804 // count to zero.
805 if (url_idx < 0 || do_advance_url) {
806 url_num_errors = 0;
807 int start_url_idx = -1;
808 do {
809 if (++url_idx == num_urls) {
810 url_idx = 0;
811 // We only mark failure if an actual advancing of a URL was required.
812 if (do_advance_url)
813 is_failure_occurred = true;
814 }
815
816 if (start_url_idx < 0)
817 start_url_idx = url_idx;
818 else if (url_idx == start_url_idx)
819 url_idx = -1; // No usable URL.
820 } while (url_idx >= 0 &&
821 !IsUrlUsable(update_state.download_urls[url_idx], http_allowed));
822 }
823
824 // If we have a download URL but a failure was observed, compute a new backoff
825 // expiry (if allowed). The backoff period is generally 2 ^ (num_failures - 1)
826 // days, bounded by the size of int and kAttemptBackoffMaxIntervalInDays, and
827 // fuzzed by kAttemptBackoffFuzzInHours hours. Backoff expiry is computed from
828 // the latest recorded time of error.
829 Time backoff_expiry;
830 if (url_idx >= 0 && is_failure_occurred && may_backoff) {
831 CHECK(!err_time.is_null())
832 << "We must have an error timestamp if a failure occurred!";
833 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
834 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
835 PRNG prng(*seed);
Alex Deymof329b932014-10-30 01:37:48 -0700836 int exp = min(update_state.num_failures,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700837 static_cast<int>(sizeof(int)) * 8 - 2);
838 TimeDelta backoff_interval = TimeDelta::FromDays(
Alex Deymof329b932014-10-30 01:37:48 -0700839 min(1 << exp, kAttemptBackoffMaxIntervalInDays));
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700840 TimeDelta backoff_fuzz = TimeDelta::FromHours(kAttemptBackoffFuzzInHours);
841 TimeDelta wait_period = FuzzedInterval(&prng, backoff_interval.InSeconds(),
842 backoff_fuzz.InSeconds());
843 backoff_expiry = err_time + wait_period;
844
845 // If the newly computed backoff already expired, nullify it.
846 if (ec->IsWallclockTimeGreaterThan(backoff_expiry))
847 backoff_expiry = Time();
848 }
849
850 result->do_increment_failures = is_failure_occurred;
851 result->backoff_expiry = backoff_expiry;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700852 result->url_idx = url_idx;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700853 result->url_num_errors = url_num_errors;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700854 return EvalStatus::kSucceeded;
855}
856
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700857EvalStatus ChromeOSPolicy::UpdateScattering(
858 EvaluationContext* ec,
859 State* state,
860 string* error,
861 UpdateScatteringResult* result,
862 const UpdateState& update_state) const {
863 // Preconditions. These stem from the postconditions and usage contract.
864 DCHECK(update_state.scatter_wait_period >= kZeroInterval);
865 DCHECK_GE(update_state.scatter_check_threshold, 0);
866
867 // Set default result values.
868 result->is_scattering = false;
869 result->wait_period = kZeroInterval;
870 result->check_threshold = 0;
871
872 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
873
874 // Ensure that a device policy is loaded.
875 const bool* device_policy_is_loaded_p = ec->GetValue(
876 dp_provider->var_device_policy_is_loaded());
877 if (!(device_policy_is_loaded_p && *device_policy_is_loaded_p))
878 return EvalStatus::kSucceeded;
879
880 // Is scattering enabled by policy?
881 const TimeDelta* scatter_factor_p = ec->GetValue(
882 dp_provider->var_scatter_factor());
883 if (!scatter_factor_p || *scatter_factor_p == kZeroInterval)
884 return EvalStatus::kSucceeded;
885
886 // Obtain a pseudo-random number generator.
887 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
888 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
889 PRNG prng(*seed);
890
891 // Step 1: Maintain the scattering wait period.
892 //
893 // If no wait period was previously determined, or it no longer fits in the
894 // scatter factor, then generate a new one. Otherwise, keep the one we have.
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700895 TimeDelta wait_period = update_state.scatter_wait_period;
896 if (wait_period == kZeroInterval || wait_period > *scatter_factor_p) {
897 wait_period = TimeDelta::FromSeconds(
898 prng.RandMinMax(1, scatter_factor_p->InSeconds()));
899 }
900
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700901 // If we surpassed the wait period or the max scatter period associated with
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700902 // the update, then no wait is needed.
903 Time wait_expires = (update_state.first_seen +
904 min(wait_period, update_state.scatter_wait_period_max));
Gilad Arnolda65fced2014-07-23 09:01:31 -0700905 if (ec->IsWallclockTimeGreaterThan(wait_expires))
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700906 wait_period = kZeroInterval;
907
908 // Step 2: Maintain the update check threshold count.
909 //
910 // If an update check threshold is not specified then generate a new
911 // one.
912 int check_threshold = update_state.scatter_check_threshold;
913 if (check_threshold == 0) {
914 check_threshold = prng.RandMinMax(
915 update_state.scatter_check_threshold_min,
916 update_state.scatter_check_threshold_max);
917 }
918
919 // If the update check threshold is not within allowed range then nullify it.
920 // TODO(garnold) This is compliant with current logic found in
921 // OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied(). We may want
922 // to change it so that it behaves similarly to the wait period case, namely
923 // if the current value exceeds the maximum, we set a new one within range.
924 if (check_threshold > update_state.scatter_check_threshold_max)
925 check_threshold = 0;
926
927 // If the update check threshold is non-zero and satisfied, then nullify it.
928 if (check_threshold > 0 && update_state.num_checks >= check_threshold)
929 check_threshold = 0;
930
931 bool is_scattering = (wait_period != kZeroInterval || check_threshold);
932 EvalStatus ret = EvalStatus::kSucceeded;
933 if (is_scattering && wait_period == update_state.scatter_wait_period &&
934 check_threshold == update_state.scatter_check_threshold)
935 ret = EvalStatus::kAskMeAgainLater;
936 result->is_scattering = is_scattering;
937 result->wait_period = wait_period;
938 result->check_threshold = check_threshold;
939 return ret;
940}
941
Alex Deymo63784a52014-05-28 10:46:14 -0700942} // namespace chromeos_update_manager