• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright (C) 2014 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16 
17 #include "update_engine/update_manager/chromeos_policy.h"
18 
19 #include <algorithm>
20 #include <memory>
21 #include <set>
22 #include <string>
23 #include <vector>
24 
25 #include <base/logging.h>
26 #include <base/strings/string_util.h>
27 #include <base/time/time.h>
28 
29 #include "update_engine/common/error_code.h"
30 #include "update_engine/common/error_code_utils.h"
31 #include "update_engine/common/utils.h"
32 #include "update_engine/update_manager/device_policy_provider.h"
33 #include "update_engine/update_manager/enough_slots_ab_updates_policy_impl.h"
34 #include "update_engine/update_manager/enterprise_device_policy_impl.h"
35 #include "update_engine/update_manager/interactive_update_policy_impl.h"
36 #include "update_engine/update_manager/official_build_check_policy_impl.h"
37 #include "update_engine/update_manager/out_of_box_experience_policy_impl.h"
38 #include "update_engine/update_manager/policy_utils.h"
39 #include "update_engine/update_manager/shill_provider.h"
40 #include "update_engine/update_manager/update_time_restrictions_policy_impl.h"
41 
42 using base::Time;
43 using base::TimeDelta;
44 using chromeos_update_engine::ConnectionTethering;
45 using chromeos_update_engine::ConnectionType;
46 using chromeos_update_engine::ErrorCode;
47 using chromeos_update_engine::InstallPlan;
48 using std::get;
49 using std::min;
50 using std::set;
51 using std::string;
52 using std::unique_ptr;
53 using std::vector;
54 
55 namespace {
56 
57 // Examines |err_code| and decides whether the URL index needs to be advanced,
58 // the error count for the URL incremented, or none of the above. In the first
59 // case, returns true; in the second case, increments |*url_num_error_p| and
60 // returns false; otherwise just returns false.
61 //
62 // TODO(garnold) Adapted from PayloadState::UpdateFailed() (to be retired).
HandleErrorCode(ErrorCode err_code,int * url_num_error_p)63 bool HandleErrorCode(ErrorCode err_code, int* url_num_error_p) {
64   err_code = chromeos_update_engine::utils::GetBaseErrorCode(err_code);
65   switch (err_code) {
66     // Errors which are good indicators of a problem with a particular URL or
67     // the protocol used in the URL or entities in the communication channel
68     // (e.g. proxies). We should try the next available URL in the next update
69     // check to quickly recover from these errors.
70     case ErrorCode::kPayloadHashMismatchError:
71     case ErrorCode::kPayloadSizeMismatchError:
72     case ErrorCode::kDownloadPayloadVerificationError:
73     case ErrorCode::kDownloadPayloadPubKeyVerificationError:
74     case ErrorCode::kSignedDeltaPayloadExpectedError:
75     case ErrorCode::kDownloadInvalidMetadataMagicString:
76     case ErrorCode::kDownloadSignatureMissingInManifest:
77     case ErrorCode::kDownloadManifestParseError:
78     case ErrorCode::kDownloadMetadataSignatureError:
79     case ErrorCode::kDownloadMetadataSignatureVerificationError:
80     case ErrorCode::kDownloadMetadataSignatureMismatch:
81     case ErrorCode::kDownloadOperationHashVerificationError:
82     case ErrorCode::kDownloadOperationExecutionError:
83     case ErrorCode::kDownloadOperationHashMismatch:
84     case ErrorCode::kDownloadInvalidMetadataSize:
85     case ErrorCode::kDownloadInvalidMetadataSignature:
86     case ErrorCode::kDownloadOperationHashMissingError:
87     case ErrorCode::kDownloadMetadataSignatureMissingError:
88     case ErrorCode::kPayloadMismatchedType:
89     case ErrorCode::kUnsupportedMajorPayloadVersion:
90     case ErrorCode::kUnsupportedMinorPayloadVersion:
91     case ErrorCode::kPayloadTimestampError:
92     case ErrorCode::kVerityCalculationError:
93       LOG(INFO) << "Advancing download URL due to error "
94                 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
95                 << " (" << static_cast<int>(err_code) << ")";
96       return true;
97 
98     // Errors which seem to be just transient network/communication related
99     // failures and do not indicate any inherent problem with the URL itself.
100     // So, we should keep the current URL but just increment the
101     // failure count to give it more chances. This way, while we maximize our
102     // chances of downloading from the URLs that appear earlier in the response
103     // (because download from a local server URL that appears earlier in a
104     // response is preferable than downloading from the next URL which could be
105     // an Internet URL and thus could be more expensive).
106     case ErrorCode::kError:
107     case ErrorCode::kDownloadTransferError:
108     case ErrorCode::kDownloadWriteError:
109     case ErrorCode::kDownloadStateInitializationError:
110     case ErrorCode::kOmahaErrorInHTTPResponse:  // Aggregate for HTTP errors.
111       LOG(INFO) << "Incrementing URL failure count due to error "
112                 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
113                 << " (" << static_cast<int>(err_code) << ")";
114       *url_num_error_p += 1;
115       return false;
116 
117     // Errors which are not specific to a URL and hence shouldn't result in
118     // the URL being penalized. This can happen in two cases:
119     // 1. We haven't started downloading anything: These errors don't cost us
120     // anything in terms of actual payload bytes, so we should just do the
121     // regular retries at the next update check.
122     // 2. We have successfully downloaded the payload: In this case, the
123     // payload attempt number would have been incremented and would take care
124     // of the back-off at the next update check.
125     // In either case, there's no need to update URL index or failure count.
126     case ErrorCode::kOmahaRequestError:
127     case ErrorCode::kOmahaResponseHandlerError:
128     case ErrorCode::kPostinstallRunnerError:
129     case ErrorCode::kFilesystemCopierError:
130     case ErrorCode::kInstallDeviceOpenError:
131     case ErrorCode::kKernelDeviceOpenError:
132     case ErrorCode::kDownloadNewPartitionInfoError:
133     case ErrorCode::kNewRootfsVerificationError:
134     case ErrorCode::kNewKernelVerificationError:
135     case ErrorCode::kPostinstallBootedFromFirmwareB:
136     case ErrorCode::kPostinstallFirmwareRONotUpdatable:
137     case ErrorCode::kOmahaRequestEmptyResponseError:
138     case ErrorCode::kOmahaRequestXMLParseError:
139     case ErrorCode::kOmahaResponseInvalid:
140     case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
141     case ErrorCode::kOmahaUpdateDeferredPerPolicy:
142     case ErrorCode::kNonCriticalUpdateInOOBE:
143     case ErrorCode::kOmahaUpdateDeferredForBackoff:
144     case ErrorCode::kPostinstallPowerwashError:
145     case ErrorCode::kUpdateCanceledByChannelChange:
146     case ErrorCode::kOmahaRequestXMLHasEntityDecl:
147     case ErrorCode::kFilesystemVerifierError:
148     case ErrorCode::kUserCanceled:
149     case ErrorCode::kOmahaUpdateIgnoredOverCellular:
150     case ErrorCode::kUpdatedButNotActive:
151     case ErrorCode::kNoUpdate:
152     case ErrorCode::kRollbackNotPossible:
153     case ErrorCode::kFirstActiveOmahaPingSentPersistenceError:
154     case ErrorCode::kInternalLibCurlError:
155     case ErrorCode::kUnresolvedHostError:
156     case ErrorCode::kUnresolvedHostRecovered:
157     case ErrorCode::kNotEnoughSpace:
158     case ErrorCode::kDeviceCorrupted:
159     case ErrorCode::kPackageExcludedFromUpdate:
160       LOG(INFO) << "Not changing URL index or failure count due to error "
161                 << chromeos_update_engine::utils::ErrorCodeToString(err_code)
162                 << " (" << static_cast<int>(err_code) << ")";
163       return false;
164 
165     case ErrorCode::kSuccess:                       // success code
166     case ErrorCode::kUmaReportedMax:                // not an error code
167     case ErrorCode::kOmahaRequestHTTPResponseBase:  // aggregated already
168     case ErrorCode::kDevModeFlag:                   // not an error code
169     case ErrorCode::kResumedFlag:                   // not an error code
170     case ErrorCode::kTestImageFlag:                 // not an error code
171     case ErrorCode::kTestOmahaUrlFlag:              // not an error code
172     case ErrorCode::kSpecialFlags:                  // not an error code
173       // These shouldn't happen. Enumerating these  explicitly here so that we
174       // can let the compiler warn about new error codes that are added to
175       // action_processor.h but not added here.
176       LOG(WARNING) << "Unexpected error "
177                    << chromeos_update_engine::utils::ErrorCodeToString(err_code)
178                    << " (" << static_cast<int>(err_code) << ")";
179       // Note: Not adding a default here so as to let the compiler warn us of
180       // any new enums that were added in the .h but not listed in this switch.
181   }
182   return false;
183 }
184 
185 // Checks whether |url| can be used under given download restrictions.
IsUrlUsable(const string & url,bool http_allowed)186 bool IsUrlUsable(const string& url, bool http_allowed) {
187   return http_allowed ||
188          !base::StartsWith(
189              url, "http://", base::CompareCase::INSENSITIVE_ASCII);
190 }
191 
192 }  // namespace
193 
194 namespace chromeos_update_manager {
195 
GetSystemPolicy()196 unique_ptr<Policy> GetSystemPolicy() {
197   return std::make_unique<ChromeOSPolicy>();
198 }
199 
200 const NextUpdateCheckPolicyConstants
201     ChromeOSPolicy::kNextUpdateCheckPolicyConstants = {
202         .timeout_initial_interval = 7 * 60,
203         .timeout_periodic_interval = 45 * 60,
204         .timeout_max_backoff_interval = 4 * 60 * 60,
205         .timeout_regular_fuzz = 10 * 60,
206         .attempt_backoff_max_interval_in_days = 16,
207         .attempt_backoff_fuzz_in_hours = 12,
208 };
209 
210 const int ChromeOSPolicy::kMaxP2PAttempts = 10;
211 const int ChromeOSPolicy::kMaxP2PAttemptsPeriodInSeconds = 5 * 24 * 60 * 60;
212 
UpdateCheckAllowed(EvaluationContext * ec,State * state,string * error,UpdateCheckParams * result) const213 EvalStatus ChromeOSPolicy::UpdateCheckAllowed(EvaluationContext* ec,
214                                               State* state,
215                                               string* error,
216                                               UpdateCheckParams* result) const {
217   // Set the default return values.
218   result->updates_enabled = true;
219   result->target_channel.clear();
220   result->lts_tag.clear();
221   result->target_version_prefix.clear();
222   result->rollback_allowed = false;
223   result->rollback_allowed_milestones = -1;
224   result->rollback_on_channel_downgrade = false;
225   result->interactive = false;
226   result->quick_fix_build_token.clear();
227 
228   EnoughSlotsAbUpdatesPolicyImpl enough_slots_ab_updates_policy;
229   EnterpriseDevicePolicyImpl enterprise_device_policy;
230   OnlyUpdateOfficialBuildsPolicyImpl only_update_official_builds_policy;
231   InteractiveUpdatePolicyImpl interactive_update_policy;
232   OobePolicyImpl oobe_policy;
233   NextUpdateCheckTimePolicyImpl next_update_check_time_policy(
234       kNextUpdateCheckPolicyConstants);
235 
236   vector<Policy const*> policies_to_consult = {
237       // Do not perform any updates if there are not enough slots to do A/B
238       // updates.
239       &enough_slots_ab_updates_policy,
240 
241       // Check to see if Enterprise-managed (has DevicePolicy) and/or
242       // Kiosk-mode.  If so, then defer to those settings.
243       &enterprise_device_policy,
244 
245       // Check to see if an interactive update was requested.
246       &interactive_update_policy,
247 
248       // Unofficial builds should not perform periodic update checks.
249       &only_update_official_builds_policy,
250 
251       // If OOBE is enabled, wait until it is completed.
252       &oobe_policy,
253 
254       // Ensure that periodic update checks are timed properly.
255       &next_update_check_time_policy,
256   };
257 
258   // Now that the list of policy implementations, and the order to consult them,
259   // has been setup, consult the policies. If none of the policies make a
260   // definitive decisions about whether or not to check for updates, then allow
261   // the update check to happen.
262   EvalStatus status = ConsultPolicies(policies_to_consult,
263                                       &Policy::UpdateCheckAllowed,
264                                       ec,
265                                       state,
266                                       error,
267                                       result);
268   if (EvalStatus::kContinue != status) {
269     return status;
270   } else {
271     // It is time to check for an update.
272     LOG(INFO) << "Allowing update check.";
273     return EvalStatus::kSucceeded;
274   }
275 }
276 
UpdateCanBeApplied(EvaluationContext * ec,State * state,std::string * error,ErrorCode * result,InstallPlan * install_plan) const277 EvalStatus ChromeOSPolicy::UpdateCanBeApplied(EvaluationContext* ec,
278                                               State* state,
279                                               std::string* error,
280                                               ErrorCode* result,
281                                               InstallPlan* install_plan) const {
282   UpdateTimeRestrictionsPolicyImpl update_time_restrictions_policy;
283   InteractiveUpdatePolicyImpl interactive_update_policy;
284 
285   vector<Policy const*> policies_to_consult = {
286       // Check to see if an interactive update has been requested.
287       &interactive_update_policy,
288 
289       // Do not apply or download an update if we are inside one of the
290       // restricted times.
291       &update_time_restrictions_policy,
292   };
293 
294   EvalStatus status = ConsultPolicies(policies_to_consult,
295                                       &Policy::UpdateCanBeApplied,
296                                       ec,
297                                       state,
298                                       error,
299                                       result,
300                                       install_plan);
301   if (EvalStatus::kContinue != status) {
302     return status;
303   } else {
304     // The update can proceed.
305     LOG(INFO) << "Allowing update to be applied.";
306     *result = ErrorCode::kSuccess;
307     return EvalStatus::kSucceeded;
308   }
309 }
310 
UpdateCanStart(EvaluationContext * ec,State * state,string * error,UpdateDownloadParams * result,const UpdateState update_state) const311 EvalStatus ChromeOSPolicy::UpdateCanStart(
312     EvaluationContext* ec,
313     State* state,
314     string* error,
315     UpdateDownloadParams* result,
316     const UpdateState update_state) const {
317   // Set the default return values. Note that we set persisted values (backoff,
318   // scattering) to the same values presented in the update state. The reason is
319   // that preemptive returns, such as the case where an update check is due,
320   // should not clear off the said values; rather, it is the deliberate
321   // inference of new values that should cause them to be reset.
322   result->update_can_start = false;
323   result->cannot_start_reason = UpdateCannotStartReason::kUndefined;
324   result->download_url_idx = -1;
325   result->download_url_allowed = true;
326   result->download_url_num_errors = 0;
327   result->p2p_downloading_allowed = false;
328   result->p2p_sharing_allowed = false;
329   result->do_increment_failures = false;
330   result->backoff_expiry = update_state.backoff_expiry;
331   result->scatter_wait_period = update_state.scatter_wait_period;
332   result->scatter_check_threshold = update_state.scatter_check_threshold;
333 
334   // Make sure that we're not due for an update check.
335   UpdateCheckParams check_result;
336   EvalStatus check_status = UpdateCheckAllowed(ec, state, error, &check_result);
337   if (check_status == EvalStatus::kFailed)
338     return EvalStatus::kFailed;
339   bool is_check_due = (check_status == EvalStatus::kSucceeded &&
340                        check_result.updates_enabled == true);
341 
342   // Check whether backoff applies, and if not then which URL can be used for
343   // downloading. These require scanning the download error log, and so they are
344   // done together.
345   UpdateBackoffAndDownloadUrlResult backoff_url_result;
346   EvalStatus backoff_url_status = UpdateBackoffAndDownloadUrl(
347       ec, state, error, &backoff_url_result, update_state);
348   if (backoff_url_status == EvalStatus::kFailed)
349     return EvalStatus::kFailed;
350   result->download_url_idx = backoff_url_result.url_idx;
351   result->download_url_num_errors = backoff_url_result.url_num_errors;
352   result->do_increment_failures = backoff_url_result.do_increment_failures;
353   result->backoff_expiry = backoff_url_result.backoff_expiry;
354   bool is_backoff_active =
355       (backoff_url_status == EvalStatus::kAskMeAgainLater) ||
356       !backoff_url_result.backoff_expiry.is_null();
357 
358   DevicePolicyProvider* const dp_provider = state->device_policy_provider();
359   bool is_scattering_active = false;
360   EvalStatus scattering_status = EvalStatus::kSucceeded;
361 
362   const bool* device_policy_is_loaded_p =
363       ec->GetValue(dp_provider->var_device_policy_is_loaded());
364   if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
365     // Check whether scattering applies to this update attempt. We should not be
366     // scattering if this is an interactive update check, or if OOBE is enabled
367     // but not completed.
368     //
369     // Note: current code further suppresses scattering if a "deadline"
370     // attribute is found in the Omaha response. However, it appears that the
371     // presence of this attribute is merely indicative of an OOBE update, during
372     // which we suppress scattering anyway.
373     bool is_scattering_applicable = false;
374     result->scatter_wait_period = kZeroInterval;
375     result->scatter_check_threshold = 0;
376     if (!update_state.interactive) {
377       const bool* is_oobe_enabled_p =
378           ec->GetValue(state->config_provider()->var_is_oobe_enabled());
379       if (is_oobe_enabled_p && !(*is_oobe_enabled_p)) {
380         is_scattering_applicable = true;
381       } else {
382         const bool* is_oobe_complete_p =
383             ec->GetValue(state->system_provider()->var_is_oobe_complete());
384         is_scattering_applicable = (is_oobe_complete_p && *is_oobe_complete_p);
385       }
386     }
387 
388     // Compute scattering values.
389     if (is_scattering_applicable) {
390       UpdateScatteringResult scatter_result;
391       scattering_status =
392           UpdateScattering(ec, state, error, &scatter_result, update_state);
393       if (scattering_status == EvalStatus::kFailed) {
394         return EvalStatus::kFailed;
395       } else {
396         result->scatter_wait_period = scatter_result.wait_period;
397         result->scatter_check_threshold = scatter_result.check_threshold;
398         if (scattering_status == EvalStatus::kAskMeAgainLater ||
399             scatter_result.is_scattering)
400           is_scattering_active = true;
401       }
402     }
403   }
404 
405   // Find out whether P2P is globally enabled.
406   bool p2p_enabled;
407   EvalStatus p2p_enabled_status = P2PEnabled(ec, state, error, &p2p_enabled);
408   if (p2p_enabled_status != EvalStatus::kSucceeded)
409     return EvalStatus::kFailed;
410 
411   // Is P2P is enabled, consider allowing it for downloading and/or sharing.
412   if (p2p_enabled) {
413     // Sharing via P2P is allowed if not disabled by Omaha.
414     if (update_state.p2p_sharing_disabled) {
415       LOG(INFO) << "Blocked P2P sharing because it is disabled by Omaha.";
416     } else {
417       result->p2p_sharing_allowed = true;
418     }
419 
420     // Downloading via P2P is allowed if not disabled by Omaha, an update is not
421     // interactive, and other limits haven't been reached.
422     if (update_state.p2p_downloading_disabled) {
423       LOG(INFO) << "Blocked P2P downloading because it is disabled by Omaha.";
424     } else if (update_state.interactive) {
425       LOG(INFO) << "Blocked P2P downloading because update is interactive.";
426     } else if (update_state.p2p_num_attempts >= kMaxP2PAttempts) {
427       LOG(INFO) << "Blocked P2P downloading as it was attempted too many "
428                    "times.";
429     } else if (!update_state.p2p_first_attempted.is_null() &&
430                ec->IsWallclockTimeGreaterThan(
431                    update_state.p2p_first_attempted +
432                    TimeDelta::FromSeconds(kMaxP2PAttemptsPeriodInSeconds))) {
433       LOG(INFO) << "Blocked P2P downloading as its usage timespan exceeds "
434                    "limit.";
435     } else {
436       // P2P download is allowed; if backoff or scattering are active, be sure
437       // to suppress them, yet prevent any download URL from being used.
438       result->p2p_downloading_allowed = true;
439       if (is_backoff_active || is_scattering_active) {
440         is_backoff_active = is_scattering_active = false;
441         result->download_url_allowed = false;
442       }
443     }
444   }
445 
446   // Check for various deterrents.
447   if (is_check_due) {
448     result->cannot_start_reason = UpdateCannotStartReason::kCheckDue;
449     return EvalStatus::kSucceeded;
450   }
451   if (is_backoff_active) {
452     result->cannot_start_reason = UpdateCannotStartReason::kBackoff;
453     return backoff_url_status;
454   }
455   if (is_scattering_active) {
456     result->cannot_start_reason = UpdateCannotStartReason::kScattering;
457     return scattering_status;
458   }
459   if (result->download_url_idx < 0 && !result->p2p_downloading_allowed) {
460     result->cannot_start_reason = UpdateCannotStartReason::kCannotDownload;
461     return EvalStatus::kSucceeded;
462   }
463 
464   // Update is good to go.
465   result->update_can_start = true;
466   return EvalStatus::kSucceeded;
467 }
468 
P2PEnabled(EvaluationContext * ec,State * state,string * error,bool * result) const469 EvalStatus ChromeOSPolicy::P2PEnabled(EvaluationContext* ec,
470                                       State* state,
471                                       string* error,
472                                       bool* result) const {
473   bool enabled = false;
474 
475   // Determine whether use of P2P is allowed by policy. Even if P2P is not
476   // explicitly allowed, we allow it if the device is enterprise enrolled (that
477   // is, missing or empty owner string).
478   DevicePolicyProvider* const dp_provider = state->device_policy_provider();
479   const bool* device_policy_is_loaded_p =
480       ec->GetValue(dp_provider->var_device_policy_is_loaded());
481   if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
482     const bool* policy_au_p2p_enabled_p =
483         ec->GetValue(dp_provider->var_au_p2p_enabled());
484     if (policy_au_p2p_enabled_p) {
485       enabled = *policy_au_p2p_enabled_p;
486     } else {
487       const bool* policy_has_owner_p =
488           ec->GetValue(dp_provider->var_has_owner());
489       if (!policy_has_owner_p || !*policy_has_owner_p)
490         enabled = true;
491     }
492   }
493 
494   // Enable P2P, if so mandated by the updater configuration. This is additive
495   // to whether or not P2P is enabled by device policy.
496   if (!enabled) {
497     const bool* updater_p2p_enabled_p =
498         ec->GetValue(state->updater_provider()->var_p2p_enabled());
499     enabled = updater_p2p_enabled_p && *updater_p2p_enabled_p;
500   }
501 
502   *result = enabled;
503   return EvalStatus::kSucceeded;
504 }
505 
P2PEnabledChanged(EvaluationContext * ec,State * state,string * error,bool * result,bool prev_result) const506 EvalStatus ChromeOSPolicy::P2PEnabledChanged(EvaluationContext* ec,
507                                              State* state,
508                                              string* error,
509                                              bool* result,
510                                              bool prev_result) const {
511   EvalStatus status = P2PEnabled(ec, state, error, result);
512   if (status == EvalStatus::kSucceeded && *result == prev_result)
513     return EvalStatus::kAskMeAgainLater;
514   return status;
515 }
516 
UpdateBackoffAndDownloadUrl(EvaluationContext * ec,State * state,string * error,UpdateBackoffAndDownloadUrlResult * result,const UpdateState & update_state) const517 EvalStatus ChromeOSPolicy::UpdateBackoffAndDownloadUrl(
518     EvaluationContext* ec,
519     State* state,
520     string* error,
521     UpdateBackoffAndDownloadUrlResult* result,
522     const UpdateState& update_state) const {
523   DCHECK_GE(update_state.download_errors_max, 0);
524 
525   // Set default result values.
526   result->do_increment_failures = false;
527   result->backoff_expiry = update_state.backoff_expiry;
528   result->url_idx = -1;
529   result->url_num_errors = 0;
530 
531   const bool* is_official_build_p =
532       ec->GetValue(state->system_provider()->var_is_official_build());
533   bool is_official_build = (is_official_build_p ? *is_official_build_p : true);
534 
535   // Check whether backoff is enabled.
536   bool may_backoff = false;
537   if (update_state.is_backoff_disabled) {
538     LOG(INFO) << "Backoff disabled by Omaha.";
539   } else if (update_state.interactive) {
540     LOG(INFO) << "No backoff for interactive updates.";
541   } else if (update_state.is_delta_payload) {
542     LOG(INFO) << "No backoff for delta payloads.";
543   } else if (!is_official_build) {
544     LOG(INFO) << "No backoff for unofficial builds.";
545   } else {
546     may_backoff = true;
547   }
548 
549   // If previous backoff still in effect, block.
550   if (may_backoff && !update_state.backoff_expiry.is_null() &&
551       !ec->IsWallclockTimeGreaterThan(update_state.backoff_expiry)) {
552     LOG(INFO) << "Previous backoff has not expired, waiting.";
553     return EvalStatus::kAskMeAgainLater;
554   }
555 
556   // Determine whether HTTP downloads are forbidden by policy. This only
557   // applies to official system builds; otherwise, HTTP is always enabled.
558   bool http_allowed = true;
559   if (is_official_build) {
560     DevicePolicyProvider* const dp_provider = state->device_policy_provider();
561     const bool* device_policy_is_loaded_p =
562         ec->GetValue(dp_provider->var_device_policy_is_loaded());
563     if (device_policy_is_loaded_p && *device_policy_is_loaded_p) {
564       const bool* policy_http_downloads_enabled_p =
565           ec->GetValue(dp_provider->var_http_downloads_enabled());
566       http_allowed = (!policy_http_downloads_enabled_p ||
567                       *policy_http_downloads_enabled_p);
568     }
569   }
570 
571   int url_idx = update_state.last_download_url_idx;
572   if (url_idx < 0)
573     url_idx = -1;
574   bool do_advance_url = false;
575   bool is_failure_occurred = false;
576   Time err_time;
577 
578   // Scan the relevant part of the download error log, tracking which URLs are
579   // being used, and accounting the number of errors for each URL. Note that
580   // this process may not traverse all errors provided, as it may decide to bail
581   // out midway depending on the particular errors exhibited, the number of
582   // failures allowed, etc. When this ends, |url_idx| will point to the last URL
583   // used (-1 if starting fresh), |do_advance_url| will determine whether the
584   // URL needs to be advanced, and |err_time| the point in time when the last
585   // reported error occurred.  Additionally, if the error log indicates that an
586   // update attempt has failed (abnormal), then |is_failure_occurred| will be
587   // set to true.
588   const int num_urls = update_state.download_urls.size();
589   int prev_url_idx = -1;
590   int url_num_errors = update_state.last_download_url_num_errors;
591   Time prev_err_time;
592   bool is_first = true;
593   for (const auto& err_tuple : update_state.download_errors) {
594     // Do some validation checks.
595     int used_url_idx = get<0>(err_tuple);
596     if (is_first && url_idx >= 0 && used_url_idx != url_idx) {
597       LOG(WARNING) << "First URL in error log (" << used_url_idx
598                    << ") not as expected (" << url_idx << ")";
599     }
600     is_first = false;
601     url_idx = used_url_idx;
602     if (url_idx < 0 || url_idx >= num_urls) {
603       LOG(ERROR) << "Download error log contains an invalid URL index ("
604                  << url_idx << ")";
605       return EvalStatus::kFailed;
606     }
607     err_time = get<2>(err_tuple);
608     if (!(prev_err_time.is_null() || err_time >= prev_err_time)) {
609       // TODO(garnold) Monotonicity cannot really be assumed when dealing with
610       // wallclock-based timestamps. However, we're making a simplifying
611       // assumption so as to keep the policy implementation straightforward, for
612       // now. In general, we should convert all timestamp handling in the
613       // UpdateManager to use monotonic time (instead of wallclock), including
614       // the computation of various expiration times (backoff, scattering, etc).
615       // The client will do whatever conversions necessary when
616       // persisting/retrieving these values across reboots. See chromium:408794.
617       LOG(ERROR) << "Download error timestamps not monotonically increasing.";
618       return EvalStatus::kFailed;
619     }
620     prev_err_time = err_time;
621 
622     // Ignore errors that happened before the last known failed attempt.
623     if (!update_state.failures_last_updated.is_null() &&
624         err_time <= update_state.failures_last_updated)
625       continue;
626 
627     if (prev_url_idx >= 0) {
628       if (url_idx < prev_url_idx) {
629         LOG(ERROR) << "The URLs in the download error log have wrapped around ("
630                    << prev_url_idx << "->" << url_idx
631                    << "). This should not have happened and means that there's "
632                       "a bug. To be conservative, we record a failed attempt "
633                       "(invalidating the rest of the error log) and resume "
634                       "download from the first usable URL.";
635         url_idx = -1;
636         is_failure_occurred = true;
637         break;
638       }
639 
640       if (url_idx > prev_url_idx) {
641         url_num_errors = 0;
642         do_advance_url = false;
643       }
644     }
645 
646     if (HandleErrorCode(get<1>(err_tuple), &url_num_errors) ||
647         url_num_errors > update_state.download_errors_max)
648       do_advance_url = true;
649 
650     prev_url_idx = url_idx;
651   }
652 
653   // If required, advance to the next usable URL. If the URLs wraparound, we
654   // mark an update attempt failure. Also be sure to set the download error
655   // count to zero.
656   if (url_idx < 0 || do_advance_url) {
657     url_num_errors = 0;
658     int start_url_idx = -1;
659     do {
660       if (++url_idx == num_urls) {
661         url_idx = 0;
662         // We only mark failure if an actual advancing of a URL was required.
663         if (do_advance_url)
664           is_failure_occurred = true;
665       }
666 
667       if (start_url_idx < 0)
668         start_url_idx = url_idx;
669       else if (url_idx == start_url_idx)
670         url_idx = -1;  // No usable URL.
671     } while (url_idx >= 0 &&
672              !IsUrlUsable(update_state.download_urls[url_idx], http_allowed));
673   }
674 
675   // If we have a download URL but a failure was observed, compute a new backoff
676   // expiry (if allowed). The backoff period is generally 2 ^ (num_failures - 1)
677   // days, bounded by the size of int and kAttemptBackoffMaxIntervalInDays, and
678   // fuzzed by kAttemptBackoffFuzzInHours hours. Backoff expiry is computed from
679   // the latest recorded time of error.
680   Time backoff_expiry;
681   if (url_idx >= 0 && is_failure_occurred && may_backoff) {
682     CHECK(!err_time.is_null())
683         << "We must have an error timestamp if a failure occurred!";
684     const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
685     POLICY_CHECK_VALUE_AND_FAIL(seed, error);
686     PRNG prng(*seed);
687     int exp =
688         min(update_state.num_failures, static_cast<int>(sizeof(int)) * 8 - 2);
689     TimeDelta backoff_interval = TimeDelta::FromDays(min(
690         1 << exp,
691         kNextUpdateCheckPolicyConstants.attempt_backoff_max_interval_in_days));
692     TimeDelta backoff_fuzz = TimeDelta::FromHours(
693         kNextUpdateCheckPolicyConstants.attempt_backoff_fuzz_in_hours);
694     TimeDelta wait_period = NextUpdateCheckTimePolicyImpl::FuzzedInterval(
695         &prng, backoff_interval.InSeconds(), backoff_fuzz.InSeconds());
696     backoff_expiry = err_time + wait_period;
697 
698     // If the newly computed backoff already expired, nullify it.
699     if (ec->IsWallclockTimeGreaterThan(backoff_expiry))
700       backoff_expiry = Time();
701   }
702 
703   result->do_increment_failures = is_failure_occurred;
704   result->backoff_expiry = backoff_expiry;
705   result->url_idx = url_idx;
706   result->url_num_errors = url_num_errors;
707   return EvalStatus::kSucceeded;
708 }
709 
UpdateScattering(EvaluationContext * ec,State * state,string * error,UpdateScatteringResult * result,const UpdateState & update_state) const710 EvalStatus ChromeOSPolicy::UpdateScattering(
711     EvaluationContext* ec,
712     State* state,
713     string* error,
714     UpdateScatteringResult* result,
715     const UpdateState& update_state) const {
716   // Preconditions. These stem from the postconditions and usage contract.
717   DCHECK(update_state.scatter_wait_period >= kZeroInterval);
718   DCHECK_GE(update_state.scatter_check_threshold, 0);
719 
720   // Set default result values.
721   result->is_scattering = false;
722   result->wait_period = kZeroInterval;
723   result->check_threshold = 0;
724 
725   DevicePolicyProvider* const dp_provider = state->device_policy_provider();
726 
727   // Ensure that a device policy is loaded.
728   const bool* device_policy_is_loaded_p =
729       ec->GetValue(dp_provider->var_device_policy_is_loaded());
730   if (!(device_policy_is_loaded_p && *device_policy_is_loaded_p))
731     return EvalStatus::kSucceeded;
732 
733   // Is scattering enabled by policy?
734   const TimeDelta* scatter_factor_p =
735       ec->GetValue(dp_provider->var_scatter_factor());
736   if (!scatter_factor_p || *scatter_factor_p == kZeroInterval)
737     return EvalStatus::kSucceeded;
738 
739   // Obtain a pseudo-random number generator.
740   const uint64_t* seed = ec->GetValue(state->random_provider()->var_seed());
741   POLICY_CHECK_VALUE_AND_FAIL(seed, error);
742   PRNG prng(*seed);
743 
744   // Step 1: Maintain the scattering wait period.
745   //
746   // If no wait period was previously determined, or it no longer fits in the
747   // scatter factor, then generate a new one. Otherwise, keep the one we have.
748   TimeDelta wait_period = update_state.scatter_wait_period;
749   if (wait_period == kZeroInterval || wait_period > *scatter_factor_p) {
750     wait_period = TimeDelta::FromSeconds(
751         prng.RandMinMax(1, scatter_factor_p->InSeconds()));
752   }
753 
754   // If we surpassed the wait period or the max scatter period associated with
755   // the update, then no wait is needed.
756   Time wait_expires = (update_state.first_seen +
757                        min(wait_period, update_state.scatter_wait_period_max));
758   if (ec->IsWallclockTimeGreaterThan(wait_expires))
759     wait_period = kZeroInterval;
760 
761   // Step 2: Maintain the update check threshold count.
762   //
763   // If an update check threshold is not specified then generate a new
764   // one.
765   int check_threshold = update_state.scatter_check_threshold;
766   if (check_threshold == 0) {
767     check_threshold = prng.RandMinMax(update_state.scatter_check_threshold_min,
768                                       update_state.scatter_check_threshold_max);
769   }
770 
771   // If the update check threshold is not within allowed range then nullify it.
772   // TODO(garnold) This is compliant with current logic found in
773   // OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied(). We may want
774   // to change it so that it behaves similarly to the wait period case, namely
775   // if the current value exceeds the maximum, we set a new one within range.
776   if (check_threshold > update_state.scatter_check_threshold_max)
777     check_threshold = 0;
778 
779   // If the update check threshold is non-zero and satisfied, then nullify it.
780   if (check_threshold > 0 && update_state.num_checks >= check_threshold)
781     check_threshold = 0;
782 
783   bool is_scattering = (wait_period != kZeroInterval || check_threshold);
784   EvalStatus ret = EvalStatus::kSucceeded;
785   if (is_scattering && wait_period == update_state.scatter_wait_period &&
786       check_threshold == update_state.scatter_check_threshold)
787     ret = EvalStatus::kAskMeAgainLater;
788   result->is_scattering = is_scattering;
789   result->wait_period = wait_period;
790   result->check_threshold = check_threshold;
791   return ret;
792 }
793 
794 }  // namespace chromeos_update_manager
795