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