blob: 0dc0ad6592d9c1d3e6138113f8fb91393ef0a4d5 [file] [log] [blame]
Alex Deymoc705cc82014-02-19 11:15:00 -08001// Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Alex Deymo63784a52014-05-28 10:46:14 -07005#include "update_engine/update_manager/chromeos_policy.h"
Alex Deymo0d11c602014-04-23 20:12:20 -07006
Gilad Arnolde1218812014-05-07 12:21:36 -07007#include <algorithm>
Gilad Arnold0adbc942014-05-12 10:35:43 -07008#include <set>
Alex Deymoc705cc82014-02-19 11:15:00 -08009#include <string>
10
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070011#include <base/logging.h>
Gilad Arnoldb3b05442014-05-30 14:25:05 -070012#include <base/strings/string_util.h>
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070013#include <base/time/time.h>
14
Gilad Arnoldb3b05442014-05-30 14:25:05 -070015#include "update_engine/error_code.h"
Alex Deymo63784a52014-05-28 10:46:14 -070016#include "update_engine/update_manager/device_policy_provider.h"
17#include "update_engine/update_manager/policy_utils.h"
18#include "update_engine/update_manager/shill_provider.h"
Gilad Arnoldb3b05442014-05-30 14:25:05 -070019#include "update_engine/utils.h"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070020
Alex Deymo0d11c602014-04-23 20:12:20 -070021using base::Time;
22using base::TimeDelta;
Gilad Arnoldb3b05442014-05-30 14:25:05 -070023using chromeos_update_engine::ErrorCode;
24using std::max;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -070025using std::min;
Gilad Arnold0adbc942014-05-12 10:35:43 -070026using std::set;
Alex Deymoc705cc82014-02-19 11:15:00 -080027using std::string;
28
Gilad Arnoldb3b05442014-05-30 14:25:05 -070029namespace {
30
31// Increment |url_idx|, |url_num_failures| or none of them based on the provided
32// error code. If |url_idx| is incremented, then sets |url_num_failures| to zero
33// and returns true; otherwise, returns false.
34//
35// TODO(garnold) Adapted from PayloadState::UpdateFailed() (to be retired).
36bool HandleErrorCode(ErrorCode err_code, int* url_idx, int* url_num_failures) {
37 err_code = chromeos_update_engine::utils::GetBaseErrorCode(err_code);
38 switch (err_code) {
39 // Errors which are good indicators of a problem with a particular URL or
40 // the protocol used in the URL or entities in the communication channel
41 // (e.g. proxies). We should try the next available URL in the next update
42 // check to quickly recover from these errors.
43 case ErrorCode::kPayloadHashMismatchError:
44 case ErrorCode::kPayloadSizeMismatchError:
45 case ErrorCode::kDownloadPayloadVerificationError:
46 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
47 case ErrorCode::kSignedDeltaPayloadExpectedError:
48 case ErrorCode::kDownloadInvalidMetadataMagicString:
49 case ErrorCode::kDownloadSignatureMissingInManifest:
50 case ErrorCode::kDownloadManifestParseError:
51 case ErrorCode::kDownloadMetadataSignatureError:
52 case ErrorCode::kDownloadMetadataSignatureVerificationError:
53 case ErrorCode::kDownloadMetadataSignatureMismatch:
54 case ErrorCode::kDownloadOperationHashVerificationError:
55 case ErrorCode::kDownloadOperationExecutionError:
56 case ErrorCode::kDownloadOperationHashMismatch:
57 case ErrorCode::kDownloadInvalidMetadataSize:
58 case ErrorCode::kDownloadInvalidMetadataSignature:
59 case ErrorCode::kDownloadOperationHashMissingError:
60 case ErrorCode::kDownloadMetadataSignatureMissingError:
61 case ErrorCode::kPayloadMismatchedType:
62 case ErrorCode::kUnsupportedMajorPayloadVersion:
63 case ErrorCode::kUnsupportedMinorPayloadVersion:
64 LOG(INFO) << "Advancing download URL due to error "
65 << chromeos_update_engine::utils::CodeToString(err_code)
66 << " (" << static_cast<int>(err_code) << ")";
67 *url_idx += 1;
68 *url_num_failures = 0;
69 return true;
70
71 // Errors which seem to be just transient network/communication related
72 // failures and do not indicate any inherent problem with the URL itself.
73 // So, we should keep the current URL but just increment the
74 // failure count to give it more chances. This way, while we maximize our
75 // chances of downloading from the URLs that appear earlier in the response
76 // (because download from a local server URL that appears earlier in a
77 // response is preferable than downloading from the next URL which could be
Alex Vakulenko072359c2014-07-18 11:41:07 -070078 // an Internet URL and thus could be more expensive).
Gilad Arnoldb3b05442014-05-30 14:25:05 -070079 case ErrorCode::kError:
80 case ErrorCode::kDownloadTransferError:
81 case ErrorCode::kDownloadWriteError:
82 case ErrorCode::kDownloadStateInitializationError:
Gilad Arnold684219d2014-07-07 14:54:57 -070083 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Gilad Arnoldb3b05442014-05-30 14:25:05 -070084 LOG(INFO) << "Incrementing URL failure count due to error "
85 << chromeos_update_engine::utils::CodeToString(err_code)
86 << " (" << static_cast<int>(err_code) << ")";
87 *url_num_failures += 1;
88 return false;
89
90 // Errors which are not specific to a URL and hence shouldn't result in
91 // the URL being penalized. This can happen in two cases:
92 // 1. We haven't started downloading anything: These errors don't cost us
93 // anything in terms of actual payload bytes, so we should just do the
94 // regular retries at the next update check.
95 // 2. We have successfully downloaded the payload: In this case, the
96 // payload attempt number would have been incremented and would take care
Alex Vakulenko072359c2014-07-18 11:41:07 -070097 // of the back-off at the next update check.
Gilad Arnoldb3b05442014-05-30 14:25:05 -070098 // In either case, there's no need to update URL index or failure count.
99 case ErrorCode::kOmahaRequestError:
100 case ErrorCode::kOmahaResponseHandlerError:
101 case ErrorCode::kPostinstallRunnerError:
102 case ErrorCode::kFilesystemCopierError:
103 case ErrorCode::kInstallDeviceOpenError:
104 case ErrorCode::kKernelDeviceOpenError:
105 case ErrorCode::kDownloadNewPartitionInfoError:
106 case ErrorCode::kNewRootfsVerificationError:
107 case ErrorCode::kNewKernelVerificationError:
108 case ErrorCode::kPostinstallBootedFromFirmwareB:
109 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
110 case ErrorCode::kOmahaRequestEmptyResponseError:
111 case ErrorCode::kOmahaRequestXMLParseError:
112 case ErrorCode::kOmahaResponseInvalid:
113 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
114 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
115 case ErrorCode::kOmahaUpdateDeferredForBackoff:
116 case ErrorCode::kPostinstallPowerwashError:
117 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400118 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700119 LOG(INFO) << "Not changing URL index or failure count due to error "
120 << chromeos_update_engine::utils::CodeToString(err_code)
121 << " (" << static_cast<int>(err_code) << ")";
122 return false;
123
124 case ErrorCode::kSuccess: // success code
125 case ErrorCode::kUmaReportedMax: // not an error code
126 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
127 case ErrorCode::kDevModeFlag: // not an error code
128 case ErrorCode::kResumedFlag: // not an error code
129 case ErrorCode::kTestImageFlag: // not an error code
130 case ErrorCode::kTestOmahaUrlFlag: // not an error code
131 case ErrorCode::kSpecialFlags: // not an error code
132 // These shouldn't happen. Enumerating these explicitly here so that we
133 // can let the compiler warn about new error codes that are added to
134 // action_processor.h but not added here.
135 LOG(WARNING) << "Unexpected error "
136 << chromeos_update_engine::utils::CodeToString(err_code)
137 << " (" << static_cast<int>(err_code) << ")";
138 // Note: Not adding a default here so as to let the compiler warn us of
139 // any new enums that were added in the .h but not listed in this switch.
140 }
141 return false;
142}
143
144// Checks whether |download_url| can be used under given download restrictions.
145bool DownloadUrlIsUsable(const string& download_url, bool http_allowed) {
146 return http_allowed || !StartsWithASCII(download_url, "http://", false);
147}
148
149} // namespace
150
Alex Deymo63784a52014-05-28 10:46:14 -0700151namespace chromeos_update_manager {
Alex Deymoc705cc82014-02-19 11:15:00 -0800152
Alex Deymo0d11c602014-04-23 20:12:20 -0700153EvalStatus ChromeOSPolicy::UpdateCheckAllowed(
154 EvaluationContext* ec, State* state, string* error,
155 UpdateCheckParams* result) const {
Gilad Arnold42f253b2014-06-25 12:39:17 -0700156 // Set the default return values.
157 result->updates_enabled = true;
158 result->target_channel.clear();
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700159 result->target_version_prefix.clear();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700160 result->is_interactive = false;
Gilad Arnold42f253b2014-06-25 12:39:17 -0700161
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700162 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700163 UpdaterProvider* const updater_provider = state->updater_provider();
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700164 SystemProvider* const system_provider = state->system_provider();
165
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700166 // Do not perform any updates if booted from removable device. This decision
167 // is final.
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700168 const bool* is_boot_device_removable_p = ec->GetValue(
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700169 system_provider->var_is_boot_device_removable());
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700170 if (is_boot_device_removable_p && *is_boot_device_removable_p) {
171 result->updates_enabled = false;
172 return EvalStatus::kSucceeded;
173 }
174
Gilad Arnold42f253b2014-06-25 12:39:17 -0700175 const bool* device_policy_is_loaded_p = ec->GetValue(
176 dp_provider->var_device_policy_is_loaded());
177 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
178 // Check whether updates are disabled by policy.
179 const bool* update_disabled_p = ec->GetValue(
180 dp_provider->var_update_disabled());
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700181 if (update_disabled_p && *update_disabled_p)
Gilad Arnold42f253b2014-06-25 12:39:17 -0700182 return EvalStatus::kAskMeAgainLater;
Gilad Arnold42f253b2014-06-25 12:39:17 -0700183
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700184 // Determine whether a target version prefix is dictated by policy.
185 const string* target_version_prefix_p = ec->GetValue(
186 dp_provider->var_target_version_prefix());
187 if (target_version_prefix_p)
188 result->target_version_prefix = *target_version_prefix_p;
189
Gilad Arnold42f253b2014-06-25 12:39:17 -0700190 // Determine whether a target channel is dictated by policy.
191 const bool* release_channel_delegated_p = ec->GetValue(
192 dp_provider->var_release_channel_delegated());
193 if (release_channel_delegated_p && !(*release_channel_delegated_p)) {
194 const string* release_channel_p = ec->GetValue(
195 dp_provider->var_release_channel());
196 if (release_channel_p)
197 result->target_channel = *release_channel_p;
198 }
199 }
200
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700201 // First, check to see if an interactive update was requested.
202 const bool* interactive_update_requested_p = ec->GetValue(
203 updater_provider->var_interactive_update_requested());
204 if (interactive_update_requested_p && *interactive_update_requested_p) {
205 result->is_interactive = true;
206 return EvalStatus::kSucceeded;
207 }
208
209 // The logic thereafter applies to periodic updates. Bear in mind that we
210 // should not return a final "no" if any of these criteria are not satisfied,
211 // because the system may still update due to an interactive update request.
212
213 // Unofficial builds should not perform periodic update checks.
214 const bool* is_official_build_p = ec->GetValue(
215 system_provider->var_is_official_build());
216 if (is_official_build_p && !(*is_official_build_p)) {
217 return EvalStatus::kAskMeAgainLater;
218 }
219
220 // If OOBE is enabled, wait until it is completed.
221 const bool* is_oobe_enabled_p = ec->GetValue(
222 state->config_provider()->var_is_oobe_enabled());
223 if (is_oobe_enabled_p && *is_oobe_enabled_p) {
224 const bool* is_oobe_complete_p = ec->GetValue(
225 system_provider->var_is_oobe_complete());
226 if (is_oobe_complete_p && !(*is_oobe_complete_p))
227 return EvalStatus::kAskMeAgainLater;
228 }
229
230 // Ensure that periodic update checks are timed properly.
Alex Deymo0d11c602014-04-23 20:12:20 -0700231 Time next_update_check;
232 if (NextUpdateCheckTime(ec, state, error, &next_update_check) !=
233 EvalStatus::kSucceeded) {
234 return EvalStatus::kFailed;
235 }
Gilad Arnolda65fced2014-07-23 09:01:31 -0700236 if (!ec->IsWallclockTimeGreaterThan(next_update_check))
Alex Deymo0d11c602014-04-23 20:12:20 -0700237 return EvalStatus::kAskMeAgainLater;
238
239 // It is time to check for an update.
Alex Deymoe636c3c2014-03-11 19:02:08 -0700240 return EvalStatus::kSucceeded;
Alex Deymoc705cc82014-02-19 11:15:00 -0800241}
242
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700243EvalStatus ChromeOSPolicy::UpdateCanStart(
244 EvaluationContext* ec,
245 State* state,
246 string* error,
Gilad Arnold42f253b2014-06-25 12:39:17 -0700247 UpdateDownloadParams* result,
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700248 const bool interactive,
249 const UpdateState& update_state) const {
250 // Set the default return values.
251 result->update_can_start = true;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700252 result->p2p_allowed = false;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700253 result->cannot_start_reason = UpdateCannotStartReason::kUndefined;
254 result->scatter_wait_period = kZeroInterval;
255 result->scatter_check_threshold = 0;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700256 result->download_url_idx = -1;
257 result->download_url_num_failures = 0;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700258
259 // Make sure that we're not due for an update check.
260 UpdateCheckParams check_result;
261 EvalStatus check_status = UpdateCheckAllowed(ec, state, error, &check_result);
262 if (check_status == EvalStatus::kFailed)
263 return EvalStatus::kFailed;
264 if (check_status == EvalStatus::kSucceeded &&
265 check_result.updates_enabled == true) {
266 result->update_can_start = false;
267 result->cannot_start_reason = UpdateCannotStartReason::kCheckDue;
268 return EvalStatus::kSucceeded;
269 }
270
271 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
272
273 const bool* device_policy_is_loaded_p = ec->GetValue(
274 dp_provider->var_device_policy_is_loaded());
275 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700276 // Check whether scattering applies to this update attempt. We should not be
277 // scattering if this is an interactive update check, or if OOBE is enabled
278 // but not completed.
279 //
280 // Note: current code further suppresses scattering if a "deadline"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700281 // attribute is found in the Omaha response. However, it appears that the
Gilad Arnold76a11f62014-05-20 09:02:12 -0700282 // presence of this attribute is merely indicative of an OOBE update, during
283 // which we suppress scattering anyway.
284 bool scattering_applies = false;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700285 if (!interactive) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700286 const bool* is_oobe_enabled_p = ec->GetValue(
287 state->config_provider()->var_is_oobe_enabled());
288 if (is_oobe_enabled_p && !(*is_oobe_enabled_p)) {
289 scattering_applies = true;
290 } else {
291 const bool* is_oobe_complete_p = ec->GetValue(
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700292 state->system_provider()->var_is_oobe_complete());
Gilad Arnold76a11f62014-05-20 09:02:12 -0700293 scattering_applies = (is_oobe_complete_p && *is_oobe_complete_p);
294 }
295 }
296
297 // Compute scattering values.
298 if (scattering_applies) {
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700299 UpdateScatteringResult scatter_result;
300 EvalStatus scattering_status = UpdateScattering(
301 ec, state, error, &scatter_result, update_state);
302 if (scattering_status != EvalStatus::kSucceeded ||
303 scatter_result.is_scattering) {
304 if (scattering_status != EvalStatus::kFailed) {
305 result->update_can_start = false;
306 result->cannot_start_reason = UpdateCannotStartReason::kScattering;
307 result->scatter_wait_period = scatter_result.wait_period;
308 result->scatter_check_threshold = scatter_result.check_threshold;
309 }
310 return scattering_status;
311 }
312 }
313
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700314 // Determine whether use of P2P is allowed by policy.
315 const bool* policy_au_p2p_enabled_p = ec->GetValue(
316 dp_provider->var_au_p2p_enabled());
317 result->p2p_allowed = policy_au_p2p_enabled_p && *policy_au_p2p_enabled_p;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700318 }
319
320 // Enable P2P, if so mandated by the updater configuration.
321 if (!result->p2p_allowed) {
322 const bool* updater_p2p_enabled_p = ec->GetValue(
323 state->updater_provider()->var_p2p_enabled());
324 result->p2p_allowed = updater_p2p_enabled_p && *updater_p2p_enabled_p;
325 }
326
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700327 // Determine the URL to download the update from. Note that a failure to find
328 // a download URL will only fail this policy iff no other means of download
329 // (such as P2P) are enabled.
330 UpdateDownloadUrlResult download_url_result;
331 EvalStatus download_url_status = UpdateDownloadUrl(
332 ec, state, error, &download_url_result, update_state);
333 if (download_url_status == EvalStatus::kSucceeded) {
334 result->download_url_idx = download_url_result.url_idx;
335 result->download_url_num_failures = download_url_result.url_num_failures;
336 } else if (!result->p2p_allowed) {
337 if (download_url_status != EvalStatus::kFailed) {
338 result->update_can_start = false;
339 result->cannot_start_reason = UpdateCannotStartReason::kCannotDownload;
340 }
341 return download_url_status;
342 }
343
Gilad Arnoldaf2f6ae2014-04-28 14:14:52 -0700344 return EvalStatus::kSucceeded;
345}
346
Gilad Arnolda8262e22014-06-02 13:54:27 -0700347// TODO(garnold) Logic in this method is based on
348// ConnectionManager::IsUpdateAllowedOver(); be sure to deprecate the latter.
349//
350// TODO(garnold) The current logic generally treats the list of allowed
351// connections coming from the device policy as a whitelist, meaning that it
352// can only be used for enabling connections, but not disable them. Further,
353// certain connection types (like Bluetooth) cannot be enabled even by policy.
354// In effect, the only thing that device policy can change is to enable
355// updates over a cellular network (disabled by default). We may want to
356// revisit this semantics, allowing greater flexibility in defining specific
357// permissions over all types of networks.
Gilad Arnold684219d2014-07-07 14:54:57 -0700358EvalStatus ChromeOSPolicy::UpdateDownloadAllowed(
Gilad Arnolda8262e22014-06-02 13:54:27 -0700359 EvaluationContext* ec,
360 State* state,
361 string* error,
362 bool* result) const {
363 // Get the current connection type.
364 ShillProvider* const shill_provider = state->shill_provider();
365 const ConnectionType* conn_type_p = ec->GetValue(
366 shill_provider->var_conn_type());
367 POLICY_CHECK_VALUE_AND_FAIL(conn_type_p, error);
368 ConnectionType conn_type = *conn_type_p;
369
370 // If we're tethering, treat it as a cellular connection.
371 if (conn_type != ConnectionType::kCellular) {
372 const ConnectionTethering* conn_tethering_p = ec->GetValue(
373 shill_provider->var_conn_tethering());
374 POLICY_CHECK_VALUE_AND_FAIL(conn_tethering_p, error);
375 if (*conn_tethering_p == ConnectionTethering::kConfirmed)
376 conn_type = ConnectionType::kCellular;
377 }
378
379 // By default, we allow updates for all connection types, with exceptions as
380 // noted below. This also determines whether a device policy can override the
381 // default.
382 *result = true;
383 bool device_policy_can_override = false;
384 switch (conn_type) {
385 case ConnectionType::kBluetooth:
386 *result = false;
387 break;
388
389 case ConnectionType::kCellular:
390 *result = false;
391 device_policy_can_override = true;
392 break;
393
394 case ConnectionType::kUnknown:
395 if (error)
396 *error = "Unknown connection type";
397 return EvalStatus::kFailed;
398
399 default:
400 break; // Nothing to do.
401 }
402
403 // If update is allowed, we're done.
404 if (*result)
405 return EvalStatus::kSucceeded;
406
407 // Check whether the device policy specifically allows this connection.
Gilad Arnolda8262e22014-06-02 13:54:27 -0700408 if (device_policy_can_override) {
409 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
410 const bool* device_policy_is_loaded_p = ec->GetValue(
411 dp_provider->var_device_policy_is_loaded());
412 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
413 const set<ConnectionType>* allowed_conn_types_p = ec->GetValue(
414 dp_provider->var_allowed_connection_types_for_update());
415 if (allowed_conn_types_p) {
416 if (allowed_conn_types_p->count(conn_type)) {
417 *result = true;
418 return EvalStatus::kSucceeded;
419 }
Gilad Arnold28d6be62014-06-30 14:04:04 -0700420 } else if (conn_type == ConnectionType::kCellular) {
421 // Local user settings can allow updates over cellular iff a policy was
422 // loaded but no allowed connections were specified in it.
423 const bool* update_over_cellular_allowed_p = ec->GetValue(
424 state->updater_provider()->var_cellular_enabled());
425 if (update_over_cellular_allowed_p && *update_over_cellular_allowed_p)
426 *result = true;
Gilad Arnolda8262e22014-06-02 13:54:27 -0700427 }
428 }
429 }
430
Gilad Arnold28d6be62014-06-30 14:04:04 -0700431 return (*result ? EvalStatus::kSucceeded : EvalStatus::kAskMeAgainLater);
Gilad Arnolda8262e22014-06-02 13:54:27 -0700432}
433
Alex Deymo0d11c602014-04-23 20:12:20 -0700434EvalStatus ChromeOSPolicy::NextUpdateCheckTime(EvaluationContext* ec,
435 State* state, string* error,
436 Time* next_update_check) const {
Gilad Arnolda0258a52014-07-10 16:21:19 -0700437 UpdaterProvider* const updater_provider = state->updater_provider();
438
Alex Deymo0d11c602014-04-23 20:12:20 -0700439 // Don't check for updates too often. We limit the update checks to once every
440 // some interval. The interval is kTimeoutInitialInterval the first time and
441 // kTimeoutPeriodicInterval for the subsequent update checks. If the update
442 // check fails, we increase the interval between the update checks
443 // exponentially until kTimeoutMaxBackoffInterval. Finally, to avoid having
444 // many chromebooks running update checks at the exact same time, we add some
445 // fuzz to the interval.
446 const Time* updater_started_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700447 ec->GetValue(updater_provider->var_updater_started_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700448 POLICY_CHECK_VALUE_AND_FAIL(updater_started_time, error);
449
450 const base::Time* last_checked_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700451 ec->GetValue(updater_provider->var_last_checked_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700452
453 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
454 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
455
456 PRNG prng(*seed);
457
Gilad Arnold38b14022014-07-09 12:45:56 -0700458 // If this is the first attempt, compute and return an initial value.
Alex Deymo0d11c602014-04-23 20:12:20 -0700459 if (!last_checked_time || *last_checked_time < *updater_started_time) {
Alex Deymo0d11c602014-04-23 20:12:20 -0700460 *next_update_check = *updater_started_time + FuzzedInterval(
461 &prng, kTimeoutInitialInterval, kTimeoutRegularFuzz);
462 return EvalStatus::kSucceeded;
463 }
Gilad Arnold38b14022014-07-09 12:45:56 -0700464
Gilad Arnolda0258a52014-07-10 16:21:19 -0700465 // Check whether the server is enforcing a poll interval; if not, this value
466 // will be zero.
467 const unsigned int* server_dictated_poll_interval = ec->GetValue(
468 updater_provider->var_server_dictated_poll_interval());
469 POLICY_CHECK_VALUE_AND_FAIL(server_dictated_poll_interval, error);
Alex Deymo0d11c602014-04-23 20:12:20 -0700470
Gilad Arnolda0258a52014-07-10 16:21:19 -0700471 int interval = *server_dictated_poll_interval;
472 int fuzz = 0;
473
Alex Vakulenko072359c2014-07-18 11:41:07 -0700474 // If no poll interval was dictated by server compute a back-off period,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700475 // starting from a predetermined base periodic interval and increasing
476 // exponentially by the number of consecutive failed attempts.
477 if (interval == 0) {
478 const unsigned int* consecutive_failed_update_checks = ec->GetValue(
479 updater_provider->var_consecutive_failed_update_checks());
480 POLICY_CHECK_VALUE_AND_FAIL(consecutive_failed_update_checks, error);
481
482 interval = kTimeoutPeriodicInterval;
483 unsigned int num_failures = *consecutive_failed_update_checks;
484 while (interval < kTimeoutMaxBackoffInterval && num_failures) {
485 interval *= 2;
486 num_failures--;
Alex Deymo0d11c602014-04-23 20:12:20 -0700487 }
488 }
489
Alex Vakulenko072359c2014-07-18 11:41:07 -0700490 // We cannot back off longer than the predetermined maximum interval.
Gilad Arnolda0258a52014-07-10 16:21:19 -0700491 if (interval > kTimeoutMaxBackoffInterval)
492 interval = kTimeoutMaxBackoffInterval;
493
Alex Vakulenko072359c2014-07-18 11:41:07 -0700494 // We cannot back off shorter than the predetermined periodic interval. Also,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700495 // in this case set the fuzz to a predetermined regular value.
496 if (interval <= kTimeoutPeriodicInterval) {
497 interval = kTimeoutPeriodicInterval;
498 fuzz = kTimeoutRegularFuzz;
499 }
500
501 // If not otherwise determined, defer to a fuzz of +/-(interval / 2).
Gilad Arnold38b14022014-07-09 12:45:56 -0700502 if (fuzz == 0)
503 fuzz = interval;
504
Alex Deymo0d11c602014-04-23 20:12:20 -0700505 *next_update_check = *last_checked_time + FuzzedInterval(
Gilad Arnold38b14022014-07-09 12:45:56 -0700506 &prng, interval, fuzz);
Alex Deymo0d11c602014-04-23 20:12:20 -0700507 return EvalStatus::kSucceeded;
508}
509
510TimeDelta ChromeOSPolicy::FuzzedInterval(PRNG* prng, int interval, int fuzz) {
Gilad Arnolde1218812014-05-07 12:21:36 -0700511 DCHECK_GE(interval, 0);
512 DCHECK_GE(fuzz, 0);
Alex Deymo0d11c602014-04-23 20:12:20 -0700513 int half_fuzz = fuzz / 2;
Alex Deymo0d11c602014-04-23 20:12:20 -0700514 // This guarantees the output interval is non negative.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700515 int interval_min = max(interval - half_fuzz, 0);
Gilad Arnolde1218812014-05-07 12:21:36 -0700516 int interval_max = interval + half_fuzz;
517 return TimeDelta::FromSeconds(prng->RandMinMax(interval_min, interval_max));
Alex Deymo0d11c602014-04-23 20:12:20 -0700518}
519
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700520EvalStatus ChromeOSPolicy::UpdateDownloadUrl(
521 EvaluationContext* ec, State* state, std::string* error,
522 UpdateDownloadUrlResult* result, const UpdateState& update_state) const {
523 int url_idx = 0;
524 int url_num_failures = 0;
525 if (update_state.num_checks > 1) {
526 // Ignore negative URL indexes, which indicate that no previous suitable
527 // download URL was found.
528 url_idx = max(0, update_state.download_url_idx);
529 url_num_failures = update_state.download_url_num_failures;
530 }
531
532 // Preconditions / sanity checks.
533 DCHECK_GE(update_state.download_failures_max, 0);
534 DCHECK_LT(url_idx, static_cast<int>(update_state.download_urls.size()));
535 DCHECK_LE(url_num_failures, update_state.download_failures_max);
536
537 // Determine whether HTTP downloads are forbidden by policy. This only
538 // applies to official system builds; otherwise, HTTP is always enabled.
539 bool http_allowed = true;
540 const bool* is_official_build_p = ec->GetValue(
541 state->system_provider()->var_is_official_build());
542 if (is_official_build_p && *is_official_build_p) {
543 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
544 const bool* device_policy_is_loaded_p = ec->GetValue(
545 dp_provider->var_device_policy_is_loaded());
546 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
547 const bool* policy_http_downloads_enabled_p = ec->GetValue(
548 dp_provider->var_http_downloads_enabled());
549 http_allowed = (!policy_http_downloads_enabled_p ||
550 *policy_http_downloads_enabled_p);
551 }
552 }
553
554 // Process recent failures, stop if the URL index advances.
555 for (auto& err_code : update_state.download_url_error_codes) {
556 if (HandleErrorCode(err_code, &url_idx, &url_num_failures))
557 break;
558 if (url_num_failures > update_state.download_failures_max) {
559 url_idx++;
560 url_num_failures = 0;
561 break;
562 }
563 }
564 url_idx %= update_state.download_urls.size();
565
566 // Scan through URLs until a usable one is found.
567 const int start_url_idx = url_idx;
568 while (!DownloadUrlIsUsable(update_state.download_urls[url_idx],
569 http_allowed)) {
570 url_idx = (url_idx + 1) % update_state.download_urls.size();
571 url_num_failures = 0;
572 if (url_idx == start_url_idx)
573 return EvalStatus::kFailed; // No usable URLs.
574 }
575
576 result->url_idx = url_idx;
577 result->url_num_failures = url_num_failures;
578 return EvalStatus::kSucceeded;
579}
580
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700581EvalStatus ChromeOSPolicy::UpdateScattering(
582 EvaluationContext* ec,
583 State* state,
584 string* error,
585 UpdateScatteringResult* result,
586 const UpdateState& update_state) const {
587 // Preconditions. These stem from the postconditions and usage contract.
588 DCHECK(update_state.scatter_wait_period >= kZeroInterval);
589 DCHECK_GE(update_state.scatter_check_threshold, 0);
590
591 // Set default result values.
592 result->is_scattering = false;
593 result->wait_period = kZeroInterval;
594 result->check_threshold = 0;
595
596 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
597
598 // Ensure that a device policy is loaded.
599 const bool* device_policy_is_loaded_p = ec->GetValue(
600 dp_provider->var_device_policy_is_loaded());
601 if (!(device_policy_is_loaded_p && *device_policy_is_loaded_p))
602 return EvalStatus::kSucceeded;
603
604 // Is scattering enabled by policy?
605 const TimeDelta* scatter_factor_p = ec->GetValue(
606 dp_provider->var_scatter_factor());
607 if (!scatter_factor_p || *scatter_factor_p == kZeroInterval)
608 return EvalStatus::kSucceeded;
609
610 // Obtain a pseudo-random number generator.
611 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
612 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
613 PRNG prng(*seed);
614
615 // Step 1: Maintain the scattering wait period.
616 //
617 // If no wait period was previously determined, or it no longer fits in the
618 // scatter factor, then generate a new one. Otherwise, keep the one we have.
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700619 TimeDelta wait_period = update_state.scatter_wait_period;
620 if (wait_period == kZeroInterval || wait_period > *scatter_factor_p) {
621 wait_period = TimeDelta::FromSeconds(
622 prng.RandMinMax(1, scatter_factor_p->InSeconds()));
623 }
624
625 // If we surpass the wait period or the max scatter period associated with
626 // the update, then no wait is needed.
627 Time wait_expires = (update_state.first_seen +
628 min(wait_period, update_state.scatter_wait_period_max));
Gilad Arnolda65fced2014-07-23 09:01:31 -0700629 if (ec->IsWallclockTimeGreaterThan(wait_expires))
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700630 wait_period = kZeroInterval;
631
632 // Step 2: Maintain the update check threshold count.
633 //
634 // If an update check threshold is not specified then generate a new
635 // one.
636 int check_threshold = update_state.scatter_check_threshold;
637 if (check_threshold == 0) {
638 check_threshold = prng.RandMinMax(
639 update_state.scatter_check_threshold_min,
640 update_state.scatter_check_threshold_max);
641 }
642
643 // If the update check threshold is not within allowed range then nullify it.
644 // TODO(garnold) This is compliant with current logic found in
645 // OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied(). We may want
646 // to change it so that it behaves similarly to the wait period case, namely
647 // if the current value exceeds the maximum, we set a new one within range.
648 if (check_threshold > update_state.scatter_check_threshold_max)
649 check_threshold = 0;
650
651 // If the update check threshold is non-zero and satisfied, then nullify it.
652 if (check_threshold > 0 && update_state.num_checks >= check_threshold)
653 check_threshold = 0;
654
655 bool is_scattering = (wait_period != kZeroInterval || check_threshold);
656 EvalStatus ret = EvalStatus::kSucceeded;
657 if (is_scattering && wait_period == update_state.scatter_wait_period &&
658 check_threshold == update_state.scatter_check_threshold)
659 ret = EvalStatus::kAskMeAgainLater;
660 result->is_scattering = is_scattering;
661 result->wait_period = wait_period;
662 result->check_threshold = check_threshold;
663 return ret;
664}
665
Alex Deymo63784a52014-05-28 10:46:14 -0700666} // namespace chromeos_update_manager