blob: 9abb21f511e40a2520ccdfcc46f8bd646237eb84 [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2014 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
Alex Deymoc705cc82014-02-19 11:15:00 -080016
Alex Deymo63784a52014-05-28 10:46:14 -070017#include "update_engine/update_manager/chromeos_policy.h"
Alex Deymo0d11c602014-04-23 20:12:20 -070018
Gilad Arnolde1218812014-05-07 12:21:36 -070019#include <algorithm>
Gilad Arnold0adbc942014-05-12 10:35:43 -070020#include <set>
Alex Deymoc705cc82014-02-19 11:15:00 -080021#include <string>
22
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070023#include <base/logging.h>
Gilad Arnoldb3b05442014-05-30 14:25:05 -070024#include <base/strings/string_util.h>
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070025#include <base/time/time.h>
26
Alex Deymo39910dc2015-11-09 17:04:30 -080027#include "update_engine/common/error_code.h"
28#include "update_engine/common/utils.h"
Alex Deymo63784a52014-05-28 10:46:14 -070029#include "update_engine/update_manager/device_policy_provider.h"
30#include "update_engine/update_manager/policy_utils.h"
31#include "update_engine/update_manager/shill_provider.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:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800132 case ErrorCode::kUserCanceled:
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700133 LOG(INFO) << "Not changing URL index or failure count due to error "
134 << chromeos_update_engine::utils::CodeToString(err_code)
135 << " (" << static_cast<int>(err_code) << ")";
136 return false;
137
138 case ErrorCode::kSuccess: // success code
139 case ErrorCode::kUmaReportedMax: // not an error code
140 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800141 case ErrorCode::kDevModeFlag: // not an error code
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700142 case ErrorCode::kResumedFlag: // not an error code
143 case ErrorCode::kTestImageFlag: // not an error code
144 case ErrorCode::kTestOmahaUrlFlag: // not an error code
145 case ErrorCode::kSpecialFlags: // not an error code
146 // These shouldn't happen. Enumerating these explicitly here so that we
147 // can let the compiler warn about new error codes that are added to
148 // action_processor.h but not added here.
149 LOG(WARNING) << "Unexpected error "
150 << chromeos_update_engine::utils::CodeToString(err_code)
151 << " (" << static_cast<int>(err_code) << ")";
152 // Note: Not adding a default here so as to let the compiler warn us of
153 // any new enums that were added in the .h but not listed in this switch.
154 }
155 return false;
156}
157
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700158// Checks whether |url| can be used under given download restrictions.
159bool IsUrlUsable(const string& url, bool http_allowed) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800160 return http_allowed ||
161 !base::StartsWith(url, "http://",
162 base::CompareCase::INSENSITIVE_ASCII);
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700163}
164
165} // namespace
166
Alex Deymo63784a52014-05-28 10:46:14 -0700167namespace chromeos_update_manager {
Alex Deymoc705cc82014-02-19 11:15:00 -0800168
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700169const int ChromeOSPolicy::kTimeoutInitialInterval = 7 * 60;
Alex Deymo14e7dde2015-10-20 14:46:33 -0700170
171// TODO(deymo): Split the update_manager policies for Brillo and ChromeOS and
172// make the update check periodic interval configurable.
173#ifdef __ANDROID__
174const int ChromeOSPolicy::kTimeoutPeriodicInterval = 5 * 60 * 60;
Alex Deymodbe13b42015-11-06 11:15:08 -0800175const int ChromeOSPolicy::kTimeoutMaxBackoffInterval = 26 * 60 * 60;
Alex Deymo14e7dde2015-10-20 14:46:33 -0700176#else
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700177const int ChromeOSPolicy::kTimeoutPeriodicInterval = 45 * 60;
Alex Deymodbe13b42015-11-06 11:15:08 -0800178const int ChromeOSPolicy::kTimeoutMaxBackoffInterval = 4 * 60 * 60;
Alex Deymo14e7dde2015-10-20 14:46:33 -0700179#endif // __ANDROID__
180
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700181const int ChromeOSPolicy::kTimeoutRegularFuzz = 10 * 60;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700182const int ChromeOSPolicy::kAttemptBackoffMaxIntervalInDays = 16;
183const int ChromeOSPolicy::kAttemptBackoffFuzzInHours = 12;
Gilad Arnold349ac832014-10-06 14:20:28 -0700184const int ChromeOSPolicy::kMaxP2PAttempts = 10;
185const int ChromeOSPolicy::kMaxP2PAttemptsPeriodInSeconds = 5 * 24 * 60 * 60;
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700186
Alex Deymo0d11c602014-04-23 20:12:20 -0700187EvalStatus ChromeOSPolicy::UpdateCheckAllowed(
188 EvaluationContext* ec, State* state, string* error,
189 UpdateCheckParams* result) const {
Gilad Arnold42f253b2014-06-25 12:39:17 -0700190 // Set the default return values.
191 result->updates_enabled = true;
192 result->target_channel.clear();
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700193 result->target_version_prefix.clear();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700194 result->is_interactive = false;
Gilad Arnold42f253b2014-06-25 12:39:17 -0700195
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700196 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700197 UpdaterProvider* const updater_provider = state->updater_provider();
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700198 SystemProvider* const system_provider = state->system_provider();
199
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700200 // Do not perform any updates if booted from removable device. This decision
201 // is final.
Alex Deymo763e7db2015-08-27 21:08:08 -0700202 const unsigned int* num_slots_p = ec->GetValue(
203 system_provider->var_num_slots());
204 if (!num_slots_p || *num_slots_p < 2) {
205 LOG(INFO) << "Not enough slots for A/B updates, disabling update checks.";
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700206 result->updates_enabled = false;
207 return EvalStatus::kSucceeded;
208 }
209
Gilad Arnold42f253b2014-06-25 12:39:17 -0700210 const bool* device_policy_is_loaded_p = ec->GetValue(
211 dp_provider->var_device_policy_is_loaded());
212 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
213 // Check whether updates are disabled by policy.
214 const bool* update_disabled_p = ec->GetValue(
215 dp_provider->var_update_disabled());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700216 if (update_disabled_p && *update_disabled_p) {
217 LOG(INFO) << "Updates disabled by policy, blocking update checks.";
Gilad Arnold42f253b2014-06-25 12:39:17 -0700218 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700219 }
Gilad Arnold42f253b2014-06-25 12:39:17 -0700220
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700221 // Determine whether a target version prefix is dictated by policy.
222 const string* target_version_prefix_p = ec->GetValue(
223 dp_provider->var_target_version_prefix());
224 if (target_version_prefix_p)
225 result->target_version_prefix = *target_version_prefix_p;
226
Gilad Arnold42f253b2014-06-25 12:39:17 -0700227 // Determine whether a target channel is dictated by policy.
228 const bool* release_channel_delegated_p = ec->GetValue(
229 dp_provider->var_release_channel_delegated());
230 if (release_channel_delegated_p && !(*release_channel_delegated_p)) {
231 const string* release_channel_p = ec->GetValue(
232 dp_provider->var_release_channel());
233 if (release_channel_p)
234 result->target_channel = *release_channel_p;
235 }
236 }
237
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700238 // First, check to see if an interactive update was requested.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700239 const UpdateRequestStatus* forced_update_requested_p = ec->GetValue(
240 updater_provider->var_forced_update_requested());
241 if (forced_update_requested_p &&
242 *forced_update_requested_p != UpdateRequestStatus::kNone) {
243 result->is_interactive =
244 (*forced_update_requested_p == UpdateRequestStatus::kInteractive);
245 LOG(INFO) << "Forced update signaled ("
246 << (result->is_interactive ? "interactive" : "periodic")
247 << "), allowing update check.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700248 return EvalStatus::kSucceeded;
249 }
250
251 // The logic thereafter applies to periodic updates. Bear in mind that we
252 // should not return a final "no" if any of these criteria are not satisfied,
253 // because the system may still update due to an interactive update request.
254
255 // Unofficial builds should not perform periodic update checks.
256 const bool* is_official_build_p = ec->GetValue(
257 system_provider->var_is_official_build());
258 if (is_official_build_p && !(*is_official_build_p)) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700259 LOG(INFO) << "Unofficial build, blocking periodic update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700260 return EvalStatus::kAskMeAgainLater;
261 }
262
263 // If OOBE is enabled, wait until it is completed.
264 const bool* is_oobe_enabled_p = ec->GetValue(
265 state->config_provider()->var_is_oobe_enabled());
266 if (is_oobe_enabled_p && *is_oobe_enabled_p) {
267 const bool* is_oobe_complete_p = ec->GetValue(
268 system_provider->var_is_oobe_complete());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700269 if (is_oobe_complete_p && !(*is_oobe_complete_p)) {
270 LOG(INFO) << "OOBE not completed, blocking update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700271 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700272 }
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700273 }
274
275 // Ensure that periodic update checks are timed properly.
Alex Deymo0d11c602014-04-23 20:12:20 -0700276 Time next_update_check;
277 if (NextUpdateCheckTime(ec, state, error, &next_update_check) !=
278 EvalStatus::kSucceeded) {
279 return EvalStatus::kFailed;
280 }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700281 if (!ec->IsWallclockTimeGreaterThan(next_update_check)) {
282 LOG(INFO) << "Periodic check interval not satisfied, blocking until "
283 << chromeos_update_engine::utils::ToString(next_update_check);
Alex Deymo0d11c602014-04-23 20:12:20 -0700284 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700285 }
Alex Deymo0d11c602014-04-23 20:12:20 -0700286
287 // It is time to check for an update.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700288 LOG(INFO) << "Allowing update check.";
Alex Deymoe636c3c2014-03-11 19:02:08 -0700289 return EvalStatus::kSucceeded;
Alex Deymoc705cc82014-02-19 11:15:00 -0800290}
291
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700292EvalStatus ChromeOSPolicy::UpdateCanStart(
293 EvaluationContext* ec,
294 State* state,
295 string* error,
Gilad Arnold42f253b2014-06-25 12:39:17 -0700296 UpdateDownloadParams* result,
Gilad Arnoldd78caf92014-09-24 09:28:14 -0700297 const UpdateState update_state) const {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700298 // Set the default return values. Note that we set persisted values (backoff,
299 // scattering) to the same values presented in the update state. The reason is
300 // that preemptive returns, such as the case where an update check is due,
301 // should not clear off the said values; rather, it is the deliberate
302 // inference of new values that should cause them to be reset.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700303 result->update_can_start = false;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700304 result->cannot_start_reason = UpdateCannotStartReason::kUndefined;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700305 result->download_url_idx = -1;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700306 result->download_url_allowed = true;
307 result->download_url_num_errors = 0;
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700308 result->p2p_downloading_allowed = false;
309 result->p2p_sharing_allowed = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700310 result->do_increment_failures = false;
311 result->backoff_expiry = update_state.backoff_expiry;
312 result->scatter_wait_period = update_state.scatter_wait_period;
313 result->scatter_check_threshold = update_state.scatter_check_threshold;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700314
315 // Make sure that we're not due for an update check.
316 UpdateCheckParams check_result;
317 EvalStatus check_status = UpdateCheckAllowed(ec, state, error, &check_result);
318 if (check_status == EvalStatus::kFailed)
319 return EvalStatus::kFailed;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700320 bool is_check_due = (check_status == EvalStatus::kSucceeded &&
321 check_result.updates_enabled == true);
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700322
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700323 // Check whether backoff applies, and if not then which URL can be used for
324 // downloading. These require scanning the download error log, and so they are
325 // done together.
326 UpdateBackoffAndDownloadUrlResult backoff_url_result;
327 EvalStatus backoff_url_status = UpdateBackoffAndDownloadUrl(
328 ec, state, error, &backoff_url_result, update_state);
Gilad Arnold14a9e702014-10-08 08:09:09 -0700329 if (backoff_url_status == EvalStatus::kFailed)
330 return EvalStatus::kFailed;
331 result->download_url_idx = backoff_url_result.url_idx;
332 result->download_url_num_errors = backoff_url_result.url_num_errors;
333 result->do_increment_failures = backoff_url_result.do_increment_failures;
334 result->backoff_expiry = backoff_url_result.backoff_expiry;
335 bool is_backoff_active =
336 (backoff_url_status == EvalStatus::kAskMeAgainLater) ||
337 !backoff_url_result.backoff_expiry.is_null();
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700338
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700339 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold14a9e702014-10-08 08:09:09 -0700340 bool is_scattering_active = false;
341 EvalStatus scattering_status = EvalStatus::kSucceeded;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700342
343 const bool* device_policy_is_loaded_p = ec->GetValue(
344 dp_provider->var_device_policy_is_loaded());
345 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700346 // Check whether scattering applies to this update attempt. We should not be
347 // scattering if this is an interactive update check, or if OOBE is enabled
348 // but not completed.
349 //
350 // Note: current code further suppresses scattering if a "deadline"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700351 // attribute is found in the Omaha response. However, it appears that the
Gilad Arnold76a11f62014-05-20 09:02:12 -0700352 // presence of this attribute is merely indicative of an OOBE update, during
353 // which we suppress scattering anyway.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700354 bool is_scattering_applicable = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700355 result->scatter_wait_period = kZeroInterval;
356 result->scatter_check_threshold = 0;
357 if (!update_state.is_interactive) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700358 const bool* is_oobe_enabled_p = ec->GetValue(
359 state->config_provider()->var_is_oobe_enabled());
360 if (is_oobe_enabled_p && !(*is_oobe_enabled_p)) {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700361 is_scattering_applicable = true;
Gilad Arnold76a11f62014-05-20 09:02:12 -0700362 } else {
363 const bool* is_oobe_complete_p = ec->GetValue(
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700364 state->system_provider()->var_is_oobe_complete());
Gilad Arnold14a9e702014-10-08 08:09:09 -0700365 is_scattering_applicable = (is_oobe_complete_p && *is_oobe_complete_p);
Gilad Arnold76a11f62014-05-20 09:02:12 -0700366 }
367 }
368
369 // Compute scattering values.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700370 if (is_scattering_applicable) {
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700371 UpdateScatteringResult scatter_result;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700372 scattering_status = UpdateScattering(ec, state, error, &scatter_result,
373 update_state);
374 if (scattering_status == EvalStatus::kFailed) {
375 return EvalStatus::kFailed;
376 } else {
377 result->scatter_wait_period = scatter_result.wait_period;
378 result->scatter_check_threshold = scatter_result.check_threshold;
379 if (scattering_status == EvalStatus::kAskMeAgainLater ||
380 scatter_result.is_scattering)
381 is_scattering_active = true;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700382 }
383 }
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700384 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700385
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700386 // Find out whether P2P is globally enabled.
387 bool p2p_enabled;
388 EvalStatus p2p_enabled_status = P2PEnabled(ec, state, error, &p2p_enabled);
389 if (p2p_enabled_status != EvalStatus::kSucceeded)
390 return EvalStatus::kFailed;
391
392 // Is P2P is enabled, consider allowing it for downloading and/or sharing.
393 if (p2p_enabled) {
394 // Sharing via P2P is allowed if not disabled by Omaha.
395 if (update_state.p2p_sharing_disabled) {
396 LOG(INFO) << "Blocked P2P sharing because it is disabled by Omaha.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700397 } else {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700398 result->p2p_sharing_allowed = true;
Gilad Arnoldef8d0872014-10-03 14:14:06 -0700399 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700400
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700401 // Downloading via P2P is allowed if not disabled by Omaha, an update is not
402 // interactive, and other limits haven't been reached.
403 if (update_state.p2p_downloading_disabled) {
404 LOG(INFO) << "Blocked P2P downloading because it is disabled by Omaha.";
405 } else if (update_state.is_interactive) {
406 LOG(INFO) << "Blocked P2P downloading because update is interactive.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700407 } else if (update_state.p2p_num_attempts >= kMaxP2PAttempts) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700408 LOG(INFO) << "Blocked P2P downloading as it was attempted too many "
409 "times.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700410 } else if (!update_state.p2p_first_attempted.is_null() &&
411 ec->IsWallclockTimeGreaterThan(
412 update_state.p2p_first_attempted +
413 TimeDelta::FromSeconds(kMaxP2PAttemptsPeriodInSeconds))) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700414 LOG(INFO) << "Blocked P2P downloading as its usage timespan exceeds "
415 "limit.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700416 } else {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700417 // P2P download is allowed; if backoff or scattering are active, be sure
418 // to suppress them, yet prevent any download URL from being used.
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700419 result->p2p_downloading_allowed = true;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700420 if (is_backoff_active || is_scattering_active) {
421 is_backoff_active = is_scattering_active = false;
422 result->download_url_allowed = false;
423 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700424 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700425 }
426
Gilad Arnold14a9e702014-10-08 08:09:09 -0700427 // Check for various deterrents.
428 if (is_check_due) {
429 result->cannot_start_reason = UpdateCannotStartReason::kCheckDue;
430 return EvalStatus::kSucceeded;
431 }
432 if (is_backoff_active) {
433 result->cannot_start_reason = UpdateCannotStartReason::kBackoff;
434 return backoff_url_status;
435 }
436 if (is_scattering_active) {
437 result->cannot_start_reason = UpdateCannotStartReason::kScattering;
438 return scattering_status;
439 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700440 if (result->download_url_idx < 0 && !result->p2p_downloading_allowed) {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700441 result->cannot_start_reason = UpdateCannotStartReason::kCannotDownload;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700442 return EvalStatus::kSucceeded;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700443 }
444
Gilad Arnold14a9e702014-10-08 08:09:09 -0700445 // Update is good to go.
446 result->update_can_start = true;
Gilad Arnoldaf2f6ae2014-04-28 14:14:52 -0700447 return EvalStatus::kSucceeded;
448}
449
Gilad Arnolda8262e22014-06-02 13:54:27 -0700450// TODO(garnold) Logic in this method is based on
451// ConnectionManager::IsUpdateAllowedOver(); be sure to deprecate the latter.
452//
453// TODO(garnold) The current logic generally treats the list of allowed
454// connections coming from the device policy as a whitelist, meaning that it
455// can only be used for enabling connections, but not disable them. Further,
456// certain connection types (like Bluetooth) cannot be enabled even by policy.
457// In effect, the only thing that device policy can change is to enable
458// updates over a cellular network (disabled by default). We may want to
459// revisit this semantics, allowing greater flexibility in defining specific
460// permissions over all types of networks.
Gilad Arnold684219d2014-07-07 14:54:57 -0700461EvalStatus ChromeOSPolicy::UpdateDownloadAllowed(
Gilad Arnolda8262e22014-06-02 13:54:27 -0700462 EvaluationContext* ec,
463 State* state,
464 string* error,
465 bool* result) const {
466 // Get the current connection type.
467 ShillProvider* const shill_provider = state->shill_provider();
468 const ConnectionType* conn_type_p = ec->GetValue(
469 shill_provider->var_conn_type());
470 POLICY_CHECK_VALUE_AND_FAIL(conn_type_p, error);
471 ConnectionType conn_type = *conn_type_p;
472
473 // If we're tethering, treat it as a cellular connection.
474 if (conn_type != ConnectionType::kCellular) {
475 const ConnectionTethering* conn_tethering_p = ec->GetValue(
476 shill_provider->var_conn_tethering());
477 POLICY_CHECK_VALUE_AND_FAIL(conn_tethering_p, error);
478 if (*conn_tethering_p == ConnectionTethering::kConfirmed)
479 conn_type = ConnectionType::kCellular;
480 }
481
482 // By default, we allow updates for all connection types, with exceptions as
483 // noted below. This also determines whether a device policy can override the
484 // default.
485 *result = true;
486 bool device_policy_can_override = false;
487 switch (conn_type) {
488 case ConnectionType::kBluetooth:
489 *result = false;
490 break;
491
492 case ConnectionType::kCellular:
493 *result = false;
494 device_policy_can_override = true;
495 break;
496
497 case ConnectionType::kUnknown:
498 if (error)
499 *error = "Unknown connection type";
500 return EvalStatus::kFailed;
501
502 default:
503 break; // Nothing to do.
504 }
505
506 // If update is allowed, we're done.
507 if (*result)
508 return EvalStatus::kSucceeded;
509
510 // Check whether the device policy specifically allows this connection.
Gilad Arnolda8262e22014-06-02 13:54:27 -0700511 if (device_policy_can_override) {
512 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
513 const bool* device_policy_is_loaded_p = ec->GetValue(
514 dp_provider->var_device_policy_is_loaded());
515 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
516 const set<ConnectionType>* allowed_conn_types_p = ec->GetValue(
517 dp_provider->var_allowed_connection_types_for_update());
518 if (allowed_conn_types_p) {
519 if (allowed_conn_types_p->count(conn_type)) {
520 *result = true;
521 return EvalStatus::kSucceeded;
522 }
Gilad Arnold28d6be62014-06-30 14:04:04 -0700523 } else if (conn_type == ConnectionType::kCellular) {
524 // Local user settings can allow updates over cellular iff a policy was
525 // loaded but no allowed connections were specified in it.
526 const bool* update_over_cellular_allowed_p = ec->GetValue(
527 state->updater_provider()->var_cellular_enabled());
528 if (update_over_cellular_allowed_p && *update_over_cellular_allowed_p)
529 *result = true;
Gilad Arnolda8262e22014-06-02 13:54:27 -0700530 }
531 }
532 }
533
Gilad Arnold28d6be62014-06-30 14:04:04 -0700534 return (*result ? EvalStatus::kSucceeded : EvalStatus::kAskMeAgainLater);
Gilad Arnolda8262e22014-06-02 13:54:27 -0700535}
536
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700537EvalStatus ChromeOSPolicy::P2PEnabled(EvaluationContext* ec,
538 State* state,
Alex Deymo39910dc2015-11-09 17:04:30 -0800539 string* error,
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700540 bool* result) const {
541 bool enabled = false;
542
543 // Determine whether use of P2P is allowed by policy. Even if P2P is not
544 // explicitly allowed, we allow it if the device is enterprise enrolled (that
545 // is, missing or empty owner string).
546 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
547 const bool* device_policy_is_loaded_p = ec->GetValue(
548 dp_provider->var_device_policy_is_loaded());
549 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
550 const bool* policy_au_p2p_enabled_p = ec->GetValue(
551 dp_provider->var_au_p2p_enabled());
552 if (policy_au_p2p_enabled_p) {
553 enabled = *policy_au_p2p_enabled_p;
554 } else {
555 const string* policy_owner_p = ec->GetValue(dp_provider->var_owner());
556 if (!policy_owner_p || policy_owner_p->empty())
557 enabled = true;
558 }
559 }
560
561 // Enable P2P, if so mandated by the updater configuration. This is additive
562 // to whether or not P2P is enabled by device policy.
563 if (!enabled) {
564 const bool* updater_p2p_enabled_p = ec->GetValue(
565 state->updater_provider()->var_p2p_enabled());
566 enabled = updater_p2p_enabled_p && *updater_p2p_enabled_p;
567 }
568
569 *result = enabled;
570 return EvalStatus::kSucceeded;
571}
572
573EvalStatus ChromeOSPolicy::P2PEnabledChanged(EvaluationContext* ec,
574 State* state,
Alex Deymo39910dc2015-11-09 17:04:30 -0800575 string* error,
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700576 bool* result,
577 bool prev_result) const {
578 EvalStatus status = P2PEnabled(ec, state, error, result);
579 if (status == EvalStatus::kSucceeded && *result == prev_result)
580 return EvalStatus::kAskMeAgainLater;
581 return status;
582}
583
Alex Deymo0d11c602014-04-23 20:12:20 -0700584EvalStatus ChromeOSPolicy::NextUpdateCheckTime(EvaluationContext* ec,
585 State* state, string* error,
586 Time* next_update_check) const {
Gilad Arnolda0258a52014-07-10 16:21:19 -0700587 UpdaterProvider* const updater_provider = state->updater_provider();
588
Alex Deymo0d11c602014-04-23 20:12:20 -0700589 // Don't check for updates too often. We limit the update checks to once every
590 // some interval. The interval is kTimeoutInitialInterval the first time and
591 // kTimeoutPeriodicInterval for the subsequent update checks. If the update
592 // check fails, we increase the interval between the update checks
593 // exponentially until kTimeoutMaxBackoffInterval. Finally, to avoid having
594 // many chromebooks running update checks at the exact same time, we add some
595 // fuzz to the interval.
596 const Time* updater_started_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700597 ec->GetValue(updater_provider->var_updater_started_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700598 POLICY_CHECK_VALUE_AND_FAIL(updater_started_time, error);
599
Alex Deymof329b932014-10-30 01:37:48 -0700600 const Time* last_checked_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700601 ec->GetValue(updater_provider->var_last_checked_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700602
603 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
604 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
605
606 PRNG prng(*seed);
607
Gilad Arnold38b14022014-07-09 12:45:56 -0700608 // If this is the first attempt, compute and return an initial value.
Alex Deymo0d11c602014-04-23 20:12:20 -0700609 if (!last_checked_time || *last_checked_time < *updater_started_time) {
Alex Deymo0d11c602014-04-23 20:12:20 -0700610 *next_update_check = *updater_started_time + FuzzedInterval(
611 &prng, kTimeoutInitialInterval, kTimeoutRegularFuzz);
612 return EvalStatus::kSucceeded;
613 }
Gilad Arnold38b14022014-07-09 12:45:56 -0700614
Gilad Arnolda0258a52014-07-10 16:21:19 -0700615 // Check whether the server is enforcing a poll interval; if not, this value
616 // will be zero.
617 const unsigned int* server_dictated_poll_interval = ec->GetValue(
618 updater_provider->var_server_dictated_poll_interval());
619 POLICY_CHECK_VALUE_AND_FAIL(server_dictated_poll_interval, error);
Alex Deymo0d11c602014-04-23 20:12:20 -0700620
Gilad Arnolda0258a52014-07-10 16:21:19 -0700621 int interval = *server_dictated_poll_interval;
622 int fuzz = 0;
623
Alex Vakulenko072359c2014-07-18 11:41:07 -0700624 // If no poll interval was dictated by server compute a back-off period,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700625 // starting from a predetermined base periodic interval and increasing
626 // exponentially by the number of consecutive failed attempts.
627 if (interval == 0) {
628 const unsigned int* consecutive_failed_update_checks = ec->GetValue(
629 updater_provider->var_consecutive_failed_update_checks());
630 POLICY_CHECK_VALUE_AND_FAIL(consecutive_failed_update_checks, error);
631
632 interval = kTimeoutPeriodicInterval;
633 unsigned int num_failures = *consecutive_failed_update_checks;
634 while (interval < kTimeoutMaxBackoffInterval && num_failures) {
635 interval *= 2;
636 num_failures--;
Alex Deymo0d11c602014-04-23 20:12:20 -0700637 }
638 }
639
Alex Vakulenko072359c2014-07-18 11:41:07 -0700640 // We cannot back off longer than the predetermined maximum interval.
Gilad Arnolda0258a52014-07-10 16:21:19 -0700641 if (interval > kTimeoutMaxBackoffInterval)
642 interval = kTimeoutMaxBackoffInterval;
643
Alex Vakulenko072359c2014-07-18 11:41:07 -0700644 // We cannot back off shorter than the predetermined periodic interval. Also,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700645 // in this case set the fuzz to a predetermined regular value.
646 if (interval <= kTimeoutPeriodicInterval) {
647 interval = kTimeoutPeriodicInterval;
648 fuzz = kTimeoutRegularFuzz;
649 }
650
651 // If not otherwise determined, defer to a fuzz of +/-(interval / 2).
Gilad Arnold38b14022014-07-09 12:45:56 -0700652 if (fuzz == 0)
653 fuzz = interval;
654
Alex Deymo0d11c602014-04-23 20:12:20 -0700655 *next_update_check = *last_checked_time + FuzzedInterval(
Gilad Arnold38b14022014-07-09 12:45:56 -0700656 &prng, interval, fuzz);
Alex Deymo0d11c602014-04-23 20:12:20 -0700657 return EvalStatus::kSucceeded;
658}
659
660TimeDelta ChromeOSPolicy::FuzzedInterval(PRNG* prng, int interval, int fuzz) {
Gilad Arnolde1218812014-05-07 12:21:36 -0700661 DCHECK_GE(interval, 0);
662 DCHECK_GE(fuzz, 0);
Alex Deymo0d11c602014-04-23 20:12:20 -0700663 int half_fuzz = fuzz / 2;
Alex Deymo0d11c602014-04-23 20:12:20 -0700664 // This guarantees the output interval is non negative.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700665 int interval_min = max(interval - half_fuzz, 0);
Gilad Arnolde1218812014-05-07 12:21:36 -0700666 int interval_max = interval + half_fuzz;
667 return TimeDelta::FromSeconds(prng->RandMinMax(interval_min, interval_max));
Alex Deymo0d11c602014-04-23 20:12:20 -0700668}
669
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700670EvalStatus ChromeOSPolicy::UpdateBackoffAndDownloadUrl(
Alex Deymof329b932014-10-30 01:37:48 -0700671 EvaluationContext* ec, State* state, string* error,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700672 UpdateBackoffAndDownloadUrlResult* result,
673 const UpdateState& update_state) const {
674 // Sanity checks.
675 DCHECK_GE(update_state.download_errors_max, 0);
676
677 // Set default result values.
678 result->do_increment_failures = false;
679 result->backoff_expiry = update_state.backoff_expiry;
680 result->url_idx = -1;
681 result->url_num_errors = 0;
682
683 const bool* is_official_build_p = ec->GetValue(
684 state->system_provider()->var_is_official_build());
685 bool is_official_build = (is_official_build_p ? *is_official_build_p : true);
686
687 // Check whether backoff is enabled.
688 bool may_backoff = false;
689 if (update_state.is_backoff_disabled) {
690 LOG(INFO) << "Backoff disabled by Omaha.";
691 } else if (update_state.is_interactive) {
692 LOG(INFO) << "No backoff for interactive updates.";
693 } else if (update_state.is_delta_payload) {
694 LOG(INFO) << "No backoff for delta payloads.";
695 } else if (!is_official_build) {
696 LOG(INFO) << "No backoff for unofficial builds.";
697 } else {
698 may_backoff = true;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700699 }
700
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700701 // If previous backoff still in effect, block.
702 if (may_backoff && !update_state.backoff_expiry.is_null() &&
703 !ec->IsWallclockTimeGreaterThan(update_state.backoff_expiry)) {
704 LOG(INFO) << "Previous backoff has not expired, waiting.";
705 return EvalStatus::kAskMeAgainLater;
706 }
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700707
708 // Determine whether HTTP downloads are forbidden by policy. This only
709 // applies to official system builds; otherwise, HTTP is always enabled.
710 bool http_allowed = true;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700711 if (is_official_build) {
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700712 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
713 const bool* device_policy_is_loaded_p = ec->GetValue(
714 dp_provider->var_device_policy_is_loaded());
715 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
716 const bool* policy_http_downloads_enabled_p = ec->GetValue(
717 dp_provider->var_http_downloads_enabled());
718 http_allowed = (!policy_http_downloads_enabled_p ||
719 *policy_http_downloads_enabled_p);
720 }
721 }
722
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700723 int url_idx = update_state.last_download_url_idx;
724 if (url_idx < 0)
725 url_idx = -1;
726 bool do_advance_url = false;
727 bool is_failure_occurred = false;
728 Time err_time;
729
730 // Scan the relevant part of the download error log, tracking which URLs are
731 // being used, and accounting the number of errors for each URL. Note that
732 // this process may not traverse all errors provided, as it may decide to bail
733 // out midway depending on the particular errors exhibited, the number of
734 // failures allowed, etc. When this ends, |url_idx| will point to the last URL
735 // used (-1 if starting fresh), |do_advance_url| will determine whether the
736 // URL needs to be advanced, and |err_time| the point in time when the last
737 // reported error occurred. Additionally, if the error log indicates that an
738 // update attempt has failed (abnormal), then |is_failure_occurred| will be
739 // set to true.
740 const int num_urls = update_state.download_urls.size();
741 int prev_url_idx = -1;
742 int url_num_errors = update_state.last_download_url_num_errors;
743 Time prev_err_time;
744 bool is_first = true;
745 for (const auto& err_tuple : update_state.download_errors) {
746 // Do some sanity checks.
747 int used_url_idx = get<0>(err_tuple);
748 if (is_first && url_idx >= 0 && used_url_idx != url_idx) {
749 LOG(WARNING) << "First URL in error log (" << used_url_idx
750 << ") not as expected (" << url_idx << ")";
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700751 }
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700752 is_first = false;
753 url_idx = used_url_idx;
754 if (url_idx < 0 || url_idx >= num_urls) {
755 LOG(ERROR) << "Download error log contains an invalid URL index ("
756 << url_idx << ")";
757 return EvalStatus::kFailed;
758 }
759 err_time = get<2>(err_tuple);
760 if (!(prev_err_time.is_null() || err_time >= prev_err_time)) {
761 // TODO(garnold) Monotonicity cannot really be assumed when dealing with
762 // wallclock-based timestamps. However, we're making a simplifying
763 // assumption so as to keep the policy implementation straightforward, for
764 // now. In general, we should convert all timestamp handling in the
765 // UpdateManager to use monotonic time (instead of wallclock), including
766 // the computation of various expiration times (backoff, scattering, etc).
767 // The client will do whatever conversions necessary when
768 // persisting/retrieving these values across reboots. See chromium:408794.
769 LOG(ERROR) << "Download error timestamps not monotonically increasing.";
770 return EvalStatus::kFailed;
771 }
772 prev_err_time = err_time;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700773
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700774 // Ignore errors that happened before the last known failed attempt.
775 if (!update_state.failures_last_updated.is_null() &&
776 err_time <= update_state.failures_last_updated)
777 continue;
778
779 if (prev_url_idx >= 0) {
780 if (url_idx < prev_url_idx) {
781 LOG(ERROR) << "The URLs in the download error log have wrapped around ("
782 << prev_url_idx << "->" << url_idx
783 << "). This should not have happened and means that there's "
784 "a bug. To be conservative, we record a failed attempt "
785 "(invalidating the rest of the error log) and resume "
786 "download from the first usable URL.";
787 url_idx = -1;
788 is_failure_occurred = true;
789 break;
790 }
791
792 if (url_idx > prev_url_idx) {
793 url_num_errors = 0;
794 do_advance_url = false;
795 }
796 }
797
798 if (HandleErrorCode(get<1>(err_tuple), &url_num_errors) ||
799 url_num_errors > update_state.download_errors_max)
800 do_advance_url = true;
801
802 prev_url_idx = url_idx;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700803 }
804
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700805 // If required, advance to the next usable URL. If the URLs wraparound, we
806 // mark an update attempt failure. Also be sure to set the download error
807 // count to zero.
808 if (url_idx < 0 || do_advance_url) {
809 url_num_errors = 0;
810 int start_url_idx = -1;
811 do {
812 if (++url_idx == num_urls) {
813 url_idx = 0;
814 // We only mark failure if an actual advancing of a URL was required.
815 if (do_advance_url)
816 is_failure_occurred = true;
817 }
818
819 if (start_url_idx < 0)
820 start_url_idx = url_idx;
821 else if (url_idx == start_url_idx)
822 url_idx = -1; // No usable URL.
823 } while (url_idx >= 0 &&
824 !IsUrlUsable(update_state.download_urls[url_idx], http_allowed));
825 }
826
827 // If we have a download URL but a failure was observed, compute a new backoff
828 // expiry (if allowed). The backoff period is generally 2 ^ (num_failures - 1)
829 // days, bounded by the size of int and kAttemptBackoffMaxIntervalInDays, and
830 // fuzzed by kAttemptBackoffFuzzInHours hours. Backoff expiry is computed from
831 // the latest recorded time of error.
832 Time backoff_expiry;
833 if (url_idx >= 0 && is_failure_occurred && may_backoff) {
834 CHECK(!err_time.is_null())
835 << "We must have an error timestamp if a failure occurred!";
836 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
837 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
838 PRNG prng(*seed);
Alex Deymof329b932014-10-30 01:37:48 -0700839 int exp = min(update_state.num_failures,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700840 static_cast<int>(sizeof(int)) * 8 - 2);
841 TimeDelta backoff_interval = TimeDelta::FromDays(
Alex Deymof329b932014-10-30 01:37:48 -0700842 min(1 << exp, kAttemptBackoffMaxIntervalInDays));
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700843 TimeDelta backoff_fuzz = TimeDelta::FromHours(kAttemptBackoffFuzzInHours);
844 TimeDelta wait_period = FuzzedInterval(&prng, backoff_interval.InSeconds(),
845 backoff_fuzz.InSeconds());
846 backoff_expiry = err_time + wait_period;
847
848 // If the newly computed backoff already expired, nullify it.
849 if (ec->IsWallclockTimeGreaterThan(backoff_expiry))
850 backoff_expiry = Time();
851 }
852
853 result->do_increment_failures = is_failure_occurred;
854 result->backoff_expiry = backoff_expiry;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700855 result->url_idx = url_idx;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700856 result->url_num_errors = url_num_errors;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700857 return EvalStatus::kSucceeded;
858}
859
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700860EvalStatus ChromeOSPolicy::UpdateScattering(
861 EvaluationContext* ec,
862 State* state,
863 string* error,
864 UpdateScatteringResult* result,
865 const UpdateState& update_state) const {
866 // Preconditions. These stem from the postconditions and usage contract.
867 DCHECK(update_state.scatter_wait_period >= kZeroInterval);
868 DCHECK_GE(update_state.scatter_check_threshold, 0);
869
870 // Set default result values.
871 result->is_scattering = false;
872 result->wait_period = kZeroInterval;
873 result->check_threshold = 0;
874
875 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
876
877 // Ensure that a device policy is loaded.
878 const bool* device_policy_is_loaded_p = ec->GetValue(
879 dp_provider->var_device_policy_is_loaded());
880 if (!(device_policy_is_loaded_p && *device_policy_is_loaded_p))
881 return EvalStatus::kSucceeded;
882
883 // Is scattering enabled by policy?
884 const TimeDelta* scatter_factor_p = ec->GetValue(
885 dp_provider->var_scatter_factor());
886 if (!scatter_factor_p || *scatter_factor_p == kZeroInterval)
887 return EvalStatus::kSucceeded;
888
889 // Obtain a pseudo-random number generator.
890 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
891 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
892 PRNG prng(*seed);
893
894 // Step 1: Maintain the scattering wait period.
895 //
896 // If no wait period was previously determined, or it no longer fits in the
897 // scatter factor, then generate a new one. Otherwise, keep the one we have.
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700898 TimeDelta wait_period = update_state.scatter_wait_period;
899 if (wait_period == kZeroInterval || wait_period > *scatter_factor_p) {
900 wait_period = TimeDelta::FromSeconds(
901 prng.RandMinMax(1, scatter_factor_p->InSeconds()));
902 }
903
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700904 // If we surpassed the wait period or the max scatter period associated with
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700905 // the update, then no wait is needed.
906 Time wait_expires = (update_state.first_seen +
907 min(wait_period, update_state.scatter_wait_period_max));
Gilad Arnolda65fced2014-07-23 09:01:31 -0700908 if (ec->IsWallclockTimeGreaterThan(wait_expires))
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700909 wait_period = kZeroInterval;
910
911 // Step 2: Maintain the update check threshold count.
912 //
913 // If an update check threshold is not specified then generate a new
914 // one.
915 int check_threshold = update_state.scatter_check_threshold;
916 if (check_threshold == 0) {
917 check_threshold = prng.RandMinMax(
918 update_state.scatter_check_threshold_min,
919 update_state.scatter_check_threshold_max);
920 }
921
922 // If the update check threshold is not within allowed range then nullify it.
923 // TODO(garnold) This is compliant with current logic found in
924 // OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied(). We may want
925 // to change it so that it behaves similarly to the wait period case, namely
926 // if the current value exceeds the maximum, we set a new one within range.
927 if (check_threshold > update_state.scatter_check_threshold_max)
928 check_threshold = 0;
929
930 // If the update check threshold is non-zero and satisfied, then nullify it.
931 if (check_threshold > 0 && update_state.num_checks >= check_threshold)
932 check_threshold = 0;
933
934 bool is_scattering = (wait_period != kZeroInterval || check_threshold);
935 EvalStatus ret = EvalStatus::kSucceeded;
936 if (is_scattering && wait_period == update_state.scatter_wait_period &&
937 check_threshold == update_state.scatter_check_threshold)
938 ret = EvalStatus::kAskMeAgainLater;
939 result->is_scattering = is_scattering;
940 result->wait_period = wait_period;
941 result->check_threshold = check_threshold;
942 return ret;
943}
944
Alex Deymo63784a52014-05-28 10:46:14 -0700945} // namespace chromeos_update_manager