blob: 67799ce2d1380b274a252d6fd0697e68237f685d [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) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700171 LOG(INFO) << "Booted from removable device, disabling update checks.";
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700172 result->updates_enabled = false;
173 return EvalStatus::kSucceeded;
174 }
175
Gilad Arnold42f253b2014-06-25 12:39:17 -0700176 const bool* device_policy_is_loaded_p = ec->GetValue(
177 dp_provider->var_device_policy_is_loaded());
178 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
179 // Check whether updates are disabled by policy.
180 const bool* update_disabled_p = ec->GetValue(
181 dp_provider->var_update_disabled());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700182 if (update_disabled_p && *update_disabled_p) {
183 LOG(INFO) << "Updates disabled by policy, blocking update checks.";
Gilad Arnold42f253b2014-06-25 12:39:17 -0700184 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700185 }
Gilad Arnold42f253b2014-06-25 12:39:17 -0700186
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700187 // Determine whether a target version prefix is dictated by policy.
188 const string* target_version_prefix_p = ec->GetValue(
189 dp_provider->var_target_version_prefix());
190 if (target_version_prefix_p)
191 result->target_version_prefix = *target_version_prefix_p;
192
Gilad Arnold42f253b2014-06-25 12:39:17 -0700193 // Determine whether a target channel is dictated by policy.
194 const bool* release_channel_delegated_p = ec->GetValue(
195 dp_provider->var_release_channel_delegated());
196 if (release_channel_delegated_p && !(*release_channel_delegated_p)) {
197 const string* release_channel_p = ec->GetValue(
198 dp_provider->var_release_channel());
199 if (release_channel_p)
200 result->target_channel = *release_channel_p;
201 }
202 }
203
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700204 // First, check to see if an interactive update was requested.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700205 const UpdateRequestStatus* forced_update_requested_p = ec->GetValue(
206 updater_provider->var_forced_update_requested());
207 if (forced_update_requested_p &&
208 *forced_update_requested_p != UpdateRequestStatus::kNone) {
209 result->is_interactive =
210 (*forced_update_requested_p == UpdateRequestStatus::kInteractive);
211 LOG(INFO) << "Forced update signaled ("
212 << (result->is_interactive ? "interactive" : "periodic")
213 << "), allowing update check.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700214 return EvalStatus::kSucceeded;
215 }
216
217 // The logic thereafter applies to periodic updates. Bear in mind that we
218 // should not return a final "no" if any of these criteria are not satisfied,
219 // because the system may still update due to an interactive update request.
220
221 // Unofficial builds should not perform periodic update checks.
222 const bool* is_official_build_p = ec->GetValue(
223 system_provider->var_is_official_build());
224 if (is_official_build_p && !(*is_official_build_p)) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700225 LOG(INFO) << "Unofficial build, blocking periodic update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700226 return EvalStatus::kAskMeAgainLater;
227 }
228
229 // If OOBE is enabled, wait until it is completed.
230 const bool* is_oobe_enabled_p = ec->GetValue(
231 state->config_provider()->var_is_oobe_enabled());
232 if (is_oobe_enabled_p && *is_oobe_enabled_p) {
233 const bool* is_oobe_complete_p = ec->GetValue(
234 system_provider->var_is_oobe_complete());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700235 if (is_oobe_complete_p && !(*is_oobe_complete_p)) {
236 LOG(INFO) << "OOBE not completed, blocking update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700237 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700238 }
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700239 }
240
241 // Ensure that periodic update checks are timed properly.
Alex Deymo0d11c602014-04-23 20:12:20 -0700242 Time next_update_check;
243 if (NextUpdateCheckTime(ec, state, error, &next_update_check) !=
244 EvalStatus::kSucceeded) {
245 return EvalStatus::kFailed;
246 }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700247 if (!ec->IsWallclockTimeGreaterThan(next_update_check)) {
248 LOG(INFO) << "Periodic check interval not satisfied, blocking until "
249 << chromeos_update_engine::utils::ToString(next_update_check);
Alex Deymo0d11c602014-04-23 20:12:20 -0700250 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700251 }
Alex Deymo0d11c602014-04-23 20:12:20 -0700252
253 // It is time to check for an update.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700254 LOG(INFO) << "Allowing update check.";
Alex Deymoe636c3c2014-03-11 19:02:08 -0700255 return EvalStatus::kSucceeded;
Alex Deymoc705cc82014-02-19 11:15:00 -0800256}
257
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700258EvalStatus ChromeOSPolicy::UpdateCanStart(
259 EvaluationContext* ec,
260 State* state,
261 string* error,
Gilad Arnold42f253b2014-06-25 12:39:17 -0700262 UpdateDownloadParams* result,
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700263 const bool interactive,
264 const UpdateState& update_state) const {
265 // Set the default return values.
266 result->update_can_start = true;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700267 result->p2p_allowed = false;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700268 result->cannot_start_reason = UpdateCannotStartReason::kUndefined;
269 result->scatter_wait_period = kZeroInterval;
270 result->scatter_check_threshold = 0;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700271 result->download_url_idx = -1;
272 result->download_url_num_failures = 0;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700273
274 // Make sure that we're not due for an update check.
275 UpdateCheckParams check_result;
276 EvalStatus check_status = UpdateCheckAllowed(ec, state, error, &check_result);
277 if (check_status == EvalStatus::kFailed)
278 return EvalStatus::kFailed;
279 if (check_status == EvalStatus::kSucceeded &&
280 check_result.updates_enabled == true) {
281 result->update_can_start = false;
282 result->cannot_start_reason = UpdateCannotStartReason::kCheckDue;
283 return EvalStatus::kSucceeded;
284 }
285
286 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
287
288 const bool* device_policy_is_loaded_p = ec->GetValue(
289 dp_provider->var_device_policy_is_loaded());
290 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700291 // Check whether scattering applies to this update attempt. We should not be
292 // scattering if this is an interactive update check, or if OOBE is enabled
293 // but not completed.
294 //
295 // Note: current code further suppresses scattering if a "deadline"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700296 // attribute is found in the Omaha response. However, it appears that the
Gilad Arnold76a11f62014-05-20 09:02:12 -0700297 // presence of this attribute is merely indicative of an OOBE update, during
298 // which we suppress scattering anyway.
299 bool scattering_applies = false;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700300 if (!interactive) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700301 const bool* is_oobe_enabled_p = ec->GetValue(
302 state->config_provider()->var_is_oobe_enabled());
303 if (is_oobe_enabled_p && !(*is_oobe_enabled_p)) {
304 scattering_applies = true;
305 } else {
306 const bool* is_oobe_complete_p = ec->GetValue(
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700307 state->system_provider()->var_is_oobe_complete());
Gilad Arnold76a11f62014-05-20 09:02:12 -0700308 scattering_applies = (is_oobe_complete_p && *is_oobe_complete_p);
309 }
310 }
311
312 // Compute scattering values.
313 if (scattering_applies) {
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700314 UpdateScatteringResult scatter_result;
315 EvalStatus scattering_status = UpdateScattering(
316 ec, state, error, &scatter_result, update_state);
317 if (scattering_status != EvalStatus::kSucceeded ||
318 scatter_result.is_scattering) {
319 if (scattering_status != EvalStatus::kFailed) {
320 result->update_can_start = false;
321 result->cannot_start_reason = UpdateCannotStartReason::kScattering;
322 result->scatter_wait_period = scatter_result.wait_period;
323 result->scatter_check_threshold = scatter_result.check_threshold;
324 }
325 return scattering_status;
326 }
327 }
328
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700329 // Determine whether use of P2P is allowed by policy.
330 const bool* policy_au_p2p_enabled_p = ec->GetValue(
331 dp_provider->var_au_p2p_enabled());
332 result->p2p_allowed = policy_au_p2p_enabled_p && *policy_au_p2p_enabled_p;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700333 }
334
335 // Enable P2P, if so mandated by the updater configuration.
336 if (!result->p2p_allowed) {
337 const bool* updater_p2p_enabled_p = ec->GetValue(
338 state->updater_provider()->var_p2p_enabled());
339 result->p2p_allowed = updater_p2p_enabled_p && *updater_p2p_enabled_p;
340 }
341
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700342 // Determine the URL to download the update from. Note that a failure to find
343 // a download URL will only fail this policy iff no other means of download
344 // (such as P2P) are enabled.
345 UpdateDownloadUrlResult download_url_result;
346 EvalStatus download_url_status = UpdateDownloadUrl(
347 ec, state, error, &download_url_result, update_state);
348 if (download_url_status == EvalStatus::kSucceeded) {
349 result->download_url_idx = download_url_result.url_idx;
350 result->download_url_num_failures = download_url_result.url_num_failures;
351 } else if (!result->p2p_allowed) {
352 if (download_url_status != EvalStatus::kFailed) {
353 result->update_can_start = false;
354 result->cannot_start_reason = UpdateCannotStartReason::kCannotDownload;
355 }
356 return download_url_status;
357 }
358
Gilad Arnoldaf2f6ae2014-04-28 14:14:52 -0700359 return EvalStatus::kSucceeded;
360}
361
Gilad Arnolda8262e22014-06-02 13:54:27 -0700362// TODO(garnold) Logic in this method is based on
363// ConnectionManager::IsUpdateAllowedOver(); be sure to deprecate the latter.
364//
365// TODO(garnold) The current logic generally treats the list of allowed
366// connections coming from the device policy as a whitelist, meaning that it
367// can only be used for enabling connections, but not disable them. Further,
368// certain connection types (like Bluetooth) cannot be enabled even by policy.
369// In effect, the only thing that device policy can change is to enable
370// updates over a cellular network (disabled by default). We may want to
371// revisit this semantics, allowing greater flexibility in defining specific
372// permissions over all types of networks.
Gilad Arnold684219d2014-07-07 14:54:57 -0700373EvalStatus ChromeOSPolicy::UpdateDownloadAllowed(
Gilad Arnolda8262e22014-06-02 13:54:27 -0700374 EvaluationContext* ec,
375 State* state,
376 string* error,
377 bool* result) const {
378 // Get the current connection type.
379 ShillProvider* const shill_provider = state->shill_provider();
380 const ConnectionType* conn_type_p = ec->GetValue(
381 shill_provider->var_conn_type());
382 POLICY_CHECK_VALUE_AND_FAIL(conn_type_p, error);
383 ConnectionType conn_type = *conn_type_p;
384
385 // If we're tethering, treat it as a cellular connection.
386 if (conn_type != ConnectionType::kCellular) {
387 const ConnectionTethering* conn_tethering_p = ec->GetValue(
388 shill_provider->var_conn_tethering());
389 POLICY_CHECK_VALUE_AND_FAIL(conn_tethering_p, error);
390 if (*conn_tethering_p == ConnectionTethering::kConfirmed)
391 conn_type = ConnectionType::kCellular;
392 }
393
394 // By default, we allow updates for all connection types, with exceptions as
395 // noted below. This also determines whether a device policy can override the
396 // default.
397 *result = true;
398 bool device_policy_can_override = false;
399 switch (conn_type) {
400 case ConnectionType::kBluetooth:
401 *result = false;
402 break;
403
404 case ConnectionType::kCellular:
405 *result = false;
406 device_policy_can_override = true;
407 break;
408
409 case ConnectionType::kUnknown:
410 if (error)
411 *error = "Unknown connection type";
412 return EvalStatus::kFailed;
413
414 default:
415 break; // Nothing to do.
416 }
417
418 // If update is allowed, we're done.
419 if (*result)
420 return EvalStatus::kSucceeded;
421
422 // Check whether the device policy specifically allows this connection.
Gilad Arnolda8262e22014-06-02 13:54:27 -0700423 if (device_policy_can_override) {
424 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
425 const bool* device_policy_is_loaded_p = ec->GetValue(
426 dp_provider->var_device_policy_is_loaded());
427 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
428 const set<ConnectionType>* allowed_conn_types_p = ec->GetValue(
429 dp_provider->var_allowed_connection_types_for_update());
430 if (allowed_conn_types_p) {
431 if (allowed_conn_types_p->count(conn_type)) {
432 *result = true;
433 return EvalStatus::kSucceeded;
434 }
Gilad Arnold28d6be62014-06-30 14:04:04 -0700435 } else if (conn_type == ConnectionType::kCellular) {
436 // Local user settings can allow updates over cellular iff a policy was
437 // loaded but no allowed connections were specified in it.
438 const bool* update_over_cellular_allowed_p = ec->GetValue(
439 state->updater_provider()->var_cellular_enabled());
440 if (update_over_cellular_allowed_p && *update_over_cellular_allowed_p)
441 *result = true;
Gilad Arnolda8262e22014-06-02 13:54:27 -0700442 }
443 }
444 }
445
Gilad Arnold28d6be62014-06-30 14:04:04 -0700446 return (*result ? EvalStatus::kSucceeded : EvalStatus::kAskMeAgainLater);
Gilad Arnolda8262e22014-06-02 13:54:27 -0700447}
448
Alex Deymo0d11c602014-04-23 20:12:20 -0700449EvalStatus ChromeOSPolicy::NextUpdateCheckTime(EvaluationContext* ec,
450 State* state, string* error,
451 Time* next_update_check) const {
Gilad Arnolda0258a52014-07-10 16:21:19 -0700452 UpdaterProvider* const updater_provider = state->updater_provider();
453
Alex Deymo0d11c602014-04-23 20:12:20 -0700454 // Don't check for updates too often. We limit the update checks to once every
455 // some interval. The interval is kTimeoutInitialInterval the first time and
456 // kTimeoutPeriodicInterval for the subsequent update checks. If the update
457 // check fails, we increase the interval between the update checks
458 // exponentially until kTimeoutMaxBackoffInterval. Finally, to avoid having
459 // many chromebooks running update checks at the exact same time, we add some
460 // fuzz to the interval.
461 const Time* updater_started_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700462 ec->GetValue(updater_provider->var_updater_started_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700463 POLICY_CHECK_VALUE_AND_FAIL(updater_started_time, error);
464
465 const base::Time* last_checked_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700466 ec->GetValue(updater_provider->var_last_checked_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700467
468 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
469 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
470
471 PRNG prng(*seed);
472
Gilad Arnold38b14022014-07-09 12:45:56 -0700473 // If this is the first attempt, compute and return an initial value.
Alex Deymo0d11c602014-04-23 20:12:20 -0700474 if (!last_checked_time || *last_checked_time < *updater_started_time) {
Alex Deymo0d11c602014-04-23 20:12:20 -0700475 *next_update_check = *updater_started_time + FuzzedInterval(
476 &prng, kTimeoutInitialInterval, kTimeoutRegularFuzz);
477 return EvalStatus::kSucceeded;
478 }
Gilad Arnold38b14022014-07-09 12:45:56 -0700479
Gilad Arnolda0258a52014-07-10 16:21:19 -0700480 // Check whether the server is enforcing a poll interval; if not, this value
481 // will be zero.
482 const unsigned int* server_dictated_poll_interval = ec->GetValue(
483 updater_provider->var_server_dictated_poll_interval());
484 POLICY_CHECK_VALUE_AND_FAIL(server_dictated_poll_interval, error);
Alex Deymo0d11c602014-04-23 20:12:20 -0700485
Gilad Arnolda0258a52014-07-10 16:21:19 -0700486 int interval = *server_dictated_poll_interval;
487 int fuzz = 0;
488
Alex Vakulenko072359c2014-07-18 11:41:07 -0700489 // If no poll interval was dictated by server compute a back-off period,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700490 // starting from a predetermined base periodic interval and increasing
491 // exponentially by the number of consecutive failed attempts.
492 if (interval == 0) {
493 const unsigned int* consecutive_failed_update_checks = ec->GetValue(
494 updater_provider->var_consecutive_failed_update_checks());
495 POLICY_CHECK_VALUE_AND_FAIL(consecutive_failed_update_checks, error);
496
497 interval = kTimeoutPeriodicInterval;
498 unsigned int num_failures = *consecutive_failed_update_checks;
499 while (interval < kTimeoutMaxBackoffInterval && num_failures) {
500 interval *= 2;
501 num_failures--;
Alex Deymo0d11c602014-04-23 20:12:20 -0700502 }
503 }
504
Alex Vakulenko072359c2014-07-18 11:41:07 -0700505 // We cannot back off longer than the predetermined maximum interval.
Gilad Arnolda0258a52014-07-10 16:21:19 -0700506 if (interval > kTimeoutMaxBackoffInterval)
507 interval = kTimeoutMaxBackoffInterval;
508
Alex Vakulenko072359c2014-07-18 11:41:07 -0700509 // We cannot back off shorter than the predetermined periodic interval. Also,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700510 // in this case set the fuzz to a predetermined regular value.
511 if (interval <= kTimeoutPeriodicInterval) {
512 interval = kTimeoutPeriodicInterval;
513 fuzz = kTimeoutRegularFuzz;
514 }
515
516 // If not otherwise determined, defer to a fuzz of +/-(interval / 2).
Gilad Arnold38b14022014-07-09 12:45:56 -0700517 if (fuzz == 0)
518 fuzz = interval;
519
Alex Deymo0d11c602014-04-23 20:12:20 -0700520 *next_update_check = *last_checked_time + FuzzedInterval(
Gilad Arnold38b14022014-07-09 12:45:56 -0700521 &prng, interval, fuzz);
Alex Deymo0d11c602014-04-23 20:12:20 -0700522 return EvalStatus::kSucceeded;
523}
524
525TimeDelta ChromeOSPolicy::FuzzedInterval(PRNG* prng, int interval, int fuzz) {
Gilad Arnolde1218812014-05-07 12:21:36 -0700526 DCHECK_GE(interval, 0);
527 DCHECK_GE(fuzz, 0);
Alex Deymo0d11c602014-04-23 20:12:20 -0700528 int half_fuzz = fuzz / 2;
Alex Deymo0d11c602014-04-23 20:12:20 -0700529 // This guarantees the output interval is non negative.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700530 int interval_min = max(interval - half_fuzz, 0);
Gilad Arnolde1218812014-05-07 12:21:36 -0700531 int interval_max = interval + half_fuzz;
532 return TimeDelta::FromSeconds(prng->RandMinMax(interval_min, interval_max));
Alex Deymo0d11c602014-04-23 20:12:20 -0700533}
534
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700535EvalStatus ChromeOSPolicy::UpdateDownloadUrl(
536 EvaluationContext* ec, State* state, std::string* error,
537 UpdateDownloadUrlResult* result, const UpdateState& update_state) const {
538 int url_idx = 0;
539 int url_num_failures = 0;
540 if (update_state.num_checks > 1) {
541 // Ignore negative URL indexes, which indicate that no previous suitable
542 // download URL was found.
543 url_idx = max(0, update_state.download_url_idx);
544 url_num_failures = update_state.download_url_num_failures;
545 }
546
547 // Preconditions / sanity checks.
548 DCHECK_GE(update_state.download_failures_max, 0);
549 DCHECK_LT(url_idx, static_cast<int>(update_state.download_urls.size()));
550 DCHECK_LE(url_num_failures, update_state.download_failures_max);
551
552 // Determine whether HTTP downloads are forbidden by policy. This only
553 // applies to official system builds; otherwise, HTTP is always enabled.
554 bool http_allowed = true;
555 const bool* is_official_build_p = ec->GetValue(
556 state->system_provider()->var_is_official_build());
557 if (is_official_build_p && *is_official_build_p) {
558 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
559 const bool* device_policy_is_loaded_p = ec->GetValue(
560 dp_provider->var_device_policy_is_loaded());
561 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
562 const bool* policy_http_downloads_enabled_p = ec->GetValue(
563 dp_provider->var_http_downloads_enabled());
564 http_allowed = (!policy_http_downloads_enabled_p ||
565 *policy_http_downloads_enabled_p);
566 }
567 }
568
569 // Process recent failures, stop if the URL index advances.
570 for (auto& err_code : update_state.download_url_error_codes) {
571 if (HandleErrorCode(err_code, &url_idx, &url_num_failures))
572 break;
573 if (url_num_failures > update_state.download_failures_max) {
574 url_idx++;
575 url_num_failures = 0;
576 break;
577 }
578 }
579 url_idx %= update_state.download_urls.size();
580
581 // Scan through URLs until a usable one is found.
582 const int start_url_idx = url_idx;
583 while (!DownloadUrlIsUsable(update_state.download_urls[url_idx],
584 http_allowed)) {
585 url_idx = (url_idx + 1) % update_state.download_urls.size();
586 url_num_failures = 0;
587 if (url_idx == start_url_idx)
588 return EvalStatus::kFailed; // No usable URLs.
589 }
590
591 result->url_idx = url_idx;
592 result->url_num_failures = url_num_failures;
593 return EvalStatus::kSucceeded;
594}
595
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700596EvalStatus ChromeOSPolicy::UpdateScattering(
597 EvaluationContext* ec,
598 State* state,
599 string* error,
600 UpdateScatteringResult* result,
601 const UpdateState& update_state) const {
602 // Preconditions. These stem from the postconditions and usage contract.
603 DCHECK(update_state.scatter_wait_period >= kZeroInterval);
604 DCHECK_GE(update_state.scatter_check_threshold, 0);
605
606 // Set default result values.
607 result->is_scattering = false;
608 result->wait_period = kZeroInterval;
609 result->check_threshold = 0;
610
611 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
612
613 // Ensure that a device policy is loaded.
614 const bool* device_policy_is_loaded_p = ec->GetValue(
615 dp_provider->var_device_policy_is_loaded());
616 if (!(device_policy_is_loaded_p && *device_policy_is_loaded_p))
617 return EvalStatus::kSucceeded;
618
619 // Is scattering enabled by policy?
620 const TimeDelta* scatter_factor_p = ec->GetValue(
621 dp_provider->var_scatter_factor());
622 if (!scatter_factor_p || *scatter_factor_p == kZeroInterval)
623 return EvalStatus::kSucceeded;
624
625 // Obtain a pseudo-random number generator.
626 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
627 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
628 PRNG prng(*seed);
629
630 // Step 1: Maintain the scattering wait period.
631 //
632 // If no wait period was previously determined, or it no longer fits in the
633 // scatter factor, then generate a new one. Otherwise, keep the one we have.
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700634 TimeDelta wait_period = update_state.scatter_wait_period;
635 if (wait_period == kZeroInterval || wait_period > *scatter_factor_p) {
636 wait_period = TimeDelta::FromSeconds(
637 prng.RandMinMax(1, scatter_factor_p->InSeconds()));
638 }
639
640 // If we surpass the wait period or the max scatter period associated with
641 // the update, then no wait is needed.
642 Time wait_expires = (update_state.first_seen +
643 min(wait_period, update_state.scatter_wait_period_max));
Gilad Arnolda65fced2014-07-23 09:01:31 -0700644 if (ec->IsWallclockTimeGreaterThan(wait_expires))
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700645 wait_period = kZeroInterval;
646
647 // Step 2: Maintain the update check threshold count.
648 //
649 // If an update check threshold is not specified then generate a new
650 // one.
651 int check_threshold = update_state.scatter_check_threshold;
652 if (check_threshold == 0) {
653 check_threshold = prng.RandMinMax(
654 update_state.scatter_check_threshold_min,
655 update_state.scatter_check_threshold_max);
656 }
657
658 // If the update check threshold is not within allowed range then nullify it.
659 // TODO(garnold) This is compliant with current logic found in
660 // OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied(). We may want
661 // to change it so that it behaves similarly to the wait period case, namely
662 // if the current value exceeds the maximum, we set a new one within range.
663 if (check_threshold > update_state.scatter_check_threshold_max)
664 check_threshold = 0;
665
666 // If the update check threshold is non-zero and satisfied, then nullify it.
667 if (check_threshold > 0 && update_state.num_checks >= check_threshold)
668 check_threshold = 0;
669
670 bool is_scattering = (wait_period != kZeroInterval || check_threshold);
671 EvalStatus ret = EvalStatus::kSucceeded;
672 if (is_scattering && wait_period == update_state.scatter_wait_period &&
673 check_threshold == update_state.scatter_check_threshold)
674 ret = EvalStatus::kAskMeAgainLater;
675 result->is_scattering = is_scattering;
676 result->wait_period = wait_period;
677 result->check_threshold = check_threshold;
678 return ret;
679}
680
Alex Deymo63784a52014-05-28 10:46:14 -0700681} // namespace chromeos_update_manager