blob: 7032074e7bbfc8bb4dcf88564e66e903b245e3a9 [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:
118 LOG(INFO) << "Not changing URL index or failure count due to error "
119 << chromeos_update_engine::utils::CodeToString(err_code)
120 << " (" << static_cast<int>(err_code) << ")";
121 return false;
122
123 case ErrorCode::kSuccess: // success code
124 case ErrorCode::kUmaReportedMax: // not an error code
125 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
126 case ErrorCode::kDevModeFlag: // not an error code
127 case ErrorCode::kResumedFlag: // not an error code
128 case ErrorCode::kTestImageFlag: // not an error code
129 case ErrorCode::kTestOmahaUrlFlag: // not an error code
130 case ErrorCode::kSpecialFlags: // not an error code
131 // These shouldn't happen. Enumerating these explicitly here so that we
132 // can let the compiler warn about new error codes that are added to
133 // action_processor.h but not added here.
134 LOG(WARNING) << "Unexpected error "
135 << chromeos_update_engine::utils::CodeToString(err_code)
136 << " (" << static_cast<int>(err_code) << ")";
137 // Note: Not adding a default here so as to let the compiler warn us of
138 // any new enums that were added in the .h but not listed in this switch.
139 }
140 return false;
141}
142
143// Checks whether |download_url| can be used under given download restrictions.
144bool DownloadUrlIsUsable(const string& download_url, bool http_allowed) {
145 return http_allowed || !StartsWithASCII(download_url, "http://", false);
146}
147
148} // namespace
149
Alex Deymo63784a52014-05-28 10:46:14 -0700150namespace chromeos_update_manager {
Alex Deymoc705cc82014-02-19 11:15:00 -0800151
Alex Deymo0d11c602014-04-23 20:12:20 -0700152EvalStatus ChromeOSPolicy::UpdateCheckAllowed(
153 EvaluationContext* ec, State* state, string* error,
154 UpdateCheckParams* result) const {
Gilad Arnold42f253b2014-06-25 12:39:17 -0700155 // Set the default return values.
156 result->updates_enabled = true;
157 result->target_channel.clear();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700158 result->is_interactive = false;
Gilad Arnold42f253b2014-06-25 12:39:17 -0700159
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700160 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700161 UpdaterProvider* const updater_provider = state->updater_provider();
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700162 SystemProvider* const system_provider = state->system_provider();
163
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700164 // Do not perform any updates if booted from removable device. This decision
165 // is final.
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700166 const bool* is_boot_device_removable_p = ec->GetValue(
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700167 system_provider->var_is_boot_device_removable());
Gilad Arnoldbfc44f72014-07-09 14:41:39 -0700168 if (is_boot_device_removable_p && *is_boot_device_removable_p) {
169 result->updates_enabled = false;
170 return EvalStatus::kSucceeded;
171 }
172
Gilad Arnold42f253b2014-06-25 12:39:17 -0700173 const bool* device_policy_is_loaded_p = ec->GetValue(
174 dp_provider->var_device_policy_is_loaded());
175 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
176 // Check whether updates are disabled by policy.
177 const bool* update_disabled_p = ec->GetValue(
178 dp_provider->var_update_disabled());
Gilad Arnolda1eabcd2014-07-09 15:42:40 -0700179 if (update_disabled_p && *update_disabled_p)
Gilad Arnold42f253b2014-06-25 12:39:17 -0700180 return EvalStatus::kAskMeAgainLater;
Gilad Arnold42f253b2014-06-25 12:39:17 -0700181
182 // Determine whether a target channel is dictated by policy.
183 const bool* release_channel_delegated_p = ec->GetValue(
184 dp_provider->var_release_channel_delegated());
185 if (release_channel_delegated_p && !(*release_channel_delegated_p)) {
186 const string* release_channel_p = ec->GetValue(
187 dp_provider->var_release_channel());
188 if (release_channel_p)
189 result->target_channel = *release_channel_p;
190 }
191 }
192
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700193 // First, check to see if an interactive update was requested.
194 const bool* interactive_update_requested_p = ec->GetValue(
195 updater_provider->var_interactive_update_requested());
196 if (interactive_update_requested_p && *interactive_update_requested_p) {
197 result->is_interactive = true;
198 return EvalStatus::kSucceeded;
199 }
200
201 // The logic thereafter applies to periodic updates. Bear in mind that we
202 // should not return a final "no" if any of these criteria are not satisfied,
203 // because the system may still update due to an interactive update request.
204
205 // Unofficial builds should not perform periodic update checks.
206 const bool* is_official_build_p = ec->GetValue(
207 system_provider->var_is_official_build());
208 if (is_official_build_p && !(*is_official_build_p)) {
209 return EvalStatus::kAskMeAgainLater;
210 }
211
212 // If OOBE is enabled, wait until it is completed.
213 const bool* is_oobe_enabled_p = ec->GetValue(
214 state->config_provider()->var_is_oobe_enabled());
215 if (is_oobe_enabled_p && *is_oobe_enabled_p) {
216 const bool* is_oobe_complete_p = ec->GetValue(
217 system_provider->var_is_oobe_complete());
218 if (is_oobe_complete_p && !(*is_oobe_complete_p))
219 return EvalStatus::kAskMeAgainLater;
220 }
221
222 // Ensure that periodic update checks are timed properly.
Alex Deymo0d11c602014-04-23 20:12:20 -0700223 Time next_update_check;
224 if (NextUpdateCheckTime(ec, state, error, &next_update_check) !=
225 EvalStatus::kSucceeded) {
226 return EvalStatus::kFailed;
227 }
Gilad Arnolda65fced2014-07-23 09:01:31 -0700228 if (!ec->IsWallclockTimeGreaterThan(next_update_check))
Alex Deymo0d11c602014-04-23 20:12:20 -0700229 return EvalStatus::kAskMeAgainLater;
230
231 // It is time to check for an update.
Alex Deymoe636c3c2014-03-11 19:02:08 -0700232 return EvalStatus::kSucceeded;
Alex Deymoc705cc82014-02-19 11:15:00 -0800233}
234
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700235EvalStatus ChromeOSPolicy::UpdateCanStart(
236 EvaluationContext* ec,
237 State* state,
238 string* error,
Gilad Arnold42f253b2014-06-25 12:39:17 -0700239 UpdateDownloadParams* result,
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700240 const bool interactive,
241 const UpdateState& update_state) const {
242 // Set the default return values.
243 result->update_can_start = true;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700244 result->p2p_allowed = false;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700245 result->cannot_start_reason = UpdateCannotStartReason::kUndefined;
246 result->scatter_wait_period = kZeroInterval;
247 result->scatter_check_threshold = 0;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700248 result->download_url_idx = -1;
249 result->download_url_num_failures = 0;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700250
251 // Make sure that we're not due for an update check.
252 UpdateCheckParams check_result;
253 EvalStatus check_status = UpdateCheckAllowed(ec, state, error, &check_result);
254 if (check_status == EvalStatus::kFailed)
255 return EvalStatus::kFailed;
256 if (check_status == EvalStatus::kSucceeded &&
257 check_result.updates_enabled == true) {
258 result->update_can_start = false;
259 result->cannot_start_reason = UpdateCannotStartReason::kCheckDue;
260 return EvalStatus::kSucceeded;
261 }
262
263 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
264
265 const bool* device_policy_is_loaded_p = ec->GetValue(
266 dp_provider->var_device_policy_is_loaded());
267 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700268 // Check whether scattering applies to this update attempt. We should not be
269 // scattering if this is an interactive update check, or if OOBE is enabled
270 // but not completed.
271 //
272 // Note: current code further suppresses scattering if a "deadline"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700273 // attribute is found in the Omaha response. However, it appears that the
Gilad Arnold76a11f62014-05-20 09:02:12 -0700274 // presence of this attribute is merely indicative of an OOBE update, during
275 // which we suppress scattering anyway.
276 bool scattering_applies = false;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700277 if (!interactive) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700278 const bool* is_oobe_enabled_p = ec->GetValue(
279 state->config_provider()->var_is_oobe_enabled());
280 if (is_oobe_enabled_p && !(*is_oobe_enabled_p)) {
281 scattering_applies = true;
282 } else {
283 const bool* is_oobe_complete_p = ec->GetValue(
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700284 state->system_provider()->var_is_oobe_complete());
Gilad Arnold76a11f62014-05-20 09:02:12 -0700285 scattering_applies = (is_oobe_complete_p && *is_oobe_complete_p);
286 }
287 }
288
289 // Compute scattering values.
290 if (scattering_applies) {
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700291 UpdateScatteringResult scatter_result;
292 EvalStatus scattering_status = UpdateScattering(
293 ec, state, error, &scatter_result, update_state);
294 if (scattering_status != EvalStatus::kSucceeded ||
295 scatter_result.is_scattering) {
296 if (scattering_status != EvalStatus::kFailed) {
297 result->update_can_start = false;
298 result->cannot_start_reason = UpdateCannotStartReason::kScattering;
299 result->scatter_wait_period = scatter_result.wait_period;
300 result->scatter_check_threshold = scatter_result.check_threshold;
301 }
302 return scattering_status;
303 }
304 }
305
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700306 // Determine whether use of P2P is allowed by policy.
307 const bool* policy_au_p2p_enabled_p = ec->GetValue(
308 dp_provider->var_au_p2p_enabled());
309 result->p2p_allowed = policy_au_p2p_enabled_p && *policy_au_p2p_enabled_p;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700310 }
311
312 // Enable P2P, if so mandated by the updater configuration.
313 if (!result->p2p_allowed) {
314 const bool* updater_p2p_enabled_p = ec->GetValue(
315 state->updater_provider()->var_p2p_enabled());
316 result->p2p_allowed = updater_p2p_enabled_p && *updater_p2p_enabled_p;
317 }
318
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700319 // Determine the URL to download the update from. Note that a failure to find
320 // a download URL will only fail this policy iff no other means of download
321 // (such as P2P) are enabled.
322 UpdateDownloadUrlResult download_url_result;
323 EvalStatus download_url_status = UpdateDownloadUrl(
324 ec, state, error, &download_url_result, update_state);
325 if (download_url_status == EvalStatus::kSucceeded) {
326 result->download_url_idx = download_url_result.url_idx;
327 result->download_url_num_failures = download_url_result.url_num_failures;
328 } else if (!result->p2p_allowed) {
329 if (download_url_status != EvalStatus::kFailed) {
330 result->update_can_start = false;
331 result->cannot_start_reason = UpdateCannotStartReason::kCannotDownload;
332 }
333 return download_url_status;
334 }
335
Gilad Arnoldaf2f6ae2014-04-28 14:14:52 -0700336 return EvalStatus::kSucceeded;
337}
338
Gilad Arnolda8262e22014-06-02 13:54:27 -0700339// TODO(garnold) Logic in this method is based on
340// ConnectionManager::IsUpdateAllowedOver(); be sure to deprecate the latter.
341//
342// TODO(garnold) The current logic generally treats the list of allowed
343// connections coming from the device policy as a whitelist, meaning that it
344// can only be used for enabling connections, but not disable them. Further,
345// certain connection types (like Bluetooth) cannot be enabled even by policy.
346// In effect, the only thing that device policy can change is to enable
347// updates over a cellular network (disabled by default). We may want to
348// revisit this semantics, allowing greater flexibility in defining specific
349// permissions over all types of networks.
Gilad Arnold684219d2014-07-07 14:54:57 -0700350EvalStatus ChromeOSPolicy::UpdateDownloadAllowed(
Gilad Arnolda8262e22014-06-02 13:54:27 -0700351 EvaluationContext* ec,
352 State* state,
353 string* error,
354 bool* result) const {
355 // Get the current connection type.
356 ShillProvider* const shill_provider = state->shill_provider();
357 const ConnectionType* conn_type_p = ec->GetValue(
358 shill_provider->var_conn_type());
359 POLICY_CHECK_VALUE_AND_FAIL(conn_type_p, error);
360 ConnectionType conn_type = *conn_type_p;
361
362 // If we're tethering, treat it as a cellular connection.
363 if (conn_type != ConnectionType::kCellular) {
364 const ConnectionTethering* conn_tethering_p = ec->GetValue(
365 shill_provider->var_conn_tethering());
366 POLICY_CHECK_VALUE_AND_FAIL(conn_tethering_p, error);
367 if (*conn_tethering_p == ConnectionTethering::kConfirmed)
368 conn_type = ConnectionType::kCellular;
369 }
370
371 // By default, we allow updates for all connection types, with exceptions as
372 // noted below. This also determines whether a device policy can override the
373 // default.
374 *result = true;
375 bool device_policy_can_override = false;
376 switch (conn_type) {
377 case ConnectionType::kBluetooth:
378 *result = false;
379 break;
380
381 case ConnectionType::kCellular:
382 *result = false;
383 device_policy_can_override = true;
384 break;
385
386 case ConnectionType::kUnknown:
387 if (error)
388 *error = "Unknown connection type";
389 return EvalStatus::kFailed;
390
391 default:
392 break; // Nothing to do.
393 }
394
395 // If update is allowed, we're done.
396 if (*result)
397 return EvalStatus::kSucceeded;
398
399 // Check whether the device policy specifically allows this connection.
Gilad Arnolda8262e22014-06-02 13:54:27 -0700400 if (device_policy_can_override) {
401 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
402 const bool* device_policy_is_loaded_p = ec->GetValue(
403 dp_provider->var_device_policy_is_loaded());
404 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
405 const set<ConnectionType>* allowed_conn_types_p = ec->GetValue(
406 dp_provider->var_allowed_connection_types_for_update());
407 if (allowed_conn_types_p) {
408 if (allowed_conn_types_p->count(conn_type)) {
409 *result = true;
410 return EvalStatus::kSucceeded;
411 }
Gilad Arnold28d6be62014-06-30 14:04:04 -0700412 } else if (conn_type == ConnectionType::kCellular) {
413 // Local user settings can allow updates over cellular iff a policy was
414 // loaded but no allowed connections were specified in it.
415 const bool* update_over_cellular_allowed_p = ec->GetValue(
416 state->updater_provider()->var_cellular_enabled());
417 if (update_over_cellular_allowed_p && *update_over_cellular_allowed_p)
418 *result = true;
Gilad Arnolda8262e22014-06-02 13:54:27 -0700419 }
420 }
421 }
422
Gilad Arnold28d6be62014-06-30 14:04:04 -0700423 return (*result ? EvalStatus::kSucceeded : EvalStatus::kAskMeAgainLater);
Gilad Arnolda8262e22014-06-02 13:54:27 -0700424}
425
Alex Deymo0d11c602014-04-23 20:12:20 -0700426EvalStatus ChromeOSPolicy::NextUpdateCheckTime(EvaluationContext* ec,
427 State* state, string* error,
428 Time* next_update_check) const {
Gilad Arnolda0258a52014-07-10 16:21:19 -0700429 UpdaterProvider* const updater_provider = state->updater_provider();
430
Alex Deymo0d11c602014-04-23 20:12:20 -0700431 // Don't check for updates too often. We limit the update checks to once every
432 // some interval. The interval is kTimeoutInitialInterval the first time and
433 // kTimeoutPeriodicInterval for the subsequent update checks. If the update
434 // check fails, we increase the interval between the update checks
435 // exponentially until kTimeoutMaxBackoffInterval. Finally, to avoid having
436 // many chromebooks running update checks at the exact same time, we add some
437 // fuzz to the interval.
438 const Time* updater_started_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700439 ec->GetValue(updater_provider->var_updater_started_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700440 POLICY_CHECK_VALUE_AND_FAIL(updater_started_time, error);
441
442 const base::Time* last_checked_time =
Gilad Arnolda0258a52014-07-10 16:21:19 -0700443 ec->GetValue(updater_provider->var_last_checked_time());
Alex Deymo0d11c602014-04-23 20:12:20 -0700444
445 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
446 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
447
448 PRNG prng(*seed);
449
Gilad Arnold38b14022014-07-09 12:45:56 -0700450 // If this is the first attempt, compute and return an initial value.
Alex Deymo0d11c602014-04-23 20:12:20 -0700451 if (!last_checked_time || *last_checked_time < *updater_started_time) {
Alex Deymo0d11c602014-04-23 20:12:20 -0700452 *next_update_check = *updater_started_time + FuzzedInterval(
453 &prng, kTimeoutInitialInterval, kTimeoutRegularFuzz);
454 return EvalStatus::kSucceeded;
455 }
Gilad Arnold38b14022014-07-09 12:45:56 -0700456
Gilad Arnolda0258a52014-07-10 16:21:19 -0700457 // Check whether the server is enforcing a poll interval; if not, this value
458 // will be zero.
459 const unsigned int* server_dictated_poll_interval = ec->GetValue(
460 updater_provider->var_server_dictated_poll_interval());
461 POLICY_CHECK_VALUE_AND_FAIL(server_dictated_poll_interval, error);
Alex Deymo0d11c602014-04-23 20:12:20 -0700462
Gilad Arnolda0258a52014-07-10 16:21:19 -0700463 int interval = *server_dictated_poll_interval;
464 int fuzz = 0;
465
Alex Vakulenko072359c2014-07-18 11:41:07 -0700466 // If no poll interval was dictated by server compute a back-off period,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700467 // starting from a predetermined base periodic interval and increasing
468 // exponentially by the number of consecutive failed attempts.
469 if (interval == 0) {
470 const unsigned int* consecutive_failed_update_checks = ec->GetValue(
471 updater_provider->var_consecutive_failed_update_checks());
472 POLICY_CHECK_VALUE_AND_FAIL(consecutive_failed_update_checks, error);
473
474 interval = kTimeoutPeriodicInterval;
475 unsigned int num_failures = *consecutive_failed_update_checks;
476 while (interval < kTimeoutMaxBackoffInterval && num_failures) {
477 interval *= 2;
478 num_failures--;
Alex Deymo0d11c602014-04-23 20:12:20 -0700479 }
480 }
481
Alex Vakulenko072359c2014-07-18 11:41:07 -0700482 // We cannot back off longer than the predetermined maximum interval.
Gilad Arnolda0258a52014-07-10 16:21:19 -0700483 if (interval > kTimeoutMaxBackoffInterval)
484 interval = kTimeoutMaxBackoffInterval;
485
Alex Vakulenko072359c2014-07-18 11:41:07 -0700486 // We cannot back off shorter than the predetermined periodic interval. Also,
Gilad Arnolda0258a52014-07-10 16:21:19 -0700487 // in this case set the fuzz to a predetermined regular value.
488 if (interval <= kTimeoutPeriodicInterval) {
489 interval = kTimeoutPeriodicInterval;
490 fuzz = kTimeoutRegularFuzz;
491 }
492
493 // If not otherwise determined, defer to a fuzz of +/-(interval / 2).
Gilad Arnold38b14022014-07-09 12:45:56 -0700494 if (fuzz == 0)
495 fuzz = interval;
496
Alex Deymo0d11c602014-04-23 20:12:20 -0700497 *next_update_check = *last_checked_time + FuzzedInterval(
Gilad Arnold38b14022014-07-09 12:45:56 -0700498 &prng, interval, fuzz);
Alex Deymo0d11c602014-04-23 20:12:20 -0700499 return EvalStatus::kSucceeded;
500}
501
502TimeDelta ChromeOSPolicy::FuzzedInterval(PRNG* prng, int interval, int fuzz) {
Gilad Arnolde1218812014-05-07 12:21:36 -0700503 DCHECK_GE(interval, 0);
504 DCHECK_GE(fuzz, 0);
Alex Deymo0d11c602014-04-23 20:12:20 -0700505 int half_fuzz = fuzz / 2;
Alex Deymo0d11c602014-04-23 20:12:20 -0700506 // This guarantees the output interval is non negative.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700507 int interval_min = max(interval - half_fuzz, 0);
Gilad Arnolde1218812014-05-07 12:21:36 -0700508 int interval_max = interval + half_fuzz;
509 return TimeDelta::FromSeconds(prng->RandMinMax(interval_min, interval_max));
Alex Deymo0d11c602014-04-23 20:12:20 -0700510}
511
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700512EvalStatus ChromeOSPolicy::UpdateDownloadUrl(
513 EvaluationContext* ec, State* state, std::string* error,
514 UpdateDownloadUrlResult* result, const UpdateState& update_state) const {
515 int url_idx = 0;
516 int url_num_failures = 0;
517 if (update_state.num_checks > 1) {
518 // Ignore negative URL indexes, which indicate that no previous suitable
519 // download URL was found.
520 url_idx = max(0, update_state.download_url_idx);
521 url_num_failures = update_state.download_url_num_failures;
522 }
523
524 // Preconditions / sanity checks.
525 DCHECK_GE(update_state.download_failures_max, 0);
526 DCHECK_LT(url_idx, static_cast<int>(update_state.download_urls.size()));
527 DCHECK_LE(url_num_failures, update_state.download_failures_max);
528
529 // Determine whether HTTP downloads are forbidden by policy. This only
530 // applies to official system builds; otherwise, HTTP is always enabled.
531 bool http_allowed = true;
532 const bool* is_official_build_p = ec->GetValue(
533 state->system_provider()->var_is_official_build());
534 if (is_official_build_p && *is_official_build_p) {
535 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
536 const bool* device_policy_is_loaded_p = ec->GetValue(
537 dp_provider->var_device_policy_is_loaded());
538 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
539 const bool* policy_http_downloads_enabled_p = ec->GetValue(
540 dp_provider->var_http_downloads_enabled());
541 http_allowed = (!policy_http_downloads_enabled_p ||
542 *policy_http_downloads_enabled_p);
543 }
544 }
545
546 // Process recent failures, stop if the URL index advances.
547 for (auto& err_code : update_state.download_url_error_codes) {
548 if (HandleErrorCode(err_code, &url_idx, &url_num_failures))
549 break;
550 if (url_num_failures > update_state.download_failures_max) {
551 url_idx++;
552 url_num_failures = 0;
553 break;
554 }
555 }
556 url_idx %= update_state.download_urls.size();
557
558 // Scan through URLs until a usable one is found.
559 const int start_url_idx = url_idx;
560 while (!DownloadUrlIsUsable(update_state.download_urls[url_idx],
561 http_allowed)) {
562 url_idx = (url_idx + 1) % update_state.download_urls.size();
563 url_num_failures = 0;
564 if (url_idx == start_url_idx)
565 return EvalStatus::kFailed; // No usable URLs.
566 }
567
568 result->url_idx = url_idx;
569 result->url_num_failures = url_num_failures;
570 return EvalStatus::kSucceeded;
571}
572
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700573EvalStatus ChromeOSPolicy::UpdateScattering(
574 EvaluationContext* ec,
575 State* state,
576 string* error,
577 UpdateScatteringResult* result,
578 const UpdateState& update_state) const {
579 // Preconditions. These stem from the postconditions and usage contract.
580 DCHECK(update_state.scatter_wait_period >= kZeroInterval);
581 DCHECK_GE(update_state.scatter_check_threshold, 0);
582
583 // Set default result values.
584 result->is_scattering = false;
585 result->wait_period = kZeroInterval;
586 result->check_threshold = 0;
587
588 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
589
590 // Ensure that a device policy is loaded.
591 const bool* device_policy_is_loaded_p = ec->GetValue(
592 dp_provider->var_device_policy_is_loaded());
593 if (!(device_policy_is_loaded_p && *device_policy_is_loaded_p))
594 return EvalStatus::kSucceeded;
595
596 // Is scattering enabled by policy?
597 const TimeDelta* scatter_factor_p = ec->GetValue(
598 dp_provider->var_scatter_factor());
599 if (!scatter_factor_p || *scatter_factor_p == kZeroInterval)
600 return EvalStatus::kSucceeded;
601
602 // Obtain a pseudo-random number generator.
603 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
604 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
605 PRNG prng(*seed);
606
607 // Step 1: Maintain the scattering wait period.
608 //
609 // If no wait period was previously determined, or it no longer fits in the
610 // scatter factor, then generate a new one. Otherwise, keep the one we have.
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700611 TimeDelta wait_period = update_state.scatter_wait_period;
612 if (wait_period == kZeroInterval || wait_period > *scatter_factor_p) {
613 wait_period = TimeDelta::FromSeconds(
614 prng.RandMinMax(1, scatter_factor_p->InSeconds()));
615 }
616
617 // If we surpass the wait period or the max scatter period associated with
618 // the update, then no wait is needed.
619 Time wait_expires = (update_state.first_seen +
620 min(wait_period, update_state.scatter_wait_period_max));
Gilad Arnolda65fced2014-07-23 09:01:31 -0700621 if (ec->IsWallclockTimeGreaterThan(wait_expires))
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700622 wait_period = kZeroInterval;
623
624 // Step 2: Maintain the update check threshold count.
625 //
626 // If an update check threshold is not specified then generate a new
627 // one.
628 int check_threshold = update_state.scatter_check_threshold;
629 if (check_threshold == 0) {
630 check_threshold = prng.RandMinMax(
631 update_state.scatter_check_threshold_min,
632 update_state.scatter_check_threshold_max);
633 }
634
635 // If the update check threshold is not within allowed range then nullify it.
636 // TODO(garnold) This is compliant with current logic found in
637 // OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied(). We may want
638 // to change it so that it behaves similarly to the wait period case, namely
639 // if the current value exceeds the maximum, we set a new one within range.
640 if (check_threshold > update_state.scatter_check_threshold_max)
641 check_threshold = 0;
642
643 // If the update check threshold is non-zero and satisfied, then nullify it.
644 if (check_threshold > 0 && update_state.num_checks >= check_threshold)
645 check_threshold = 0;
646
647 bool is_scattering = (wait_period != kZeroInterval || check_threshold);
648 EvalStatus ret = EvalStatus::kSucceeded;
649 if (is_scattering && wait_period == update_state.scatter_wait_period &&
650 check_threshold == update_state.scatter_check_threshold)
651 ret = EvalStatus::kAskMeAgainLater;
652 result->is_scattering = is_scattering;
653 result->wait_period = wait_period;
654 result->check_threshold = check_threshold;
655 return ret;
656}
657
Alex Deymo63784a52014-05-28 10:46:14 -0700658} // namespace chromeos_update_manager