blob: fd2f8823edc59b8ca8e9a0425e15b0e5970b3421 [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
78 // a internet URL and thus could be more expensive).
79 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
97 // of the backoff at the next update check.
98 // 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();
158
Gilad Arnoldfe12a0f2014-07-09 14:26:57 -0700159 // Unofficial builds should not perform any automatic update checks.
160 const bool* is_official_build_p = ec->GetValue(
161 state->system_provider()->var_is_official_build());
162 if (is_official_build_p && !(*is_official_build_p)) {
163 result->updates_enabled = false;
164 return EvalStatus::kSucceeded;
165 }
166
Gilad Arnold42f253b2014-06-25 12:39:17 -0700167 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
168
169 const bool* device_policy_is_loaded_p = ec->GetValue(
170 dp_provider->var_device_policy_is_loaded());
171 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
172 // Check whether updates are disabled by policy.
173 const bool* update_disabled_p = ec->GetValue(
174 dp_provider->var_update_disabled());
175 if (update_disabled_p && *update_disabled_p) {
176 result->updates_enabled = false;
177 return EvalStatus::kAskMeAgainLater;
178 }
179
180 // Determine whether a target channel is dictated by policy.
181 const bool* release_channel_delegated_p = ec->GetValue(
182 dp_provider->var_release_channel_delegated());
183 if (release_channel_delegated_p && !(*release_channel_delegated_p)) {
184 const string* release_channel_p = ec->GetValue(
185 dp_provider->var_release_channel());
186 if (release_channel_p)
187 result->target_channel = *release_channel_p;
188 }
189 }
190
191 // Ensure that update checks are timed properly.
Alex Deymo0d11c602014-04-23 20:12:20 -0700192 Time next_update_check;
193 if (NextUpdateCheckTime(ec, state, error, &next_update_check) !=
194 EvalStatus::kSucceeded) {
195 return EvalStatus::kFailed;
196 }
Alex Deymo0d11c602014-04-23 20:12:20 -0700197 if (!ec->IsTimeGreaterThan(next_update_check))
198 return EvalStatus::kAskMeAgainLater;
199
200 // It is time to check for an update.
Alex Deymoe636c3c2014-03-11 19:02:08 -0700201 return EvalStatus::kSucceeded;
Alex Deymoc705cc82014-02-19 11:15:00 -0800202}
203
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700204EvalStatus ChromeOSPolicy::UpdateCanStart(
205 EvaluationContext* ec,
206 State* state,
207 string* error,
Gilad Arnold42f253b2014-06-25 12:39:17 -0700208 UpdateDownloadParams* result,
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700209 const bool interactive,
210 const UpdateState& update_state) const {
211 // Set the default return values.
212 result->update_can_start = true;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700213 result->p2p_allowed = false;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700214 result->cannot_start_reason = UpdateCannotStartReason::kUndefined;
215 result->scatter_wait_period = kZeroInterval;
216 result->scatter_check_threshold = 0;
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700217 result->download_url_idx = -1;
218 result->download_url_num_failures = 0;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700219
220 // Make sure that we're not due for an update check.
221 UpdateCheckParams check_result;
222 EvalStatus check_status = UpdateCheckAllowed(ec, state, error, &check_result);
223 if (check_status == EvalStatus::kFailed)
224 return EvalStatus::kFailed;
225 if (check_status == EvalStatus::kSucceeded &&
226 check_result.updates_enabled == true) {
227 result->update_can_start = false;
228 result->cannot_start_reason = UpdateCannotStartReason::kCheckDue;
229 return EvalStatus::kSucceeded;
230 }
231
232 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
233
234 const bool* device_policy_is_loaded_p = ec->GetValue(
235 dp_provider->var_device_policy_is_loaded());
236 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700237 // Check whether scattering applies to this update attempt. We should not be
238 // scattering if this is an interactive update check, or if OOBE is enabled
239 // but not completed.
240 //
241 // Note: current code further suppresses scattering if a "deadline"
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700242 // attribute is found in the Omaha response. However, it appears that the
Gilad Arnold76a11f62014-05-20 09:02:12 -0700243 // presence of this attribute is merely indicative of an OOBE update, during
244 // which we suppress scattering anyway.
245 bool scattering_applies = false;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700246 if (!interactive) {
Gilad Arnold76a11f62014-05-20 09:02:12 -0700247 const bool* is_oobe_enabled_p = ec->GetValue(
248 state->config_provider()->var_is_oobe_enabled());
249 if (is_oobe_enabled_p && !(*is_oobe_enabled_p)) {
250 scattering_applies = true;
251 } else {
252 const bool* is_oobe_complete_p = ec->GetValue(
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700253 state->system_provider()->var_is_oobe_complete());
Gilad Arnold76a11f62014-05-20 09:02:12 -0700254 scattering_applies = (is_oobe_complete_p && *is_oobe_complete_p);
255 }
256 }
257
258 // Compute scattering values.
259 if (scattering_applies) {
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700260 UpdateScatteringResult scatter_result;
261 EvalStatus scattering_status = UpdateScattering(
262 ec, state, error, &scatter_result, update_state);
263 if (scattering_status != EvalStatus::kSucceeded ||
264 scatter_result.is_scattering) {
265 if (scattering_status != EvalStatus::kFailed) {
266 result->update_can_start = false;
267 result->cannot_start_reason = UpdateCannotStartReason::kScattering;
268 result->scatter_wait_period = scatter_result.wait_period;
269 result->scatter_check_threshold = scatter_result.check_threshold;
270 }
271 return scattering_status;
272 }
273 }
274
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700275 // Determine whether use of P2P is allowed by policy.
276 const bool* policy_au_p2p_enabled_p = ec->GetValue(
277 dp_provider->var_au_p2p_enabled());
278 result->p2p_allowed = policy_au_p2p_enabled_p && *policy_au_p2p_enabled_p;
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700279 }
280
281 // Enable P2P, if so mandated by the updater configuration.
282 if (!result->p2p_allowed) {
283 const bool* updater_p2p_enabled_p = ec->GetValue(
284 state->updater_provider()->var_p2p_enabled());
285 result->p2p_allowed = updater_p2p_enabled_p && *updater_p2p_enabled_p;
286 }
287
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700288 // Determine the URL to download the update from. Note that a failure to find
289 // a download URL will only fail this policy iff no other means of download
290 // (such as P2P) are enabled.
291 UpdateDownloadUrlResult download_url_result;
292 EvalStatus download_url_status = UpdateDownloadUrl(
293 ec, state, error, &download_url_result, update_state);
294 if (download_url_status == EvalStatus::kSucceeded) {
295 result->download_url_idx = download_url_result.url_idx;
296 result->download_url_num_failures = download_url_result.url_num_failures;
297 } else if (!result->p2p_allowed) {
298 if (download_url_status != EvalStatus::kFailed) {
299 result->update_can_start = false;
300 result->cannot_start_reason = UpdateCannotStartReason::kCannotDownload;
301 }
302 return download_url_status;
303 }
304
Gilad Arnoldaf2f6ae2014-04-28 14:14:52 -0700305 return EvalStatus::kSucceeded;
306}
307
Gilad Arnolda8262e22014-06-02 13:54:27 -0700308// TODO(garnold) Logic in this method is based on
309// ConnectionManager::IsUpdateAllowedOver(); be sure to deprecate the latter.
310//
311// TODO(garnold) The current logic generally treats the list of allowed
312// connections coming from the device policy as a whitelist, meaning that it
313// can only be used for enabling connections, but not disable them. Further,
314// certain connection types (like Bluetooth) cannot be enabled even by policy.
315// In effect, the only thing that device policy can change is to enable
316// updates over a cellular network (disabled by default). We may want to
317// revisit this semantics, allowing greater flexibility in defining specific
318// permissions over all types of networks.
Gilad Arnold684219d2014-07-07 14:54:57 -0700319EvalStatus ChromeOSPolicy::UpdateDownloadAllowed(
Gilad Arnolda8262e22014-06-02 13:54:27 -0700320 EvaluationContext* ec,
321 State* state,
322 string* error,
323 bool* result) const {
324 // Get the current connection type.
325 ShillProvider* const shill_provider = state->shill_provider();
326 const ConnectionType* conn_type_p = ec->GetValue(
327 shill_provider->var_conn_type());
328 POLICY_CHECK_VALUE_AND_FAIL(conn_type_p, error);
329 ConnectionType conn_type = *conn_type_p;
330
331 // If we're tethering, treat it as a cellular connection.
332 if (conn_type != ConnectionType::kCellular) {
333 const ConnectionTethering* conn_tethering_p = ec->GetValue(
334 shill_provider->var_conn_tethering());
335 POLICY_CHECK_VALUE_AND_FAIL(conn_tethering_p, error);
336 if (*conn_tethering_p == ConnectionTethering::kConfirmed)
337 conn_type = ConnectionType::kCellular;
338 }
339
340 // By default, we allow updates for all connection types, with exceptions as
341 // noted below. This also determines whether a device policy can override the
342 // default.
343 *result = true;
344 bool device_policy_can_override = false;
345 switch (conn_type) {
346 case ConnectionType::kBluetooth:
347 *result = false;
348 break;
349
350 case ConnectionType::kCellular:
351 *result = false;
352 device_policy_can_override = true;
353 break;
354
355 case ConnectionType::kUnknown:
356 if (error)
357 *error = "Unknown connection type";
358 return EvalStatus::kFailed;
359
360 default:
361 break; // Nothing to do.
362 }
363
364 // If update is allowed, we're done.
365 if (*result)
366 return EvalStatus::kSucceeded;
367
368 // Check whether the device policy specifically allows this connection.
Gilad Arnolda8262e22014-06-02 13:54:27 -0700369 if (device_policy_can_override) {
370 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
371 const bool* device_policy_is_loaded_p = ec->GetValue(
372 dp_provider->var_device_policy_is_loaded());
373 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
374 const set<ConnectionType>* allowed_conn_types_p = ec->GetValue(
375 dp_provider->var_allowed_connection_types_for_update());
376 if (allowed_conn_types_p) {
377 if (allowed_conn_types_p->count(conn_type)) {
378 *result = true;
379 return EvalStatus::kSucceeded;
380 }
Gilad Arnold28d6be62014-06-30 14:04:04 -0700381 } else if (conn_type == ConnectionType::kCellular) {
382 // Local user settings can allow updates over cellular iff a policy was
383 // loaded but no allowed connections were specified in it.
384 const bool* update_over_cellular_allowed_p = ec->GetValue(
385 state->updater_provider()->var_cellular_enabled());
386 if (update_over_cellular_allowed_p && *update_over_cellular_allowed_p)
387 *result = true;
Gilad Arnolda8262e22014-06-02 13:54:27 -0700388 }
389 }
390 }
391
Gilad Arnold28d6be62014-06-30 14:04:04 -0700392 return (*result ? EvalStatus::kSucceeded : EvalStatus::kAskMeAgainLater);
Gilad Arnolda8262e22014-06-02 13:54:27 -0700393}
394
Alex Deymo0d11c602014-04-23 20:12:20 -0700395EvalStatus ChromeOSPolicy::NextUpdateCheckTime(EvaluationContext* ec,
396 State* state, string* error,
397 Time* next_update_check) const {
398 // Don't check for updates too often. We limit the update checks to once every
399 // some interval. The interval is kTimeoutInitialInterval the first time and
400 // kTimeoutPeriodicInterval for the subsequent update checks. If the update
401 // check fails, we increase the interval between the update checks
402 // exponentially until kTimeoutMaxBackoffInterval. Finally, to avoid having
403 // many chromebooks running update checks at the exact same time, we add some
404 // fuzz to the interval.
405 const Time* updater_started_time =
406 ec->GetValue(state->updater_provider()->var_updater_started_time());
407 POLICY_CHECK_VALUE_AND_FAIL(updater_started_time, error);
408
409 const base::Time* last_checked_time =
410 ec->GetValue(state->updater_provider()->var_last_checked_time());
411
412 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
413 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
414
415 PRNG prng(*seed);
416
Gilad Arnold38b14022014-07-09 12:45:56 -0700417 // If this is the first attempt, compute and return an initial value.
Alex Deymo0d11c602014-04-23 20:12:20 -0700418 if (!last_checked_time || *last_checked_time < *updater_started_time) {
Alex Deymo0d11c602014-04-23 20:12:20 -0700419 *next_update_check = *updater_started_time + FuzzedInterval(
420 &prng, kTimeoutInitialInterval, kTimeoutRegularFuzz);
421 return EvalStatus::kSucceeded;
422 }
Gilad Arnold38b14022014-07-09 12:45:56 -0700423
424 // Check for previous failed attempts to implement an exponential backoff.
Alex Deymo0d11c602014-04-23 20:12:20 -0700425 const unsigned int* consecutive_failed_update_checks = ec->GetValue(
426 state->updater_provider()->var_consecutive_failed_update_checks());
427 POLICY_CHECK_VALUE_AND_FAIL(consecutive_failed_update_checks, error);
428
Gilad Arnold38b14022014-07-09 12:45:56 -0700429 int interval = kTimeoutPeriodicInterval;
430 int fuzz = kTimeoutRegularFuzz;
Alex Deymo0d11c602014-04-23 20:12:20 -0700431 for (unsigned int i = 0; i < *consecutive_failed_update_checks; ++i) {
432 interval *= 2;
Gilad Arnold38b14022014-07-09 12:45:56 -0700433 fuzz = 0; // In case of backoff, fuzz is different (see below).
Alex Deymo0d11c602014-04-23 20:12:20 -0700434 if (interval > kTimeoutMaxBackoffInterval) {
435 interval = kTimeoutMaxBackoffInterval;
436 break;
437 }
438 }
439
Gilad Arnold38b14022014-07-09 12:45:56 -0700440 // Defer to a fuzz of +/-(interval / 2) in case of backoff.
441 if (fuzz == 0)
442 fuzz = interval;
443
Alex Deymo0d11c602014-04-23 20:12:20 -0700444 *next_update_check = *last_checked_time + FuzzedInterval(
Gilad Arnold38b14022014-07-09 12:45:56 -0700445 &prng, interval, fuzz);
Alex Deymo0d11c602014-04-23 20:12:20 -0700446 return EvalStatus::kSucceeded;
447}
448
449TimeDelta ChromeOSPolicy::FuzzedInterval(PRNG* prng, int interval, int fuzz) {
Gilad Arnolde1218812014-05-07 12:21:36 -0700450 DCHECK_GE(interval, 0);
451 DCHECK_GE(fuzz, 0);
Alex Deymo0d11c602014-04-23 20:12:20 -0700452 int half_fuzz = fuzz / 2;
Alex Deymo0d11c602014-04-23 20:12:20 -0700453 // This guarantees the output interval is non negative.
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700454 int interval_min = max(interval - half_fuzz, 0);
Gilad Arnolde1218812014-05-07 12:21:36 -0700455 int interval_max = interval + half_fuzz;
456 return TimeDelta::FromSeconds(prng->RandMinMax(interval_min, interval_max));
Alex Deymo0d11c602014-04-23 20:12:20 -0700457}
458
Gilad Arnoldb3b05442014-05-30 14:25:05 -0700459EvalStatus ChromeOSPolicy::UpdateDownloadUrl(
460 EvaluationContext* ec, State* state, std::string* error,
461 UpdateDownloadUrlResult* result, const UpdateState& update_state) const {
462 int url_idx = 0;
463 int url_num_failures = 0;
464 if (update_state.num_checks > 1) {
465 // Ignore negative URL indexes, which indicate that no previous suitable
466 // download URL was found.
467 url_idx = max(0, update_state.download_url_idx);
468 url_num_failures = update_state.download_url_num_failures;
469 }
470
471 // Preconditions / sanity checks.
472 DCHECK_GE(update_state.download_failures_max, 0);
473 DCHECK_LT(url_idx, static_cast<int>(update_state.download_urls.size()));
474 DCHECK_LE(url_num_failures, update_state.download_failures_max);
475
476 // Determine whether HTTP downloads are forbidden by policy. This only
477 // applies to official system builds; otherwise, HTTP is always enabled.
478 bool http_allowed = true;
479 const bool* is_official_build_p = ec->GetValue(
480 state->system_provider()->var_is_official_build());
481 if (is_official_build_p && *is_official_build_p) {
482 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
483 const bool* device_policy_is_loaded_p = ec->GetValue(
484 dp_provider->var_device_policy_is_loaded());
485 if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
486 const bool* policy_http_downloads_enabled_p = ec->GetValue(
487 dp_provider->var_http_downloads_enabled());
488 http_allowed = (!policy_http_downloads_enabled_p ||
489 *policy_http_downloads_enabled_p);
490 }
491 }
492
493 // Process recent failures, stop if the URL index advances.
494 for (auto& err_code : update_state.download_url_error_codes) {
495 if (HandleErrorCode(err_code, &url_idx, &url_num_failures))
496 break;
497 if (url_num_failures > update_state.download_failures_max) {
498 url_idx++;
499 url_num_failures = 0;
500 break;
501 }
502 }
503 url_idx %= update_state.download_urls.size();
504
505 // Scan through URLs until a usable one is found.
506 const int start_url_idx = url_idx;
507 while (!DownloadUrlIsUsable(update_state.download_urls[url_idx],
508 http_allowed)) {
509 url_idx = (url_idx + 1) % update_state.download_urls.size();
510 url_num_failures = 0;
511 if (url_idx == start_url_idx)
512 return EvalStatus::kFailed; // No usable URLs.
513 }
514
515 result->url_idx = url_idx;
516 result->url_num_failures = url_num_failures;
517 return EvalStatus::kSucceeded;
518}
519
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700520EvalStatus ChromeOSPolicy::UpdateScattering(
521 EvaluationContext* ec,
522 State* state,
523 string* error,
524 UpdateScatteringResult* result,
525 const UpdateState& update_state) const {
526 // Preconditions. These stem from the postconditions and usage contract.
527 DCHECK(update_state.scatter_wait_period >= kZeroInterval);
528 DCHECK_GE(update_state.scatter_check_threshold, 0);
529
530 // Set default result values.
531 result->is_scattering = false;
532 result->wait_period = kZeroInterval;
533 result->check_threshold = 0;
534
535 DevicePolicyProvider* const dp_provider = state->device_policy_provider();
536
537 // Ensure that a device policy is loaded.
538 const bool* device_policy_is_loaded_p = ec->GetValue(
539 dp_provider->var_device_policy_is_loaded());
540 if (!(device_policy_is_loaded_p && *device_policy_is_loaded_p))
541 return EvalStatus::kSucceeded;
542
543 // Is scattering enabled by policy?
544 const TimeDelta* scatter_factor_p = ec->GetValue(
545 dp_provider->var_scatter_factor());
546 if (!scatter_factor_p || *scatter_factor_p == kZeroInterval)
547 return EvalStatus::kSucceeded;
548
549 // Obtain a pseudo-random number generator.
550 const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
551 POLICY_CHECK_VALUE_AND_FAIL(seed, error);
552 PRNG prng(*seed);
553
554 // Step 1: Maintain the scattering wait period.
555 //
556 // If no wait period was previously determined, or it no longer fits in the
557 // scatter factor, then generate a new one. Otherwise, keep the one we have.
Gilad Arnoldf62a4b82014-05-01 07:41:07 -0700558 TimeDelta wait_period = update_state.scatter_wait_period;
559 if (wait_period == kZeroInterval || wait_period > *scatter_factor_p) {
560 wait_period = TimeDelta::FromSeconds(
561 prng.RandMinMax(1, scatter_factor_p->InSeconds()));
562 }
563
564 // If we surpass the wait period or the max scatter period associated with
565 // the update, then no wait is needed.
566 Time wait_expires = (update_state.first_seen +
567 min(wait_period, update_state.scatter_wait_period_max));
568 if (ec->IsTimeGreaterThan(wait_expires))
569 wait_period = kZeroInterval;
570
571 // Step 2: Maintain the update check threshold count.
572 //
573 // If an update check threshold is not specified then generate a new
574 // one.
575 int check_threshold = update_state.scatter_check_threshold;
576 if (check_threshold == 0) {
577 check_threshold = prng.RandMinMax(
578 update_state.scatter_check_threshold_min,
579 update_state.scatter_check_threshold_max);
580 }
581
582 // If the update check threshold is not within allowed range then nullify it.
583 // TODO(garnold) This is compliant with current logic found in
584 // OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied(). We may want
585 // to change it so that it behaves similarly to the wait period case, namely
586 // if the current value exceeds the maximum, we set a new one within range.
587 if (check_threshold > update_state.scatter_check_threshold_max)
588 check_threshold = 0;
589
590 // If the update check threshold is non-zero and satisfied, then nullify it.
591 if (check_threshold > 0 && update_state.num_checks >= check_threshold)
592 check_threshold = 0;
593
594 bool is_scattering = (wait_period != kZeroInterval || check_threshold);
595 EvalStatus ret = EvalStatus::kSucceeded;
596 if (is_scattering && wait_period == update_state.scatter_wait_period &&
597 check_threshold == update_state.scatter_check_threshold)
598 ret = EvalStatus::kAskMeAgainLater;
599 result->is_scattering = is_scattering;
600 result->wait_period = wait_period;
601 result->check_threshold = check_threshold;
602 return ret;
603}
604
Alex Deymo63784a52014-05-28 10:46:14 -0700605} // namespace chromeos_update_manager