blob: 81a169fbf79f13cfb4dd291cf5d4f56688afeb82 [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;
Gilad Arnolddc4bb262014-07-23 10:45:19 -070039using std::get;
Gilad Arnoldb3b05442014-05-30 14:25:05 -070040using std::max;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070041using std::min;
Gilad Arnold0adbc942014-05-12 10:35:43 -070042using std::set;
Alex Deymoc705cc82014-02-19 11:15:00 -080043using std::string;
44
Gilad Arnoldb3b05442014-05-30 14:25:05 -070045namespace {
46
Gilad Arnolddc4bb262014-07-23 10:45:19 -070047// Examines |err_code| and decides whether the URL index needs to be advanced,
48// the error count for the URL incremented, or none of the above. In the first
49// case, returns true; in the second case, increments |*url_num_error_p| and
50// returns false; otherwise just returns false.
Gilad Arnoldb3b05442014-05-30 14:25:05 -070051//
52// TODO(garnold) Adapted from PayloadState::UpdateFailed() (to be retired).
Gilad Arnolddc4bb262014-07-23 10:45:19 -070053bool HandleErrorCode(ErrorCode err_code, int* url_num_error_p) {
Gilad Arnoldb3b05442014-05-30 14:25:05 -070054 err_code = chromeos_update_engine::utils::GetBaseErrorCode(err_code);
55 switch (err_code) {
56 // Errors which are good indicators of a problem with a particular URL or
57 // the protocol used in the URL or entities in the communication channel
58 // (e.g. proxies). We should try the next available URL in the next update
59 // check to quickly recover from these errors.
60 case ErrorCode::kPayloadHashMismatchError:
61 case ErrorCode::kPayloadSizeMismatchError:
62 case ErrorCode::kDownloadPayloadVerificationError:
63 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
64 case ErrorCode::kSignedDeltaPayloadExpectedError:
65 case ErrorCode::kDownloadInvalidMetadataMagicString:
66 case ErrorCode::kDownloadSignatureMissingInManifest:
67 case ErrorCode::kDownloadManifestParseError:
68 case ErrorCode::kDownloadMetadataSignatureError:
69 case ErrorCode::kDownloadMetadataSignatureVerificationError:
70 case ErrorCode::kDownloadMetadataSignatureMismatch:
71 case ErrorCode::kDownloadOperationHashVerificationError:
72 case ErrorCode::kDownloadOperationExecutionError:
73 case ErrorCode::kDownloadOperationHashMismatch:
74 case ErrorCode::kDownloadInvalidMetadataSize:
75 case ErrorCode::kDownloadInvalidMetadataSignature:
76 case ErrorCode::kDownloadOperationHashMissingError:
77 case ErrorCode::kDownloadMetadataSignatureMissingError:
78 case ErrorCode::kPayloadMismatchedType:
79 case ErrorCode::kUnsupportedMajorPayloadVersion:
80 case ErrorCode::kUnsupportedMinorPayloadVersion:
Sen Jiang8e768e92017-06-28 17:13:19 -070081 case ErrorCode::kPayloadTimestampError:
Gilad Arnoldb3b05442014-05-30 14:25:05 -070082 LOG(INFO) << "Advancing download URL due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -080083 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -070084 << " (" << static_cast<int>(err_code) << ")";
Gilad Arnoldb3b05442014-05-30 14:25:05 -070085 return true;
86
87 // Errors which seem to be just transient network/communication related
88 // failures and do not indicate any inherent problem with the URL itself.
89 // So, we should keep the current URL but just increment the
90 // failure count to give it more chances. This way, while we maximize our
91 // chances of downloading from the URLs that appear earlier in the response
92 // (because download from a local server URL that appears earlier in a
93 // response is preferable than downloading from the next URL which could be
Alex Vakulenko072359c2014-07-18 11:41:07 -070094 // an Internet URL and thus could be more expensive).
Gilad Arnoldb3b05442014-05-30 14:25:05 -070095 case ErrorCode::kError:
96 case ErrorCode::kDownloadTransferError:
97 case ErrorCode::kDownloadWriteError:
98 case ErrorCode::kDownloadStateInitializationError:
Gilad Arnold684219d2014-07-07 14:54:57 -070099 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700100 LOG(INFO) << "Incrementing URL failure count due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800101 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700102 << " (" << static_cast<int>(err_code) << ")";
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700103 *url_num_error_p += 1;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700104 return false;
105
106 // Errors which are not specific to a URL and hence shouldn't result in
107 // the URL being penalized. This can happen in two cases:
108 // 1. We haven't started downloading anything: These errors don't cost us
109 // anything in terms of actual payload bytes, so we should just do the
110 // regular retries at the next update check.
111 // 2. We have successfully downloaded the payload: In this case, the
112 // payload attempt number would have been incremented and would take care
Alex Vakulenko072359c2014-07-18 11:41:07 -0700113 // of the back-off at the next update check.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700114 // In either case, there's no need to update URL index or failure count.
115 case ErrorCode::kOmahaRequestError:
116 case ErrorCode::kOmahaResponseHandlerError:
117 case ErrorCode::kPostinstallRunnerError:
118 case ErrorCode::kFilesystemCopierError:
119 case ErrorCode::kInstallDeviceOpenError:
120 case ErrorCode::kKernelDeviceOpenError:
121 case ErrorCode::kDownloadNewPartitionInfoError:
122 case ErrorCode::kNewRootfsVerificationError:
123 case ErrorCode::kNewKernelVerificationError:
124 case ErrorCode::kPostinstallBootedFromFirmwareB:
125 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
126 case ErrorCode::kOmahaRequestEmptyResponseError:
127 case ErrorCode::kOmahaRequestXMLParseError:
128 case ErrorCode::kOmahaResponseInvalid:
129 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
130 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
Kevin Cernekee2494e282016-03-29 18:03:53 -0700131 case ErrorCode::kNonCriticalUpdateInOOBE:
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700132 case ErrorCode::kOmahaUpdateDeferredForBackoff:
133 case ErrorCode::kPostinstallPowerwashError:
134 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400135 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700136 case ErrorCode::kFilesystemVerifierError:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800137 case ErrorCode::kUserCanceled:
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700138 LOG(INFO) << "Not changing URL index or failure count due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800139 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700140 << " (" << static_cast<int>(err_code) << ")";
141 return false;
142
143 case ErrorCode::kSuccess: // success code
144 case ErrorCode::kUmaReportedMax: // not an error code
145 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800146 case ErrorCode::kDevModeFlag: // not an error code
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700147 case ErrorCode::kResumedFlag: // not an error code
148 case ErrorCode::kTestImageFlag: // not an error code
149 case ErrorCode::kTestOmahaUrlFlag: // not an error code
150 case ErrorCode::kSpecialFlags: // not an error code
151 // These shouldn't happen. Enumerating these explicitly here so that we
152 // can let the compiler warn about new error codes that are added to
153 // action_processor.h but not added here.
154 LOG(WARNING) << "Unexpected error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800155 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700156 << " (" << static_cast<int>(err_code) << ")";
157 // Note: Not adding a default here so as to let the compiler warn us of
158 // any new enums that were added in the .h but not listed in this switch.
159 }
160 return false;
161}
162
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700163// Checks whether |url| can be used under given download restrictions.
164bool IsUrlUsable(const string& url, bool http_allowed) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800165 return http_allowed ||
166 !base::StartsWith(url, "http://",
167 base::CompareCase::INSENSITIVE_ASCII);
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700168}
169
170} // namespace
171
Alex Deymo63784a52014-05-28 10:46:14 -0700172namespace chromeos_update_manager {
Alex Deymoc705cc82014-02-19 11:15:00 -0800173
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700174const int ChromeOSPolicy::kTimeoutInitialInterval = 7 * 60;
Alex Deymo14e7dde2015-10-20 14:46:33 -0700175
176// TODO(deymo): Split the update_manager policies for Brillo and ChromeOS and
177// make the update check periodic interval configurable.
178#ifdef __ANDROID__
179const int ChromeOSPolicy::kTimeoutPeriodicInterval = 5 * 60 * 60;
Alex Deymodbe13b42015-11-06 11:15:08 -0800180const int ChromeOSPolicy::kTimeoutMaxBackoffInterval = 26 * 60 * 60;
Alex Deymo14e7dde2015-10-20 14:46:33 -0700181#else
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700182const int ChromeOSPolicy::kTimeoutPeriodicInterval = 45 * 60;
Alex Deymodbe13b42015-11-06 11:15:08 -0800183const int ChromeOSPolicy::kTimeoutMaxBackoffInterval = 4 * 60 * 60;
Alex Deymo14e7dde2015-10-20 14:46:33 -0700184#endif // __ANDROID__
185
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700186const int ChromeOSPolicy::kTimeoutRegularFuzz = 10 * 60;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700187const int ChromeOSPolicy::kAttemptBackoffMaxIntervalInDays = 16;
188const int ChromeOSPolicy::kAttemptBackoffFuzzInHours = 12;
Gilad Arnold349ac832014-10-06 14:20:28 -0700189const int ChromeOSPolicy::kMaxP2PAttempts = 10;
190const int ChromeOSPolicy::kMaxP2PAttemptsPeriodInSeconds = 5 * 24 * 60 * 60;
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700191
Alex Deymo0d11c602014-04-23 20:12:20 -0700192EvalStatus ChromeOSPolicy::UpdateCheckAllowed(
193 EvaluationContext* ec, State* state, string* error,
194 UpdateCheckParams* result) const {
Gilad Arnold42f253b2014-06-25 12:39:17 -0700195 // Set the default return values.
196 result->updates_enabled = true;
197 result->target_channel.clear();
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700198 result->target_version_prefix.clear();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700199 result->is_interactive = false;
Gilad Arnold42f253b2014-06-25 12:39:17 -0700200
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700201 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700202 UpdaterProvider* const updater_provider = state->updater_provider();
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700203 SystemProvider* const system_provider = state->system_provider();
204
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700205 // Do not perform any updates if booted from removable device. This decision
206 // is final.
Alex Deymo763e7db2015-08-27 21:08:08 -0700207 const unsigned int* num_slots_p = ec->GetValue(
208 system_provider->var_num_slots());
209 if (!num_slots_p || *num_slots_p < 2) {
210 LOG(INFO) << "Not enough slots for A/B updates, disabling update checks.";
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700211 result->updates_enabled = false;
212 return EvalStatus::kSucceeded;
213 }
214
Gilad Arnold42f253b2014-06-25 12:39:17 -0700215 const bool* device_policy_is_loaded_p = ec->GetValue(
216 dp_provider->var_device_policy_is_loaded());
217 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Xiyuan Xia6e30bc52016-02-24 15:35:42 -0800218 bool kiosk_app_control_chrome_version = false;
219
Gilad Arnold42f253b2014-06-25 12:39:17 -0700220 // Check whether updates are disabled by policy.
221 const bool* update_disabled_p = ec->GetValue(
222 dp_provider->var_update_disabled());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700223 if (update_disabled_p && *update_disabled_p) {
Xiyuan Xia6e30bc52016-02-24 15:35:42 -0800224 // Check whether allow kiosk app to control chrome version policy. This
225 // policy is only effective when AU is disabled by admin.
226 const bool* allow_kiosk_app_control_chrome_version_p = ec->GetValue(
227 dp_provider->var_allow_kiosk_app_control_chrome_version());
228 kiosk_app_control_chrome_version =
229 allow_kiosk_app_control_chrome_version_p &&
230 *allow_kiosk_app_control_chrome_version_p;
231 if (!kiosk_app_control_chrome_version) {
232 // No kiosk pin chrome version policy. AU is really disabled.
233 LOG(INFO) << "Updates disabled by policy, blocking update checks.";
234 return EvalStatus::kAskMeAgainLater;
235 }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700236 }
Gilad Arnold42f253b2014-06-25 12:39:17 -0700237
Xiyuan Xia6e30bc52016-02-24 15:35:42 -0800238 if (kiosk_app_control_chrome_version) {
239 // Get the required platform version from Chrome.
240 const string* kiosk_required_platform_version_p =
241 ec->GetValue(system_provider->var_kiosk_required_platform_version());
Xiyuan Xiaed9bd922016-04-07 14:45:16 -0700242 if (!kiosk_required_platform_version_p) {
243 LOG(INFO) << "Kiosk app required platform version is not fetched, "
244 "blocking update checks";
245 return EvalStatus::kAskMeAgainLater;
246 }
247
248 result->target_version_prefix = *kiosk_required_platform_version_p;
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -0800249 LOG(INFO) << "Allow kiosk app to control Chrome version policy is set, "
250 << "target version is "
251 << (!kiosk_required_platform_version_p->empty()
Xiyuan Xia6e30bc52016-02-24 15:35:42 -0800252 ? *kiosk_required_platform_version_p
253 : std::string("latest"));
254 } else {
255 // Determine whether a target version prefix is dictated by policy.
256 const string* target_version_prefix_p = ec->GetValue(
257 dp_provider->var_target_version_prefix());
258 if (target_version_prefix_p)
259 result->target_version_prefix = *target_version_prefix_p;
260 }
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700261
Gilad Arnold42f253b2014-06-25 12:39:17 -0700262 // Determine whether a target channel is dictated by policy.
263 const bool* release_channel_delegated_p = ec->GetValue(
264 dp_provider->var_release_channel_delegated());
265 if (release_channel_delegated_p && !(*release_channel_delegated_p)) {
266 const string* release_channel_p = ec->GetValue(
267 dp_provider->var_release_channel());
268 if (release_channel_p)
269 result->target_channel = *release_channel_p;
270 }
271 }
272
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700273 // First, check to see if an interactive update was requested.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700274 const UpdateRequestStatus* forced_update_requested_p = ec->GetValue(
275 updater_provider->var_forced_update_requested());
276 if (forced_update_requested_p &&
277 *forced_update_requested_p != UpdateRequestStatus::kNone) {
278 result->is_interactive =
279 (*forced_update_requested_p == UpdateRequestStatus::kInteractive);
280 LOG(INFO) << "Forced update signaled ("
281 << (result->is_interactive ? "interactive" : "periodic")
282 << "), allowing update check.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700283 return EvalStatus::kSucceeded;
284 }
285
286 // The logic thereafter applies to periodic updates. Bear in mind that we
287 // should not return a final "no" if any of these criteria are not satisfied,
288 // because the system may still update due to an interactive update request.
289
290 // Unofficial builds should not perform periodic update checks.
291 const bool* is_official_build_p = ec->GetValue(
292 system_provider->var_is_official_build());
293 if (is_official_build_p && !(*is_official_build_p)) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700294 LOG(INFO) << "Unofficial build, blocking periodic update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700295 return EvalStatus::kAskMeAgainLater;
296 }
297
298 // If OOBE is enabled, wait until it is completed.
299 const bool* is_oobe_enabled_p = ec->GetValue(
300 state->config_provider()->var_is_oobe_enabled());
301 if (is_oobe_enabled_p && *is_oobe_enabled_p) {
302 const bool* is_oobe_complete_p = ec->GetValue(
303 system_provider->var_is_oobe_complete());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700304 if (is_oobe_complete_p && !(*is_oobe_complete_p)) {
305 LOG(INFO) << "OOBE not completed, blocking update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700306 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700307 }
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700308 }
309
310 // Ensure that periodic update checks are timed properly.
Alex Deymo0d11c602014-04-23 20:12:20 -0700311 Time next_update_check;
312 if (NextUpdateCheckTime(ec, state, error, &next_update_check) !=
313 EvalStatus::kSucceeded) {
314 return EvalStatus::kFailed;
315 }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700316 if (!ec->IsWallclockTimeGreaterThan(next_update_check)) {
317 LOG(INFO) << "Periodic check interval not satisfied, blocking until "
318 << chromeos_update_engine::utils::ToString(next_update_check);
Alex Deymo0d11c602014-04-23 20:12:20 -0700319 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700320 }
Alex Deymo0d11c602014-04-23 20:12:20 -0700321
322 // It is time to check for an update.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700323 LOG(INFO) << "Allowing update check.";
Alex Deymoe636c3c2014-03-11 19:02:08 -0700324 return EvalStatus::kSucceeded;
Alex Deymoc705cc82014-02-19 11:15:00 -0800325}
326
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700327EvalStatus ChromeOSPolicy::UpdateCanStart(
328 EvaluationContext* ec,
329 State* state,
330 string* error,
Gilad Arnold42f253b2014-06-25 12:39:17 -0700331 UpdateDownloadParams* result,
Gilad Arnoldd78caf92014-09-24 09:28:14 -0700332 const UpdateState update_state) const {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700333 // Set the default return values. Note that we set persisted values (backoff,
334 // scattering) to the same values presented in the update state. The reason is
335 // that preemptive returns, such as the case where an update check is due,
336 // should not clear off the said values; rather, it is the deliberate
337 // inference of new values that should cause them to be reset.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700338 result->update_can_start = false;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700339 result->cannot_start_reason = UpdateCannotStartReason::kUndefined;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700340 result->download_url_idx = -1;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700341 result->download_url_allowed = true;
342 result->download_url_num_errors = 0;
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700343 result->p2p_downloading_allowed = false;
344 result->p2p_sharing_allowed = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700345 result->do_increment_failures = false;
346 result->backoff_expiry = update_state.backoff_expiry;
347 result->scatter_wait_period = update_state.scatter_wait_period;
348 result->scatter_check_threshold = update_state.scatter_check_threshold;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700349
350 // Make sure that we're not due for an update check.
351 UpdateCheckParams check_result;
352 EvalStatus check_status = UpdateCheckAllowed(ec, state, error, &check_result);
353 if (check_status == EvalStatus::kFailed)
354 return EvalStatus::kFailed;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700355 bool is_check_due = (check_status == EvalStatus::kSucceeded &&
356 check_result.updates_enabled == true);
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700357
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700358 // Check whether backoff applies, and if not then which URL can be used for
359 // downloading. These require scanning the download error log, and so they are
360 // done together.
361 UpdateBackoffAndDownloadUrlResult backoff_url_result;
362 EvalStatus backoff_url_status = UpdateBackoffAndDownloadUrl(
363 ec, state, error, &backoff_url_result, update_state);
Gilad Arnold14a9e702014-10-08 08:09:09 -0700364 if (backoff_url_status == EvalStatus::kFailed)
365 return EvalStatus::kFailed;
366 result->download_url_idx = backoff_url_result.url_idx;
367 result->download_url_num_errors = backoff_url_result.url_num_errors;
368 result->do_increment_failures = backoff_url_result.do_increment_failures;
369 result->backoff_expiry = backoff_url_result.backoff_expiry;
370 bool is_backoff_active =
371 (backoff_url_status == EvalStatus::kAskMeAgainLater) ||
372 !backoff_url_result.backoff_expiry.is_null();
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700373
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700374 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold14a9e702014-10-08 08:09:09 -0700375 bool is_scattering_active = false;
376 EvalStatus scattering_status = EvalStatus::kSucceeded;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700377
378 const bool* device_policy_is_loaded_p = ec->GetValue(
379 dp_provider->var_device_policy_is_loaded());
380 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700381 // Check whether scattering applies to this update attempt. We should not be
382 // scattering if this is an interactive update check, or if OOBE is enabled
383 // but not completed.
384 //
385 // Note: current code further suppresses scattering if a "deadline"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700386 // attribute is found in the Omaha response. However, it appears that the
Gilad Arnold76a11f62014-05-20 09:02:12 -0700387 // presence of this attribute is merely indicative of an OOBE update, during
388 // which we suppress scattering anyway.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700389 bool is_scattering_applicable = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700390 result->scatter_wait_period = kZeroInterval;
391 result->scatter_check_threshold = 0;
392 if (!update_state.is_interactive) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700393 const bool* is_oobe_enabled_p = ec->GetValue(
394 state->config_provider()->var_is_oobe_enabled());
395 if (is_oobe_enabled_p && !(*is_oobe_enabled_p)) {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700396 is_scattering_applicable = true;
Gilad Arnold76a11f62014-05-20 09:02:12 -0700397 } else {
398 const bool* is_oobe_complete_p = ec->GetValue(
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700399 state->system_provider()->var_is_oobe_complete());
Gilad Arnold14a9e702014-10-08 08:09:09 -0700400 is_scattering_applicable = (is_oobe_complete_p && *is_oobe_complete_p);
Gilad Arnold76a11f62014-05-20 09:02:12 -0700401 }
402 }
403
404 // Compute scattering values.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700405 if (is_scattering_applicable) {
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700406 UpdateScatteringResult scatter_result;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700407 scattering_status = UpdateScattering(ec, state, error, &scatter_result,
408 update_state);
409 if (scattering_status == EvalStatus::kFailed) {
410 return EvalStatus::kFailed;
411 } else {
412 result->scatter_wait_period = scatter_result.wait_period;
413 result->scatter_check_threshold = scatter_result.check_threshold;
414 if (scattering_status == EvalStatus::kAskMeAgainLater ||
415 scatter_result.is_scattering)
416 is_scattering_active = true;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700417 }
418 }
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700419 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700420
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700421 // Find out whether P2P is globally enabled.
422 bool p2p_enabled;
423 EvalStatus p2p_enabled_status = P2PEnabled(ec, state, error, &p2p_enabled);
424 if (p2p_enabled_status != EvalStatus::kSucceeded)
425 return EvalStatus::kFailed;
426
427 // Is P2P is enabled, consider allowing it for downloading and/or sharing.
428 if (p2p_enabled) {
429 // Sharing via P2P is allowed if not disabled by Omaha.
430 if (update_state.p2p_sharing_disabled) {
431 LOG(INFO) << "Blocked P2P sharing because it is disabled by Omaha.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700432 } else {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700433 result->p2p_sharing_allowed = true;
Gilad Arnoldef8d0872014-10-03 14:14:06 -0700434 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700435
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700436 // Downloading via P2P is allowed if not disabled by Omaha, an update is not
437 // interactive, and other limits haven't been reached.
438 if (update_state.p2p_downloading_disabled) {
439 LOG(INFO) << "Blocked P2P downloading because it is disabled by Omaha.";
440 } else if (update_state.is_interactive) {
441 LOG(INFO) << "Blocked P2P downloading because update is interactive.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700442 } else if (update_state.p2p_num_attempts >= kMaxP2PAttempts) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700443 LOG(INFO) << "Blocked P2P downloading as it was attempted too many "
444 "times.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700445 } else if (!update_state.p2p_first_attempted.is_null() &&
446 ec->IsWallclockTimeGreaterThan(
447 update_state.p2p_first_attempted +
448 TimeDelta::FromSeconds(kMaxP2PAttemptsPeriodInSeconds))) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700449 LOG(INFO) << "Blocked P2P downloading as its usage timespan exceeds "
450 "limit.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700451 } else {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700452 // P2P download is allowed; if backoff or scattering are active, be sure
453 // to suppress them, yet prevent any download URL from being used.
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700454 result->p2p_downloading_allowed = true;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700455 if (is_backoff_active || is_scattering_active) {
456 is_backoff_active = is_scattering_active = false;
457 result->download_url_allowed = false;
458 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700459 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700460 }
461
Gilad Arnold14a9e702014-10-08 08:09:09 -0700462 // Check for various deterrents.
463 if (is_check_due) {
464 result->cannot_start_reason = UpdateCannotStartReason::kCheckDue;
465 return EvalStatus::kSucceeded;
466 }
467 if (is_backoff_active) {
468 result->cannot_start_reason = UpdateCannotStartReason::kBackoff;
469 return backoff_url_status;
470 }
471 if (is_scattering_active) {
472 result->cannot_start_reason = UpdateCannotStartReason::kScattering;
473 return scattering_status;
474 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700475 if (result->download_url_idx < 0 && !result->p2p_downloading_allowed) {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700476 result->cannot_start_reason = UpdateCannotStartReason::kCannotDownload;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700477 return EvalStatus::kSucceeded;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700478 }
479
Gilad Arnold14a9e702014-10-08 08:09:09 -0700480 // Update is good to go.
481 result->update_can_start = true;
Gilad Arnoldaf2f6ae2014-04-28 14:14:52 -0700482 return EvalStatus::kSucceeded;
483}
484
Gilad Arnolda8262e22014-06-02 13:54:27 -0700485// TODO(garnold) Logic in this method is based on
486// ConnectionManager::IsUpdateAllowedOver(); be sure to deprecate the latter.
487//
488// TODO(garnold) The current logic generally treats the list of allowed
489// connections coming from the device policy as a whitelist, meaning that it
490// can only be used for enabling connections, but not disable them. Further,
491// certain connection types (like Bluetooth) cannot be enabled even by policy.
492// In effect, the only thing that device policy can change is to enable
493// updates over a cellular network (disabled by default). We may want to
494// revisit this semantics, allowing greater flexibility in defining specific
495// permissions over all types of networks.
Gilad Arnold684219d2014-07-07 14:54:57 -0700496EvalStatus ChromeOSPolicy::UpdateDownloadAllowed(
Gilad Arnolda8262e22014-06-02 13:54:27 -0700497 EvaluationContext* ec,
498 State* state,
499 string* error,
500 bool* result) const {
501 // Get the current connection type.
502 ShillProvider* const shill_provider = state->shill_provider();
503 const ConnectionType* conn_type_p = ec->GetValue(
504 shill_provider->var_conn_type());
505 POLICY_CHECK_VALUE_AND_FAIL(conn_type_p, error);
506 ConnectionType conn_type = *conn_type_p;
507
508 // If we're tethering, treat it as a cellular connection.
509 if (conn_type != ConnectionType::kCellular) {
510 const ConnectionTethering* conn_tethering_p = ec->GetValue(
511 shill_provider->var_conn_tethering());
512 POLICY_CHECK_VALUE_AND_FAIL(conn_tethering_p, error);
513 if (*conn_tethering_p == ConnectionTethering::kConfirmed)
514 conn_type = ConnectionType::kCellular;
515 }
516
517 // By default, we allow updates for all connection types, with exceptions as
518 // noted below. This also determines whether a device policy can override the
519 // default.
520 *result = true;
521 bool device_policy_can_override = false;
522 switch (conn_type) {
523 case ConnectionType::kBluetooth:
524 *result = false;
525 break;
526
527 case ConnectionType::kCellular:
528 *result = false;
529 device_policy_can_override = true;
530 break;
531
532 case ConnectionType::kUnknown:
533 if (error)
534 *error = "Unknown connection type";
535 return EvalStatus::kFailed;
536
537 default:
538 break; // Nothing to do.
539 }
540
541 // If update is allowed, we're done.
542 if (*result)
543 return EvalStatus::kSucceeded;
544
545 // Check whether the device policy specifically allows this connection.
Gilad Arnolda8262e22014-06-02 13:54:27 -0700546 if (device_policy_can_override) {
547 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
548 const bool* device_policy_is_loaded_p = ec->GetValue(
549 dp_provider->var_device_policy_is_loaded());
550 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
551 const set<ConnectionType>* allowed_conn_types_p = ec->GetValue(
552 dp_provider->var_allowed_connection_types_for_update());
553 if (allowed_conn_types_p) {
554 if (allowed_conn_types_p->count(conn_type)) {
555 *result = true;
556 return EvalStatus::kSucceeded;
557 }
Gilad Arnold28d6be62014-06-30 14:04:04 -0700558 } else if (conn_type == ConnectionType::kCellular) {
559 // Local user settings can allow updates over cellular iff a policy was
560 // loaded but no allowed connections were specified in it.
561 const bool* update_over_cellular_allowed_p = ec->GetValue(
562 state->updater_provider()->var_cellular_enabled());
563 if (update_over_cellular_allowed_p && *update_over_cellular_allowed_p)
564 *result = true;
Gilad Arnolda8262e22014-06-02 13:54:27 -0700565 }
566 }
567 }
568
Gilad Arnold28d6be62014-06-30 14:04:04 -0700569 return (*result ? EvalStatus::kSucceeded : EvalStatus::kAskMeAgainLater);
Gilad Arnolda8262e22014-06-02 13:54:27 -0700570}
571
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700572EvalStatus ChromeOSPolicy::P2PEnabled(EvaluationContext* ec,
573 State* state,
Alex Deymo39910dc2015-11-09 17:04:30 -0800574 string* error,
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700575 bool* result) const {
576 bool enabled = false;
577
578 // Determine whether use of P2P is allowed by policy. Even if P2P is not
579 // explicitly allowed, we allow it if the device is enterprise enrolled (that
580 // is, missing or empty owner string).
581 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
582 const bool* device_policy_is_loaded_p = ec->GetValue(
583 dp_provider->var_device_policy_is_loaded());
584 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
585 const bool* policy_au_p2p_enabled_p = ec->GetValue(
586 dp_provider->var_au_p2p_enabled());
587 if (policy_au_p2p_enabled_p) {
588 enabled = *policy_au_p2p_enabled_p;
589 } else {
590 const string* policy_owner_p = ec->GetValue(dp_provider->var_owner());
591 if (!policy_owner_p || policy_owner_p->empty())
592 enabled = true;
593 }
594 }
595
596 // Enable P2P, if so mandated by the updater configuration. This is additive
597 // to whether or not P2P is enabled by device policy.
598 if (!enabled) {
599 const bool* updater_p2p_enabled_p = ec->GetValue(
600 state->updater_provider()->var_p2p_enabled());
601 enabled = updater_p2p_enabled_p && *updater_p2p_enabled_p;
602 }
603
604 *result = enabled;
605 return EvalStatus::kSucceeded;
606}
607
608EvalStatus ChromeOSPolicy::P2PEnabledChanged(EvaluationContext* ec,
609 State* state,
Alex Deymo39910dc2015-11-09 17:04:30 -0800610 string* error,
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700611 bool* result,
612 bool prev_result) const {
613 EvalStatus status = P2PEnabled(ec, state, error, result);
614 if (status == EvalStatus::kSucceeded && *result == prev_result)
615 return EvalStatus::kAskMeAgainLater;
616 return status;
617}
618
Alex Deymo0d11c602014-04-23 20:12:20 -0700619EvalStatus ChromeOSPolicy::NextUpdateCheckTime(EvaluationContext* ec,
620 State* state, string* error,
621 Time* next_update_check) const {
Gilad Arnolda0258a52014-07-10 16:21:19 -0700622 UpdaterProvider* const updater_provider = state->updater_provider();
623
Alex Deymo0d11c602014-04-23 20:12:20 -0700624 // Don't check for updates too often. We limit the update checks to once every
625 // some interval. The interval is kTimeoutInitialInterval the first time and
626 // kTimeoutPeriodicInterval for the subsequent update checks. If the update
627 // check fails, we increase the interval between the update checks
628 // exponentially until kTimeoutMaxBackoffInterval. Finally, to avoid having
629 // many chromebooks running update checks at the exact same time, we add some
630 // fuzz to the interval.
631 const Time* updater_started_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700632 ec->GetValue(updater_provider->var_updater_started_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700633 POLICY_CHECK_VALUE_AND_FAIL(updater_started_time, error);
634
Alex Deymof329b932014-10-30 01:37:48 -0700635 const Time* last_checked_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700636 ec->GetValue(updater_provider->var_last_checked_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700637
638 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
639 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
640
641 PRNG prng(*seed);
642
Gilad Arnold38b14022014-07-09 12:45:56 -0700643 // If this is the first attempt, compute and return an initial value.
Alex Deymo0d11c602014-04-23 20:12:20 -0700644 if (!last_checked_time || *last_checked_time < *updater_started_time) {
Alex Deymo0d11c602014-04-23 20:12:20 -0700645 *next_update_check = *updater_started_time + FuzzedInterval(
646 &prng, kTimeoutInitialInterval, kTimeoutRegularFuzz);
647 return EvalStatus::kSucceeded;
648 }
Gilad Arnold38b14022014-07-09 12:45:56 -0700649
Gilad Arnolda0258a52014-07-10 16:21:19 -0700650 // Check whether the server is enforcing a poll interval; if not, this value
651 // will be zero.
652 const unsigned int* server_dictated_poll_interval = ec->GetValue(
653 updater_provider->var_server_dictated_poll_interval());
654 POLICY_CHECK_VALUE_AND_FAIL(server_dictated_poll_interval, error);
Alex Deymo0d11c602014-04-23 20:12:20 -0700655
Gilad Arnolda0258a52014-07-10 16:21:19 -0700656 int interval = *server_dictated_poll_interval;
657 int fuzz = 0;
658
Alex Vakulenko072359c2014-07-18 11:41:07 -0700659 // If no poll interval was dictated by server compute a back-off period,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700660 // starting from a predetermined base periodic interval and increasing
661 // exponentially by the number of consecutive failed attempts.
662 if (interval == 0) {
663 const unsigned int* consecutive_failed_update_checks = ec->GetValue(
664 updater_provider->var_consecutive_failed_update_checks());
665 POLICY_CHECK_VALUE_AND_FAIL(consecutive_failed_update_checks, error);
666
667 interval = kTimeoutPeriodicInterval;
668 unsigned int num_failures = *consecutive_failed_update_checks;
669 while (interval < kTimeoutMaxBackoffInterval && num_failures) {
670 interval *= 2;
671 num_failures--;
Alex Deymo0d11c602014-04-23 20:12:20 -0700672 }
673 }
674
Alex Vakulenko072359c2014-07-18 11:41:07 -0700675 // We cannot back off longer than the predetermined maximum interval.
Gilad Arnolda0258a52014-07-10 16:21:19 -0700676 if (interval > kTimeoutMaxBackoffInterval)
677 interval = kTimeoutMaxBackoffInterval;
678
Alex Vakulenko072359c2014-07-18 11:41:07 -0700679 // We cannot back off shorter than the predetermined periodic interval. Also,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700680 // in this case set the fuzz to a predetermined regular value.
681 if (interval <= kTimeoutPeriodicInterval) {
682 interval = kTimeoutPeriodicInterval;
683 fuzz = kTimeoutRegularFuzz;
684 }
685
686 // If not otherwise determined, defer to a fuzz of +/-(interval / 2).
Gilad Arnold38b14022014-07-09 12:45:56 -0700687 if (fuzz == 0)
688 fuzz = interval;
689
Alex Deymo0d11c602014-04-23 20:12:20 -0700690 *next_update_check = *last_checked_time + FuzzedInterval(
Gilad Arnold38b14022014-07-09 12:45:56 -0700691 &prng, interval, fuzz);
Alex Deymo0d11c602014-04-23 20:12:20 -0700692 return EvalStatus::kSucceeded;
693}
694
695TimeDelta ChromeOSPolicy::FuzzedInterval(PRNG* prng, int interval, int fuzz) {
Gilad Arnolde1218812014-05-07 12:21:36 -0700696 DCHECK_GE(interval, 0);
697 DCHECK_GE(fuzz, 0);
Alex Deymo0d11c602014-04-23 20:12:20 -0700698 int half_fuzz = fuzz / 2;
Alex Deymo0d11c602014-04-23 20:12:20 -0700699 // This guarantees the output interval is non negative.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700700 int interval_min = max(interval - half_fuzz, 0);
Gilad Arnolde1218812014-05-07 12:21:36 -0700701 int interval_max = interval + half_fuzz;
702 return TimeDelta::FromSeconds(prng->RandMinMax(interval_min, interval_max));
Alex Deymo0d11c602014-04-23 20:12:20 -0700703}
704
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700705EvalStatus ChromeOSPolicy::UpdateBackoffAndDownloadUrl(
Alex Deymof329b932014-10-30 01:37:48 -0700706 EvaluationContext* ec, State* state, string* error,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700707 UpdateBackoffAndDownloadUrlResult* result,
708 const UpdateState& update_state) const {
709 // Sanity checks.
710 DCHECK_GE(update_state.download_errors_max, 0);
711
712 // Set default result values.
713 result->do_increment_failures = false;
714 result->backoff_expiry = update_state.backoff_expiry;
715 result->url_idx = -1;
716 result->url_num_errors = 0;
717
718 const bool* is_official_build_p = ec->GetValue(
719 state->system_provider()->var_is_official_build());
720 bool is_official_build = (is_official_build_p ? *is_official_build_p : true);
721
722 // Check whether backoff is enabled.
723 bool may_backoff = false;
724 if (update_state.is_backoff_disabled) {
725 LOG(INFO) << "Backoff disabled by Omaha.";
726 } else if (update_state.is_interactive) {
727 LOG(INFO) << "No backoff for interactive updates.";
728 } else if (update_state.is_delta_payload) {
729 LOG(INFO) << "No backoff for delta payloads.";
730 } else if (!is_official_build) {
731 LOG(INFO) << "No backoff for unofficial builds.";
732 } else {
733 may_backoff = true;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700734 }
735
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700736 // If previous backoff still in effect, block.
737 if (may_backoff && !update_state.backoff_expiry.is_null() &&
738 !ec->IsWallclockTimeGreaterThan(update_state.backoff_expiry)) {
739 LOG(INFO) << "Previous backoff has not expired, waiting.";
740 return EvalStatus::kAskMeAgainLater;
741 }
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700742
743 // Determine whether HTTP downloads are forbidden by policy. This only
744 // applies to official system builds; otherwise, HTTP is always enabled.
745 bool http_allowed = true;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700746 if (is_official_build) {
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700747 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
748 const bool* device_policy_is_loaded_p = ec->GetValue(
749 dp_provider->var_device_policy_is_loaded());
750 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
751 const bool* policy_http_downloads_enabled_p = ec->GetValue(
752 dp_provider->var_http_downloads_enabled());
753 http_allowed = (!policy_http_downloads_enabled_p ||
754 *policy_http_downloads_enabled_p);
755 }
756 }
757
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700758 int url_idx = update_state.last_download_url_idx;
759 if (url_idx < 0)
760 url_idx = -1;
761 bool do_advance_url = false;
762 bool is_failure_occurred = false;
763 Time err_time;
764
765 // Scan the relevant part of the download error log, tracking which URLs are
766 // being used, and accounting the number of errors for each URL. Note that
767 // this process may not traverse all errors provided, as it may decide to bail
768 // out midway depending on the particular errors exhibited, the number of
769 // failures allowed, etc. When this ends, |url_idx| will point to the last URL
770 // used (-1 if starting fresh), |do_advance_url| will determine whether the
771 // URL needs to be advanced, and |err_time| the point in time when the last
772 // reported error occurred. Additionally, if the error log indicates that an
773 // update attempt has failed (abnormal), then |is_failure_occurred| will be
774 // set to true.
775 const int num_urls = update_state.download_urls.size();
776 int prev_url_idx = -1;
777 int url_num_errors = update_state.last_download_url_num_errors;
778 Time prev_err_time;
779 bool is_first = true;
780 for (const auto& err_tuple : update_state.download_errors) {
781 // Do some sanity checks.
782 int used_url_idx = get<0>(err_tuple);
783 if (is_first && url_idx >= 0 && used_url_idx != url_idx) {
784 LOG(WARNING) << "First URL in error log (" << used_url_idx
785 << ") not as expected (" << url_idx << ")";
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700786 }
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700787 is_first = false;
788 url_idx = used_url_idx;
789 if (url_idx < 0 || url_idx >= num_urls) {
790 LOG(ERROR) << "Download error log contains an invalid URL index ("
791 << url_idx << ")";
792 return EvalStatus::kFailed;
793 }
794 err_time = get<2>(err_tuple);
795 if (!(prev_err_time.is_null() || err_time >= prev_err_time)) {
796 // TODO(garnold) Monotonicity cannot really be assumed when dealing with
797 // wallclock-based timestamps. However, we're making a simplifying
798 // assumption so as to keep the policy implementation straightforward, for
799 // now. In general, we should convert all timestamp handling in the
800 // UpdateManager to use monotonic time (instead of wallclock), including
801 // the computation of various expiration times (backoff, scattering, etc).
802 // The client will do whatever conversions necessary when
803 // persisting/retrieving these values across reboots. See chromium:408794.
804 LOG(ERROR) << "Download error timestamps not monotonically increasing.";
805 return EvalStatus::kFailed;
806 }
807 prev_err_time = err_time;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700808
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700809 // Ignore errors that happened before the last known failed attempt.
810 if (!update_state.failures_last_updated.is_null() &&
811 err_time <= update_state.failures_last_updated)
812 continue;
813
814 if (prev_url_idx >= 0) {
815 if (url_idx < prev_url_idx) {
816 LOG(ERROR) << "The URLs in the download error log have wrapped around ("
817 << prev_url_idx << "->" << url_idx
818 << "). This should not have happened and means that there's "
819 "a bug. To be conservative, we record a failed attempt "
820 "(invalidating the rest of the error log) and resume "
821 "download from the first usable URL.";
822 url_idx = -1;
823 is_failure_occurred = true;
824 break;
825 }
826
827 if (url_idx > prev_url_idx) {
828 url_num_errors = 0;
829 do_advance_url = false;
830 }
831 }
832
833 if (HandleErrorCode(get<1>(err_tuple), &url_num_errors) ||
834 url_num_errors > update_state.download_errors_max)
835 do_advance_url = true;
836
837 prev_url_idx = url_idx;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700838 }
839
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700840 // If required, advance to the next usable URL. If the URLs wraparound, we
841 // mark an update attempt failure. Also be sure to set the download error
842 // count to zero.
843 if (url_idx < 0 || do_advance_url) {
844 url_num_errors = 0;
845 int start_url_idx = -1;
846 do {
847 if (++url_idx == num_urls) {
848 url_idx = 0;
849 // We only mark failure if an actual advancing of a URL was required.
850 if (do_advance_url)
851 is_failure_occurred = true;
852 }
853
854 if (start_url_idx < 0)
855 start_url_idx = url_idx;
856 else if (url_idx == start_url_idx)
857 url_idx = -1; // No usable URL.
858 } while (url_idx >= 0 &&
859 !IsUrlUsable(update_state.download_urls[url_idx], http_allowed));
860 }
861
862 // If we have a download URL but a failure was observed, compute a new backoff
863 // expiry (if allowed). The backoff period is generally 2 ^ (num_failures - 1)
864 // days, bounded by the size of int and kAttemptBackoffMaxIntervalInDays, and
865 // fuzzed by kAttemptBackoffFuzzInHours hours. Backoff expiry is computed from
866 // the latest recorded time of error.
867 Time backoff_expiry;
868 if (url_idx >= 0 && is_failure_occurred && may_backoff) {
869 CHECK(!err_time.is_null())
870 << "We must have an error timestamp if a failure occurred!";
871 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
872 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
873 PRNG prng(*seed);
Alex Deymof329b932014-10-30 01:37:48 -0700874 int exp = min(update_state.num_failures,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700875 static_cast<int>(sizeof(int)) * 8 - 2);
876 TimeDelta backoff_interval = TimeDelta::FromDays(
Alex Deymof329b932014-10-30 01:37:48 -0700877 min(1 << exp, kAttemptBackoffMaxIntervalInDays));
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700878 TimeDelta backoff_fuzz = TimeDelta::FromHours(kAttemptBackoffFuzzInHours);
879 TimeDelta wait_period = FuzzedInterval(&prng, backoff_interval.InSeconds(),
880 backoff_fuzz.InSeconds());
881 backoff_expiry = err_time + wait_period;
882
883 // If the newly computed backoff already expired, nullify it.
884 if (ec->IsWallclockTimeGreaterThan(backoff_expiry))
885 backoff_expiry = Time();
886 }
887
888 result->do_increment_failures = is_failure_occurred;
889 result->backoff_expiry = backoff_expiry;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700890 result->url_idx = url_idx;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700891 result->url_num_errors = url_num_errors;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700892 return EvalStatus::kSucceeded;
893}
894
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700895EvalStatus ChromeOSPolicy::UpdateScattering(
896 EvaluationContext* ec,
897 State* state,
898 string* error,
899 UpdateScatteringResult* result,
900 const UpdateState& update_state) const {
901 // Preconditions. These stem from the postconditions and usage contract.
902 DCHECK(update_state.scatter_wait_period >= kZeroInterval);
903 DCHECK_GE(update_state.scatter_check_threshold, 0);
904
905 // Set default result values.
906 result->is_scattering = false;
907 result->wait_period = kZeroInterval;
908 result->check_threshold = 0;
909
910 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
911
912 // Ensure that a device policy is loaded.
913 const bool* device_policy_is_loaded_p = ec->GetValue(
914 dp_provider->var_device_policy_is_loaded());
915 if (!(device_policy_is_loaded_p && *device_policy_is_loaded_p))
916 return EvalStatus::kSucceeded;
917
918 // Is scattering enabled by policy?
919 const TimeDelta* scatter_factor_p = ec->GetValue(
920 dp_provider->var_scatter_factor());
921 if (!scatter_factor_p || *scatter_factor_p == kZeroInterval)
922 return EvalStatus::kSucceeded;
923
924 // Obtain a pseudo-random number generator.
925 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
926 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
927 PRNG prng(*seed);
928
929 // Step 1: Maintain the scattering wait period.
930 //
931 // If no wait period was previously determined, or it no longer fits in the
932 // scatter factor, then generate a new one. Otherwise, keep the one we have.
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700933 TimeDelta wait_period = update_state.scatter_wait_period;
934 if (wait_period == kZeroInterval || wait_period > *scatter_factor_p) {
935 wait_period = TimeDelta::FromSeconds(
936 prng.RandMinMax(1, scatter_factor_p->InSeconds()));
937 }
938
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700939 // If we surpassed the wait period or the max scatter period associated with
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700940 // the update, then no wait is needed.
941 Time wait_expires = (update_state.first_seen +
942 min(wait_period, update_state.scatter_wait_period_max));
Gilad Arnolda65fced2014-07-23 09:01:31 -0700943 if (ec->IsWallclockTimeGreaterThan(wait_expires))
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700944 wait_period = kZeroInterval;
945
946 // Step 2: Maintain the update check threshold count.
947 //
948 // If an update check threshold is not specified then generate a new
949 // one.
950 int check_threshold = update_state.scatter_check_threshold;
951 if (check_threshold == 0) {
952 check_threshold = prng.RandMinMax(
953 update_state.scatter_check_threshold_min,
954 update_state.scatter_check_threshold_max);
955 }
956
957 // If the update check threshold is not within allowed range then nullify it.
958 // TODO(garnold) This is compliant with current logic found in
959 // OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied(). We may want
960 // to change it so that it behaves similarly to the wait period case, namely
961 // if the current value exceeds the maximum, we set a new one within range.
962 if (check_threshold > update_state.scatter_check_threshold_max)
963 check_threshold = 0;
964
965 // If the update check threshold is non-zero and satisfied, then nullify it.
966 if (check_threshold > 0 && update_state.num_checks >= check_threshold)
967 check_threshold = 0;
968
969 bool is_scattering = (wait_period != kZeroInterval || check_threshold);
970 EvalStatus ret = EvalStatus::kSucceeded;
971 if (is_scattering && wait_period == update_state.scatter_wait_period &&
972 check_threshold == update_state.scatter_check_threshold)
973 ret = EvalStatus::kAskMeAgainLater;
974 result->is_scattering = is_scattering;
975 result->wait_period = wait_period;
976 result->check_threshold = check_threshold;
977 return ret;
978}
979
Alex Deymo63784a52014-05-28 10:46:14 -0700980} // namespace chromeos_update_manager