blob: b32b6261bec7a55527d11bafcda25e1b3c43821f [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2014 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
Alex Deymoc705cc82014-02-19 11:15:00 -080016
Alex Deymo63784a52014-05-28 10:46:14 -070017#include "update_engine/update_manager/chromeos_policy.h"
Alex Deymo0d11c602014-04-23 20:12:20 -070018
Gilad Arnolde1218812014-05-07 12:21:36 -070019#include <algorithm>
Gilad Arnold0adbc942014-05-12 10:35:43 -070020#include <set>
Alex Deymoc705cc82014-02-19 11:15:00 -080021#include <string>
22
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070023#include <base/logging.h>
Gilad Arnoldb3b05442014-05-30 14:25:05 -070024#include <base/strings/string_util.h>
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070025#include <base/time/time.h>
26
Alex Deymo39910dc2015-11-09 17:04:30 -080027#include "update_engine/common/error_code.h"
Alex Deymoe88e9fe2016-02-03 16:38:00 -080028#include "update_engine/common/error_code_utils.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080029#include "update_engine/common/utils.h"
Alex Deymo63784a52014-05-28 10:46:14 -070030#include "update_engine/update_manager/device_policy_provider.h"
31#include "update_engine/update_manager/policy_utils.h"
32#include "update_engine/update_manager/shill_provider.h"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070033
Alex Deymo0d11c602014-04-23 20:12:20 -070034using base::Time;
35using base::TimeDelta;
Sen Jiang255e22b2016-05-20 16:15:29 -070036using chromeos_update_engine::ConnectionTethering;
37using chromeos_update_engine::ConnectionType;
Gilad Arnoldb3b05442014-05-30 14:25:05 -070038using chromeos_update_engine::ErrorCode;
Aaron Wood987ffc12017-10-06 14:48:25 -070039using chromeos_update_engine::InstallPlan;
Gilad Arnolddc4bb262014-07-23 10:45:19 -070040using std::get;
Gilad Arnoldb3b05442014-05-30 14:25:05 -070041using std::max;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070042using std::min;
Gilad Arnold0adbc942014-05-12 10:35:43 -070043using std::set;
Alex Deymoc705cc82014-02-19 11:15:00 -080044using std::string;
45
Gilad Arnoldb3b05442014-05-30 14:25:05 -070046namespace {
47
Gilad Arnolddc4bb262014-07-23 10:45:19 -070048// Examines |err_code| and decides whether the URL index needs to be advanced,
49// the error count for the URL incremented, or none of the above. In the first
50// case, returns true; in the second case, increments |*url_num_error_p| and
51// returns false; otherwise just returns false.
Gilad Arnoldb3b05442014-05-30 14:25:05 -070052//
53// TODO(garnold) Adapted from PayloadState::UpdateFailed() (to be retired).
Gilad Arnolddc4bb262014-07-23 10:45:19 -070054bool HandleErrorCode(ErrorCode err_code, int* url_num_error_p) {
Gilad Arnoldb3b05442014-05-30 14:25:05 -070055 err_code = chromeos_update_engine::utils::GetBaseErrorCode(err_code);
56 switch (err_code) {
57 // Errors which are good indicators of a problem with a particular URL or
58 // the protocol used in the URL or entities in the communication channel
59 // (e.g. proxies). We should try the next available URL in the next update
60 // check to quickly recover from these errors.
61 case ErrorCode::kPayloadHashMismatchError:
62 case ErrorCode::kPayloadSizeMismatchError:
63 case ErrorCode::kDownloadPayloadVerificationError:
64 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
65 case ErrorCode::kSignedDeltaPayloadExpectedError:
66 case ErrorCode::kDownloadInvalidMetadataMagicString:
67 case ErrorCode::kDownloadSignatureMissingInManifest:
68 case ErrorCode::kDownloadManifestParseError:
69 case ErrorCode::kDownloadMetadataSignatureError:
70 case ErrorCode::kDownloadMetadataSignatureVerificationError:
71 case ErrorCode::kDownloadMetadataSignatureMismatch:
72 case ErrorCode::kDownloadOperationHashVerificationError:
73 case ErrorCode::kDownloadOperationExecutionError:
74 case ErrorCode::kDownloadOperationHashMismatch:
75 case ErrorCode::kDownloadInvalidMetadataSize:
76 case ErrorCode::kDownloadInvalidMetadataSignature:
77 case ErrorCode::kDownloadOperationHashMissingError:
78 case ErrorCode::kDownloadMetadataSignatureMissingError:
79 case ErrorCode::kPayloadMismatchedType:
80 case ErrorCode::kUnsupportedMajorPayloadVersion:
81 case ErrorCode::kUnsupportedMinorPayloadVersion:
Sen Jiang8e768e92017-06-28 17:13:19 -070082 case ErrorCode::kPayloadTimestampError:
Gilad Arnoldb3b05442014-05-30 14:25:05 -070083 LOG(INFO) << "Advancing download URL due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -080084 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -070085 << " (" << static_cast<int>(err_code) << ")";
Gilad Arnoldb3b05442014-05-30 14:25:05 -070086 return true;
87
88 // Errors which seem to be just transient network/communication related
89 // failures and do not indicate any inherent problem with the URL itself.
90 // So, we should keep the current URL but just increment the
91 // failure count to give it more chances. This way, while we maximize our
92 // chances of downloading from the URLs that appear earlier in the response
93 // (because download from a local server URL that appears earlier in a
94 // response is preferable than downloading from the next URL which could be
Alex Vakulenko072359c2014-07-18 11:41:07 -070095 // an Internet URL and thus could be more expensive).
Gilad Arnoldb3b05442014-05-30 14:25:05 -070096 case ErrorCode::kError:
97 case ErrorCode::kDownloadTransferError:
98 case ErrorCode::kDownloadWriteError:
99 case ErrorCode::kDownloadStateInitializationError:
Gilad Arnold684219d2014-07-07 14:54:57 -0700100 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700101 LOG(INFO) << "Incrementing URL failure count due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800102 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700103 << " (" << static_cast<int>(err_code) << ")";
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700104 *url_num_error_p += 1;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700105 return false;
106
107 // Errors which are not specific to a URL and hence shouldn't result in
108 // the URL being penalized. This can happen in two cases:
109 // 1. We haven't started downloading anything: These errors don't cost us
110 // anything in terms of actual payload bytes, so we should just do the
111 // regular retries at the next update check.
112 // 2. We have successfully downloaded the payload: In this case, the
113 // payload attempt number would have been incremented and would take care
Alex Vakulenko072359c2014-07-18 11:41:07 -0700114 // of the back-off at the next update check.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700115 // In either case, there's no need to update URL index or failure count.
116 case ErrorCode::kOmahaRequestError:
117 case ErrorCode::kOmahaResponseHandlerError:
118 case ErrorCode::kPostinstallRunnerError:
119 case ErrorCode::kFilesystemCopierError:
120 case ErrorCode::kInstallDeviceOpenError:
121 case ErrorCode::kKernelDeviceOpenError:
122 case ErrorCode::kDownloadNewPartitionInfoError:
123 case ErrorCode::kNewRootfsVerificationError:
124 case ErrorCode::kNewKernelVerificationError:
125 case ErrorCode::kPostinstallBootedFromFirmwareB:
126 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
127 case ErrorCode::kOmahaRequestEmptyResponseError:
128 case ErrorCode::kOmahaRequestXMLParseError:
129 case ErrorCode::kOmahaResponseInvalid:
130 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
131 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
Kevin Cernekee2494e282016-03-29 18:03:53 -0700132 case ErrorCode::kNonCriticalUpdateInOOBE:
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700133 case ErrorCode::kOmahaUpdateDeferredForBackoff:
134 case ErrorCode::kPostinstallPowerwashError:
135 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400136 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700137 case ErrorCode::kFilesystemVerifierError:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800138 case ErrorCode::kUserCanceled:
Sen Jiangfe522822017-10-31 15:14:11 -0700139 case ErrorCode::kUpdatedButNotActive:
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700140 LOG(INFO) << "Not changing URL index or failure count due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800141 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700142 << " (" << static_cast<int>(err_code) << ")";
143 return false;
144
145 case ErrorCode::kSuccess: // success code
146 case ErrorCode::kUmaReportedMax: // not an error code
147 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800148 case ErrorCode::kDevModeFlag: // not an error code
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700149 case ErrorCode::kResumedFlag: // not an error code
150 case ErrorCode::kTestImageFlag: // not an error code
151 case ErrorCode::kTestOmahaUrlFlag: // not an error code
152 case ErrorCode::kSpecialFlags: // not an error code
153 // These shouldn't happen. Enumerating these explicitly here so that we
154 // can let the compiler warn about new error codes that are added to
155 // action_processor.h but not added here.
156 LOG(WARNING) << "Unexpected error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800157 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700158 << " (" << static_cast<int>(err_code) << ")";
159 // Note: Not adding a default here so as to let the compiler warn us of
160 // any new enums that were added in the .h but not listed in this switch.
161 }
162 return false;
163}
164
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700165// Checks whether |url| can be used under given download restrictions.
166bool IsUrlUsable(const string& url, bool http_allowed) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800167 return http_allowed ||
168 !base::StartsWith(url, "http://",
169 base::CompareCase::INSENSITIVE_ASCII);
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700170}
171
172} // namespace
173
Alex Deymo63784a52014-05-28 10:46:14 -0700174namespace chromeos_update_manager {
Alex Deymoc705cc82014-02-19 11:15:00 -0800175
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700176const int ChromeOSPolicy::kTimeoutInitialInterval = 7 * 60;
Alex Deymo14e7dde2015-10-20 14:46:33 -0700177
178// TODO(deymo): Split the update_manager policies for Brillo and ChromeOS and
179// make the update check periodic interval configurable.
180#ifdef __ANDROID__
181const int ChromeOSPolicy::kTimeoutPeriodicInterval = 5 * 60 * 60;
Alex Deymodbe13b42015-11-06 11:15:08 -0800182const int ChromeOSPolicy::kTimeoutMaxBackoffInterval = 26 * 60 * 60;
Alex Deymo14e7dde2015-10-20 14:46:33 -0700183#else
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700184const int ChromeOSPolicy::kTimeoutPeriodicInterval = 45 * 60;
Alex Deymodbe13b42015-11-06 11:15:08 -0800185const int ChromeOSPolicy::kTimeoutMaxBackoffInterval = 4 * 60 * 60;
Alex Deymo14e7dde2015-10-20 14:46:33 -0700186#endif // __ANDROID__
187
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700188const int ChromeOSPolicy::kTimeoutRegularFuzz = 10 * 60;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700189const int ChromeOSPolicy::kAttemptBackoffMaxIntervalInDays = 16;
190const int ChromeOSPolicy::kAttemptBackoffFuzzInHours = 12;
Gilad Arnold349ac832014-10-06 14:20:28 -0700191const int ChromeOSPolicy::kMaxP2PAttempts = 10;
192const int ChromeOSPolicy::kMaxP2PAttemptsPeriodInSeconds = 5 * 24 * 60 * 60;
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700193
Alex Deymo0d11c602014-04-23 20:12:20 -0700194EvalStatus ChromeOSPolicy::UpdateCheckAllowed(
195 EvaluationContext* ec, State* state, string* error,
196 UpdateCheckParams* result) const {
Gilad Arnold42f253b2014-06-25 12:39:17 -0700197 // Set the default return values.
198 result->updates_enabled = true;
199 result->target_channel.clear();
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700200 result->target_version_prefix.clear();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700201 result->is_interactive = false;
Gilad Arnold42f253b2014-06-25 12:39:17 -0700202
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700203 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700204 UpdaterProvider* const updater_provider = state->updater_provider();
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700205 SystemProvider* const system_provider = state->system_provider();
206
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700207 // Do not perform any updates if booted from removable device. This decision
208 // is final.
Alex Deymo763e7db2015-08-27 21:08:08 -0700209 const unsigned int* num_slots_p = ec->GetValue(
210 system_provider->var_num_slots());
211 if (!num_slots_p || *num_slots_p < 2) {
212 LOG(INFO) << "Not enough slots for A/B updates, disabling update checks.";
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700213 result->updates_enabled = false;
214 return EvalStatus::kSucceeded;
215 }
216
Gilad Arnold42f253b2014-06-25 12:39:17 -0700217 const bool* device_policy_is_loaded_p = ec->GetValue(
218 dp_provider->var_device_policy_is_loaded());
219 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Xiyuan Xia6e30bc52016-02-24 15:35:42 -0800220 bool kiosk_app_control_chrome_version = false;
221
Gilad Arnold42f253b2014-06-25 12:39:17 -0700222 // Check whether updates are disabled by policy.
223 const bool* update_disabled_p = ec->GetValue(
224 dp_provider->var_update_disabled());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700225 if (update_disabled_p && *update_disabled_p) {
Xiyuan Xia6e30bc52016-02-24 15:35:42 -0800226 // Check whether allow kiosk app to control chrome version policy. This
227 // policy is only effective when AU is disabled by admin.
228 const bool* allow_kiosk_app_control_chrome_version_p = ec->GetValue(
229 dp_provider->var_allow_kiosk_app_control_chrome_version());
230 kiosk_app_control_chrome_version =
231 allow_kiosk_app_control_chrome_version_p &&
232 *allow_kiosk_app_control_chrome_version_p;
233 if (!kiosk_app_control_chrome_version) {
234 // No kiosk pin chrome version policy. AU is really disabled.
235 LOG(INFO) << "Updates disabled by policy, blocking update checks.";
236 return EvalStatus::kAskMeAgainLater;
237 }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700238 }
Gilad Arnold42f253b2014-06-25 12:39:17 -0700239
Xiyuan Xia6e30bc52016-02-24 15:35:42 -0800240 if (kiosk_app_control_chrome_version) {
241 // Get the required platform version from Chrome.
242 const string* kiosk_required_platform_version_p =
243 ec->GetValue(system_provider->var_kiosk_required_platform_version());
Xiyuan Xiaed9bd922016-04-07 14:45:16 -0700244 if (!kiosk_required_platform_version_p) {
245 LOG(INFO) << "Kiosk app required platform version is not fetched, "
246 "blocking update checks";
247 return EvalStatus::kAskMeAgainLater;
248 }
249
250 result->target_version_prefix = *kiosk_required_platform_version_p;
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -0800251 LOG(INFO) << "Allow kiosk app to control Chrome version policy is set, "
252 << "target version is "
253 << (!kiosk_required_platform_version_p->empty()
Xiyuan Xia6e30bc52016-02-24 15:35:42 -0800254 ? *kiosk_required_platform_version_p
255 : std::string("latest"));
256 } else {
257 // Determine whether a target version prefix is dictated by policy.
258 const string* target_version_prefix_p = ec->GetValue(
259 dp_provider->var_target_version_prefix());
260 if (target_version_prefix_p)
261 result->target_version_prefix = *target_version_prefix_p;
262 }
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700263
Gilad Arnold42f253b2014-06-25 12:39:17 -0700264 // Determine whether a target channel is dictated by policy.
265 const bool* release_channel_delegated_p = ec->GetValue(
266 dp_provider->var_release_channel_delegated());
267 if (release_channel_delegated_p && !(*release_channel_delegated_p)) {
268 const string* release_channel_p = ec->GetValue(
269 dp_provider->var_release_channel());
270 if (release_channel_p)
271 result->target_channel = *release_channel_p;
272 }
273 }
274
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700275 // First, check to see if an interactive update was requested.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700276 const UpdateRequestStatus* forced_update_requested_p = ec->GetValue(
277 updater_provider->var_forced_update_requested());
278 if (forced_update_requested_p &&
279 *forced_update_requested_p != UpdateRequestStatus::kNone) {
280 result->is_interactive =
281 (*forced_update_requested_p == UpdateRequestStatus::kInteractive);
282 LOG(INFO) << "Forced update signaled ("
283 << (result->is_interactive ? "interactive" : "periodic")
284 << "), allowing update check.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700285 return EvalStatus::kSucceeded;
286 }
287
288 // The logic thereafter applies to periodic updates. Bear in mind that we
289 // should not return a final "no" if any of these criteria are not satisfied,
290 // because the system may still update due to an interactive update request.
291
292 // Unofficial builds should not perform periodic update checks.
293 const bool* is_official_build_p = ec->GetValue(
294 system_provider->var_is_official_build());
295 if (is_official_build_p && !(*is_official_build_p)) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700296 LOG(INFO) << "Unofficial build, blocking periodic update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700297 return EvalStatus::kAskMeAgainLater;
298 }
299
300 // If OOBE is enabled, wait until it is completed.
301 const bool* is_oobe_enabled_p = ec->GetValue(
302 state->config_provider()->var_is_oobe_enabled());
303 if (is_oobe_enabled_p && *is_oobe_enabled_p) {
304 const bool* is_oobe_complete_p = ec->GetValue(
305 system_provider->var_is_oobe_complete());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700306 if (is_oobe_complete_p && !(*is_oobe_complete_p)) {
307 LOG(INFO) << "OOBE not completed, blocking update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700308 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700309 }
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700310 }
311
312 // Ensure that periodic update checks are timed properly.
Alex Deymo0d11c602014-04-23 20:12:20 -0700313 Time next_update_check;
314 if (NextUpdateCheckTime(ec, state, error, &next_update_check) !=
315 EvalStatus::kSucceeded) {
316 return EvalStatus::kFailed;
317 }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700318 if (!ec->IsWallclockTimeGreaterThan(next_update_check)) {
319 LOG(INFO) << "Periodic check interval not satisfied, blocking until "
320 << chromeos_update_engine::utils::ToString(next_update_check);
Alex Deymo0d11c602014-04-23 20:12:20 -0700321 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700322 }
Alex Deymo0d11c602014-04-23 20:12:20 -0700323
324 // It is time to check for an update.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700325 LOG(INFO) << "Allowing update check.";
Alex Deymoe636c3c2014-03-11 19:02:08 -0700326 return EvalStatus::kSucceeded;
Alex Deymoc705cc82014-02-19 11:15:00 -0800327}
328
Aaron Wood987ffc12017-10-06 14:48:25 -0700329EvalStatus ChromeOSPolicy::UpdateCanBeApplied(EvaluationContext* ec,
330 State* state,
331 std::string* error,
332 ErrorCode* result,
333 InstallPlan* install_plan) const {
334 *result = ErrorCode::kSuccess;
335 return EvalStatus::kSucceeded;
336}
337
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700338EvalStatus ChromeOSPolicy::UpdateCanStart(
339 EvaluationContext* ec,
340 State* state,
341 string* error,
Gilad Arnold42f253b2014-06-25 12:39:17 -0700342 UpdateDownloadParams* result,
Gilad Arnoldd78caf92014-09-24 09:28:14 -0700343 const UpdateState update_state) const {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700344 // Set the default return values. Note that we set persisted values (backoff,
345 // scattering) to the same values presented in the update state. The reason is
346 // that preemptive returns, such as the case where an update check is due,
347 // should not clear off the said values; rather, it is the deliberate
348 // inference of new values that should cause them to be reset.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700349 result->update_can_start = false;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700350 result->cannot_start_reason = UpdateCannotStartReason::kUndefined;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700351 result->download_url_idx = -1;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700352 result->download_url_allowed = true;
353 result->download_url_num_errors = 0;
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700354 result->p2p_downloading_allowed = false;
355 result->p2p_sharing_allowed = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700356 result->do_increment_failures = false;
357 result->backoff_expiry = update_state.backoff_expiry;
358 result->scatter_wait_period = update_state.scatter_wait_period;
359 result->scatter_check_threshold = update_state.scatter_check_threshold;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700360
361 // Make sure that we're not due for an update check.
362 UpdateCheckParams check_result;
363 EvalStatus check_status = UpdateCheckAllowed(ec, state, error, &check_result);
364 if (check_status == EvalStatus::kFailed)
365 return EvalStatus::kFailed;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700366 bool is_check_due = (check_status == EvalStatus::kSucceeded &&
367 check_result.updates_enabled == true);
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700368
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700369 // Check whether backoff applies, and if not then which URL can be used for
370 // downloading. These require scanning the download error log, and so they are
371 // done together.
372 UpdateBackoffAndDownloadUrlResult backoff_url_result;
373 EvalStatus backoff_url_status = UpdateBackoffAndDownloadUrl(
374 ec, state, error, &backoff_url_result, update_state);
Gilad Arnold14a9e702014-10-08 08:09:09 -0700375 if (backoff_url_status == EvalStatus::kFailed)
376 return EvalStatus::kFailed;
377 result->download_url_idx = backoff_url_result.url_idx;
378 result->download_url_num_errors = backoff_url_result.url_num_errors;
379 result->do_increment_failures = backoff_url_result.do_increment_failures;
380 result->backoff_expiry = backoff_url_result.backoff_expiry;
381 bool is_backoff_active =
382 (backoff_url_status == EvalStatus::kAskMeAgainLater) ||
383 !backoff_url_result.backoff_expiry.is_null();
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700384
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700385 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold14a9e702014-10-08 08:09:09 -0700386 bool is_scattering_active = false;
387 EvalStatus scattering_status = EvalStatus::kSucceeded;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700388
389 const bool* device_policy_is_loaded_p = ec->GetValue(
390 dp_provider->var_device_policy_is_loaded());
391 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700392 // Check whether scattering applies to this update attempt. We should not be
393 // scattering if this is an interactive update check, or if OOBE is enabled
394 // but not completed.
395 //
396 // Note: current code further suppresses scattering if a "deadline"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700397 // attribute is found in the Omaha response. However, it appears that the
Gilad Arnold76a11f62014-05-20 09:02:12 -0700398 // presence of this attribute is merely indicative of an OOBE update, during
399 // which we suppress scattering anyway.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700400 bool is_scattering_applicable = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700401 result->scatter_wait_period = kZeroInterval;
402 result->scatter_check_threshold = 0;
403 if (!update_state.is_interactive) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700404 const bool* is_oobe_enabled_p = ec->GetValue(
405 state->config_provider()->var_is_oobe_enabled());
406 if (is_oobe_enabled_p && !(*is_oobe_enabled_p)) {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700407 is_scattering_applicable = true;
Gilad Arnold76a11f62014-05-20 09:02:12 -0700408 } else {
409 const bool* is_oobe_complete_p = ec->GetValue(
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700410 state->system_provider()->var_is_oobe_complete());
Gilad Arnold14a9e702014-10-08 08:09:09 -0700411 is_scattering_applicable = (is_oobe_complete_p && *is_oobe_complete_p);
Gilad Arnold76a11f62014-05-20 09:02:12 -0700412 }
413 }
414
415 // Compute scattering values.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700416 if (is_scattering_applicable) {
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700417 UpdateScatteringResult scatter_result;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700418 scattering_status = UpdateScattering(ec, state, error, &scatter_result,
419 update_state);
420 if (scattering_status == EvalStatus::kFailed) {
421 return EvalStatus::kFailed;
422 } else {
423 result->scatter_wait_period = scatter_result.wait_period;
424 result->scatter_check_threshold = scatter_result.check_threshold;
425 if (scattering_status == EvalStatus::kAskMeAgainLater ||
426 scatter_result.is_scattering)
427 is_scattering_active = true;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700428 }
429 }
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700430 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700431
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700432 // Find out whether P2P is globally enabled.
433 bool p2p_enabled;
434 EvalStatus p2p_enabled_status = P2PEnabled(ec, state, error, &p2p_enabled);
435 if (p2p_enabled_status != EvalStatus::kSucceeded)
436 return EvalStatus::kFailed;
437
438 // Is P2P is enabled, consider allowing it for downloading and/or sharing.
439 if (p2p_enabled) {
440 // Sharing via P2P is allowed if not disabled by Omaha.
441 if (update_state.p2p_sharing_disabled) {
442 LOG(INFO) << "Blocked P2P sharing because it is disabled by Omaha.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700443 } else {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700444 result->p2p_sharing_allowed = true;
Gilad Arnoldef8d0872014-10-03 14:14:06 -0700445 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700446
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700447 // Downloading via P2P is allowed if not disabled by Omaha, an update is not
448 // interactive, and other limits haven't been reached.
449 if (update_state.p2p_downloading_disabled) {
450 LOG(INFO) << "Blocked P2P downloading because it is disabled by Omaha.";
451 } else if (update_state.is_interactive) {
452 LOG(INFO) << "Blocked P2P downloading because update is interactive.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700453 } else if (update_state.p2p_num_attempts >= kMaxP2PAttempts) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700454 LOG(INFO) << "Blocked P2P downloading as it was attempted too many "
455 "times.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700456 } else if (!update_state.p2p_first_attempted.is_null() &&
457 ec->IsWallclockTimeGreaterThan(
458 update_state.p2p_first_attempted +
459 TimeDelta::FromSeconds(kMaxP2PAttemptsPeriodInSeconds))) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700460 LOG(INFO) << "Blocked P2P downloading as its usage timespan exceeds "
461 "limit.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700462 } else {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700463 // P2P download is allowed; if backoff or scattering are active, be sure
464 // to suppress them, yet prevent any download URL from being used.
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700465 result->p2p_downloading_allowed = true;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700466 if (is_backoff_active || is_scattering_active) {
467 is_backoff_active = is_scattering_active = false;
468 result->download_url_allowed = false;
469 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700470 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700471 }
472
Gilad Arnold14a9e702014-10-08 08:09:09 -0700473 // Check for various deterrents.
474 if (is_check_due) {
475 result->cannot_start_reason = UpdateCannotStartReason::kCheckDue;
476 return EvalStatus::kSucceeded;
477 }
478 if (is_backoff_active) {
479 result->cannot_start_reason = UpdateCannotStartReason::kBackoff;
480 return backoff_url_status;
481 }
482 if (is_scattering_active) {
483 result->cannot_start_reason = UpdateCannotStartReason::kScattering;
484 return scattering_status;
485 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700486 if (result->download_url_idx < 0 && !result->p2p_downloading_allowed) {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700487 result->cannot_start_reason = UpdateCannotStartReason::kCannotDownload;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700488 return EvalStatus::kSucceeded;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700489 }
490
Gilad Arnold14a9e702014-10-08 08:09:09 -0700491 // Update is good to go.
492 result->update_can_start = true;
Gilad Arnoldaf2f6ae2014-04-28 14:14:52 -0700493 return EvalStatus::kSucceeded;
494}
495
Gilad Arnolda8262e22014-06-02 13:54:27 -0700496// TODO(garnold) Logic in this method is based on
497// ConnectionManager::IsUpdateAllowedOver(); be sure to deprecate the latter.
498//
499// TODO(garnold) The current logic generally treats the list of allowed
500// connections coming from the device policy as a whitelist, meaning that it
501// can only be used for enabling connections, but not disable them. Further,
502// certain connection types (like Bluetooth) cannot be enabled even by policy.
503// In effect, the only thing that device policy can change is to enable
504// updates over a cellular network (disabled by default). We may want to
505// revisit this semantics, allowing greater flexibility in defining specific
506// permissions over all types of networks.
Gilad Arnold684219d2014-07-07 14:54:57 -0700507EvalStatus ChromeOSPolicy::UpdateDownloadAllowed(
Gilad Arnolda8262e22014-06-02 13:54:27 -0700508 EvaluationContext* ec,
509 State* state,
510 string* error,
511 bool* result) const {
512 // Get the current connection type.
513 ShillProvider* const shill_provider = state->shill_provider();
514 const ConnectionType* conn_type_p = ec->GetValue(
515 shill_provider->var_conn_type());
516 POLICY_CHECK_VALUE_AND_FAIL(conn_type_p, error);
517 ConnectionType conn_type = *conn_type_p;
518
519 // If we're tethering, treat it as a cellular connection.
520 if (conn_type != ConnectionType::kCellular) {
521 const ConnectionTethering* conn_tethering_p = ec->GetValue(
522 shill_provider->var_conn_tethering());
523 POLICY_CHECK_VALUE_AND_FAIL(conn_tethering_p, error);
524 if (*conn_tethering_p == ConnectionTethering::kConfirmed)
525 conn_type = ConnectionType::kCellular;
526 }
527
528 // By default, we allow updates for all connection types, with exceptions as
529 // noted below. This also determines whether a device policy can override the
530 // default.
531 *result = true;
532 bool device_policy_can_override = false;
533 switch (conn_type) {
534 case ConnectionType::kBluetooth:
535 *result = false;
536 break;
537
538 case ConnectionType::kCellular:
539 *result = false;
540 device_policy_can_override = true;
541 break;
542
543 case ConnectionType::kUnknown:
544 if (error)
545 *error = "Unknown connection type";
546 return EvalStatus::kFailed;
547
548 default:
549 break; // Nothing to do.
550 }
551
552 // If update is allowed, we're done.
553 if (*result)
554 return EvalStatus::kSucceeded;
555
556 // Check whether the device policy specifically allows this connection.
Gilad Arnolda8262e22014-06-02 13:54:27 -0700557 if (device_policy_can_override) {
558 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
559 const bool* device_policy_is_loaded_p = ec->GetValue(
560 dp_provider->var_device_policy_is_loaded());
561 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
562 const set<ConnectionType>* allowed_conn_types_p = ec->GetValue(
563 dp_provider->var_allowed_connection_types_for_update());
564 if (allowed_conn_types_p) {
565 if (allowed_conn_types_p->count(conn_type)) {
566 *result = true;
567 return EvalStatus::kSucceeded;
568 }
Gilad Arnold28d6be62014-06-30 14:04:04 -0700569 } else if (conn_type == ConnectionType::kCellular) {
570 // Local user settings can allow updates over cellular iff a policy was
571 // loaded but no allowed connections were specified in it.
572 const bool* update_over_cellular_allowed_p = ec->GetValue(
573 state->updater_provider()->var_cellular_enabled());
574 if (update_over_cellular_allowed_p && *update_over_cellular_allowed_p)
575 *result = true;
Gilad Arnolda8262e22014-06-02 13:54:27 -0700576 }
577 }
578 }
579
Gilad Arnold28d6be62014-06-30 14:04:04 -0700580 return (*result ? EvalStatus::kSucceeded : EvalStatus::kAskMeAgainLater);
Gilad Arnolda8262e22014-06-02 13:54:27 -0700581}
582
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700583EvalStatus ChromeOSPolicy::P2PEnabled(EvaluationContext* ec,
584 State* state,
Alex Deymo39910dc2015-11-09 17:04:30 -0800585 string* error,
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700586 bool* result) const {
587 bool enabled = false;
588
589 // Determine whether use of P2P is allowed by policy. Even if P2P is not
590 // explicitly allowed, we allow it if the device is enterprise enrolled (that
591 // is, missing or empty owner string).
592 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
593 const bool* device_policy_is_loaded_p = ec->GetValue(
594 dp_provider->var_device_policy_is_loaded());
595 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
596 const bool* policy_au_p2p_enabled_p = ec->GetValue(
597 dp_provider->var_au_p2p_enabled());
598 if (policy_au_p2p_enabled_p) {
599 enabled = *policy_au_p2p_enabled_p;
600 } else {
601 const string* policy_owner_p = ec->GetValue(dp_provider->var_owner());
602 if (!policy_owner_p || policy_owner_p->empty())
603 enabled = true;
604 }
605 }
606
607 // Enable P2P, if so mandated by the updater configuration. This is additive
608 // to whether or not P2P is enabled by device policy.
609 if (!enabled) {
610 const bool* updater_p2p_enabled_p = ec->GetValue(
611 state->updater_provider()->var_p2p_enabled());
612 enabled = updater_p2p_enabled_p && *updater_p2p_enabled_p;
613 }
614
615 *result = enabled;
616 return EvalStatus::kSucceeded;
617}
618
619EvalStatus ChromeOSPolicy::P2PEnabledChanged(EvaluationContext* ec,
620 State* state,
Alex Deymo39910dc2015-11-09 17:04:30 -0800621 string* error,
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700622 bool* result,
623 bool prev_result) const {
624 EvalStatus status = P2PEnabled(ec, state, error, result);
625 if (status == EvalStatus::kSucceeded && *result == prev_result)
626 return EvalStatus::kAskMeAgainLater;
627 return status;
628}
629
Alex Deymo0d11c602014-04-23 20:12:20 -0700630EvalStatus ChromeOSPolicy::NextUpdateCheckTime(EvaluationContext* ec,
631 State* state, string* error,
632 Time* next_update_check) const {
Gilad Arnolda0258a52014-07-10 16:21:19 -0700633 UpdaterProvider* const updater_provider = state->updater_provider();
634
Alex Deymo0d11c602014-04-23 20:12:20 -0700635 // Don't check for updates too often. We limit the update checks to once every
636 // some interval. The interval is kTimeoutInitialInterval the first time and
637 // kTimeoutPeriodicInterval for the subsequent update checks. If the update
638 // check fails, we increase the interval between the update checks
639 // exponentially until kTimeoutMaxBackoffInterval. Finally, to avoid having
640 // many chromebooks running update checks at the exact same time, we add some
641 // fuzz to the interval.
642 const Time* updater_started_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700643 ec->GetValue(updater_provider->var_updater_started_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700644 POLICY_CHECK_VALUE_AND_FAIL(updater_started_time, error);
645
Alex Deymof329b932014-10-30 01:37:48 -0700646 const Time* last_checked_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700647 ec->GetValue(updater_provider->var_last_checked_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700648
649 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
650 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
651
652 PRNG prng(*seed);
653
Gilad Arnold38b14022014-07-09 12:45:56 -0700654 // If this is the first attempt, compute and return an initial value.
Alex Deymo0d11c602014-04-23 20:12:20 -0700655 if (!last_checked_time || *last_checked_time < *updater_started_time) {
Alex Deymo0d11c602014-04-23 20:12:20 -0700656 *next_update_check = *updater_started_time + FuzzedInterval(
657 &prng, kTimeoutInitialInterval, kTimeoutRegularFuzz);
658 return EvalStatus::kSucceeded;
659 }
Gilad Arnold38b14022014-07-09 12:45:56 -0700660
Gilad Arnolda0258a52014-07-10 16:21:19 -0700661 // Check whether the server is enforcing a poll interval; if not, this value
662 // will be zero.
663 const unsigned int* server_dictated_poll_interval = ec->GetValue(
664 updater_provider->var_server_dictated_poll_interval());
665 POLICY_CHECK_VALUE_AND_FAIL(server_dictated_poll_interval, error);
Alex Deymo0d11c602014-04-23 20:12:20 -0700666
Gilad Arnolda0258a52014-07-10 16:21:19 -0700667 int interval = *server_dictated_poll_interval;
668 int fuzz = 0;
669
Alex Vakulenko072359c2014-07-18 11:41:07 -0700670 // If no poll interval was dictated by server compute a back-off period,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700671 // starting from a predetermined base periodic interval and increasing
672 // exponentially by the number of consecutive failed attempts.
673 if (interval == 0) {
674 const unsigned int* consecutive_failed_update_checks = ec->GetValue(
675 updater_provider->var_consecutive_failed_update_checks());
676 POLICY_CHECK_VALUE_AND_FAIL(consecutive_failed_update_checks, error);
677
678 interval = kTimeoutPeriodicInterval;
679 unsigned int num_failures = *consecutive_failed_update_checks;
680 while (interval < kTimeoutMaxBackoffInterval && num_failures) {
681 interval *= 2;
682 num_failures--;
Alex Deymo0d11c602014-04-23 20:12:20 -0700683 }
684 }
685
Alex Vakulenko072359c2014-07-18 11:41:07 -0700686 // We cannot back off longer than the predetermined maximum interval.
Gilad Arnolda0258a52014-07-10 16:21:19 -0700687 if (interval > kTimeoutMaxBackoffInterval)
688 interval = kTimeoutMaxBackoffInterval;
689
Alex Vakulenko072359c2014-07-18 11:41:07 -0700690 // We cannot back off shorter than the predetermined periodic interval. Also,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700691 // in this case set the fuzz to a predetermined regular value.
692 if (interval <= kTimeoutPeriodicInterval) {
693 interval = kTimeoutPeriodicInterval;
694 fuzz = kTimeoutRegularFuzz;
695 }
696
697 // If not otherwise determined, defer to a fuzz of +/-(interval / 2).
Gilad Arnold38b14022014-07-09 12:45:56 -0700698 if (fuzz == 0)
699 fuzz = interval;
700
Alex Deymo0d11c602014-04-23 20:12:20 -0700701 *next_update_check = *last_checked_time + FuzzedInterval(
Gilad Arnold38b14022014-07-09 12:45:56 -0700702 &prng, interval, fuzz);
Alex Deymo0d11c602014-04-23 20:12:20 -0700703 return EvalStatus::kSucceeded;
704}
705
706TimeDelta ChromeOSPolicy::FuzzedInterval(PRNG* prng, int interval, int fuzz) {
Gilad Arnolde1218812014-05-07 12:21:36 -0700707 DCHECK_GE(interval, 0);
708 DCHECK_GE(fuzz, 0);
Alex Deymo0d11c602014-04-23 20:12:20 -0700709 int half_fuzz = fuzz / 2;
Alex Deymo0d11c602014-04-23 20:12:20 -0700710 // This guarantees the output interval is non negative.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700711 int interval_min = max(interval - half_fuzz, 0);
Gilad Arnolde1218812014-05-07 12:21:36 -0700712 int interval_max = interval + half_fuzz;
713 return TimeDelta::FromSeconds(prng->RandMinMax(interval_min, interval_max));
Alex Deymo0d11c602014-04-23 20:12:20 -0700714}
715
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700716EvalStatus ChromeOSPolicy::UpdateBackoffAndDownloadUrl(
Alex Deymof329b932014-10-30 01:37:48 -0700717 EvaluationContext* ec, State* state, string* error,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700718 UpdateBackoffAndDownloadUrlResult* result,
719 const UpdateState& update_state) const {
720 // Sanity checks.
721 DCHECK_GE(update_state.download_errors_max, 0);
722
723 // Set default result values.
724 result->do_increment_failures = false;
725 result->backoff_expiry = update_state.backoff_expiry;
726 result->url_idx = -1;
727 result->url_num_errors = 0;
728
729 const bool* is_official_build_p = ec->GetValue(
730 state->system_provider()->var_is_official_build());
731 bool is_official_build = (is_official_build_p ? *is_official_build_p : true);
732
733 // Check whether backoff is enabled.
734 bool may_backoff = false;
735 if (update_state.is_backoff_disabled) {
736 LOG(INFO) << "Backoff disabled by Omaha.";
737 } else if (update_state.is_interactive) {
738 LOG(INFO) << "No backoff for interactive updates.";
739 } else if (update_state.is_delta_payload) {
740 LOG(INFO) << "No backoff for delta payloads.";
741 } else if (!is_official_build) {
742 LOG(INFO) << "No backoff for unofficial builds.";
743 } else {
744 may_backoff = true;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700745 }
746
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700747 // If previous backoff still in effect, block.
748 if (may_backoff && !update_state.backoff_expiry.is_null() &&
749 !ec->IsWallclockTimeGreaterThan(update_state.backoff_expiry)) {
750 LOG(INFO) << "Previous backoff has not expired, waiting.";
751 return EvalStatus::kAskMeAgainLater;
752 }
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700753
754 // Determine whether HTTP downloads are forbidden by policy. This only
755 // applies to official system builds; otherwise, HTTP is always enabled.
756 bool http_allowed = true;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700757 if (is_official_build) {
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700758 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
759 const bool* device_policy_is_loaded_p = ec->GetValue(
760 dp_provider->var_device_policy_is_loaded());
761 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
762 const bool* policy_http_downloads_enabled_p = ec->GetValue(
763 dp_provider->var_http_downloads_enabled());
764 http_allowed = (!policy_http_downloads_enabled_p ||
765 *policy_http_downloads_enabled_p);
766 }
767 }
768
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700769 int url_idx = update_state.last_download_url_idx;
770 if (url_idx < 0)
771 url_idx = -1;
772 bool do_advance_url = false;
773 bool is_failure_occurred = false;
774 Time err_time;
775
776 // Scan the relevant part of the download error log, tracking which URLs are
777 // being used, and accounting the number of errors for each URL. Note that
778 // this process may not traverse all errors provided, as it may decide to bail
779 // out midway depending on the particular errors exhibited, the number of
780 // failures allowed, etc. When this ends, |url_idx| will point to the last URL
781 // used (-1 if starting fresh), |do_advance_url| will determine whether the
782 // URL needs to be advanced, and |err_time| the point in time when the last
783 // reported error occurred. Additionally, if the error log indicates that an
784 // update attempt has failed (abnormal), then |is_failure_occurred| will be
785 // set to true.
786 const int num_urls = update_state.download_urls.size();
787 int prev_url_idx = -1;
788 int url_num_errors = update_state.last_download_url_num_errors;
789 Time prev_err_time;
790 bool is_first = true;
791 for (const auto& err_tuple : update_state.download_errors) {
792 // Do some sanity checks.
793 int used_url_idx = get<0>(err_tuple);
794 if (is_first && url_idx >= 0 && used_url_idx != url_idx) {
795 LOG(WARNING) << "First URL in error log (" << used_url_idx
796 << ") not as expected (" << url_idx << ")";
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700797 }
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700798 is_first = false;
799 url_idx = used_url_idx;
800 if (url_idx < 0 || url_idx >= num_urls) {
801 LOG(ERROR) << "Download error log contains an invalid URL index ("
802 << url_idx << ")";
803 return EvalStatus::kFailed;
804 }
805 err_time = get<2>(err_tuple);
806 if (!(prev_err_time.is_null() || err_time >= prev_err_time)) {
807 // TODO(garnold) Monotonicity cannot really be assumed when dealing with
808 // wallclock-based timestamps. However, we're making a simplifying
809 // assumption so as to keep the policy implementation straightforward, for
810 // now. In general, we should convert all timestamp handling in the
811 // UpdateManager to use monotonic time (instead of wallclock), including
812 // the computation of various expiration times (backoff, scattering, etc).
813 // The client will do whatever conversions necessary when
814 // persisting/retrieving these values across reboots. See chromium:408794.
815 LOG(ERROR) << "Download error timestamps not monotonically increasing.";
816 return EvalStatus::kFailed;
817 }
818 prev_err_time = err_time;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700819
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700820 // Ignore errors that happened before the last known failed attempt.
821 if (!update_state.failures_last_updated.is_null() &&
822 err_time <= update_state.failures_last_updated)
823 continue;
824
825 if (prev_url_idx >= 0) {
826 if (url_idx < prev_url_idx) {
827 LOG(ERROR) << "The URLs in the download error log have wrapped around ("
828 << prev_url_idx << "->" << url_idx
829 << "). This should not have happened and means that there's "
830 "a bug. To be conservative, we record a failed attempt "
831 "(invalidating the rest of the error log) and resume "
832 "download from the first usable URL.";
833 url_idx = -1;
834 is_failure_occurred = true;
835 break;
836 }
837
838 if (url_idx > prev_url_idx) {
839 url_num_errors = 0;
840 do_advance_url = false;
841 }
842 }
843
844 if (HandleErrorCode(get<1>(err_tuple), &url_num_errors) ||
845 url_num_errors > update_state.download_errors_max)
846 do_advance_url = true;
847
848 prev_url_idx = url_idx;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700849 }
850
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700851 // If required, advance to the next usable URL. If the URLs wraparound, we
852 // mark an update attempt failure. Also be sure to set the download error
853 // count to zero.
854 if (url_idx < 0 || do_advance_url) {
855 url_num_errors = 0;
856 int start_url_idx = -1;
857 do {
858 if (++url_idx == num_urls) {
859 url_idx = 0;
860 // We only mark failure if an actual advancing of a URL was required.
861 if (do_advance_url)
862 is_failure_occurred = true;
863 }
864
865 if (start_url_idx < 0)
866 start_url_idx = url_idx;
867 else if (url_idx == start_url_idx)
868 url_idx = -1; // No usable URL.
869 } while (url_idx >= 0 &&
870 !IsUrlUsable(update_state.download_urls[url_idx], http_allowed));
871 }
872
873 // If we have a download URL but a failure was observed, compute a new backoff
874 // expiry (if allowed). The backoff period is generally 2 ^ (num_failures - 1)
875 // days, bounded by the size of int and kAttemptBackoffMaxIntervalInDays, and
876 // fuzzed by kAttemptBackoffFuzzInHours hours. Backoff expiry is computed from
877 // the latest recorded time of error.
878 Time backoff_expiry;
879 if (url_idx >= 0 && is_failure_occurred && may_backoff) {
880 CHECK(!err_time.is_null())
881 << "We must have an error timestamp if a failure occurred!";
882 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
883 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
884 PRNG prng(*seed);
Alex Deymof329b932014-10-30 01:37:48 -0700885 int exp = min(update_state.num_failures,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700886 static_cast<int>(sizeof(int)) * 8 - 2);
887 TimeDelta backoff_interval = TimeDelta::FromDays(
Alex Deymof329b932014-10-30 01:37:48 -0700888 min(1 << exp, kAttemptBackoffMaxIntervalInDays));
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700889 TimeDelta backoff_fuzz = TimeDelta::FromHours(kAttemptBackoffFuzzInHours);
890 TimeDelta wait_period = FuzzedInterval(&prng, backoff_interval.InSeconds(),
891 backoff_fuzz.InSeconds());
892 backoff_expiry = err_time + wait_period;
893
894 // If the newly computed backoff already expired, nullify it.
895 if (ec->IsWallclockTimeGreaterThan(backoff_expiry))
896 backoff_expiry = Time();
897 }
898
899 result->do_increment_failures = is_failure_occurred;
900 result->backoff_expiry = backoff_expiry;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700901 result->url_idx = url_idx;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700902 result->url_num_errors = url_num_errors;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700903 return EvalStatus::kSucceeded;
904}
905
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700906EvalStatus ChromeOSPolicy::UpdateScattering(
907 EvaluationContext* ec,
908 State* state,
909 string* error,
910 UpdateScatteringResult* result,
911 const UpdateState& update_state) const {
912 // Preconditions. These stem from the postconditions and usage contract.
913 DCHECK(update_state.scatter_wait_period >= kZeroInterval);
914 DCHECK_GE(update_state.scatter_check_threshold, 0);
915
916 // Set default result values.
917 result->is_scattering = false;
918 result->wait_period = kZeroInterval;
919 result->check_threshold = 0;
920
921 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
922
923 // Ensure that a device policy is loaded.
924 const bool* device_policy_is_loaded_p = ec->GetValue(
925 dp_provider->var_device_policy_is_loaded());
926 if (!(device_policy_is_loaded_p && *device_policy_is_loaded_p))
927 return EvalStatus::kSucceeded;
928
929 // Is scattering enabled by policy?
930 const TimeDelta* scatter_factor_p = ec->GetValue(
931 dp_provider->var_scatter_factor());
932 if (!scatter_factor_p || *scatter_factor_p == kZeroInterval)
933 return EvalStatus::kSucceeded;
934
935 // Obtain a pseudo-random number generator.
936 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
937 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
938 PRNG prng(*seed);
939
940 // Step 1: Maintain the scattering wait period.
941 //
942 // If no wait period was previously determined, or it no longer fits in the
943 // scatter factor, then generate a new one. Otherwise, keep the one we have.
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700944 TimeDelta wait_period = update_state.scatter_wait_period;
945 if (wait_period == kZeroInterval || wait_period > *scatter_factor_p) {
946 wait_period = TimeDelta::FromSeconds(
947 prng.RandMinMax(1, scatter_factor_p->InSeconds()));
948 }
949
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700950 // If we surpassed the wait period or the max scatter period associated with
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700951 // the update, then no wait is needed.
952 Time wait_expires = (update_state.first_seen +
953 min(wait_period, update_state.scatter_wait_period_max));
Gilad Arnolda65fced2014-07-23 09:01:31 -0700954 if (ec->IsWallclockTimeGreaterThan(wait_expires))
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700955 wait_period = kZeroInterval;
956
957 // Step 2: Maintain the update check threshold count.
958 //
959 // If an update check threshold is not specified then generate a new
960 // one.
961 int check_threshold = update_state.scatter_check_threshold;
962 if (check_threshold == 0) {
963 check_threshold = prng.RandMinMax(
964 update_state.scatter_check_threshold_min,
965 update_state.scatter_check_threshold_max);
966 }
967
968 // If the update check threshold is not within allowed range then nullify it.
969 // TODO(garnold) This is compliant with current logic found in
970 // OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied(). We may want
971 // to change it so that it behaves similarly to the wait period case, namely
972 // if the current value exceeds the maximum, we set a new one within range.
973 if (check_threshold > update_state.scatter_check_threshold_max)
974 check_threshold = 0;
975
976 // If the update check threshold is non-zero and satisfied, then nullify it.
977 if (check_threshold > 0 && update_state.num_checks >= check_threshold)
978 check_threshold = 0;
979
980 bool is_scattering = (wait_period != kZeroInterval || check_threshold);
981 EvalStatus ret = EvalStatus::kSucceeded;
982 if (is_scattering && wait_period == update_state.scatter_wait_period &&
983 check_threshold == update_state.scatter_check_threshold)
984 ret = EvalStatus::kAskMeAgainLater;
985 result->is_scattering = is_scattering;
986 result->wait_period = wait_period;
987 result->check_threshold = check_threshold;
988 return ret;
989}
990
Alex Deymo63784a52014-05-28 10:46:14 -0700991} // namespace chromeos_update_manager