blob: fc39bd7faae32f06ace0ad41edd2b108a98153d5 [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
Gilad Arnolda2e8eaa2014-09-24 13:12:33 -0700153const int ChromeOSPolicy::kTimeoutInitialInterval = 7 * 60;
154const int ChromeOSPolicy::kTimeoutPeriodicInterval = 45 * 60;
155const int ChromeOSPolicy::kTimeoutMaxBackoffInterval = 4 * 60 * 60;
156const int ChromeOSPolicy::kTimeoutRegularFuzz = 10 * 60;
157
Alex Deymo0d11c602014-04-23 20:12:20 -0700158EvalStatus ChromeOSPolicy::UpdateCheckAllowed(
159 EvaluationContext* ec, State* state, string* error,
160 UpdateCheckParams* result) const {
Gilad Arnold42f253b2014-06-25 12:39:17 -0700161 // Set the default return values.
162 result->updates_enabled = true;
163 result->target_channel.clear();
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700164 result->target_version_prefix.clear();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700165 result->is_interactive = false;
Gilad Arnold42f253b2014-06-25 12:39:17 -0700166
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700167 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700168 UpdaterProvider* const updater_provider = state->updater_provider();
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700169 SystemProvider* const system_provider = state->system_provider();
170
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700171 // Do not perform any updates if booted from removable device. This decision
172 // is final.
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700173 const bool* is_boot_device_removable_p = ec->GetValue(
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700174 system_provider->var_is_boot_device_removable());
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700175 if (is_boot_device_removable_p && *is_boot_device_removable_p) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700176 LOG(INFO) << "Booted from removable device, disabling update checks.";
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700177 result->updates_enabled = false;
178 return EvalStatus::kSucceeded;
179 }
180
Gilad Arnold42f253b2014-06-25 12:39:17 -0700181 const bool* device_policy_is_loaded_p = ec->GetValue(
182 dp_provider->var_device_policy_is_loaded());
183 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
184 // Check whether updates are disabled by policy.
185 const bool* update_disabled_p = ec->GetValue(
186 dp_provider->var_update_disabled());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700187 if (update_disabled_p && *update_disabled_p) {
188 LOG(INFO) << "Updates disabled by policy, blocking update checks.";
Gilad Arnold42f253b2014-06-25 12:39:17 -0700189 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700190 }
Gilad Arnold42f253b2014-06-25 12:39:17 -0700191
Gilad Arnoldd4b30322014-07-21 15:35:27 -0700192 // Determine whether a target version prefix is dictated by policy.
193 const string* target_version_prefix_p = ec->GetValue(
194 dp_provider->var_target_version_prefix());
195 if (target_version_prefix_p)
196 result->target_version_prefix = *target_version_prefix_p;
197
Gilad Arnold42f253b2014-06-25 12:39:17 -0700198 // Determine whether a target channel is dictated by policy.
199 const bool* release_channel_delegated_p = ec->GetValue(
200 dp_provider->var_release_channel_delegated());
201 if (release_channel_delegated_p && !(*release_channel_delegated_p)) {
202 const string* release_channel_p = ec->GetValue(
203 dp_provider->var_release_channel());
204 if (release_channel_p)
205 result->target_channel = *release_channel_p;
206 }
207 }
208
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700209 // First, check to see if an interactive update was requested.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700210 const UpdateRequestStatus* forced_update_requested_p = ec->GetValue(
211 updater_provider->var_forced_update_requested());
212 if (forced_update_requested_p &&
213 *forced_update_requested_p != UpdateRequestStatus::kNone) {
214 result->is_interactive =
215 (*forced_update_requested_p == UpdateRequestStatus::kInteractive);
216 LOG(INFO) << "Forced update signaled ("
217 << (result->is_interactive ? "interactive" : "periodic")
218 << "), allowing update check.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700219 return EvalStatus::kSucceeded;
220 }
221
222 // The logic thereafter applies to periodic updates. Bear in mind that we
223 // should not return a final "no" if any of these criteria are not satisfied,
224 // because the system may still update due to an interactive update request.
225
226 // Unofficial builds should not perform periodic update checks.
227 const bool* is_official_build_p = ec->GetValue(
228 system_provider->var_is_official_build());
229 if (is_official_build_p && !(*is_official_build_p)) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700230 LOG(INFO) << "Unofficial build, blocking periodic update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700231 return EvalStatus::kAskMeAgainLater;
232 }
233
234 // If OOBE is enabled, wait until it is completed.
235 const bool* is_oobe_enabled_p = ec->GetValue(
236 state->config_provider()->var_is_oobe_enabled());
237 if (is_oobe_enabled_p && *is_oobe_enabled_p) {
238 const bool* is_oobe_complete_p = ec->GetValue(
239 system_provider->var_is_oobe_complete());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700240 if (is_oobe_complete_p && !(*is_oobe_complete_p)) {
241 LOG(INFO) << "OOBE not completed, blocking update checks.";
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700242 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700243 }
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700244 }
245
246 // Ensure that periodic update checks are timed properly.
Alex Deymo0d11c602014-04-23 20:12:20 -0700247 Time next_update_check;
248 if (NextUpdateCheckTime(ec, state, error, &next_update_check) !=
249 EvalStatus::kSucceeded) {
250 return EvalStatus::kFailed;
251 }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700252 if (!ec->IsWallclockTimeGreaterThan(next_update_check)) {
253 LOG(INFO) << "Periodic check interval not satisfied, blocking until "
254 << chromeos_update_engine::utils::ToString(next_update_check);
Alex Deymo0d11c602014-04-23 20:12:20 -0700255 return EvalStatus::kAskMeAgainLater;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700256 }
Alex Deymo0d11c602014-04-23 20:12:20 -0700257
258 // It is time to check for an update.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700259 LOG(INFO) << "Allowing update check.";
Alex Deymoe636c3c2014-03-11 19:02:08 -0700260 return EvalStatus::kSucceeded;
Alex Deymoc705cc82014-02-19 11:15:00 -0800261}
262
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700263EvalStatus ChromeOSPolicy::UpdateCanStart(
264 EvaluationContext* ec,
265 State* state,
266 string* error,
Gilad Arnold42f253b2014-06-25 12:39:17 -0700267 UpdateDownloadParams* result,
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700268 const bool interactive,
269 const UpdateState& update_state) const {
270 // Set the default return values.
271 result->update_can_start = true;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700272 result->p2p_allowed = false;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700273 result->cannot_start_reason = UpdateCannotStartReason::kUndefined;
274 result->scatter_wait_period = kZeroInterval;
275 result->scatter_check_threshold = 0;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700276 result->download_url_idx = -1;
277 result->download_url_num_failures = 0;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700278
279 // Make sure that we're not due for an update check.
280 UpdateCheckParams check_result;
281 EvalStatus check_status = UpdateCheckAllowed(ec, state, error, &check_result);
282 if (check_status == EvalStatus::kFailed)
283 return EvalStatus::kFailed;
284 if (check_status == EvalStatus::kSucceeded &&
285 check_result.updates_enabled == true) {
286 result->update_can_start = false;
287 result->cannot_start_reason = UpdateCannotStartReason::kCheckDue;
288 return EvalStatus::kSucceeded;
289 }
290
291 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
292
293 const bool* device_policy_is_loaded_p = ec->GetValue(
294 dp_provider->var_device_policy_is_loaded());
295 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700296 // Check whether scattering applies to this update attempt. We should not be
297 // scattering if this is an interactive update check, or if OOBE is enabled
298 // but not completed.
299 //
300 // Note: current code further suppresses scattering if a "deadline"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700301 // attribute is found in the Omaha response. However, it appears that the
Gilad Arnold76a11f62014-05-20 09:02:12 -0700302 // presence of this attribute is merely indicative of an OOBE update, during
303 // which we suppress scattering anyway.
304 bool scattering_applies = false;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700305 if (!interactive) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700306 const bool* is_oobe_enabled_p = ec->GetValue(
307 state->config_provider()->var_is_oobe_enabled());
308 if (is_oobe_enabled_p && !(*is_oobe_enabled_p)) {
309 scattering_applies = true;
310 } else {
311 const bool* is_oobe_complete_p = ec->GetValue(
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700312 state->system_provider()->var_is_oobe_complete());
Gilad Arnold76a11f62014-05-20 09:02:12 -0700313 scattering_applies = (is_oobe_complete_p && *is_oobe_complete_p);
314 }
315 }
316
317 // Compute scattering values.
318 if (scattering_applies) {
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700319 UpdateScatteringResult scatter_result;
320 EvalStatus scattering_status = UpdateScattering(
321 ec, state, error, &scatter_result, update_state);
322 if (scattering_status != EvalStatus::kSucceeded ||
323 scatter_result.is_scattering) {
324 if (scattering_status != EvalStatus::kFailed) {
325 result->update_can_start = false;
326 result->cannot_start_reason = UpdateCannotStartReason::kScattering;
327 result->scatter_wait_period = scatter_result.wait_period;
328 result->scatter_check_threshold = scatter_result.check_threshold;
329 }
330 return scattering_status;
331 }
332 }
333
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700334 // Determine whether use of P2P is allowed by policy.
335 const bool* policy_au_p2p_enabled_p = ec->GetValue(
336 dp_provider->var_au_p2p_enabled());
337 result->p2p_allowed = policy_au_p2p_enabled_p && *policy_au_p2p_enabled_p;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700338 }
339
340 // Enable P2P, if so mandated by the updater configuration.
341 if (!result->p2p_allowed) {
342 const bool* updater_p2p_enabled_p = ec->GetValue(
343 state->updater_provider()->var_p2p_enabled());
344 result->p2p_allowed = updater_p2p_enabled_p && *updater_p2p_enabled_p;
345 }
346
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700347 // Determine the URL to download the update from. Note that a failure to find
348 // a download URL will only fail this policy iff no other means of download
349 // (such as P2P) are enabled.
350 UpdateDownloadUrlResult download_url_result;
351 EvalStatus download_url_status = UpdateDownloadUrl(
352 ec, state, error, &download_url_result, update_state);
353 if (download_url_status == EvalStatus::kSucceeded) {
354 result->download_url_idx = download_url_result.url_idx;
355 result->download_url_num_failures = download_url_result.url_num_failures;
356 } else if (!result->p2p_allowed) {
357 if (download_url_status != EvalStatus::kFailed) {
358 result->update_can_start = false;
359 result->cannot_start_reason = UpdateCannotStartReason::kCannotDownload;
360 }
361 return download_url_status;
362 }
363
Gilad Arnoldaf2f6ae2014-04-28 14:14:52 -0700364 return EvalStatus::kSucceeded;
365}
366
Gilad Arnolda8262e22014-06-02 13:54:27 -0700367// TODO(garnold) Logic in this method is based on
368// ConnectionManager::IsUpdateAllowedOver(); be sure to deprecate the latter.
369//
370// TODO(garnold) The current logic generally treats the list of allowed
371// connections coming from the device policy as a whitelist, meaning that it
372// can only be used for enabling connections, but not disable them. Further,
373// certain connection types (like Bluetooth) cannot be enabled even by policy.
374// In effect, the only thing that device policy can change is to enable
375// updates over a cellular network (disabled by default). We may want to
376// revisit this semantics, allowing greater flexibility in defining specific
377// permissions over all types of networks.
Gilad Arnold684219d2014-07-07 14:54:57 -0700378EvalStatus ChromeOSPolicy::UpdateDownloadAllowed(
Gilad Arnolda8262e22014-06-02 13:54:27 -0700379 EvaluationContext* ec,
380 State* state,
381 string* error,
382 bool* result) const {
383 // Get the current connection type.
384 ShillProvider* const shill_provider = state->shill_provider();
385 const ConnectionType* conn_type_p = ec->GetValue(
386 shill_provider->var_conn_type());
387 POLICY_CHECK_VALUE_AND_FAIL(conn_type_p, error);
388 ConnectionType conn_type = *conn_type_p;
389
390 // If we're tethering, treat it as a cellular connection.
391 if (conn_type != ConnectionType::kCellular) {
392 const ConnectionTethering* conn_tethering_p = ec->GetValue(
393 shill_provider->var_conn_tethering());
394 POLICY_CHECK_VALUE_AND_FAIL(conn_tethering_p, error);
395 if (*conn_tethering_p == ConnectionTethering::kConfirmed)
396 conn_type = ConnectionType::kCellular;
397 }
398
399 // By default, we allow updates for all connection types, with exceptions as
400 // noted below. This also determines whether a device policy can override the
401 // default.
402 *result = true;
403 bool device_policy_can_override = false;
404 switch (conn_type) {
405 case ConnectionType::kBluetooth:
406 *result = false;
407 break;
408
409 case ConnectionType::kCellular:
410 *result = false;
411 device_policy_can_override = true;
412 break;
413
414 case ConnectionType::kUnknown:
415 if (error)
416 *error = "Unknown connection type";
417 return EvalStatus::kFailed;
418
419 default:
420 break; // Nothing to do.
421 }
422
423 // If update is allowed, we're done.
424 if (*result)
425 return EvalStatus::kSucceeded;
426
427 // Check whether the device policy specifically allows this connection.
Gilad Arnolda8262e22014-06-02 13:54:27 -0700428 if (device_policy_can_override) {
429 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
430 const bool* device_policy_is_loaded_p = ec->GetValue(
431 dp_provider->var_device_policy_is_loaded());
432 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
433 const set<ConnectionType>* allowed_conn_types_p = ec->GetValue(
434 dp_provider->var_allowed_connection_types_for_update());
435 if (allowed_conn_types_p) {
436 if (allowed_conn_types_p->count(conn_type)) {
437 *result = true;
438 return EvalStatus::kSucceeded;
439 }
Gilad Arnold28d6be62014-06-30 14:04:04 -0700440 } else if (conn_type == ConnectionType::kCellular) {
441 // Local user settings can allow updates over cellular iff a policy was
442 // loaded but no allowed connections were specified in it.
443 const bool* update_over_cellular_allowed_p = ec->GetValue(
444 state->updater_provider()->var_cellular_enabled());
445 if (update_over_cellular_allowed_p && *update_over_cellular_allowed_p)
446 *result = true;
Gilad Arnolda8262e22014-06-02 13:54:27 -0700447 }
448 }
449 }
450
Gilad Arnold28d6be62014-06-30 14:04:04 -0700451 return (*result ? EvalStatus::kSucceeded : EvalStatus::kAskMeAgainLater);
Gilad Arnolda8262e22014-06-02 13:54:27 -0700452}
453
Alex Deymo0d11c602014-04-23 20:12:20 -0700454EvalStatus ChromeOSPolicy::NextUpdateCheckTime(EvaluationContext* ec,
455 State* state, string* error,
456 Time* next_update_check) const {
Gilad Arnolda0258a52014-07-10 16:21:19 -0700457 UpdaterProvider* const updater_provider = state->updater_provider();
458
Alex Deymo0d11c602014-04-23 20:12:20 -0700459 // Don't check for updates too often. We limit the update checks to once every
460 // some interval. The interval is kTimeoutInitialInterval the first time and
461 // kTimeoutPeriodicInterval for the subsequent update checks. If the update
462 // check fails, we increase the interval between the update checks
463 // exponentially until kTimeoutMaxBackoffInterval. Finally, to avoid having
464 // many chromebooks running update checks at the exact same time, we add some
465 // fuzz to the interval.
466 const Time* updater_started_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700467 ec->GetValue(updater_provider->var_updater_started_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700468 POLICY_CHECK_VALUE_AND_FAIL(updater_started_time, error);
469
470 const base::Time* last_checked_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700471 ec->GetValue(updater_provider->var_last_checked_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700472
473 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
474 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
475
476 PRNG prng(*seed);
477
Gilad Arnold38b14022014-07-09 12:45:56 -0700478 // If this is the first attempt, compute and return an initial value.
Alex Deymo0d11c602014-04-23 20:12:20 -0700479 if (!last_checked_time || *last_checked_time < *updater_started_time) {
Alex Deymo0d11c602014-04-23 20:12:20 -0700480 *next_update_check = *updater_started_time + FuzzedInterval(
481 &prng, kTimeoutInitialInterval, kTimeoutRegularFuzz);
482 return EvalStatus::kSucceeded;
483 }
Gilad Arnold38b14022014-07-09 12:45:56 -0700484
Gilad Arnolda0258a52014-07-10 16:21:19 -0700485 // Check whether the server is enforcing a poll interval; if not, this value
486 // will be zero.
487 const unsigned int* server_dictated_poll_interval = ec->GetValue(
488 updater_provider->var_server_dictated_poll_interval());
489 POLICY_CHECK_VALUE_AND_FAIL(server_dictated_poll_interval, error);
Alex Deymo0d11c602014-04-23 20:12:20 -0700490
Gilad Arnolda0258a52014-07-10 16:21:19 -0700491 int interval = *server_dictated_poll_interval;
492 int fuzz = 0;
493
Alex Vakulenko072359c2014-07-18 11:41:07 -0700494 // If no poll interval was dictated by server compute a back-off period,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700495 // starting from a predetermined base periodic interval and increasing
496 // exponentially by the number of consecutive failed attempts.
497 if (interval == 0) {
498 const unsigned int* consecutive_failed_update_checks = ec->GetValue(
499 updater_provider->var_consecutive_failed_update_checks());
500 POLICY_CHECK_VALUE_AND_FAIL(consecutive_failed_update_checks, error);
501
502 interval = kTimeoutPeriodicInterval;
503 unsigned int num_failures = *consecutive_failed_update_checks;
504 while (interval < kTimeoutMaxBackoffInterval && num_failures) {
505 interval *= 2;
506 num_failures--;
Alex Deymo0d11c602014-04-23 20:12:20 -0700507 }
508 }
509
Alex Vakulenko072359c2014-07-18 11:41:07 -0700510 // We cannot back off longer than the predetermined maximum interval.
Gilad Arnolda0258a52014-07-10 16:21:19 -0700511 if (interval > kTimeoutMaxBackoffInterval)
512 interval = kTimeoutMaxBackoffInterval;
513
Alex Vakulenko072359c2014-07-18 11:41:07 -0700514 // We cannot back off shorter than the predetermined periodic interval. Also,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700515 // in this case set the fuzz to a predetermined regular value.
516 if (interval <= kTimeoutPeriodicInterval) {
517 interval = kTimeoutPeriodicInterval;
518 fuzz = kTimeoutRegularFuzz;
519 }
520
521 // If not otherwise determined, defer to a fuzz of +/-(interval / 2).
Gilad Arnold38b14022014-07-09 12:45:56 -0700522 if (fuzz == 0)
523 fuzz = interval;
524
Alex Deymo0d11c602014-04-23 20:12:20 -0700525 *next_update_check = *last_checked_time + FuzzedInterval(
Gilad Arnold38b14022014-07-09 12:45:56 -0700526 &prng, interval, fuzz);
Alex Deymo0d11c602014-04-23 20:12:20 -0700527 return EvalStatus::kSucceeded;
528}
529
530TimeDelta ChromeOSPolicy::FuzzedInterval(PRNG* prng, int interval, int fuzz) {
Gilad Arnolde1218812014-05-07 12:21:36 -0700531 DCHECK_GE(interval, 0);
532 DCHECK_GE(fuzz, 0);
Alex Deymo0d11c602014-04-23 20:12:20 -0700533 int half_fuzz = fuzz / 2;
Alex Deymo0d11c602014-04-23 20:12:20 -0700534 // This guarantees the output interval is non negative.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700535 int interval_min = max(interval - half_fuzz, 0);
Gilad Arnolde1218812014-05-07 12:21:36 -0700536 int interval_max = interval + half_fuzz;
537 return TimeDelta::FromSeconds(prng->RandMinMax(interval_min, interval_max));
Alex Deymo0d11c602014-04-23 20:12:20 -0700538}
539
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700540EvalStatus ChromeOSPolicy::UpdateDownloadUrl(
541 EvaluationContext* ec, State* state, std::string* error,
542 UpdateDownloadUrlResult* result, const UpdateState& update_state) const {
543 int url_idx = 0;
544 int url_num_failures = 0;
545 if (update_state.num_checks > 1) {
546 // Ignore negative URL indexes, which indicate that no previous suitable
547 // download URL was found.
548 url_idx = max(0, update_state.download_url_idx);
549 url_num_failures = update_state.download_url_num_failures;
550 }
551
552 // Preconditions / sanity checks.
553 DCHECK_GE(update_state.download_failures_max, 0);
554 DCHECK_LT(url_idx, static_cast<int>(update_state.download_urls.size()));
555 DCHECK_LE(url_num_failures, update_state.download_failures_max);
556
557 // Determine whether HTTP downloads are forbidden by policy. This only
558 // applies to official system builds; otherwise, HTTP is always enabled.
559 bool http_allowed = true;
560 const bool* is_official_build_p = ec->GetValue(
561 state->system_provider()->var_is_official_build());
562 if (is_official_build_p && *is_official_build_p) {
563 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
564 const bool* device_policy_is_loaded_p = ec->GetValue(
565 dp_provider->var_device_policy_is_loaded());
566 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
567 const bool* policy_http_downloads_enabled_p = ec->GetValue(
568 dp_provider->var_http_downloads_enabled());
569 http_allowed = (!policy_http_downloads_enabled_p ||
570 *policy_http_downloads_enabled_p);
571 }
572 }
573
574 // Process recent failures, stop if the URL index advances.
575 for (auto& err_code : update_state.download_url_error_codes) {
576 if (HandleErrorCode(err_code, &url_idx, &url_num_failures))
577 break;
578 if (url_num_failures > update_state.download_failures_max) {
579 url_idx++;
580 url_num_failures = 0;
581 break;
582 }
583 }
584 url_idx %= update_state.download_urls.size();
585
586 // Scan through URLs until a usable one is found.
587 const int start_url_idx = url_idx;
588 while (!DownloadUrlIsUsable(update_state.download_urls[url_idx],
589 http_allowed)) {
590 url_idx = (url_idx + 1) % update_state.download_urls.size();
591 url_num_failures = 0;
592 if (url_idx == start_url_idx)
593 return EvalStatus::kFailed; // No usable URLs.
594 }
595
596 result->url_idx = url_idx;
597 result->url_num_failures = url_num_failures;
598 return EvalStatus::kSucceeded;
599}
600
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700601EvalStatus ChromeOSPolicy::UpdateScattering(
602 EvaluationContext* ec,
603 State* state,
604 string* error,
605 UpdateScatteringResult* result,
606 const UpdateState& update_state) const {
607 // Preconditions. These stem from the postconditions and usage contract.
608 DCHECK(update_state.scatter_wait_period >= kZeroInterval);
609 DCHECK_GE(update_state.scatter_check_threshold, 0);
610
611 // Set default result values.
612 result->is_scattering = false;
613 result->wait_period = kZeroInterval;
614 result->check_threshold = 0;
615
616 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
617
618 // Ensure that a device policy is loaded.
619 const bool* device_policy_is_loaded_p = ec->GetValue(
620 dp_provider->var_device_policy_is_loaded());
621 if (!(device_policy_is_loaded_p && *device_policy_is_loaded_p))
622 return EvalStatus::kSucceeded;
623
624 // Is scattering enabled by policy?
625 const TimeDelta* scatter_factor_p = ec->GetValue(
626 dp_provider->var_scatter_factor());
627 if (!scatter_factor_p || *scatter_factor_p == kZeroInterval)
628 return EvalStatus::kSucceeded;
629
630 // Obtain a pseudo-random number generator.
631 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
632 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
633 PRNG prng(*seed);
634
635 // Step 1: Maintain the scattering wait period.
636 //
637 // If no wait period was previously determined, or it no longer fits in the
638 // scatter factor, then generate a new one. Otherwise, keep the one we have.
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700639 TimeDelta wait_period = update_state.scatter_wait_period;
640 if (wait_period == kZeroInterval || wait_period > *scatter_factor_p) {
641 wait_period = TimeDelta::FromSeconds(
642 prng.RandMinMax(1, scatter_factor_p->InSeconds()));
643 }
644
645 // If we surpass the wait period or the max scatter period associated with
646 // the update, then no wait is needed.
647 Time wait_expires = (update_state.first_seen +
648 min(wait_period, update_state.scatter_wait_period_max));
Gilad Arnolda65fced2014-07-23 09:01:31 -0700649 if (ec->IsWallclockTimeGreaterThan(wait_expires))
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700650 wait_period = kZeroInterval;
651
652 // Step 2: Maintain the update check threshold count.
653 //
654 // If an update check threshold is not specified then generate a new
655 // one.
656 int check_threshold = update_state.scatter_check_threshold;
657 if (check_threshold == 0) {
658 check_threshold = prng.RandMinMax(
659 update_state.scatter_check_threshold_min,
660 update_state.scatter_check_threshold_max);
661 }
662
663 // If the update check threshold is not within allowed range then nullify it.
664 // TODO(garnold) This is compliant with current logic found in
665 // OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied(). We may want
666 // to change it so that it behaves similarly to the wait period case, namely
667 // if the current value exceeds the maximum, we set a new one within range.
668 if (check_threshold > update_state.scatter_check_threshold_max)
669 check_threshold = 0;
670
671 // If the update check threshold is non-zero and satisfied, then nullify it.
672 if (check_threshold > 0 && update_state.num_checks >= check_threshold)
673 check_threshold = 0;
674
675 bool is_scattering = (wait_period != kZeroInterval || check_threshold);
676 EvalStatus ret = EvalStatus::kSucceeded;
677 if (is_scattering && wait_period == update_state.scatter_wait_period &&
678 check_threshold == update_state.scatter_check_threshold)
679 ret = EvalStatus::kAskMeAgainLater;
680 result->is_scattering = is_scattering;
681 result->wait_period = wait_period;
682 result->check_threshold = check_threshold;
683 return ret;
684}
685
Alex Deymo63784a52014-05-28 10:46:14 -0700686} // namespace chromeos_update_manager