blob: e1fe398652f2f362feeeadcca5e186d80db85983 [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;
Gilad Arnoldb3b05442014-05-30 14:25:05 -070036using chromeos_update_engine::ErrorCode;
Gilad Arnolddc4bb262014-07-23 10:45:19 -070037using std::get;
Gilad Arnoldb3b05442014-05-30 14:25:05 -070038using std::max;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070039using std::min;
Gilad Arnold0adbc942014-05-12 10:35:43 -070040using std::set;
Alex Deymoc705cc82014-02-19 11:15:00 -080041using std::string;
42
Gilad Arnoldb3b05442014-05-30 14:25:05 -070043namespace {
44
Gilad Arnolddc4bb262014-07-23 10:45:19 -070045// Examines |err_code| and decides whether the URL index needs to be advanced,
46// the error count for the URL incremented, or none of the above. In the first
47// case, returns true; in the second case, increments |*url_num_error_p| and
48// returns false; otherwise just returns false.
Gilad Arnoldb3b05442014-05-30 14:25:05 -070049//
50// TODO(garnold) Adapted from PayloadState::UpdateFailed() (to be retired).
Gilad Arnolddc4bb262014-07-23 10:45:19 -070051bool HandleErrorCode(ErrorCode err_code, int* url_num_error_p) {
Gilad Arnoldb3b05442014-05-30 14:25:05 -070052 err_code = chromeos_update_engine::utils::GetBaseErrorCode(err_code);
53 switch (err_code) {
54 // Errors which are good indicators of a problem with a particular URL or
55 // the protocol used in the URL or entities in the communication channel
56 // (e.g. proxies). We should try the next available URL in the next update
57 // check to quickly recover from these errors.
58 case ErrorCode::kPayloadHashMismatchError:
59 case ErrorCode::kPayloadSizeMismatchError:
60 case ErrorCode::kDownloadPayloadVerificationError:
61 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
62 case ErrorCode::kSignedDeltaPayloadExpectedError:
63 case ErrorCode::kDownloadInvalidMetadataMagicString:
64 case ErrorCode::kDownloadSignatureMissingInManifest:
65 case ErrorCode::kDownloadManifestParseError:
66 case ErrorCode::kDownloadMetadataSignatureError:
67 case ErrorCode::kDownloadMetadataSignatureVerificationError:
68 case ErrorCode::kDownloadMetadataSignatureMismatch:
69 case ErrorCode::kDownloadOperationHashVerificationError:
70 case ErrorCode::kDownloadOperationExecutionError:
71 case ErrorCode::kDownloadOperationHashMismatch:
72 case ErrorCode::kDownloadInvalidMetadataSize:
73 case ErrorCode::kDownloadInvalidMetadataSignature:
74 case ErrorCode::kDownloadOperationHashMissingError:
75 case ErrorCode::kDownloadMetadataSignatureMissingError:
76 case ErrorCode::kPayloadMismatchedType:
77 case ErrorCode::kUnsupportedMajorPayloadVersion:
78 case ErrorCode::kUnsupportedMinorPayloadVersion:
79 LOG(INFO) << "Advancing download URL due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -080080 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -070081 << " (" << static_cast<int>(err_code) << ")";
Gilad Arnoldb3b05442014-05-30 14:25:05 -070082 return true;
83
84 // Errors which seem to be just transient network/communication related
85 // failures and do not indicate any inherent problem with the URL itself.
86 // So, we should keep the current URL but just increment the
87 // failure count to give it more chances. This way, while we maximize our
88 // chances of downloading from the URLs that appear earlier in the response
89 // (because download from a local server URL that appears earlier in a
90 // response is preferable than downloading from the next URL which could be
Alex Vakulenko072359c2014-07-18 11:41:07 -070091 // an Internet URL and thus could be more expensive).
Gilad Arnoldb3b05442014-05-30 14:25:05 -070092 case ErrorCode::kError:
93 case ErrorCode::kDownloadTransferError:
94 case ErrorCode::kDownloadWriteError:
95 case ErrorCode::kDownloadStateInitializationError:
Gilad Arnold684219d2014-07-07 14:54:57 -070096 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Gilad Arnoldb3b05442014-05-30 14:25:05 -070097 LOG(INFO) << "Incrementing URL failure count due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -080098 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -070099 << " (" << static_cast<int>(err_code) << ")";
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700100 *url_num_error_p += 1;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700101 return false;
102
103 // Errors which are not specific to a URL and hence shouldn't result in
104 // the URL being penalized. This can happen in two cases:
105 // 1. We haven't started downloading anything: These errors don't cost us
106 // anything in terms of actual payload bytes, so we should just do the
107 // regular retries at the next update check.
108 // 2. We have successfully downloaded the payload: In this case, the
109 // payload attempt number would have been incremented and would take care
Alex Vakulenko072359c2014-07-18 11:41:07 -0700110 // of the back-off at the next update check.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700111 // In either case, there's no need to update URL index or failure count.
112 case ErrorCode::kOmahaRequestError:
113 case ErrorCode::kOmahaResponseHandlerError:
114 case ErrorCode::kPostinstallRunnerError:
115 case ErrorCode::kFilesystemCopierError:
116 case ErrorCode::kInstallDeviceOpenError:
117 case ErrorCode::kKernelDeviceOpenError:
118 case ErrorCode::kDownloadNewPartitionInfoError:
119 case ErrorCode::kNewRootfsVerificationError:
120 case ErrorCode::kNewKernelVerificationError:
121 case ErrorCode::kPostinstallBootedFromFirmwareB:
122 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
123 case ErrorCode::kOmahaRequestEmptyResponseError:
124 case ErrorCode::kOmahaRequestXMLParseError:
125 case ErrorCode::kOmahaResponseInvalid:
126 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
127 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
Kevin Cernekee2494e282016-03-29 18:03:53 -0700128 case ErrorCode::kNonCriticalUpdateInOOBE:
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700129 case ErrorCode::kOmahaUpdateDeferredForBackoff:
130 case ErrorCode::kPostinstallPowerwashError:
131 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400132 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700133 case ErrorCode::kFilesystemVerifierError:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800134 case ErrorCode::kUserCanceled:
Weidong Guo70063d92017-04-17 10:08:38 -0700135 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700136 LOG(INFO) << "Not changing URL index or failure count due to error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800137 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700138 << " (" << static_cast<int>(err_code) << ")";
139 return false;
140
141 case ErrorCode::kSuccess: // success code
142 case ErrorCode::kUmaReportedMax: // not an error code
143 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800144 case ErrorCode::kDevModeFlag: // not an error code
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700145 case ErrorCode::kResumedFlag: // not an error code
146 case ErrorCode::kTestImageFlag: // not an error code
147 case ErrorCode::kTestOmahaUrlFlag: // not an error code
148 case ErrorCode::kSpecialFlags: // not an error code
149 // These shouldn't happen. Enumerating these explicitly here so that we
150 // can let the compiler warn about new error codes that are added to
151 // action_processor.h but not added here.
152 LOG(WARNING) << "Unexpected error "
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800153 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700154 << " (" << static_cast<int>(err_code) << ")";
155 // Note: Not adding a default here so as to let the compiler warn us of
156 // any new enums that were added in the .h but not listed in this switch.
157 }
158 return false;
159}
160
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700161// Checks whether |url| can be used under given download restrictions.
162bool IsUrlUsable(const string& url, bool http_allowed) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800163 return http_allowed ||
164 !base::StartsWith(url, "http://",
165 base::CompareCase::INSENSITIVE_ASCII);
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700166}
167
168} // namespace
169
Alex Deymo63784a52014-05-28 10:46:14 -0700170namespace chromeos_update_manager {
Alex Deymoc705cc82014-02-19 11:15:00 -0800171
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700172const int ChromeOSPolicy::kTimeoutInitialInterval = 7 * 60;
Alex Deymo14e7dde2015-10-20 14:46:33 -0700173
174// TODO(deymo): Split the update_manager policies for Brillo and ChromeOS and
175// make the update check periodic interval configurable.
176#ifdef __ANDROID__
177const int ChromeOSPolicy::kTimeoutPeriodicInterval = 5 * 60 * 60;
Alex Deymodbe13b42015-11-06 11:15:08 -0800178const int ChromeOSPolicy::kTimeoutMaxBackoffInterval = 26 * 60 * 60;
Alex Deymo14e7dde2015-10-20 14:46:33 -0700179#else
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700180const int ChromeOSPolicy::kTimeoutPeriodicInterval = 45 * 60;
Alex Deymodbe13b42015-11-06 11:15:08 -0800181const int ChromeOSPolicy::kTimeoutMaxBackoffInterval = 4 * 60 * 60;
Alex Deymo14e7dde2015-10-20 14:46:33 -0700182#endif // __ANDROID__
183
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700184const int ChromeOSPolicy::kTimeoutRegularFuzz = 10 * 60;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700185const int ChromeOSPolicy::kAttemptBackoffMaxIntervalInDays = 16;
186const int ChromeOSPolicy::kAttemptBackoffFuzzInHours = 12;
Gilad Arnold349ac832014-10-06 14:20:28 -0700187const int ChromeOSPolicy::kMaxP2PAttempts = 10;
188const int ChromeOSPolicy::kMaxP2PAttemptsPeriodInSeconds = 5 * 24 * 60 * 60;
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700189
Alex Deymo0d11c602014-04-23 20:12:20 -0700190EvalStatus ChromeOSPolicy::UpdateCheckAllowed(
191 EvaluationContext* ec, State* state, string* error,
192 UpdateCheckParams* result) const {
Gilad Arnold42f253b2014-06-25 12:39:17 -0700193 // Set the default return values.
194 result->updates_enabled = true;
195 result->target_channel.clear();
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700196 result->target_version_prefix.clear();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700197 result->is_interactive = false;
Gilad Arnold42f253b2014-06-25 12:39:17 -0700198
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700199 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700200 UpdaterProvider* const updater_provider = state->updater_provider();
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700201 SystemProvider* const system_provider = state->system_provider();
202
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700203 // Do not perform any updates if booted from removable device. This decision
204 // is final.
Alex Deymo763e7db2015-08-27 21:08:08 -0700205 const unsigned int* num_slots_p = ec->GetValue(
206 system_provider->var_num_slots());
207 if (!num_slots_p || *num_slots_p < 2) {
208 LOG(INFO) << "Not enough slots for A/B updates, disabling update checks.";
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700209 result->updates_enabled = false;
210 return EvalStatus::kSucceeded;
211 }
212
Gilad Arnold42f253b2014-06-25 12:39:17 -0700213 const bool* device_policy_is_loaded_p = ec->GetValue(
214 dp_provider->var_device_policy_is_loaded());
215 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Xiyuan Xia6e30bc52016-02-24 15:35:42 -0800216 bool kiosk_app_control_chrome_version = false;
217
Gilad Arnold42f253b2014-06-25 12:39:17 -0700218 // Check whether updates are disabled by policy.
219 const bool* update_disabled_p = ec->GetValue(
220 dp_provider->var_update_disabled());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700221 if (update_disabled_p && *update_disabled_p) {
Xiyuan Xia6e30bc52016-02-24 15:35:42 -0800222 // Check whether allow kiosk app to control chrome version policy. This
223 // policy is only effective when AU is disabled by admin.
224 const bool* allow_kiosk_app_control_chrome_version_p = ec->GetValue(
225 dp_provider->var_allow_kiosk_app_control_chrome_version());
226 kiosk_app_control_chrome_version =
227 allow_kiosk_app_control_chrome_version_p &&
228 *allow_kiosk_app_control_chrome_version_p;
229 if (!kiosk_app_control_chrome_version) {
230 // No kiosk pin chrome version policy. AU is really disabled.
231 LOG(INFO) << "Updates disabled by policy, blocking update checks.";
232 return EvalStatus::kAskMeAgainLater;
233 }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700234 }
Gilad Arnold42f253b2014-06-25 12:39:17 -0700235
Xiyuan Xia6e30bc52016-02-24 15:35:42 -0800236 if (kiosk_app_control_chrome_version) {
237 // Get the required platform version from Chrome.
238 const string* kiosk_required_platform_version_p =
239 ec->GetValue(system_provider->var_kiosk_required_platform_version());
Xiyuan Xiaed9bd922016-04-07 14:45:16 -0700240 if (!kiosk_required_platform_version_p) {
241 LOG(INFO) << "Kiosk app required platform version is not fetched, "
242 "blocking update checks";
243 return EvalStatus::kAskMeAgainLater;
244 }
245
246 result->target_version_prefix = *kiosk_required_platform_version_p;
Xiyuan Xia4d34c182017-02-22 13:19:35 -0800247 LOG(INFO) << "Allow kiosk app to control Chrome version policy is set, "
248 << "target version is "
249 << (!kiosk_required_platform_version_p->empty()
Xiyuan Xia6e30bc52016-02-24 15:35:42 -0800250 ? *kiosk_required_platform_version_p
251 : std::string("latest"));
252 } else {
253 // Determine whether a target version prefix is dictated by policy.
254 const string* target_version_prefix_p = ec->GetValue(
255 dp_provider->var_target_version_prefix());
256 if (target_version_prefix_p)
257 result->target_version_prefix = *target_version_prefix_p;
258 }
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700259
Gilad Arnold42f253b2014-06-25 12:39:17 -0700260 // Determine whether a target channel is dictated by policy.
261 const bool* release_channel_delegated_p = ec->GetValue(
262 dp_provider->var_release_channel_delegated());
263 if (release_channel_delegated_p && !(*release_channel_delegated_p)) {
264 const string* release_channel_p = ec->GetValue(
265 dp_provider->var_release_channel());
266 if (release_channel_p)
267 result->target_channel = *release_channel_p;
268 }
269 }
270
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700271 // First, check to see if an interactive update was requested.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700272 const UpdateRequestStatus* forced_update_requested_p = ec->GetValue(
273 updater_provider->var_forced_update_requested());
274 if (forced_update_requested_p &&
275 *forced_update_requested_p != UpdateRequestStatus::kNone) {
276 result->is_interactive =
277 (*forced_update_requested_p == UpdateRequestStatus::kInteractive);
278 LOG(INFO) << "Forced update signaled ("
279 << (result->is_interactive ? "interactive" : "periodic")
280 << "), allowing update check.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700281 return EvalStatus::kSucceeded;
282 }
283
284 // The logic thereafter applies to periodic updates. Bear in mind that we
285 // should not return a final "no" if any of these criteria are not satisfied,
286 // because the system may still update due to an interactive update request.
287
288 // Unofficial builds should not perform periodic update checks.
289 const bool* is_official_build_p = ec->GetValue(
290 system_provider->var_is_official_build());
291 if (is_official_build_p && !(*is_official_build_p)) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700292 LOG(INFO) << "Unofficial build, blocking periodic update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700293 return EvalStatus::kAskMeAgainLater;
294 }
295
296 // If OOBE is enabled, wait until it is completed.
297 const bool* is_oobe_enabled_p = ec->GetValue(
298 state->config_provider()->var_is_oobe_enabled());
299 if (is_oobe_enabled_p && *is_oobe_enabled_p) {
300 const bool* is_oobe_complete_p = ec->GetValue(
301 system_provider->var_is_oobe_complete());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700302 if (is_oobe_complete_p && !(*is_oobe_complete_p)) {
303 LOG(INFO) << "OOBE not completed, blocking update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700304 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700305 }
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700306 }
307
308 // Ensure that periodic update checks are timed properly.
Alex Deymo0d11c602014-04-23 20:12:20 -0700309 Time next_update_check;
310 if (NextUpdateCheckTime(ec, state, error, &next_update_check) !=
311 EvalStatus::kSucceeded) {
312 return EvalStatus::kFailed;
313 }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700314 if (!ec->IsWallclockTimeGreaterThan(next_update_check)) {
315 LOG(INFO) << "Periodic check interval not satisfied, blocking until "
316 << chromeos_update_engine::utils::ToString(next_update_check);
Alex Deymo0d11c602014-04-23 20:12:20 -0700317 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700318 }
Alex Deymo0d11c602014-04-23 20:12:20 -0700319
320 // It is time to check for an update.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700321 LOG(INFO) << "Allowing update check.";
Alex Deymoe636c3c2014-03-11 19:02:08 -0700322 return EvalStatus::kSucceeded;
Alex Deymoc705cc82014-02-19 11:15:00 -0800323}
324
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700325EvalStatus ChromeOSPolicy::UpdateCanStart(
326 EvaluationContext* ec,
327 State* state,
328 string* error,
Gilad Arnold42f253b2014-06-25 12:39:17 -0700329 UpdateDownloadParams* result,
Gilad Arnoldd78caf92014-09-24 09:28:14 -0700330 const UpdateState update_state) const {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700331 // Set the default return values. Note that we set persisted values (backoff,
332 // scattering) to the same values presented in the update state. The reason is
333 // that preemptive returns, such as the case where an update check is due,
334 // should not clear off the said values; rather, it is the deliberate
335 // inference of new values that should cause them to be reset.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700336 result->update_can_start = false;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700337 result->cannot_start_reason = UpdateCannotStartReason::kUndefined;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700338 result->download_url_idx = -1;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700339 result->download_url_allowed = true;
340 result->download_url_num_errors = 0;
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700341 result->p2p_downloading_allowed = false;
342 result->p2p_sharing_allowed = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700343 result->do_increment_failures = false;
344 result->backoff_expiry = update_state.backoff_expiry;
345 result->scatter_wait_period = update_state.scatter_wait_period;
346 result->scatter_check_threshold = update_state.scatter_check_threshold;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700347
348 // Make sure that we're not due for an update check.
349 UpdateCheckParams check_result;
350 EvalStatus check_status = UpdateCheckAllowed(ec, state, error, &check_result);
351 if (check_status == EvalStatus::kFailed)
352 return EvalStatus::kFailed;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700353 bool is_check_due = (check_status == EvalStatus::kSucceeded &&
354 check_result.updates_enabled == true);
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700355
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700356 // Check whether backoff applies, and if not then which URL can be used for
357 // downloading. These require scanning the download error log, and so they are
358 // done together.
359 UpdateBackoffAndDownloadUrlResult backoff_url_result;
360 EvalStatus backoff_url_status = UpdateBackoffAndDownloadUrl(
361 ec, state, error, &backoff_url_result, update_state);
Gilad Arnold14a9e702014-10-08 08:09:09 -0700362 if (backoff_url_status == EvalStatus::kFailed)
363 return EvalStatus::kFailed;
364 result->download_url_idx = backoff_url_result.url_idx;
365 result->download_url_num_errors = backoff_url_result.url_num_errors;
366 result->do_increment_failures = backoff_url_result.do_increment_failures;
367 result->backoff_expiry = backoff_url_result.backoff_expiry;
368 bool is_backoff_active =
369 (backoff_url_status == EvalStatus::kAskMeAgainLater) ||
370 !backoff_url_result.backoff_expiry.is_null();
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700371
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700372 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold14a9e702014-10-08 08:09:09 -0700373 bool is_scattering_active = false;
374 EvalStatus scattering_status = EvalStatus::kSucceeded;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700375
376 const bool* device_policy_is_loaded_p = ec->GetValue(
377 dp_provider->var_device_policy_is_loaded());
378 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700379 // Check whether scattering applies to this update attempt. We should not be
380 // scattering if this is an interactive update check, or if OOBE is enabled
381 // but not completed.
382 //
383 // Note: current code further suppresses scattering if a "deadline"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700384 // attribute is found in the Omaha response. However, it appears that the
Gilad Arnold76a11f62014-05-20 09:02:12 -0700385 // presence of this attribute is merely indicative of an OOBE update, during
386 // which we suppress scattering anyway.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700387 bool is_scattering_applicable = false;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700388 result->scatter_wait_period = kZeroInterval;
389 result->scatter_check_threshold = 0;
390 if (!update_state.is_interactive) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700391 const bool* is_oobe_enabled_p = ec->GetValue(
392 state->config_provider()->var_is_oobe_enabled());
393 if (is_oobe_enabled_p && !(*is_oobe_enabled_p)) {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700394 is_scattering_applicable = true;
Gilad Arnold76a11f62014-05-20 09:02:12 -0700395 } else {
396 const bool* is_oobe_complete_p = ec->GetValue(
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700397 state->system_provider()->var_is_oobe_complete());
Gilad Arnold14a9e702014-10-08 08:09:09 -0700398 is_scattering_applicable = (is_oobe_complete_p && *is_oobe_complete_p);
Gilad Arnold76a11f62014-05-20 09:02:12 -0700399 }
400 }
401
402 // Compute scattering values.
Gilad Arnold14a9e702014-10-08 08:09:09 -0700403 if (is_scattering_applicable) {
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700404 UpdateScatteringResult scatter_result;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700405 scattering_status = UpdateScattering(ec, state, error, &scatter_result,
406 update_state);
407 if (scattering_status == EvalStatus::kFailed) {
408 return EvalStatus::kFailed;
409 } else {
410 result->scatter_wait_period = scatter_result.wait_period;
411 result->scatter_check_threshold = scatter_result.check_threshold;
412 if (scattering_status == EvalStatus::kAskMeAgainLater ||
413 scatter_result.is_scattering)
414 is_scattering_active = true;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700415 }
416 }
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700417 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700418
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700419 // Find out whether P2P is globally enabled.
420 bool p2p_enabled;
421 EvalStatus p2p_enabled_status = P2PEnabled(ec, state, error, &p2p_enabled);
422 if (p2p_enabled_status != EvalStatus::kSucceeded)
423 return EvalStatus::kFailed;
424
425 // Is P2P is enabled, consider allowing it for downloading and/or sharing.
426 if (p2p_enabled) {
427 // Sharing via P2P is allowed if not disabled by Omaha.
428 if (update_state.p2p_sharing_disabled) {
429 LOG(INFO) << "Blocked P2P sharing because it is disabled by Omaha.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700430 } else {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700431 result->p2p_sharing_allowed = true;
Gilad Arnoldef8d0872014-10-03 14:14:06 -0700432 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700433
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700434 // Downloading via P2P is allowed if not disabled by Omaha, an update is not
435 // interactive, and other limits haven't been reached.
436 if (update_state.p2p_downloading_disabled) {
437 LOG(INFO) << "Blocked P2P downloading because it is disabled by Omaha.";
438 } else if (update_state.is_interactive) {
439 LOG(INFO) << "Blocked P2P downloading because update is interactive.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700440 } else if (update_state.p2p_num_attempts >= kMaxP2PAttempts) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700441 LOG(INFO) << "Blocked P2P downloading as it was attempted too many "
442 "times.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700443 } else if (!update_state.p2p_first_attempted.is_null() &&
444 ec->IsWallclockTimeGreaterThan(
445 update_state.p2p_first_attempted +
446 TimeDelta::FromSeconds(kMaxP2PAttemptsPeriodInSeconds))) {
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700447 LOG(INFO) << "Blocked P2P downloading as its usage timespan exceeds "
448 "limit.";
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700449 } else {
Gilad Arnold14a9e702014-10-08 08:09:09 -0700450 // P2P download is allowed; if backoff or scattering are active, be sure
451 // to suppress them, yet prevent any download URL from being used.
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700452 result->p2p_downloading_allowed = true;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700453 if (is_backoff_active || is_scattering_active) {
454 is_backoff_active = is_scattering_active = false;
455 result->download_url_allowed = false;
456 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700457 }
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700458 }
459
Gilad Arnold14a9e702014-10-08 08:09:09 -0700460 // Check for various deterrents.
461 if (is_check_due) {
462 result->cannot_start_reason = UpdateCannotStartReason::kCheckDue;
463 return EvalStatus::kSucceeded;
464 }
465 if (is_backoff_active) {
466 result->cannot_start_reason = UpdateCannotStartReason::kBackoff;
467 return backoff_url_status;
468 }
469 if (is_scattering_active) {
470 result->cannot_start_reason = UpdateCannotStartReason::kScattering;
471 return scattering_status;
472 }
Gilad Arnoldb2f99192014-10-07 13:01:52 -0700473 if (result->download_url_idx < 0 && !result->p2p_downloading_allowed) {
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700474 result->cannot_start_reason = UpdateCannotStartReason::kCannotDownload;
Gilad Arnold14a9e702014-10-08 08:09:09 -0700475 return EvalStatus::kSucceeded;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700476 }
477
Gilad Arnold14a9e702014-10-08 08:09:09 -0700478 // Update is good to go.
479 result->update_can_start = true;
Gilad Arnoldaf2f6ae2014-04-28 14:14:52 -0700480 return EvalStatus::kSucceeded;
481}
482
Gilad Arnolda8262e22014-06-02 13:54:27 -0700483// TODO(garnold) Logic in this method is based on
484// ConnectionManager::IsUpdateAllowedOver(); be sure to deprecate the latter.
485//
486// TODO(garnold) The current logic generally treats the list of allowed
487// connections coming from the device policy as a whitelist, meaning that it
488// can only be used for enabling connections, but not disable them. Further,
489// certain connection types (like Bluetooth) cannot be enabled even by policy.
490// In effect, the only thing that device policy can change is to enable
491// updates over a cellular network (disabled by default). We may want to
492// revisit this semantics, allowing greater flexibility in defining specific
493// permissions over all types of networks.
Gilad Arnold684219d2014-07-07 14:54:57 -0700494EvalStatus ChromeOSPolicy::UpdateDownloadAllowed(
Gilad Arnolda8262e22014-06-02 13:54:27 -0700495 EvaluationContext* ec,
496 State* state,
497 string* error,
498 bool* result) const {
499 // Get the current connection type.
500 ShillProvider* const shill_provider = state->shill_provider();
501 const ConnectionType* conn_type_p = ec->GetValue(
502 shill_provider->var_conn_type());
503 POLICY_CHECK_VALUE_AND_FAIL(conn_type_p, error);
504 ConnectionType conn_type = *conn_type_p;
505
506 // If we're tethering, treat it as a cellular connection.
507 if (conn_type != ConnectionType::kCellular) {
508 const ConnectionTethering* conn_tethering_p = ec->GetValue(
509 shill_provider->var_conn_tethering());
510 POLICY_CHECK_VALUE_AND_FAIL(conn_tethering_p, error);
511 if (*conn_tethering_p == ConnectionTethering::kConfirmed)
512 conn_type = ConnectionType::kCellular;
513 }
514
515 // By default, we allow updates for all connection types, with exceptions as
516 // noted below. This also determines whether a device policy can override the
517 // default.
518 *result = true;
519 bool device_policy_can_override = false;
520 switch (conn_type) {
521 case ConnectionType::kBluetooth:
522 *result = false;
523 break;
524
525 case ConnectionType::kCellular:
526 *result = false;
527 device_policy_can_override = true;
528 break;
529
530 case ConnectionType::kUnknown:
531 if (error)
532 *error = "Unknown connection type";
533 return EvalStatus::kFailed;
534
535 default:
536 break; // Nothing to do.
537 }
538
539 // If update is allowed, we're done.
540 if (*result)
541 return EvalStatus::kSucceeded;
542
543 // Check whether the device policy specifically allows this connection.
Gilad Arnolda8262e22014-06-02 13:54:27 -0700544 if (device_policy_can_override) {
545 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
546 const bool* device_policy_is_loaded_p = ec->GetValue(
547 dp_provider->var_device_policy_is_loaded());
548 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
549 const set<ConnectionType>* allowed_conn_types_p = ec->GetValue(
550 dp_provider->var_allowed_connection_types_for_update());
551 if (allowed_conn_types_p) {
552 if (allowed_conn_types_p->count(conn_type)) {
553 *result = true;
554 return EvalStatus::kSucceeded;
555 }
Gilad Arnold28d6be62014-06-30 14:04:04 -0700556 } else if (conn_type == ConnectionType::kCellular) {
557 // Local user settings can allow updates over cellular iff a policy was
558 // loaded but no allowed connections were specified in it.
559 const bool* update_over_cellular_allowed_p = ec->GetValue(
560 state->updater_provider()->var_cellular_enabled());
561 if (update_over_cellular_allowed_p && *update_over_cellular_allowed_p)
562 *result = true;
Gilad Arnolda8262e22014-06-02 13:54:27 -0700563 }
564 }
565 }
566
Gilad Arnold28d6be62014-06-30 14:04:04 -0700567 return (*result ? EvalStatus::kSucceeded : EvalStatus::kAskMeAgainLater);
Gilad Arnolda8262e22014-06-02 13:54:27 -0700568}
569
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700570EvalStatus ChromeOSPolicy::P2PEnabled(EvaluationContext* ec,
571 State* state,
Alex Deymo39910dc2015-11-09 17:04:30 -0800572 string* error,
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700573 bool* result) const {
574 bool enabled = false;
575
576 // Determine whether use of P2P is allowed by policy. Even if P2P is not
577 // explicitly allowed, we allow it if the device is enterprise enrolled (that
578 // is, missing or empty owner string).
579 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
580 const bool* device_policy_is_loaded_p = ec->GetValue(
581 dp_provider->var_device_policy_is_loaded());
582 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
583 const bool* policy_au_p2p_enabled_p = ec->GetValue(
584 dp_provider->var_au_p2p_enabled());
585 if (policy_au_p2p_enabled_p) {
586 enabled = *policy_au_p2p_enabled_p;
587 } else {
588 const string* policy_owner_p = ec->GetValue(dp_provider->var_owner());
589 if (!policy_owner_p || policy_owner_p->empty())
590 enabled = true;
591 }
592 }
593
594 // Enable P2P, if so mandated by the updater configuration. This is additive
595 // to whether or not P2P is enabled by device policy.
596 if (!enabled) {
597 const bool* updater_p2p_enabled_p = ec->GetValue(
598 state->updater_provider()->var_p2p_enabled());
599 enabled = updater_p2p_enabled_p && *updater_p2p_enabled_p;
600 }
601
602 *result = enabled;
603 return EvalStatus::kSucceeded;
604}
605
606EvalStatus ChromeOSPolicy::P2PEnabledChanged(EvaluationContext* ec,
607 State* state,
Alex Deymo39910dc2015-11-09 17:04:30 -0800608 string* error,
Gilad Arnold78ecbfc2014-10-22 14:38:25 -0700609 bool* result,
610 bool prev_result) const {
611 EvalStatus status = P2PEnabled(ec, state, error, result);
612 if (status == EvalStatus::kSucceeded && *result == prev_result)
613 return EvalStatus::kAskMeAgainLater;
614 return status;
615}
616
Alex Deymo0d11c602014-04-23 20:12:20 -0700617EvalStatus ChromeOSPolicy::NextUpdateCheckTime(EvaluationContext* ec,
618 State* state, string* error,
619 Time* next_update_check) const {
Gilad Arnolda0258a52014-07-10 16:21:19 -0700620 UpdaterProvider* const updater_provider = state->updater_provider();
621
Alex Deymo0d11c602014-04-23 20:12:20 -0700622 // Don't check for updates too often. We limit the update checks to once every
623 // some interval. The interval is kTimeoutInitialInterval the first time and
624 // kTimeoutPeriodicInterval for the subsequent update checks. If the update
625 // check fails, we increase the interval between the update checks
626 // exponentially until kTimeoutMaxBackoffInterval. Finally, to avoid having
627 // many chromebooks running update checks at the exact same time, we add some
628 // fuzz to the interval.
629 const Time* updater_started_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700630 ec->GetValue(updater_provider->var_updater_started_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700631 POLICY_CHECK_VALUE_AND_FAIL(updater_started_time, error);
632
Alex Deymof329b932014-10-30 01:37:48 -0700633 const Time* last_checked_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700634 ec->GetValue(updater_provider->var_last_checked_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700635
636 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
637 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
638
639 PRNG prng(*seed);
640
Gilad Arnold38b14022014-07-09 12:45:56 -0700641 // If this is the first attempt, compute and return an initial value.
Alex Deymo0d11c602014-04-23 20:12:20 -0700642 if (!last_checked_time || *last_checked_time < *updater_started_time) {
Alex Deymo0d11c602014-04-23 20:12:20 -0700643 *next_update_check = *updater_started_time + FuzzedInterval(
644 &prng, kTimeoutInitialInterval, kTimeoutRegularFuzz);
645 return EvalStatus::kSucceeded;
646 }
Gilad Arnold38b14022014-07-09 12:45:56 -0700647
Gilad Arnolda0258a52014-07-10 16:21:19 -0700648 // Check whether the server is enforcing a poll interval; if not, this value
649 // will be zero.
650 const unsigned int* server_dictated_poll_interval = ec->GetValue(
651 updater_provider->var_server_dictated_poll_interval());
652 POLICY_CHECK_VALUE_AND_FAIL(server_dictated_poll_interval, error);
Alex Deymo0d11c602014-04-23 20:12:20 -0700653
Gilad Arnolda0258a52014-07-10 16:21:19 -0700654 int interval = *server_dictated_poll_interval;
655 int fuzz = 0;
656
Alex Vakulenko072359c2014-07-18 11:41:07 -0700657 // If no poll interval was dictated by server compute a back-off period,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700658 // starting from a predetermined base periodic interval and increasing
659 // exponentially by the number of consecutive failed attempts.
660 if (interval == 0) {
661 const unsigned int* consecutive_failed_update_checks = ec->GetValue(
662 updater_provider->var_consecutive_failed_update_checks());
663 POLICY_CHECK_VALUE_AND_FAIL(consecutive_failed_update_checks, error);
664
665 interval = kTimeoutPeriodicInterval;
666 unsigned int num_failures = *consecutive_failed_update_checks;
667 while (interval < kTimeoutMaxBackoffInterval && num_failures) {
668 interval *= 2;
669 num_failures--;
Alex Deymo0d11c602014-04-23 20:12:20 -0700670 }
671 }
672
Alex Vakulenko072359c2014-07-18 11:41:07 -0700673 // We cannot back off longer than the predetermined maximum interval.
Gilad Arnolda0258a52014-07-10 16:21:19 -0700674 if (interval > kTimeoutMaxBackoffInterval)
675 interval = kTimeoutMaxBackoffInterval;
676
Alex Vakulenko072359c2014-07-18 11:41:07 -0700677 // We cannot back off shorter than the predetermined periodic interval. Also,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700678 // in this case set the fuzz to a predetermined regular value.
679 if (interval <= kTimeoutPeriodicInterval) {
680 interval = kTimeoutPeriodicInterval;
681 fuzz = kTimeoutRegularFuzz;
682 }
683
684 // If not otherwise determined, defer to a fuzz of +/-(interval / 2).
Gilad Arnold38b14022014-07-09 12:45:56 -0700685 if (fuzz == 0)
686 fuzz = interval;
687
Alex Deymo0d11c602014-04-23 20:12:20 -0700688 *next_update_check = *last_checked_time + FuzzedInterval(
Gilad Arnold38b14022014-07-09 12:45:56 -0700689 &prng, interval, fuzz);
Alex Deymo0d11c602014-04-23 20:12:20 -0700690 return EvalStatus::kSucceeded;
691}
692
693TimeDelta ChromeOSPolicy::FuzzedInterval(PRNG* prng, int interval, int fuzz) {
Gilad Arnolde1218812014-05-07 12:21:36 -0700694 DCHECK_GE(interval, 0);
695 DCHECK_GE(fuzz, 0);
Alex Deymo0d11c602014-04-23 20:12:20 -0700696 int half_fuzz = fuzz / 2;
Alex Deymo0d11c602014-04-23 20:12:20 -0700697 // This guarantees the output interval is non negative.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700698 int interval_min = max(interval - half_fuzz, 0);
Gilad Arnolde1218812014-05-07 12:21:36 -0700699 int interval_max = interval + half_fuzz;
700 return TimeDelta::FromSeconds(prng->RandMinMax(interval_min, interval_max));
Alex Deymo0d11c602014-04-23 20:12:20 -0700701}
702
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700703EvalStatus ChromeOSPolicy::UpdateBackoffAndDownloadUrl(
Alex Deymof329b932014-10-30 01:37:48 -0700704 EvaluationContext* ec, State* state, string* error,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700705 UpdateBackoffAndDownloadUrlResult* result,
706 const UpdateState& update_state) const {
707 // Sanity checks.
708 DCHECK_GE(update_state.download_errors_max, 0);
709
710 // Set default result values.
711 result->do_increment_failures = false;
712 result->backoff_expiry = update_state.backoff_expiry;
713 result->url_idx = -1;
714 result->url_num_errors = 0;
715
716 const bool* is_official_build_p = ec->GetValue(
717 state->system_provider()->var_is_official_build());
718 bool is_official_build = (is_official_build_p ? *is_official_build_p : true);
719
720 // Check whether backoff is enabled.
721 bool may_backoff = false;
722 if (update_state.is_backoff_disabled) {
723 LOG(INFO) << "Backoff disabled by Omaha.";
724 } else if (update_state.is_interactive) {
725 LOG(INFO) << "No backoff for interactive updates.";
726 } else if (update_state.is_delta_payload) {
727 LOG(INFO) << "No backoff for delta payloads.";
728 } else if (!is_official_build) {
729 LOG(INFO) << "No backoff for unofficial builds.";
730 } else {
731 may_backoff = true;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700732 }
733
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700734 // If previous backoff still in effect, block.
735 if (may_backoff && !update_state.backoff_expiry.is_null() &&
736 !ec->IsWallclockTimeGreaterThan(update_state.backoff_expiry)) {
737 LOG(INFO) << "Previous backoff has not expired, waiting.";
738 return EvalStatus::kAskMeAgainLater;
739 }
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700740
741 // Determine whether HTTP downloads are forbidden by policy. This only
742 // applies to official system builds; otherwise, HTTP is always enabled.
743 bool http_allowed = true;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700744 if (is_official_build) {
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700745 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
746 const bool* device_policy_is_loaded_p = ec->GetValue(
747 dp_provider->var_device_policy_is_loaded());
748 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
749 const bool* policy_http_downloads_enabled_p = ec->GetValue(
750 dp_provider->var_http_downloads_enabled());
751 http_allowed = (!policy_http_downloads_enabled_p ||
752 *policy_http_downloads_enabled_p);
753 }
754 }
755
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700756 int url_idx = update_state.last_download_url_idx;
757 if (url_idx < 0)
758 url_idx = -1;
759 bool do_advance_url = false;
760 bool is_failure_occurred = false;
761 Time err_time;
762
763 // Scan the relevant part of the download error log, tracking which URLs are
764 // being used, and accounting the number of errors for each URL. Note that
765 // this process may not traverse all errors provided, as it may decide to bail
766 // out midway depending on the particular errors exhibited, the number of
767 // failures allowed, etc. When this ends, |url_idx| will point to the last URL
768 // used (-1 if starting fresh), |do_advance_url| will determine whether the
769 // URL needs to be advanced, and |err_time| the point in time when the last
770 // reported error occurred. Additionally, if the error log indicates that an
771 // update attempt has failed (abnormal), then |is_failure_occurred| will be
772 // set to true.
773 const int num_urls = update_state.download_urls.size();
774 int prev_url_idx = -1;
775 int url_num_errors = update_state.last_download_url_num_errors;
776 Time prev_err_time;
777 bool is_first = true;
778 for (const auto& err_tuple : update_state.download_errors) {
779 // Do some sanity checks.
780 int used_url_idx = get<0>(err_tuple);
781 if (is_first && url_idx >= 0 && used_url_idx != url_idx) {
782 LOG(WARNING) << "First URL in error log (" << used_url_idx
783 << ") not as expected (" << url_idx << ")";
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700784 }
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700785 is_first = false;
786 url_idx = used_url_idx;
787 if (url_idx < 0 || url_idx >= num_urls) {
788 LOG(ERROR) << "Download error log contains an invalid URL index ("
789 << url_idx << ")";
790 return EvalStatus::kFailed;
791 }
792 err_time = get<2>(err_tuple);
793 if (!(prev_err_time.is_null() || err_time >= prev_err_time)) {
794 // TODO(garnold) Monotonicity cannot really be assumed when dealing with
795 // wallclock-based timestamps. However, we're making a simplifying
796 // assumption so as to keep the policy implementation straightforward, for
797 // now. In general, we should convert all timestamp handling in the
798 // UpdateManager to use monotonic time (instead of wallclock), including
799 // the computation of various expiration times (backoff, scattering, etc).
800 // The client will do whatever conversions necessary when
801 // persisting/retrieving these values across reboots. See chromium:408794.
802 LOG(ERROR) << "Download error timestamps not monotonically increasing.";
803 return EvalStatus::kFailed;
804 }
805 prev_err_time = err_time;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700806
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700807 // Ignore errors that happened before the last known failed attempt.
808 if (!update_state.failures_last_updated.is_null() &&
809 err_time <= update_state.failures_last_updated)
810 continue;
811
812 if (prev_url_idx >= 0) {
813 if (url_idx < prev_url_idx) {
814 LOG(ERROR) << "The URLs in the download error log have wrapped around ("
815 << prev_url_idx << "->" << url_idx
816 << "). This should not have happened and means that there's "
817 "a bug. To be conservative, we record a failed attempt "
818 "(invalidating the rest of the error log) and resume "
819 "download from the first usable URL.";
820 url_idx = -1;
821 is_failure_occurred = true;
822 break;
823 }
824
825 if (url_idx > prev_url_idx) {
826 url_num_errors = 0;
827 do_advance_url = false;
828 }
829 }
830
831 if (HandleErrorCode(get<1>(err_tuple), &url_num_errors) ||
832 url_num_errors > update_state.download_errors_max)
833 do_advance_url = true;
834
835 prev_url_idx = url_idx;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700836 }
837
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700838 // If required, advance to the next usable URL. If the URLs wraparound, we
839 // mark an update attempt failure. Also be sure to set the download error
840 // count to zero.
841 if (url_idx < 0 || do_advance_url) {
842 url_num_errors = 0;
843 int start_url_idx = -1;
844 do {
845 if (++url_idx == num_urls) {
846 url_idx = 0;
847 // We only mark failure if an actual advancing of a URL was required.
848 if (do_advance_url)
849 is_failure_occurred = true;
850 }
851
852 if (start_url_idx < 0)
853 start_url_idx = url_idx;
854 else if (url_idx == start_url_idx)
855 url_idx = -1; // No usable URL.
856 } while (url_idx >= 0 &&
857 !IsUrlUsable(update_state.download_urls[url_idx], http_allowed));
858 }
859
860 // If we have a download URL but a failure was observed, compute a new backoff
861 // expiry (if allowed). The backoff period is generally 2 ^ (num_failures - 1)
862 // days, bounded by the size of int and kAttemptBackoffMaxIntervalInDays, and
863 // fuzzed by kAttemptBackoffFuzzInHours hours. Backoff expiry is computed from
864 // the latest recorded time of error.
865 Time backoff_expiry;
866 if (url_idx >= 0 && is_failure_occurred && may_backoff) {
867 CHECK(!err_time.is_null())
868 << "We must have an error timestamp if a failure occurred!";
869 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
870 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
871 PRNG prng(*seed);
Alex Deymof329b932014-10-30 01:37:48 -0700872 int exp = min(update_state.num_failures,
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700873 static_cast<int>(sizeof(int)) * 8 - 2);
874 TimeDelta backoff_interval = TimeDelta::FromDays(
Alex Deymof329b932014-10-30 01:37:48 -0700875 min(1 << exp, kAttemptBackoffMaxIntervalInDays));
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700876 TimeDelta backoff_fuzz = TimeDelta::FromHours(kAttemptBackoffFuzzInHours);
877 TimeDelta wait_period = FuzzedInterval(&prng, backoff_interval.InSeconds(),
878 backoff_fuzz.InSeconds());
879 backoff_expiry = err_time + wait_period;
880
881 // If the newly computed backoff already expired, nullify it.
882 if (ec->IsWallclockTimeGreaterThan(backoff_expiry))
883 backoff_expiry = Time();
884 }
885
886 result->do_increment_failures = is_failure_occurred;
887 result->backoff_expiry = backoff_expiry;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700888 result->url_idx = url_idx;
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700889 result->url_num_errors = url_num_errors;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700890 return EvalStatus::kSucceeded;
891}
892
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700893EvalStatus ChromeOSPolicy::UpdateScattering(
894 EvaluationContext* ec,
895 State* state,
896 string* error,
897 UpdateScatteringResult* result,
898 const UpdateState& update_state) const {
899 // Preconditions. These stem from the postconditions and usage contract.
900 DCHECK(update_state.scatter_wait_period >= kZeroInterval);
901 DCHECK_GE(update_state.scatter_check_threshold, 0);
902
903 // Set default result values.
904 result->is_scattering = false;
905 result->wait_period = kZeroInterval;
906 result->check_threshold = 0;
907
908 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
909
910 // Ensure that a device policy is loaded.
911 const bool* device_policy_is_loaded_p = ec->GetValue(
912 dp_provider->var_device_policy_is_loaded());
913 if (!(device_policy_is_loaded_p && *device_policy_is_loaded_p))
914 return EvalStatus::kSucceeded;
915
916 // Is scattering enabled by policy?
917 const TimeDelta* scatter_factor_p = ec->GetValue(
918 dp_provider->var_scatter_factor());
919 if (!scatter_factor_p || *scatter_factor_p == kZeroInterval)
920 return EvalStatus::kSucceeded;
921
922 // Obtain a pseudo-random number generator.
923 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
924 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
925 PRNG prng(*seed);
926
927 // Step 1: Maintain the scattering wait period.
928 //
929 // If no wait period was previously determined, or it no longer fits in the
930 // scatter factor, then generate a new one. Otherwise, keep the one we have.
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700931 TimeDelta wait_period = update_state.scatter_wait_period;
932 if (wait_period == kZeroInterval || wait_period > *scatter_factor_p) {
933 wait_period = TimeDelta::FromSeconds(
934 prng.RandMinMax(1, scatter_factor_p->InSeconds()));
935 }
936
Gilad Arnolddc4bb262014-07-23 10:45:19 -0700937 // If we surpassed the wait period or the max scatter period associated with
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700938 // the update, then no wait is needed.
939 Time wait_expires = (update_state.first_seen +
940 min(wait_period, update_state.scatter_wait_period_max));
Gilad Arnolda65fced2014-07-23 09:01:31 -0700941 if (ec->IsWallclockTimeGreaterThan(wait_expires))
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700942 wait_period = kZeroInterval;
943
944 // Step 2: Maintain the update check threshold count.
945 //
946 // If an update check threshold is not specified then generate a new
947 // one.
948 int check_threshold = update_state.scatter_check_threshold;
949 if (check_threshold == 0) {
950 check_threshold = prng.RandMinMax(
951 update_state.scatter_check_threshold_min,
952 update_state.scatter_check_threshold_max);
953 }
954
955 // If the update check threshold is not within allowed range then nullify it.
956 // TODO(garnold) This is compliant with current logic found in
957 // OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied(). We may want
958 // to change it so that it behaves similarly to the wait period case, namely
959 // if the current value exceeds the maximum, we set a new one within range.
960 if (check_threshold > update_state.scatter_check_threshold_max)
961 check_threshold = 0;
962
963 // If the update check threshold is non-zero and satisfied, then nullify it.
964 if (check_threshold > 0 && update_state.num_checks >= check_threshold)
965 check_threshold = 0;
966
967 bool is_scattering = (wait_period != kZeroInterval || check_threshold);
968 EvalStatus ret = EvalStatus::kSucceeded;
969 if (is_scattering && wait_period == update_state.scatter_wait_period &&
970 check_threshold == update_state.scatter_check_threshold)
971 ret = EvalStatus::kAskMeAgainLater;
972 result->is_scattering = is_scattering;
973 result->wait_period = wait_period;
974 result->check_threshold = check_threshold;
975 return ret;
976}
977
Alex Deymo63784a52014-05-28 10:46:14 -0700978} // namespace chromeos_update_manager