blob: 80ef63b4dd3e216f4e9255a9091ac35a39706906 [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;
167const int ChromeOSPolicy::kTimeoutPeriodicInterval = 45 * 60;
168const int ChromeOSPolicy::kTimeoutMaxBackoffInterval = 4 * 60 * 60;
169const int ChromeOSPolicy::kTimeoutRegularFuzz = 10 * 60;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700170const int ChromeOSPolicy::kAttemptBackoffMaxIntervalInDays = 16;
171const int ChromeOSPolicy::kAttemptBackoffFuzzInHours = 12;
Gilad Arnold349ac832014-10-06 14:20:28 -0700172const int ChromeOSPolicy::kMaxP2PAttempts = 10;
173const int ChromeOSPolicy::kMaxP2PAttemptsPeriodInSeconds = 5 * 24 * 60 * 60;
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700174
Alex Deymo0d11c602014-04-23 20:12:20 -0700175EvalStatus ChromeOSPolicy::UpdateCheckAllowed(
176 EvaluationContext* ec, State* state, string* error,
177 UpdateCheckParams* result) const {
Gilad Arnold42f253b2014-06-25 12:39:17 -0700178 // Set the default return values.
179 result->updates_enabled = true;
180 result->target_channel.clear();
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700181 result->target_version_prefix.clear();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700182 result->is_interactive = false;
Gilad Arnold42f253b2014-06-25 12:39:17 -0700183
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700184 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700185 UpdaterProvider* const updater_provider = state->updater_provider();
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700186 SystemProvider* const system_provider = state->system_provider();
187
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700188 // Do not perform any updates if booted from removable device. This decision
189 // is final.
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700190 const bool* is_boot_device_removable_p = ec->GetValue(
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700191 system_provider->var_is_boot_device_removable());
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700192 if (is_boot_device_removable_p && *is_boot_device_removable_p) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700193 LOG(INFO) << "Booted from removable device, disabling update checks.";
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700194 result->updates_enabled = false;
195 return EvalStatus::kSucceeded;
196 }
197
Gilad Arnold42f253b2014-06-25 12:39:17 -0700198 const bool* device_policy_is_loaded_p = ec->GetValue(
199 dp_provider->var_device_policy_is_loaded());
200 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
201 // Check whether updates are disabled by policy.
202 const bool* update_disabled_p = ec->GetValue(
203 dp_provider->var_update_disabled());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700204 if (update_disabled_p && *update_disabled_p) {
205 LOG(INFO) << "Updates disabled by policy, blocking update checks.";
Gilad Arnold42f253b2014-06-25 12:39:17 -0700206 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700207 }
Gilad Arnold42f253b2014-06-25 12:39:17 -0700208
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700209 // Determine whether a target version prefix is dictated by policy.
210 const string* target_version_prefix_p = ec->GetValue(
211 dp_provider->var_target_version_prefix());
212 if (target_version_prefix_p)
213 result->target_version_prefix = *target_version_prefix_p;
214
Gilad Arnold42f253b2014-06-25 12:39:17 -0700215 // Determine whether a target channel is dictated by policy.
216 const bool* release_channel_delegated_p = ec->GetValue(
217 dp_provider->var_release_channel_delegated());
218 if (release_channel_delegated_p && !(*release_channel_delegated_p)) {
219 const string* release_channel_p = ec->GetValue(
220 dp_provider->var_release_channel());
221 if (release_channel_p)
222 result->target_channel = *release_channel_p;
223 }
224 }
225
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700226 // First, check to see if an interactive update was requested.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700227 const UpdateRequestStatus* forced_update_requested_p = ec->GetValue(
228 updater_provider->var_forced_update_requested());
229 if (forced_update_requested_p &&
230 *forced_update_requested_p != UpdateRequestStatus::kNone) {
231 result->is_interactive =
232 (*forced_update_requested_p == UpdateRequestStatus::kInteractive);
233 LOG(INFO) << "Forced update signaled ("
234 << (result->is_interactive ? "interactive" : "periodic")
235 << "), allowing update check.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700236 return EvalStatus::kSucceeded;
237 }
238
239 // The logic thereafter applies to periodic updates. Bear in mind that we
240 // should not return a final "no" if any of these criteria are not satisfied,
241 // because the system may still update due to an interactive update request.
242
243 // Unofficial builds should not perform periodic update checks.
244 const bool* is_official_build_p = ec->GetValue(
245 system_provider->var_is_official_build());
246 if (is_official_build_p && !(*is_official_build_p)) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700247 LOG(INFO) << "Unofficial build, blocking periodic update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700248 return EvalStatus::kAskMeAgainLater;
249 }
250
251 // If OOBE is enabled, wait until it is completed.
252 const bool* is_oobe_enabled_p = ec->GetValue(
253 state->config_provider()->var_is_oobe_enabled());
254 if (is_oobe_enabled_p && *is_oobe_enabled_p) {
255 const bool* is_oobe_complete_p = ec->GetValue(
256 system_provider->var_is_oobe_complete());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700257 if (is_oobe_complete_p && !(*is_oobe_complete_p)) {
258 LOG(INFO) << "OOBE not completed, blocking update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700259 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700260 }
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700261 }
262
263 // Ensure that periodic update checks are timed properly.
Alex Deymo0d11c602014-04-23 20:12:20 -0700264 Time next_update_check;
265 if (NextUpdateCheckTime(ec, state, error, &next_update_check) !=
266 EvalStatus::kSucceeded) {
267 return EvalStatus::kFailed;
268 }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700269 if (!ec->IsWallclockTimeGreaterThan(next_update_check)) {
270 LOG(INFO) << "Periodic check interval not satisfied, blocking until "
271 << chromeos_update_engine::utils::ToString(next_update_check);
Alex Deymo0d11c602014-04-23 20:12:20 -0700272 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700273 }
Alex Deymo0d11c602014-04-23 20:12:20 -0700274
275 // It is time to check for an update.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700276 LOG(INFO) << "Allowing update check.";
Alex Deymoe636c3c2014-03-11 19:02:08 -0700277 return EvalStatus::kSucceeded;
Alex Deymoc705cc82014-02-19 11:15:00 -0800278}
279
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700280EvalStatus ChromeOSPolicy::UpdateCanStart(
281 EvaluationContext* ec,
282 State* state,
283 string* error,
Gilad Arnold42f253b2014-06-25 12:39:17 -0700284 UpdateDownloadParams* result,
Gilad Arnoldd78caf92014-09-24 09:28:14 -0700285 const UpdateState update_state) const {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700286 // Set the default return values. Note that we set persisted values (backoff,
287 // scattering) to the same values presented in the update state. The reason is
288 // that preemptive returns, such as the case where an update check is due,
289 // should not clear off the said values; rather, it is the deliberate
290 // inference of new values that should cause them to be reset.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700291 result->update_can_start = false;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700292 result->cannot_start_reason = UpdateCannotStartReason::kUndefined;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700293 result->download_url_idx = -1;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700294 result->download_url_allowed = true;
295 result->download_url_num_errors = 0;
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700296 result->p2p_downloading_allowed = false;
297 result->p2p_sharing_allowed = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700298 result->do_increment_failures = false;
299 result->backoff_expiry = update_state.backoff_expiry;
300 result->scatter_wait_period = update_state.scatter_wait_period;
301 result->scatter_check_threshold = update_state.scatter_check_threshold;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700302
303 // Make sure that we're not due for an update check.
304 UpdateCheckParams check_result;
305 EvalStatus check_status = UpdateCheckAllowed(ec, state, error, &check_result);
306 if (check_status == EvalStatus::kFailed)
307 return EvalStatus::kFailed;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700308 bool is_check_due = (check_status == EvalStatus::kSucceeded &&
309 check_result.updates_enabled == true);
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700310
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700311 // Check whether backoff applies, and if not then which URL can be used for
312 // downloading. These require scanning the download error log, and so they are
313 // done together.
314 UpdateBackoffAndDownloadUrlResult backoff_url_result;
315 EvalStatus backoff_url_status = UpdateBackoffAndDownloadUrl(
316 ec, state, error, &backoff_url_result, update_state);
Gilad Arnold14a9e702014-10-08 08:09:09 -0700317 if (backoff_url_status == EvalStatus::kFailed)
318 return EvalStatus::kFailed;
319 result->download_url_idx = backoff_url_result.url_idx;
320 result->download_url_num_errors = backoff_url_result.url_num_errors;
321 result->do_increment_failures = backoff_url_result.do_increment_failures;
322 result->backoff_expiry = backoff_url_result.backoff_expiry;
323 bool is_backoff_active =
324 (backoff_url_status == EvalStatus::kAskMeAgainLater) ||
325 !backoff_url_result.backoff_expiry.is_null();
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700326
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700327 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold14a9e702014-10-08 08:09:09 -0700328 bool is_scattering_active = false;
329 EvalStatus scattering_status = EvalStatus::kSucceeded;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700330
331 const bool* device_policy_is_loaded_p = ec->GetValue(
332 dp_provider->var_device_policy_is_loaded());
333 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700334 // Check whether scattering applies to this update attempt. We should not be
335 // scattering if this is an interactive update check, or if OOBE is enabled
336 // but not completed.
337 //
338 // Note: current code further suppresses scattering if a "deadline"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700339 // attribute is found in the Omaha response. However, it appears that the
Gilad Arnold76a11f62014-05-20 09:02:12 -0700340 // presence of this attribute is merely indicative of an OOBE update, during
341 // which we suppress scattering anyway.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700342 bool is_scattering_applicable = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700343 result->scatter_wait_period = kZeroInterval;
344 result->scatter_check_threshold = 0;
345 if (!update_state.is_interactive) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700346 const bool* is_oobe_enabled_p = ec->GetValue(
347 state->config_provider()->var_is_oobe_enabled());
348 if (is_oobe_enabled_p && !(*is_oobe_enabled_p)) {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700349 is_scattering_applicable = true;
Gilad Arnold76a11f62014-05-20 09:02:12 -0700350 } else {
351 const bool* is_oobe_complete_p = ec->GetValue(
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700352 state->system_provider()->var_is_oobe_complete());
Gilad Arnold14a9e702014-10-08 08:09:09 -0700353 is_scattering_applicable = (is_oobe_complete_p && *is_oobe_complete_p);
Gilad Arnold76a11f62014-05-20 09:02:12 -0700354 }
355 }
356
357 // Compute scattering values.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700358 if (is_scattering_applicable) {
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700359 UpdateScatteringResult scatter_result;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700360 scattering_status = UpdateScattering(ec, state, error, &scatter_result,
361 update_state);
362 if (scattering_status == EvalStatus::kFailed) {
363 return EvalStatus::kFailed;
364 } else {
365 result->scatter_wait_period = scatter_result.wait_period;
366 result->scatter_check_threshold = scatter_result.check_threshold;
367 if (scattering_status == EvalStatus::kAskMeAgainLater ||
368 scatter_result.is_scattering)
369 is_scattering_active = true;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700370 }
371 }
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700372 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700373
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700374 // Find out whether P2P is globally enabled.
375 bool p2p_enabled;
376 EvalStatus p2p_enabled_status = P2PEnabled(ec, state, error, &p2p_enabled);
377 if (p2p_enabled_status != EvalStatus::kSucceeded)
378 return EvalStatus::kFailed;
379
380 // Is P2P is enabled, consider allowing it for downloading and/or sharing.
381 if (p2p_enabled) {
382 // Sharing via P2P is allowed if not disabled by Omaha.
383 if (update_state.p2p_sharing_disabled) {
384 LOG(INFO) << "Blocked P2P sharing because it is disabled by Omaha.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700385 } else {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700386 result->p2p_sharing_allowed = true;
Gilad Arnoldef8d0872014-10-03 14:14:06 -0700387 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700388
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700389 // Downloading via P2P is allowed if not disabled by Omaha, an update is not
390 // interactive, and other limits haven't been reached.
391 if (update_state.p2p_downloading_disabled) {
392 LOG(INFO) << "Blocked P2P downloading because it is disabled by Omaha.";
393 } else if (update_state.is_interactive) {
394 LOG(INFO) << "Blocked P2P downloading because update is interactive.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700395 } else if (update_state.p2p_num_attempts >= kMaxP2PAttempts) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700396 LOG(INFO) << "Blocked P2P downloading as it was attempted too many "
397 "times.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700398 } else if (!update_state.p2p_first_attempted.is_null() &&
399 ec->IsWallclockTimeGreaterThan(
400 update_state.p2p_first_attempted +
401 TimeDelta::FromSeconds(kMaxP2PAttemptsPeriodInSeconds))) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700402 LOG(INFO) << "Blocked P2P downloading as its usage timespan exceeds "
403 "limit.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700404 } else {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700405 // P2P download is allowed; if backoff or scattering are active, be sure
406 // to suppress them, yet prevent any download URL from being used.
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700407 result->p2p_downloading_allowed = true;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700408 if (is_backoff_active || is_scattering_active) {
409 is_backoff_active = is_scattering_active = false;
410 result->download_url_allowed = false;
411 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700412 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700413 }
414
Gilad Arnold14a9e702014-10-08 08:09:09 -0700415 // Check for various deterrents.
416 if (is_check_due) {
417 result->cannot_start_reason = UpdateCannotStartReason::kCheckDue;
418 return EvalStatus::kSucceeded;
419 }
420 if (is_backoff_active) {
421 result->cannot_start_reason = UpdateCannotStartReason::kBackoff;
422 return backoff_url_status;
423 }
424 if (is_scattering_active) {
425 result->cannot_start_reason = UpdateCannotStartReason::kScattering;
426 return scattering_status;
427 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700428 if (result->download_url_idx < 0 && !result->p2p_downloading_allowed) {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700429 result->cannot_start_reason = UpdateCannotStartReason::kCannotDownload;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700430 return EvalStatus::kSucceeded;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700431 }
432
Gilad Arnold14a9e702014-10-08 08:09:09 -0700433 // Update is good to go.
434 result->update_can_start = true;
Gilad Arnoldaf2f6ae2014-04-28 14:14:52 -0700435 return EvalStatus::kSucceeded;
436}
437
Gilad Arnolda8262e22014-06-02 13:54:27 -0700438// TODO(garnold) Logic in this method is based on
439// ConnectionManager::IsUpdateAllowedOver(); be sure to deprecate the latter.
440//
441// TODO(garnold) The current logic generally treats the list of allowed
442// connections coming from the device policy as a whitelist, meaning that it
443// can only be used for enabling connections, but not disable them. Further,
444// certain connection types (like Bluetooth) cannot be enabled even by policy.
445// In effect, the only thing that device policy can change is to enable
446// updates over a cellular network (disabled by default). We may want to
447// revisit this semantics, allowing greater flexibility in defining specific
448// permissions over all types of networks.
Gilad Arnold684219d2014-07-07 14:54:57 -0700449EvalStatus ChromeOSPolicy::UpdateDownloadAllowed(
Gilad Arnolda8262e22014-06-02 13:54:27 -0700450 EvaluationContext* ec,
451 State* state,
452 string* error,
453 bool* result) const {
454 // Get the current connection type.
455 ShillProvider* const shill_provider = state->shill_provider();
456 const ConnectionType* conn_type_p = ec->GetValue(
457 shill_provider->var_conn_type());
458 POLICY_CHECK_VALUE_AND_FAIL(conn_type_p, error);
459 ConnectionType conn_type = *conn_type_p;
460
461 // If we're tethering, treat it as a cellular connection.
462 if (conn_type != ConnectionType::kCellular) {
463 const ConnectionTethering* conn_tethering_p = ec->GetValue(
464 shill_provider->var_conn_tethering());
465 POLICY_CHECK_VALUE_AND_FAIL(conn_tethering_p, error);
466 if (*conn_tethering_p == ConnectionTethering::kConfirmed)
467 conn_type = ConnectionType::kCellular;
468 }
469
470 // By default, we allow updates for all connection types, with exceptions as
471 // noted below. This also determines whether a device policy can override the
472 // default.
473 *result = true;
474 bool device_policy_can_override = false;
475 switch (conn_type) {
476 case ConnectionType::kBluetooth:
477 *result = false;
478 break;
479
480 case ConnectionType::kCellular:
481 *result = false;
482 device_policy_can_override = true;
483 break;
484
485 case ConnectionType::kUnknown:
486 if (error)
487 *error = "Unknown connection type";
488 return EvalStatus::kFailed;
489
490 default:
491 break; // Nothing to do.
492 }
493
494 // If update is allowed, we're done.
495 if (*result)
496 return EvalStatus::kSucceeded;
497
498 // Check whether the device policy specifically allows this connection.
Gilad Arnolda8262e22014-06-02 13:54:27 -0700499 if (device_policy_can_override) {
500 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
501 const bool* device_policy_is_loaded_p = ec->GetValue(
502 dp_provider->var_device_policy_is_loaded());
503 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
504 const set<ConnectionType>* allowed_conn_types_p = ec->GetValue(
505 dp_provider->var_allowed_connection_types_for_update());
506 if (allowed_conn_types_p) {
507 if (allowed_conn_types_p->count(conn_type)) {
508 *result = true;
509 return EvalStatus::kSucceeded;
510 }
Gilad Arnold28d6be62014-06-30 14:04:04 -0700511 } else if (conn_type == ConnectionType::kCellular) {
512 // Local user settings can allow updates over cellular iff a policy was
513 // loaded but no allowed connections were specified in it.
514 const bool* update_over_cellular_allowed_p = ec->GetValue(
515 state->updater_provider()->var_cellular_enabled());
516 if (update_over_cellular_allowed_p && *update_over_cellular_allowed_p)
517 *result = true;
Gilad Arnolda8262e22014-06-02 13:54:27 -0700518 }
519 }
520 }
521
Gilad Arnold28d6be62014-06-30 14:04:04 -0700522 return (*result ? EvalStatus::kSucceeded : EvalStatus::kAskMeAgainLater);
Gilad Arnolda8262e22014-06-02 13:54:27 -0700523}
524
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700525EvalStatus ChromeOSPolicy::P2PEnabled(EvaluationContext* ec,
526 State* state,
527 std::string* error,
528 bool* result) const {
529 bool enabled = false;
530
531 // Determine whether use of P2P is allowed by policy. Even if P2P is not
532 // explicitly allowed, we allow it if the device is enterprise enrolled (that
533 // is, missing or empty owner string).
534 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
535 const bool* device_policy_is_loaded_p = ec->GetValue(
536 dp_provider->var_device_policy_is_loaded());
537 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
538 const bool* policy_au_p2p_enabled_p = ec->GetValue(
539 dp_provider->var_au_p2p_enabled());
540 if (policy_au_p2p_enabled_p) {
541 enabled = *policy_au_p2p_enabled_p;
542 } else {
543 const string* policy_owner_p = ec->GetValue(dp_provider->var_owner());
544 if (!policy_owner_p || policy_owner_p->empty())
545 enabled = true;
546 }
547 }
548
549 // Enable P2P, if so mandated by the updater configuration. This is additive
550 // to whether or not P2P is enabled by device policy.
551 if (!enabled) {
552 const bool* updater_p2p_enabled_p = ec->GetValue(
553 state->updater_provider()->var_p2p_enabled());
554 enabled = updater_p2p_enabled_p && *updater_p2p_enabled_p;
555 }
556
557 *result = enabled;
558 return EvalStatus::kSucceeded;
559}
560
561EvalStatus ChromeOSPolicy::P2PEnabledChanged(EvaluationContext* ec,
562 State* state,
563 std::string* error,
564 bool* result,
565 bool prev_result) const {
566 EvalStatus status = P2PEnabled(ec, state, error, result);
567 if (status == EvalStatus::kSucceeded && *result == prev_result)
568 return EvalStatus::kAskMeAgainLater;
569 return status;
570}
571
Alex Deymo0d11c602014-04-23 20:12:20 -0700572EvalStatus ChromeOSPolicy::NextUpdateCheckTime(EvaluationContext* ec,
573 State* state, string* error,
574 Time* next_update_check) const {
Gilad Arnolda0258a52014-07-10 16:21:19 -0700575 UpdaterProvider* const updater_provider = state->updater_provider();
576
Alex Deymo0d11c602014-04-23 20:12:20 -0700577 // Don't check for updates too often. We limit the update checks to once every
578 // some interval. The interval is kTimeoutInitialInterval the first time and
579 // kTimeoutPeriodicInterval for the subsequent update checks. If the update
580 // check fails, we increase the interval between the update checks
581 // exponentially until kTimeoutMaxBackoffInterval. Finally, to avoid having
582 // many chromebooks running update checks at the exact same time, we add some
583 // fuzz to the interval.
584 const Time* updater_started_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700585 ec->GetValue(updater_provider->var_updater_started_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700586 POLICY_CHECK_VALUE_AND_FAIL(updater_started_time, error);
587
Alex Deymof329b932014-10-30 01:37:48 -0700588 const Time* last_checked_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700589 ec->GetValue(updater_provider->var_last_checked_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700590
591 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
592 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
593
594 PRNG prng(*seed);
595
Gilad Arnold38b14022014-07-09 12:45:56 -0700596 // If this is the first attempt, compute and return an initial value.
Alex Deymo0d11c602014-04-23 20:12:20 -0700597 if (!last_checked_time || *last_checked_time < *updater_started_time) {
Alex Deymo0d11c602014-04-23 20:12:20 -0700598 *next_update_check = *updater_started_time + FuzzedInterval(
599 &prng, kTimeoutInitialInterval, kTimeoutRegularFuzz);
600 return EvalStatus::kSucceeded;
601 }
Gilad Arnold38b14022014-07-09 12:45:56 -0700602
Gilad Arnolda0258a52014-07-10 16:21:19 -0700603 // Check whether the server is enforcing a poll interval; if not, this value
604 // will be zero.
605 const unsigned int* server_dictated_poll_interval = ec->GetValue(
606 updater_provider->var_server_dictated_poll_interval());
607 POLICY_CHECK_VALUE_AND_FAIL(server_dictated_poll_interval, error);
Alex Deymo0d11c602014-04-23 20:12:20 -0700608
Gilad Arnolda0258a52014-07-10 16:21:19 -0700609 int interval = *server_dictated_poll_interval;
610 int fuzz = 0;
611
Alex Vakulenko072359c2014-07-18 11:41:07 -0700612 // If no poll interval was dictated by server compute a back-off period,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700613 // starting from a predetermined base periodic interval and increasing
614 // exponentially by the number of consecutive failed attempts.
615 if (interval == 0) {
616 const unsigned int* consecutive_failed_update_checks = ec->GetValue(
617 updater_provider->var_consecutive_failed_update_checks());
618 POLICY_CHECK_VALUE_AND_FAIL(consecutive_failed_update_checks, error);
619
620 interval = kTimeoutPeriodicInterval;
621 unsigned int num_failures = *consecutive_failed_update_checks;
622 while (interval < kTimeoutMaxBackoffInterval && num_failures) {
623 interval *= 2;
624 num_failures--;
Alex Deymo0d11c602014-04-23 20:12:20 -0700625 }
626 }
627
Alex Vakulenko072359c2014-07-18 11:41:07 -0700628 // We cannot back off longer than the predetermined maximum interval.
Gilad Arnolda0258a52014-07-10 16:21:19 -0700629 if (interval > kTimeoutMaxBackoffInterval)
630 interval = kTimeoutMaxBackoffInterval;
631
Alex Vakulenko072359c2014-07-18 11:41:07 -0700632 // We cannot back off shorter than the predetermined periodic interval. Also,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700633 // in this case set the fuzz to a predetermined regular value.
634 if (interval <= kTimeoutPeriodicInterval) {
635 interval = kTimeoutPeriodicInterval;
636 fuzz = kTimeoutRegularFuzz;
637 }
638
639 // If not otherwise determined, defer to a fuzz of +/-(interval / 2).
Gilad Arnold38b14022014-07-09 12:45:56 -0700640 if (fuzz == 0)
641 fuzz = interval;
642
Alex Deymo0d11c602014-04-23 20:12:20 -0700643 *next_update_check = *last_checked_time + FuzzedInterval(
Gilad Arnold38b14022014-07-09 12:45:56 -0700644 &prng, interval, fuzz);
Alex Deymo0d11c602014-04-23 20:12:20 -0700645 return EvalStatus::kSucceeded;
646}
647
648TimeDelta ChromeOSPolicy::FuzzedInterval(PRNG* prng, int interval, int fuzz) {
Gilad Arnolde1218812014-05-07 12:21:36 -0700649 DCHECK_GE(interval, 0);
650 DCHECK_GE(fuzz, 0);
Alex Deymo0d11c602014-04-23 20:12:20 -0700651 int half_fuzz = fuzz / 2;
Alex Deymo0d11c602014-04-23 20:12:20 -0700652 // This guarantees the output interval is non negative.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700653 int interval_min = max(interval - half_fuzz, 0);
Gilad Arnolde1218812014-05-07 12:21:36 -0700654 int interval_max = interval + half_fuzz;
655 return TimeDelta::FromSeconds(prng->RandMinMax(interval_min, interval_max));
Alex Deymo0d11c602014-04-23 20:12:20 -0700656}
657
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700658EvalStatus ChromeOSPolicy::UpdateBackoffAndDownloadUrl(
Alex Deymof329b932014-10-30 01:37:48 -0700659 EvaluationContext* ec, State* state, string* error,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700660 UpdateBackoffAndDownloadUrlResult* result,
661 const UpdateState& update_state) const {
662 // Sanity checks.
663 DCHECK_GE(update_state.download_errors_max, 0);
664
665 // Set default result values.
666 result->do_increment_failures = false;
667 result->backoff_expiry = update_state.backoff_expiry;
668 result->url_idx = -1;
669 result->url_num_errors = 0;
670
671 const bool* is_official_build_p = ec->GetValue(
672 state->system_provider()->var_is_official_build());
673 bool is_official_build = (is_official_build_p ? *is_official_build_p : true);
674
675 // Check whether backoff is enabled.
676 bool may_backoff = false;
677 if (update_state.is_backoff_disabled) {
678 LOG(INFO) << "Backoff disabled by Omaha.";
679 } else if (update_state.is_interactive) {
680 LOG(INFO) << "No backoff for interactive updates.";
681 } else if (update_state.is_delta_payload) {
682 LOG(INFO) << "No backoff for delta payloads.";
683 } else if (!is_official_build) {
684 LOG(INFO) << "No backoff for unofficial builds.";
685 } else {
686 may_backoff = true;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700687 }
688
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700689 // If previous backoff still in effect, block.
690 if (may_backoff && !update_state.backoff_expiry.is_null() &&
691 !ec->IsWallclockTimeGreaterThan(update_state.backoff_expiry)) {
692 LOG(INFO) << "Previous backoff has not expired, waiting.";
693 return EvalStatus::kAskMeAgainLater;
694 }
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700695
696 // Determine whether HTTP downloads are forbidden by policy. This only
697 // applies to official system builds; otherwise, HTTP is always enabled.
698 bool http_allowed = true;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700699 if (is_official_build) {
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700700 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
701 const bool* device_policy_is_loaded_p = ec->GetValue(
702 dp_provider->var_device_policy_is_loaded());
703 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
704 const bool* policy_http_downloads_enabled_p = ec->GetValue(
705 dp_provider->var_http_downloads_enabled());
706 http_allowed = (!policy_http_downloads_enabled_p ||
707 *policy_http_downloads_enabled_p);
708 }
709 }
710
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700711 int url_idx = update_state.last_download_url_idx;
712 if (url_idx < 0)
713 url_idx = -1;
714 bool do_advance_url = false;
715 bool is_failure_occurred = false;
716 Time err_time;
717
718 // Scan the relevant part of the download error log, tracking which URLs are
719 // being used, and accounting the number of errors for each URL. Note that
720 // this process may not traverse all errors provided, as it may decide to bail
721 // out midway depending on the particular errors exhibited, the number of
722 // failures allowed, etc. When this ends, |url_idx| will point to the last URL
723 // used (-1 if starting fresh), |do_advance_url| will determine whether the
724 // URL needs to be advanced, and |err_time| the point in time when the last
725 // reported error occurred. Additionally, if the error log indicates that an
726 // update attempt has failed (abnormal), then |is_failure_occurred| will be
727 // set to true.
728 const int num_urls = update_state.download_urls.size();
729 int prev_url_idx = -1;
730 int url_num_errors = update_state.last_download_url_num_errors;
731 Time prev_err_time;
732 bool is_first = true;
733 for (const auto& err_tuple : update_state.download_errors) {
734 // Do some sanity checks.
735 int used_url_idx = get<0>(err_tuple);
736 if (is_first && url_idx >= 0 && used_url_idx != url_idx) {
737 LOG(WARNING) << "First URL in error log (" << used_url_idx
738 << ") not as expected (" << url_idx << ")";
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700739 }
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700740 is_first = false;
741 url_idx = used_url_idx;
742 if (url_idx < 0 || url_idx >= num_urls) {
743 LOG(ERROR) << "Download error log contains an invalid URL index ("
744 << url_idx << ")";
745 return EvalStatus::kFailed;
746 }
747 err_time = get<2>(err_tuple);
748 if (!(prev_err_time.is_null() || err_time >= prev_err_time)) {
749 // TODO(garnold) Monotonicity cannot really be assumed when dealing with
750 // wallclock-based timestamps. However, we're making a simplifying
751 // assumption so as to keep the policy implementation straightforward, for
752 // now. In general, we should convert all timestamp handling in the
753 // UpdateManager to use monotonic time (instead of wallclock), including
754 // the computation of various expiration times (backoff, scattering, etc).
755 // The client will do whatever conversions necessary when
756 // persisting/retrieving these values across reboots. See chromium:408794.
757 LOG(ERROR) << "Download error timestamps not monotonically increasing.";
758 return EvalStatus::kFailed;
759 }
760 prev_err_time = err_time;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700761
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700762 // Ignore errors that happened before the last known failed attempt.
763 if (!update_state.failures_last_updated.is_null() &&
764 err_time <= update_state.failures_last_updated)
765 continue;
766
767 if (prev_url_idx >= 0) {
768 if (url_idx < prev_url_idx) {
769 LOG(ERROR) << "The URLs in the download error log have wrapped around ("
770 << prev_url_idx << "->" << url_idx
771 << "). This should not have happened and means that there's "
772 "a bug. To be conservative, we record a failed attempt "
773 "(invalidating the rest of the error log) and resume "
774 "download from the first usable URL.";
775 url_idx = -1;
776 is_failure_occurred = true;
777 break;
778 }
779
780 if (url_idx > prev_url_idx) {
781 url_num_errors = 0;
782 do_advance_url = false;
783 }
784 }
785
786 if (HandleErrorCode(get<1>(err_tuple), &url_num_errors) ||
787 url_num_errors > update_state.download_errors_max)
788 do_advance_url = true;
789
790 prev_url_idx = url_idx;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700791 }
792
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700793 // If required, advance to the next usable URL. If the URLs wraparound, we
794 // mark an update attempt failure. Also be sure to set the download error
795 // count to zero.
796 if (url_idx < 0 || do_advance_url) {
797 url_num_errors = 0;
798 int start_url_idx = -1;
799 do {
800 if (++url_idx == num_urls) {
801 url_idx = 0;
802 // We only mark failure if an actual advancing of a URL was required.
803 if (do_advance_url)
804 is_failure_occurred = true;
805 }
806
807 if (start_url_idx < 0)
808 start_url_idx = url_idx;
809 else if (url_idx == start_url_idx)
810 url_idx = -1; // No usable URL.
811 } while (url_idx >= 0 &&
812 !IsUrlUsable(update_state.download_urls[url_idx], http_allowed));
813 }
814
815 // If we have a download URL but a failure was observed, compute a new backoff
816 // expiry (if allowed). The backoff period is generally 2 ^ (num_failures - 1)
817 // days, bounded by the size of int and kAttemptBackoffMaxIntervalInDays, and
818 // fuzzed by kAttemptBackoffFuzzInHours hours. Backoff expiry is computed from
819 // the latest recorded time of error.
820 Time backoff_expiry;
821 if (url_idx >= 0 && is_failure_occurred && may_backoff) {
822 CHECK(!err_time.is_null())
823 << "We must have an error timestamp if a failure occurred!";
824 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
825 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
826 PRNG prng(*seed);
Alex Deymof329b932014-10-30 01:37:48 -0700827 int exp = min(update_state.num_failures,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700828 static_cast<int>(sizeof(int)) * 8 - 2);
829 TimeDelta backoff_interval = TimeDelta::FromDays(
Alex Deymof329b932014-10-30 01:37:48 -0700830 min(1 << exp, kAttemptBackoffMaxIntervalInDays));
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700831 TimeDelta backoff_fuzz = TimeDelta::FromHours(kAttemptBackoffFuzzInHours);
832 TimeDelta wait_period = FuzzedInterval(&prng, backoff_interval.InSeconds(),
833 backoff_fuzz.InSeconds());
834 backoff_expiry = err_time + wait_period;
835
836 // If the newly computed backoff already expired, nullify it.
837 if (ec->IsWallclockTimeGreaterThan(backoff_expiry))
838 backoff_expiry = Time();
839 }
840
841 result->do_increment_failures = is_failure_occurred;
842 result->backoff_expiry = backoff_expiry;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700843 result->url_idx = url_idx;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700844 result->url_num_errors = url_num_errors;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700845 return EvalStatus::kSucceeded;
846}
847
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700848EvalStatus ChromeOSPolicy::UpdateScattering(
849 EvaluationContext* ec,
850 State* state,
851 string* error,
852 UpdateScatteringResult* result,
853 const UpdateState& update_state) const {
854 // Preconditions. These stem from the postconditions and usage contract.
855 DCHECK(update_state.scatter_wait_period >= kZeroInterval);
856 DCHECK_GE(update_state.scatter_check_threshold, 0);
857
858 // Set default result values.
859 result->is_scattering = false;
860 result->wait_period = kZeroInterval;
861 result->check_threshold = 0;
862
863 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
864
865 // Ensure that a device policy is loaded.
866 const bool* device_policy_is_loaded_p = ec->GetValue(
867 dp_provider->var_device_policy_is_loaded());
868 if (!(device_policy_is_loaded_p && *device_policy_is_loaded_p))
869 return EvalStatus::kSucceeded;
870
871 // Is scattering enabled by policy?
872 const TimeDelta* scatter_factor_p = ec->GetValue(
873 dp_provider->var_scatter_factor());
874 if (!scatter_factor_p || *scatter_factor_p == kZeroInterval)
875 return EvalStatus::kSucceeded;
876
877 // Obtain a pseudo-random number generator.
878 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
879 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
880 PRNG prng(*seed);
881
882 // Step 1: Maintain the scattering wait period.
883 //
884 // If no wait period was previously determined, or it no longer fits in the
885 // scatter factor, then generate a new one. Otherwise, keep the one we have.
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700886 TimeDelta wait_period = update_state.scatter_wait_period;
887 if (wait_period == kZeroInterval || wait_period > *scatter_factor_p) {
888 wait_period = TimeDelta::FromSeconds(
889 prng.RandMinMax(1, scatter_factor_p->InSeconds()));
890 }
891
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700892 // If we surpassed the wait period or the max scatter period associated with
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700893 // the update, then no wait is needed.
894 Time wait_expires = (update_state.first_seen +
895 min(wait_period, update_state.scatter_wait_period_max));
Gilad Arnolda65fced2014-07-23 09:01:31 -0700896 if (ec->IsWallclockTimeGreaterThan(wait_expires))
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700897 wait_period = kZeroInterval;
898
899 // Step 2: Maintain the update check threshold count.
900 //
901 // If an update check threshold is not specified then generate a new
902 // one.
903 int check_threshold = update_state.scatter_check_threshold;
904 if (check_threshold == 0) {
905 check_threshold = prng.RandMinMax(
906 update_state.scatter_check_threshold_min,
907 update_state.scatter_check_threshold_max);
908 }
909
910 // If the update check threshold is not within allowed range then nullify it.
911 // TODO(garnold) This is compliant with current logic found in
912 // OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied(). We may want
913 // to change it so that it behaves similarly to the wait period case, namely
914 // if the current value exceeds the maximum, we set a new one within range.
915 if (check_threshold > update_state.scatter_check_threshold_max)
916 check_threshold = 0;
917
918 // If the update check threshold is non-zero and satisfied, then nullify it.
919 if (check_threshold > 0 && update_state.num_checks >= check_threshold)
920 check_threshold = 0;
921
922 bool is_scattering = (wait_period != kZeroInterval || check_threshold);
923 EvalStatus ret = EvalStatus::kSucceeded;
924 if (is_scattering && wait_period == update_state.scatter_wait_period &&
925 check_threshold == update_state.scatter_check_threshold)
926 ret = EvalStatus::kAskMeAgainLater;
927 result->is_scattering = is_scattering;
928 result->wait_period = wait_period;
929 result->check_threshold = check_threshold;
930 return ret;
931}
932
Alex Deymo63784a52014-05-28 10:46:14 -0700933} // namespace chromeos_update_manager